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 3.3 programming. ValueError: invalid literal for int () with base 10. (Beginner)
13,861,594
24
2012-12-13T14:09:27Z
13,861,656
29
2012-12-13T14:12:47Z
[ "python", "python-3.x" ]
beginner programmer here. I tried to find a solution before coming here but I'm completely clueless, so hopefully someone can be bothered to help me out here. So I wrote this program to solve y = a^x and then project it on a graph. The problem is that whenever a < 1 i get the error: ValueError: invalid literal for int...
# Answer: Given your traceback, the problem is obvious. `int()` takes integers, you are trying to give a decimal, so you need to use `float()`: ``` a = float(a) ``` This should work as expected: ``` >>> int(input("Type a number: ")) Type a number: 0.3 Traceback (most recent call last): File "<stdin>", line 1, in ...
Python 3.3 programming. ValueError: invalid literal for int () with base 10. (Beginner)
13,861,594
24
2012-12-13T14:09:27Z
19,845,870
7
2013-11-07T20:20:35Z
[ "python", "python-3.x" ]
beginner programmer here. I tried to find a solution before coming here but I'm completely clueless, so hopefully someone can be bothered to help me out here. So I wrote this program to solve y = a^x and then project it on a graph. The problem is that whenever a < 1 i get the error: ValueError: invalid literal for int...
As Lattyware said, there is a difference between Python2 & Python3 that leads to this error: With Python2, `int(str(5/2))` gives you 2. With Python3, the same gives you: *ValueError: invalid literal for int() with base 10: '2.5'* If you need to convert some string that could contain float instead of int, you should a...
dealing with endianness in c++
13,863,667
3
2012-12-13T16:00:52Z
13,864,257
7
2012-12-13T16:31:04Z
[ "c++", "python", "endianness" ]
I am working on translating a system from python to c++. I need to be able to perform actions in c++ that are generally performed by using Python's `struct.unpack` (interpreting binary strings as numerical values). For integer values, I am able to get this to (sort of) work, using the data types in `stdint.h`: ``` str...
**For 32 and 16-bit values:** This is exactly the problem you have for network data, which is big-endian. You can use the the [ntohl](http://linux.die.net/man/3/htonl) to turn a 32-bit into host order, little-endian in your case. > The ntohl() function converts the unsigned integer netlong from network byte order to ...
Have multiple commands when button is pressed in Tkinter with python 2.7
13,865,009
4
2012-12-13T17:15:19Z
13,865,066
7
2012-12-13T17:18:38Z
[ "python", "function", "button", "command", "tkinter" ]
I want to run multiple functions when I click a button. For example I want my button to look like ``` self.testButton = Button(self, text = "test", command = func1(), command = func2()) ``` when I execute this statement I get an error because I cannot allocate something to an argument twice....
``` def func1(evt=None): do_something1() do_something2() ... self.testButton = Button(self, text = "test", command = func1) ``` maybe? I guess maybe you could do something like ``` self.testButton = Button(self, text = "test", command = lambda x:func1(...
Have multiple commands when button is pressed in Tkinter with python 2.7
13,865,009
4
2012-12-13T17:15:19Z
13,865,150
11
2012-12-13T17:23:29Z
[ "python", "function", "button", "command", "tkinter" ]
I want to run multiple functions when I click a button. For example I want my button to look like ``` self.testButton = Button(self, text = "test", command = func1(), command = func2()) ``` when I execute this statement I get an error because I cannot allocate something to an argument twice....
You could create a generic function for combining functions, it might look something like this: ``` def combine_funcs(*funcs): def combined_func(*args, **kwargs): for f in funcs: f(*args, **kwargs) return combined_func ``` Then you could create your button like this: ``` self.testButton =...
What does error: nothing to repeat mean in this traceback from a compiled Python regex
13,865,318
3
2012-12-13T17:34:37Z
13,865,428
7
2012-12-13T17:42:16Z
[ "python", "regex" ]
I have an interesting issue going on with trying to understand and improve my use of REGEX in Python here is a regular expression ``` verbose_signature_pattern_2 = re.compile(""" ^ # begin match at new line \t* # 0-or-more tab [ ]* # 0-or-more blankspaces S # capital S [iI][gG][...
The first string is not a raw string. So when Python compiles the string (before it goes to the regex engine) it replaces all escape sequences. So `\t` will actually become a tab character in the string (not backslash-t). But you are using freespacing mode (`re.VERBOSE`). Therefore whitespace is insignificant. Your reg...
Why would a python regex compile on Linux but not Windows?
13,865,346
10
2012-12-13T17:36:33Z
13,865,760
7
2012-12-13T18:03:41Z
[ "python", "regex" ]
I have a regex to detect invalid xml 1.0 characters in a unicode string: ``` bad_xml_chars = re.compile(u'[^\x09\x0A\x0D\u0020-\uD7FF\uE000-\uFFFD\U00010000-\U0010FFFF]', re.U) ``` On Linux/python2.7, this works perfectly. On windows the following is raised: ``` File "C:\Python27\lib\re.py", line 190, in compile ...
It doesn't work because the Windows version of Python uses 16 bits to represent unicode characters, encoded as UTF-16. Code points `10000` and above are represented as two code units in UTF-16, and this confuses the `re` range representation which expects a single character on either side of the `-`. This is how the s...
Why would a python regex compile on Linux but not Windows?
13,865,346
10
2012-12-13T17:36:33Z
13,865,765
16
2012-12-13T18:03:56Z
[ "python", "regex" ]
I have a regex to detect invalid xml 1.0 characters in a unicode string: ``` bad_xml_chars = re.compile(u'[^\x09\x0A\x0D\u0020-\uD7FF\uE000-\uFFFD\U00010000-\U0010FFFF]', re.U) ``` On Linux/python2.7, this works perfectly. On windows the following is raised: ``` File "C:\Python27\lib\re.py", line 190, in compile ...
You have a [narrow Python build](http://wordaligned.org/articles/narrow-python) on Windows, so Unicode uses [UTF-16](http://en.wikipedia.org/wiki/UTF-16). This means that Unicode characters higher than `\uFFFF` will be two separate characters in the Python string. You should see something like this: ``` >>> len(u'\U00...
Quantile-Quantile Plot using SciPy
13,865,596
29
2012-12-13T17:54:07Z
13,865,874
36
2012-12-13T18:11:14Z
[ "python", "statistics", "scipy" ]
How would you create a qq-plot using Python? Assuming that you have a large set of measurements and are using some plotting function that takes XY-values as input. The function should plot the quantiles of the measurements against the corresponding quantiles of some distribution (normal, uniform...). The resulting pl...
I think that `scipy.stats.probplot` will do what you want. See the [documentation](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.probplot.html) for more detail. ``` import numpy as np import pylab import scipy.stats as stats measurements = np.random.normal(loc = 20, scale = 5, size=100) stats.p...
Quantile-Quantile Plot using SciPy
13,865,596
29
2012-12-13T17:54:07Z
22,432,395
15
2014-03-16T02:50:40Z
[ "python", "statistics", "scipy" ]
How would you create a qq-plot using Python? Assuming that you have a large set of measurements and are using some plotting function that takes XY-values as input. The function should plot the quantiles of the measurements against the corresponding quantiles of some distribution (normal, uniform...). The resulting pl...
Using `qqplot` of `statsmodels.api` is another option: Very basic example: ``` import numpy as np import statsmodels.api as sm import pylab test = np.random.normal(0,1, 1000) sm.qqplot(test, line='45') pylab.show() ``` Result: ![enter image description here](http://i.stack.imgur.com/CYssJ.png) Documentation and ...
AttributeError when running Python
13,866,772
2
2012-12-13T19:13:32Z
13,866,852
7
2012-12-13T19:19:04Z
[ "python" ]
When running my program that makes the function call ``` self.getFileButton = Button(self, text = "...", command = tkFileDialog.askopenfilename(mode="r+b", **self.file_opt)) ``` I get the error ``` File "C:/Documents and Settings/l/M...
You probably want something like: ``` self.getFileButton = Button(self, text = "...", command = lambda: tkFileDialog.askopenfilename(mode="r+b", **self.file_opt)) ``` The problem is that as you wrote it, the `askopenfilename` function gets run when the button is...
Python - Pytz - List of Timezones?
13,866,926
179
2012-12-13T19:24:37Z
13,867,305
10
2012-12-13T19:48:23Z
[ "python", "django", "pytz" ]
I would like to know what are all the possible values for the timezone argument in the Python library Pytz. **SOLUTION** ``` for tz in pytz.all_timezones: print tz Africa/Abidjan Africa/Accra Africa/Addis_Ababa Africa/Algiers Africa/Asmara Africa/Asmera Africa/Bamako Africa/Bangui Africa/Banjul Africa/Bissau Af...
The timezone name is the only reliable way to specify the timezone. You can find a list of timezone names here: <http://en.wikipedia.org/wiki/List_of_tz_database_time_zones> Note that this list contains a lot of alias names, such as US/Eastern for the timezone that is properly called America/New\_York. If you program...
Python - Pytz - List of Timezones?
13,866,926
179
2012-12-13T19:24:37Z
13,867,319
96
2012-12-13T19:49:16Z
[ "python", "django", "pytz" ]
I would like to know what are all the possible values for the timezone argument in the Python library Pytz. **SOLUTION** ``` for tz in pytz.all_timezones: print tz Africa/Abidjan Africa/Accra Africa/Addis_Ababa Africa/Algiers Africa/Asmara Africa/Asmera Africa/Bamako Africa/Bangui Africa/Banjul Africa/Bissau Af...
You can list all the available timezones with `pytz.all_timezones`: ``` In [40]: import pytz In [41]: pytz.all_timezones Out[42]: ['Africa/Abidjan', 'Africa/Accra', 'Africa/Addis_Ababa', ...] ``` There is also `pytz.common_timezones`: ``` In [45]: len(pytz.common_timezones) Out[45]: 403 In [46]: len(pytz.all_ti...
How to get object from PK inside Django template?
13,866,952
8
2012-12-13T19:26:14Z
13,867,326
10
2012-12-13T19:49:42Z
[ "python", "django", "django-templates" ]
Inside django template, I would like to get object's name using object's pk. For instance, given that I have pk of object from class `A`, I would like to do something like the following: ``` {{ A.objects.get(pk=A_pk).name }} ``` How can I do this?
From the docs on [The Django Template Language](https://docs.djangoproject.com/en/dev/topics/templates/): [Accessing method calls](https://docs.djangoproject.com/en/dev/topics/templates/#accessing-method-calls): > Because Django intentionally limits the amount of logic processing available in the template language, i...
How to get object from PK inside Django template?
13,866,952
8
2012-12-13T19:26:14Z
13,927,772
7
2012-12-18T06:50:28Z
[ "python", "django", "django-templates" ]
Inside django template, I would like to get object's name using object's pk. For instance, given that I have pk of object from class `A`, I would like to do something like the following: ``` {{ A.objects.get(pk=A_pk).name }} ``` How can I do this?
You can add your own tag if you want to. Like this: ``` from django import template register = template.Library() @register.simple_tag def get_obj(pk, attr): obj = getattr(A.objects.get(pk=int(pk)), attr) return obj ``` Then load tag in your template ``` {% load get_obj from your_module %} ``` and use it ...
cleaning big data using python
13,867,294
5
2012-12-13T19:47:51Z
13,868,278
7
2012-12-13T20:49:59Z
[ "python", "pandas" ]
I have to clean a input data file in python. Due to typo error, the datafield may have strings instead of numbers. I would like to identify all fields which are a string and fill these with NaN using pandas. Also, I would like to log the index of those fields. One of the crudest way is to loop through each and every f...
There is a `na_values` argument to [`read_csv`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parsers.read_csv.html): > `na_values` : list-like or dict, default `None` >        Additional strings to recognize as NA/NaN. If dict passed, specific per-column NA values ``` df = pd.read_csv('city.csv',...
Avoiding circular (cyclic) imports in Python?
13,867,676
5
2012-12-13T20:11:07Z
13,867,709
10
2012-12-13T20:13:38Z
[ "python", "python-2.7" ]
One way is to use import x, without using "from" keyword. So then you refer to things with their namespace everywhere. Is there any other way? like doing something like in C++ ifnotdef \_\_b\_\_ def \_\_b\_\_ type of thing?
Merge any pair of modules that depend on each other into a single module. Then introduce extra modules to get the old names back. E.g., ``` # a.py from b import B class A: whatever # b.py from a import A class B: whatever ``` becomes ``` # common.py class A: whatever class B: whatever # a.py from common import ...
Url in browser not updated after call of redirect( url_for('xxx' )) in Flask with jQuery mobile
13,868,007
7
2012-12-13T20:33:25Z
13,868,218
8
2012-12-13T20:45:48Z
[ "python", "jquery-mobile", "flask", "flask-login" ]
I have a very simple python program using Flask shown below. It handles a login with a popup and logout. The problem is that the url in the browser is not updated by the redirect(url\_for()) call. ``` @app.route('/') def index(): if not 'username' in session: # contains a button showing a login popup form ...
Finally solved it after finishing writing the question. The problem is caused by jQuery mobile and the missing data-url attribute. By adding the data-url attribute in the page div the url in the browser is updated and everything works fine. ``` <div data-role="page" id="welcome" data-url="{{ url_for('index') }}"> ``...
Using Boto to connect to S3 with Python
13,868,841
7
2012-12-13T21:31:44Z
13,868,985
14
2012-12-13T21:43:16Z
[ "python", "amazon-web-services", "amazon-s3", "boto" ]
I'm trying to access AWS using Boto, and it's not working. I've installed Boto, and the boto.cfg in /etc. Here's my code: ``` import requests, json import datetime import hashlib import boto conn = boto.connect_s3() ``` Here's the error: ``` Traceback (most recent call last): File "boto.py", line 4, in <module> ...
It looks like the file you're working on is called `boto.py`. I think what's happening here is that your file is importing itself--Python looks for modules in the directory containing the file doing the import before it looks on your `PYTHONPATH`. Try changing the name to something else.
Numpy: find elements within range
13,869,173
21
2012-12-13T21:56:38Z
13,869,233
41
2012-12-13T22:01:04Z
[ "python", "numpy" ]
I have a numpy array of numbers, for example, ``` a = [1, 3, 5, 6, 9, 10, 14, 15, 56] ``` I would like to find all elements within a specific range. For instance, if the range is (6, 10), the answer should be (3, 4, 5). Is there a built-in function to do this?
You can use `np.where` to get indices and `np.logical_and` to set two conditions: ``` In [27]: a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56]) In [28]: np.where(np.logical_and(a>=6, a<=10)) Out[28]: (array([3, 4, 5]),) ```
Numpy: find elements within range
13,869,173
21
2012-12-13T21:56:38Z
13,870,686
7
2012-12-13T23:59:29Z
[ "python", "numpy" ]
I have a numpy array of numbers, for example, ``` a = [1, 3, 5, 6, 9, 10, 14, 15, 56] ``` I would like to find all elements within a specific range. For instance, if the range is (6, 10), the answer should be (3, 4, 5). Is there a built-in function to do this?
I thought I would add this because the `a` in the example you gave is sorted: ``` import numpy as np a = [1, 3, 5, 6, 9, 10, 14, 15, 56] start = np.searchsorted(a, 6, 'left') end = np.searchsorted(a, 10, 'right') rng = np.arange(start, end) rng # array([3, 4, 5]) ```
Numpy: find elements within range
13,869,173
21
2012-12-13T21:56:38Z
13,871,987
16
2012-12-14T02:55:05Z
[ "python", "numpy" ]
I have a numpy array of numbers, for example, ``` a = [1, 3, 5, 6, 9, 10, 14, 15, 56] ``` I would like to find all elements within a specific range. For instance, if the range is (6, 10), the answer should be (3, 4, 5). Is there a built-in function to do this?
As in @deinonychusaur's reply, but even more compact: ``` In [7]: np.where((a >= 6) & (a <=10)) Out[7]: (array([3, 4, 5]),) ```
Check 4 strings if there are duplicates
13,869,628
2
2012-12-13T22:28:58Z
13,869,646
8
2012-12-13T22:30:47Z
[ "python", "python-2.7" ]
s1, s2, s3, s4 have a string as content I want to do something like this ``` if one or more is the same s1, s2, s3 or s4: print error else print s1, s2, s3, s4 ```
You could use a set: ``` if len(set([s1, s2, s3, s4])) != 4: pass # not all unique ```
ipython tab completion for custom dict class
13,870,241
6
2012-12-13T23:17:10Z
13,870,861
9
2012-12-14T00:21:03Z
[ "python" ]
I've been using the following in my code: ``` class Structure(dict,object): """ A 'fancy' dictionary that provides 'MatLab' structure-like referencing. """ def __getattr__(self, attr): # Fake a __getstate__ method that returns None if attr == "__getstate__": return lambda: None return self[attr] ...
Add this method: ``` def __dir__(self): return self.keys() ``` See here: <http://ipython.org/ipython-doc/dev/config/integrating.html> And here: <http://docs.python.org/2/library/functions.html>
python "or" operator weird behavior
13,870,378
3
2012-12-13T23:28:16Z
13,870,439
9
2012-12-13T23:33:05Z
[ "python", "operators", "boolean" ]
First, the code: ``` >>> False or 'hello' 'hello' ``` This surprising behavior lets you check if x != None and check x value in one line: ``` >>> x = 10 if randint(0,2)==1 else None >>> (x or 0) > 0 depend on x value... ``` Explanation: "or" functions like this: ([link](http://docs.python.org/2/library/stdtypes.htm...
> No language that i know lets you do this. So, why Python do? Then you don't know many languages. I can't think of one language that I do know that does not exhibit this "shortcircuiting" behaviour. It does it because it is useful to say: ``` a = b or K ``` such that a either becomes b, if b is not None (or otherw...
python "or" operator weird behavior
13,870,378
3
2012-12-13T23:28:16Z
13,870,633
10
2012-12-13T23:52:53Z
[ "python", "operators", "boolean" ]
First, the code: ``` >>> False or 'hello' 'hello' ``` This surprising behavior lets you check if x != None and check x value in one line: ``` >>> x = 10 if randint(0,2)==1 else None >>> (x or 0) > 0 depend on x value... ``` Explanation: "or" functions like this: ([link](http://docs.python.org/2/library/stdtypes.htm...
It sounds like you're combining two issues into one. First, there's the issue of short-circuiting. Marcin's answer addresses this issue perfectly, so I won't try to do any better. Second, there's `or` and `and` returning the last-evaluated value, rather than converting it to bool. There are arguments to be made both ...
How to clear/reset all configured logging handlers in Python?
13,870,555
5
2012-12-13T23:45:56Z
13,870,741
7
2012-12-14T00:05:05Z
[ "python", "logging" ]
**My Situation** There may be one or more configured loggers, but I don't know what their names are. **Requirement** For testing purposes, I need to reconfigure logging handlers that were previously configured to log to stdout with a different format and logging level. 1. [caveat] I already know how to [clear one...
``` print (logging.Logger.manager.loggerDict.keys()) ``` found by digging the sources of logging package
How to "overload" python's print function "globally"?
13,870,928
6
2012-12-14T00:29:23Z
13,870,997
7
2012-12-14T00:36:57Z
[ "python", "namespaces", "python-2.6" ]
I am using python 2.6.6 and I need to overload the default python print function. I need to do it because this code may be used on a system where a built-in function has to be used to generate output, otherwise no output is displayed. So, just for example, if you have a python script like this: ``` from __future__ im...
I don't think your question makes any sense. First, if you're running Python 2.6, everything you import, etc., will be using `print` statements, even if your own module is using the `print` function. So, overloading the function will not affect anything else. Second, you say "I need to do it because this code may be ...
How to "overload" python's print function "globally"?
13,870,928
6
2012-12-14T00:29:23Z
13,871,861
10
2012-12-14T02:36:04Z
[ "python", "namespaces", "python-2.6" ]
I am using python 2.6.6 and I need to overload the default python print function. I need to do it because this code may be used on a system where a built-in function has to be used to generate output, otherwise no output is displayed. So, just for example, if you have a python script like this: ``` from __future__ im...
As @abarnert's answer and several comments have pointed out, replacing `print` is probably not a good idea. But just for the sake of completeness, here's why your code was not successfully overriding it for other modules. The `print` function is defined in the module [`__builtin__`](http://docs.python.org/2/library/__...
Python: How to get the length of itertools _grouper
13,870,962
19
2012-12-14T00:32:08Z
13,870,985
24
2012-12-14T00:35:44Z
[ "python", "group-by", "itertools" ]
I'm working with Python itertools and using groupby to sort a bunch of pairs by the last element. I've gotten it to sort and I can iterate through the groups just fine, but I would really love to be able to get the length of each group without having to iterate through each one, incrementing a counter. The project is ...
Just because you call it `clusterList` doesn't make it a list! It's basically a lazy iterator, returning each item as it's needed. You can convert it to a list like this, though: ``` clusterList = list(clusterList) ``` Or do that and get its length in one step: ``` length = len(list(clusterList)) ``` If you don't w...
Why is Django 1.0.x not able to install from PyPI?
13,871,162
7
2012-12-14T00:55:49Z
13,871,252
12
2012-12-14T01:09:28Z
[ "python", "django", "virtualenv", "pip", "easy-install" ]
I tried it on virtualenv: ``` (venv) $ pip install Django==1.0.4 Downloading/unpacking Django==1.0.4 Could not find a version that satisfies the requirement Django==1.0.4 (from versions: ) No distributions matching the version for Django==1.0.4 Storing complete log in /home/tokibito/.pip/pip.log ```
Unfortunately, PyPI only has Django versions 1.1.4 and upwards. If you want the old version, you can just install directly from github: > pip install git+https://github.com/django/django.git@1.0.4
What is the difference between template in ZCML and ViewPageTemplateFile
13,871,915
6
2012-12-14T02:44:34Z
13,873,602
7
2012-12-14T06:11:03Z
[ "python", "plone", "zope", "zcml" ]
When creating a [BrowserView](http://developer.plone.org/views/browserviews.html) in Plone, I know that I may optionally configure a template with **ZCML** like so: ``` <configure xmlns:browser="http://namespaces.zope.org/browser" > <browser:page … class=".foo.FooView" template=...
In Plone, you can customize the template TTW (via `portal_view_customizations`) only when the template is registered explicitly (e.g. using ZCML or Grok-directives). If you define template only in your `__call__`, you won't see it in `portal_view_customizations`. Also, I'd guess that loading template within a method ...
What is the difference between template in ZCML and ViewPageTemplateFile
13,871,915
6
2012-12-14T02:44:34Z
13,876,273
7
2012-12-14T09:53:03Z
[ "python", "plone", "zope", "zcml" ]
When creating a [BrowserView](http://developer.plone.org/views/browserviews.html) in Plone, I know that I may optionally configure a template with **ZCML** like so: ``` <configure xmlns:browser="http://namespaces.zope.org/browser" > <browser:page … class=".foo.FooView" template=...
Note: To be fully equivalent to ZCML you should set the `index` variable to specify which template you are using. That way the TTW customization will work too. ``` # foo.py from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile from zope.publisher.browser import BrowserPage class FooView(BrowserPage):...
Plot different DataFrames in the same figure
13,872,533
20
2012-12-14T04:13:35Z
13,873,014
81
2012-12-14T05:09:24Z
[ "python", "matplotlib", "pandas" ]
I have a temperature file with many years temperature records, in a format as below: ``` 2012-04-12,16:13:09,20.6 2012-04-12,17:13:09,20.9 2012-04-12,18:13:09,20.6 2007-05-12,19:13:09,5.4 2007-05-12,20:13:09,20.6 2007-05-12,20:13:09,20.6 2005-08-11,11:13:09,20.6 2005-08-11,11:13:09,17.5 2005-08-13,07:13:09,20.6 2006-0...
Try: ``` ax = df1.plot() df2.plot(ax=ax) ```
Plot different DataFrames in the same figure
13,872,533
20
2012-12-14T04:13:35Z
13,876,784
11
2012-12-14T10:24:59Z
[ "python", "matplotlib", "pandas" ]
I have a temperature file with many years temperature records, in a format as below: ``` 2012-04-12,16:13:09,20.6 2012-04-12,17:13:09,20.9 2012-04-12,18:13:09,20.6 2007-05-12,19:13:09,5.4 2007-05-12,20:13:09,20.6 2007-05-12,20:13:09,20.6 2005-08-11,11:13:09,20.6 2005-08-11,11:13:09,17.5 2005-08-13,07:13:09,20.6 2006-0...
Although Chang's answer explains how to plot multiple times on the same figure, in this case you might be better off in this case using a [`groupby`](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.groupby.html#pandas.DataFrame.groupby) and [`unstack`](http://pandas.pydata.org/pandas-docs/dev/genera...
How to write multiple try statements in one block in python?
13,874,666
8
2012-12-14T07:52:40Z
13,874,853
16
2012-12-14T08:11:07Z
[ "python", "exception", "exception-handling" ]
I want to do: ``` try: do() except: do2() except: do3() except: do4() ``` If do() fails, execute do2(), if do2() fails too, exceute do3() and so on. best Regards
If you really don't care about the exceptions, you could loop over cases until you succeed: ``` for fn in (do, do2, do3, do4): try: fn() break except: continue ``` This at least avoids having to indent once for every case. If the different functions need different arguments you can use...
Comparing image in url to image in filesystem in python
13,875,989
2
2012-12-14T09:36:38Z
13,884,956
10
2012-12-14T19:18:19Z
[ "python", "image-processing", "diff", "python-imaging-library", "image-comparison" ]
Is there a quick and easy way to do such comparison? I've found few image compare questions from stackoverflow but none of those actually proved answer for this question. I have images files in my filesystem and a script that fetches images from urls. I want to check if the image in url is already the same that is on...
The question's title suggests you have two exact images to compare, and that is trivially done. Now, if you have similar images to compare then that explains why you didn't find a fully satisfactory answer: there is no metric applicable to every problem that gives the expected results (note that expected results varies...
Spyder - UMD has deleted: module
13,876,306
21
2012-12-14T09:55:31Z
13,893,663
41
2012-12-15T15:51:38Z
[ "python", "graphics", "spyder", "pythonxy" ]
I have been fooling around for about a month with python now and something is bothering me. I use the python(x,y) toolkit, which comes with the neat Spyder IDE. My question concerns the UMD (User module deleter) of Spyder. I found [this](http://mcsp.wartburg.edu/zelle/python/graphics/graphics/index.html) graphics modu...
**Short Answer:** Perhaps *deleted* is not the best word in the message you mention. It should be *reloaded*, which is what UMD is really doing and because is way less confusing. I'll fill an issue for this in our issue tracker. **Long answer:** UMD reloads not only your script but also all the local modules it depe...
How to save numpy masked array to file
13,877,063
5
2012-12-14T10:42:19Z
13,877,105
7
2012-12-14T10:44:35Z
[ "python", "numpy" ]
What is the most efficient way of saving a numpy masked array? Unfortunately `numpy.save` doesn't work: ``` import numpy as np a = np.ma.zeros((500, 500)) np.save('test', a) ``` This gives a: ``` NotImplementedError: Not implemented yet, sorry... ``` One way seems to be using pickle, but that unfortunately is not v...
``` import numpy as np a = np.ma.zeros((500, 500)) a.dump('test') ``` then read it with ``` a = np.load('test') ```
How to write a binary struct using python that can be read in c?
13,877,286
2
2012-12-14T10:55:45Z
13,877,321
7
2012-12-14T10:58:12Z
[ "python", "c" ]
say a struct like this: ``` typedef struct testVertex_s { char *vert_name; //for test only... float x; float y; float z; }testvertex_t; ``` how to write that to a binary file use python ? I want to read it using fread in c;
Why must it be binary? Text is trivial, and much simpler to interact with. If you really want binary, use the [struct](http://docs.python.org/2/library/struct.html) module. Make sure to define your endianness, and read each field *separately* in C, do *not* try to do a single `fread()` into a C structure. You could d...
How to collect my tests with py.test?
13,877,355
6
2012-12-14T11:00:07Z
13,877,481
15
2012-12-14T11:09:28Z
[ "python", "py.test" ]
I try to collect my tests with py.test but it doesn't do so. * **Do I have to provide additional options at the command line?** * Py.test was executed in the directory of my .py-file. **Are there any other requirements?** * **Are my tests named correctly?** In my code I used 'Test-' for classes and 'test\_' for method...
In the default configuration, the test file should be named `test_<something>.py`. See [Changing standard (Python) test discovery](http://pytest.org/latest/example/pythoncollection.html#changing-standard-python-test-discovery).
Running sum in pandas (without loop)
13,878,959
6
2012-12-14T12:44:18Z
13,879,549
13
2012-12-14T13:25:21Z
[ "python", "pandas" ]
I'd like to build a running sum over a pandas dataframe. I have something like: ``` 10/10/2012: 50, 0 10/11/2012: -10, 90 10/12/2012: 100, -5 ``` And I would like to get: ``` 10/10/2012: 50, 0 10/11/2012: 40, 90 10/12/2012: 140, 85 ``` So every cell should be the sum of itself and all previous cells, how shoul...
As @JonClements mentions, you can do this using the [`cumsum`](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.cumsum.html) DataFrame method: ``` from pandas import DataFrame df = DataFrame({0: {'10/10/2012': 50, '10/11/2012': -10, '10/12/2012': 100}, 1: {'10/10/2012': 0, '10/11/2012': 90, '10/12/2...
Library for SVG path calculations
13,879,230
5
2012-12-14T13:02:13Z
14,424,964
21
2013-01-20T13:23:05Z
[ "python", "svg" ]
I'm looking for a library with Python bindings that can do calculations on SVG paths, such as calculating the length, and finding the coordinates of a point on the paths (ie, say the coordinates of the point 24.4% the length of the path). Is there something around already? A C-library would be acceptable as well, as ...
OK, so I wrote it, and released it as a library. <http://pypi.python.org/pypi/svg.path>
how to call / run multiple python scripts from batch file in window xp / 7
13,880,650
4
2012-12-14T14:30:46Z
13,880,776
11
2012-12-14T14:39:10Z
[ "python", "batch-file", "scheduled-tasks" ]
I'm trying to schedule run multiple pythons using batch file. For example there are my python files that I want to schedule run them on the daily basis ``` D:\py\s1.py D:\py\s2.py ``` now how can I combine these two files into a .bat, so that I can schedule run these two file using `python.exe` (`C:\python27\python....
**Method 1**: Bat file. If you have python in the PATH Environment variable: ``` start python D:\py\s1.py start python D:\py\s2.py ``` Else literal path ``` start C:\python27\python.exe D:\py\s1.py start C:\python27\python.exe D:\py\s2.py ``` Note that this will not wait for a return from either execution. Note, d...
Python sqlite3 string variable in execute
13,880,786
5
2012-12-14T14:39:49Z
13,881,118
17
2012-12-14T15:01:36Z
[ "python", "sqlite3" ]
Great people of Stackoverflow! I try to execute this sqlite3 query in Python. I reduced the code to the minimum, sqlite.connect, etc works. ``` column = 'Pron_1_Pers_Sg' goal = 'gender' constrain = 'Mann' with con: cur = con.cursor() cur.execute("SELECT ? FROM Data where ?=?", (column, goal, constrain)) ...
Parameter markers can be used only for expressions, i.e., values. You cannot use them for identifiers like table and column names. Use this: ``` cur.execute("SELECT "+column+" FROM Data where "+goal+"=?", (constrain,)) ``` or this: ``` cur.execute("SELECT %s FROM Data where %s=?" % (column, goal), (constrain,)) ```...
Remove last 3 letters of string in Django template [:-3]
13,880,831
4
2012-12-14T14:43:00Z
13,880,899
15
2012-12-14T14:47:42Z
[ "python", "django", "django-templates" ]
I'm doing the following: ``` {% for wrapping in wrappings %} //array of strings <input type="radio" value="{{ wrapping[:-3] }}" etc ``` I want to output all the string in wrapping minus the last 3 letters but am recieving a: `TemplateSyntaxError: Could not parse the remainder: '[:-3]' from 'wrapping[:-3]`. Any ide...
You can just use the slice filter: ``` {{ wrapping|slice:":-3" }} ```
Download progressbar for Python 3
13,881,092
4
2012-12-14T15:00:17Z
13,895,723
10
2012-12-15T20:06:49Z
[ "python", "python-3.x", "download", "progress-bar" ]
> **Possible Duplicate:** > [Python urllib2 Progress Hook](http://stackoverflow.com/questions/2028517/python-urllib2-progress-hook) I need a progress to show during file download for Python 3. I have seen a few topics on Stackoverflow, but considering that I'm a noob at programming and nobody posted a complete examp...
There is [`urlretrieve()`](http://docs.python.org/3/library/urllib.request.html#urllib.request.urlretrieve) that downloads an url to a file and allows to specify a reporthook callback to report progess: ``` #!/usr/bin/env python3 import sys from urllib.request import urlretrieve def reporthook(blocknum, blocksize, to...
In Python what is a global statement?
13,881,395
5
2012-12-14T15:16:08Z
13,881,502
15
2012-12-14T15:22:40Z
[ "python", "global" ]
What is a **global statement**? And how is it used? I have read [Python's official definition](http://docs.python.org/3/reference/simple_stmts.html#the-global-statement); however, it doesn't make a lot of sense to me.
Every "variable" in python is limited to a certain scope. The scope of a python "file" is the module-scope. Consider the following: ``` #file test.py myvariable = 5 #myvariable has module-level scope def func(): x = 3 # x has "local" or function level scope. ``` Objects with local scope die as soon as the func...
Python: Memory leak?
13,882,291
10
2012-12-14T16:08:42Z
13,882,474
14
2012-12-14T16:19:45Z
[ "python", "performance", "optimization", "memory-leaks" ]
## Query in Python interpreter: ``` Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> k = [i for i in xrange(9999999)] >>> import sys >>> sys.getsizeof(k)/1024/1024 38 >>> ``` ## And here - see how much it tak...
`sys.getsizeof()` is not very useful because it accounts often for only a part of what you expect. In this case, it accounts for the list, but not all integer objects that are in the list. The list takes roughly 4 bytes per item. The integer objects take another 12 bytes each. For example, if you try this: ``` k = [42...
SQLAlchemy blocked on dropping tables
13,882,407
5
2012-12-14T16:15:20Z
13,882,520
7
2012-12-14T16:21:58Z
[ "python", "mysql", "sqlalchemy" ]
The code is a step-by-step copy from sqlahcmey's [orm tutorial](http://docs.sqlalchemy.org/en/rel_0_8/orm/tutorial.html), except the last line, I intended to drop all tables after the query. But the program blocked on `Base.metadata.drop_all(bind=engine)`, below is the status of MySQL at that time(taken from MySQL Work...
call session.close() (or commit(), or rollback()) before you do the drop\_all(). the session is still sitting on an open transaction. the tutorial is against sqlite which doesn't have aggressive table locking (I'm assuming your MySQL DB is using InnoDB here).
Stanford Parser and NLTK
13,883,277
47
2012-12-14T17:12:20Z
13,939,013
7
2012-12-18T18:16:21Z
[ "python", "parsing", "nlp", "nltk", "stanford-nlp" ]
Is it possible to use Stanford Parser in NLTK? (I am not talking about Stanford POS.)
There is python interface for stanford parser <http://projects.csail.mit.edu/spatial/Stanford_Parser>
Stanford Parser and NLTK
13,883,277
47
2012-12-14T17:12:20Z
14,376,410
20
2013-01-17T09:58:37Z
[ "python", "parsing", "nlp", "nltk", "stanford-nlp" ]
Is it possible to use Stanford Parser in NLTK? (I am not talking about Stanford POS.)
## Edited As of the current Stanford parser (2015-04-20), the default output for the `lexparser.sh` has changed so the script below will not work. But this answer is kept for legacy sake, it will still work with <http://nlp.stanford.edu/software/stanford-parser-2012-11-12.zip> though. --- ## Original Answer I sugg...
Stanford Parser and NLTK
13,883,277
47
2012-12-14T17:12:20Z
18,366,016
7
2013-08-21T19:28:10Z
[ "python", "parsing", "nlp", "nltk", "stanford-nlp" ]
Is it possible to use Stanford Parser in NLTK? (I am not talking about Stanford POS.)
The Stanford Core NLP software page has a list of python wrappers: <http://nlp.stanford.edu/software/corenlp.shtml#Extensions>
Stanford Parser and NLTK
13,883,277
47
2012-12-14T17:12:20Z
22,269,678
54
2014-03-08T13:03:36Z
[ "python", "parsing", "nlp", "nltk", "stanford-nlp" ]
Is it possible to use Stanford Parser in NLTK? (I am not talking about Stanford POS.)
## EDITED As of NLTK version 3.1 the instructions of this answer will no longer work. Please follow the instructions on <https://github.com/nltk/nltk/wiki/Installing-Third-Party-Software> This answer is kept for legacy purposes on Stackoverflow. The answer does work for NLTK v3.0 though. --- ## Original Answer Sur...
Stanford Parser and NLTK
13,883,277
47
2012-12-14T17:12:20Z
34,112,695
24
2015-12-06T00:45:28Z
[ "python", "parsing", "nlp", "nltk", "stanford-nlp" ]
Is it possible to use Stanford Parser in NLTK? (I am not talking about Stanford POS.)
## EDITED Note: The following answer will only work on: * NLTK version 3.1 * Stanford Tools compiled since 2015-04-20 As both tools changes rather quickly and the API might look very different 3-6 months later. Please treat the following answer as temporal and not an eternal fix. **Always refer to <https://github.c...
Python: trying to collapse a function mapping on the second argument
13,884,378
4
2012-12-14T18:32:52Z
13,884,557
7
2012-12-14T18:46:35Z
[ "python", "functional-programming" ]
NOTE: Please read the BETTER UPDATE section below before commenting. There is some subtlety here. None of the answers given yet work in context, as far as I can tell. I'm trying to find an analog to the python 'map' function with slightly different functionality. This is best explained by example. The 'map' function d...
What about this lazy version: ``` >>> def add(x,y): ... return x+y ... >>> def magic_map(func,*args): ... return itertools.starmap(func,itertools.izip(*args)) #just zip in python 3. ... >>> list(magic_map(add,['a', 'b', 'c'], itertools.repeat('1'))) ['a1', 'b1', 'c1'] ``` Note that we require the `zip` to t...
What is Python Whitespace and how does it work?
13,884,499
8
2012-12-14T18:42:07Z
13,884,583
8
2012-12-14T18:48:56Z
[ "python", "whitespace" ]
I've been searching google and this website for some time now, but I just can't seem to find a straight answer on the subject. **What is whitespace in Python?** I know it's something to do with indenting with each line, but I'm not sure exactly how to use it. How does it work?
Whitespace is used to denote blocks. In other languages curly brackets (`{` and `}`) are common. When you indent, it becomes a child of the previous line. In addition to the indentation, the parent also has a colon following it. ``` im_a_parent: im_a_child: im_a_grandchild im_another_child: im_...
Python nested looping Idiom
13,885,234
21
2012-12-14T19:41:12Z
13,885,250
8
2012-12-14T19:42:40Z
[ "python", "loops", "for-loop", "foreach", "idioms" ]
I often find myself doing this: ``` for x in range(x_size): for y in range(y_size): for z in range(z_size): pass # do something here ``` Is there a more concise way to do this in Python? I am thinking of something along the lines of ``` for x, z, y in ... ? : ```
If you've got `numpy` as a dependency already, [`numpy.ndindex`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndindex.html#numpy.ndindex) will do the trick ... ``` >>> for x,y,z in np.ndindex(2,2,2): ... print x,y,z ... 0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1 ```
Python nested looping Idiom
13,885,234
21
2012-12-14T19:41:12Z
13,885,266
37
2012-12-14T19:44:17Z
[ "python", "loops", "for-loop", "foreach", "idioms" ]
I often find myself doing this: ``` for x in range(x_size): for y in range(y_size): for z in range(z_size): pass # do something here ``` Is there a more concise way to do this in Python? I am thinking of something along the lines of ``` for x, z, y in ... ? : ```
You can use [itertools.product](http://docs.python.org/2/library/itertools.html#itertools.product): ``` >>> for x,y,z in itertools.product(range(2), range(2), range(3)): ... print x,y,z ... 0 0 0 0 0 1 0 0 2 0 1 0 0 1 1 0 1 2 1 0 0 1 0 1 1 0 2 1 1 0 1 1 1 1 1 2 ```
Python nested looping Idiom
13,885,234
21
2012-12-14T19:41:12Z
13,885,269
7
2012-12-14T19:44:33Z
[ "python", "loops", "for-loop", "foreach", "idioms" ]
I often find myself doing this: ``` for x in range(x_size): for y in range(y_size): for z in range(z_size): pass # do something here ``` Is there a more concise way to do this in Python? I am thinking of something along the lines of ``` for x, z, y in ... ? : ```
Use [`itertools.product()`](http://docs.python.org/2/library/itertools.html#itertools.product): ``` import itertools for x, y, z in itertools.product(range(x_size), range(y_size), range(z_size)): pass # do something here ``` From the docs: > Cartesian product of input iterables. > > Equivalent to nested for-loop...
Why does Python's dict.keys() return a list and not a set?
13,886,129
39
2012-12-14T20:56:12Z
13,886,160
37
2012-12-14T20:58:45Z
[ "python", "python-2.x" ]
I would've expected Python's keys method to return a set instead of a list. Since it most closely resembles the kind of guarantees that keys of a hashmap would give. Specifically, they are unique and not sorted, like a set. However, this method returns a list: ``` >>> d = {} >>> d.keys().__class__ <type 'list'> ``` I...
One reason is that `dict.keys()` predates the introduction of sets into the language. Note that the return type of `dict.keys()` has changed in Python 3: the function now returns a [view](http://docs.python.org/release/3.3.0/library/stdtypes.html#dict-views) rather than a list.
How To Use The Pass Statement In Python
13,886,168
113
2012-12-14T20:59:30Z
13,886,195
129
2012-12-14T21:02:09Z
[ "python" ]
I am in the process of learning Python and I have reached the section about the `pass` statement. The guide I'm using defines it as being a `Null` statement that is commonly used as a placeholder. I still don't fully understand what that means though. Can someone show me a simple/basic situation where the `pass` state...
Suppose you are designing a new class with some methods that you don't want to implement, yet. ``` class MyClass(object): def meth_a(self): pass def meth_b(self): print "I'm meth_b" ``` If you would leave out the `pass`, the code wouldn't run. You would then get an ``` IndentationError: exp...
How To Use The Pass Statement In Python
13,886,168
113
2012-12-14T20:59:30Z
17,579,272
14
2013-07-10T19:25:10Z
[ "python" ]
I am in the process of learning Python and I have reached the section about the `pass` statement. The guide I'm using defines it as being a `Null` statement that is commonly used as a placeholder. I still don't fully understand what that means though. Can someone show me a simple/basic situation where the `pass` state...
Besides its use as a placeholder for unimplemented functions, `pass` can be useful in filling out an if-else statement ("Explicit is better than implicit.") ``` def some_silly_transform(n): # Even numbers should be divided by 2 if n % 2 == 0: n /= 2 flag = True # Negative odd numbers should...
How To Use The Pass Statement In Python
13,886,168
113
2012-12-14T20:59:30Z
21,080,436
10
2014-01-12T21:21:38Z
[ "python" ]
I am in the process of learning Python and I have reached the section about the `pass` statement. The guide I'm using defines it as being a `Null` statement that is commonly used as a placeholder. I still don't fully understand what that means though. Can someone show me a simple/basic situation where the `pass` state...
The best and most accurate way to think of `pass` is as a way to explicitly tell the interpreter to do nothing. In the same way the following code: ``` def foo(x,y): return x+y ``` means "if I call the function foo(x, y), sum the two numbers the labels x and y represent and hand back the result", ``` def bar(): ...
How To Use The Pass Statement In Python
13,886,168
113
2012-12-14T20:59:30Z
22,612,774
77
2014-03-24T14:51:43Z
[ "python" ]
I am in the process of learning Python and I have reached the section about the `pass` statement. The guide I'm using defines it as being a `Null` statement that is commonly used as a placeholder. I still don't fully understand what that means though. Can someone show me a simple/basic situation where the `pass` state...
Python has the syntactical requirement that code blocks (after `if`, `except`, `def`, `class` etc.) cannot be empty. As described in [the pass statement documentation](http://stackoverflow.com/documentation/python/6891/the-pass-statement#t=201609201554064352991), empty code blocks are however useful in a variety of dif...
python map vs itertools.map: Make the iterator version behave like the former
13,886,917
3
2012-12-14T22:05:38Z
13,886,953
9
2012-12-14T22:08:37Z
[ "python", "map", "itertools" ]
Consider the following example code. The example is given just to highlight the different functionality between `map` and `itertools.imap`. What I really want to do cannot be done with a list comprehension because in my real problem I am not creating a list but filling a larger numpy array with small arrays. So in resp...
`itertools` functions return generators; they only operate when iterated over. So `itertools.imap(f, range(3))` won't actually *do* anything until you run it to completion e.g. with `list`. Per <http://docs.python.org/2/library/itertools.html#recipes>, the most efficient way to consume an iterator is with a zero-lengt...
Extract bounding box and save it as an image
13,887,863
8
2012-12-14T23:50:08Z
13,887,948
11
2012-12-15T00:00:45Z
[ "python", "opencv" ]
Suppose you have the following image:![Example:](http://i.stack.imgur.com/r5z3w.png) Now i want to extract to individual images each of the independent letters, for this task i've recovered the contours and then drawed a bounding box, in this case for the character 'a': ![Bounding box for the character 'a'](http://i....
The following will give you a single letter ``` letter = im[y:y+h,x:x+w] ```
When should I be calling flush() on SQLAlchemy?
13,887,908
15
2012-12-14T23:55:44Z
13,889,354
25
2012-12-15T04:39:02Z
[ "python", "sqlalchemy", "pyramid" ]
I'm new to SQLAlchemy and have inherited a somewhat messy codebase without access to the original author. The code is litered with calls to `DBSession.flush()`, seemingly any time the author wanted to make sure data was being saved. At first I was just following patterns I saw in this code, but as I'm reading docs, it...
The `ZopeTransactionExtension` on the `DBSession` in conjunction with the `pyramid_tm` being active on your project will handle all commits for you. The situations where you need to flush are: * You want to create a new object and get back the primary key. ``` DBSession.add(obj) DBSession.flush() log.info('lo...
Run an external command and get the amount of CPU it consumed
13,889,066
4
2012-12-15T03:39:30Z
13,933,797
10
2012-12-18T13:11:38Z
[ "python" ]
Pretty simple, I'd like to run an external command/program from within a Python script, once it is finished I would also want to know how much CPU time it consumed. Hard mode: running multiple commands in parallel won't cause inaccuracies in the CPU consumed result.
**On UNIX:** either (a) use [resource](http://docs.python.org/2/library/resource.html) module (also see answer by icktoofay), or (b) use the [time](http://linux.die.net/man/7/time) command and parse the results, or (c) use [/proc](http://www.kernel.org/doc/man-pages/online/pages/man5/proc.5.html) filesystem, parse /pro...
Does Python's time.time() return the local or UTC timestamp?
13,890,935
217
2012-12-15T09:14:57Z
13,891,070
310
2012-12-15T09:33:42Z
[ "python", "time", "timezone" ]
Does `time.time()` in the Python time module return the system's time or the time in UTC?
The [`time.time()`](https://docs.python.org/2/library/time.html#time.time) function returns the number of seconds since the epoch as seconds in UTC. Here is some sample output I ran on my computer, converting it to a string as well. ``` Python 2.7.3 (default, Apr 24 2012, 00:00:54) [GCC 4.7.0 20120414 (prerelease)] ...
Does Python's time.time() return the local or UTC timestamp?
13,890,935
217
2012-12-15T09:14:57Z
13,891,357
145
2012-12-15T10:24:06Z
[ "python", "time", "timezone" ]
Does `time.time()` in the Python time module return the system's time or the time in UTC?
This is for the **text form of a timestamp** that can be used in your text files. (The title of the question was different in the past, so the introduction to this answer was changed to clarify how it could be interpreted a the time. [updated 2016-01-14]) You can get the timestamp as a string using the `.now()` or `.u...
Does Python's time.time() return the local or UTC timestamp?
13,890,935
217
2012-12-15T09:14:57Z
16,299,439
70
2013-04-30T12:02:37Z
[ "python", "time", "timezone" ]
Does `time.time()` in the Python time module return the system's time or the time in UTC?
Based on the answer from #squiguy, to get a true timestamp I would type cast it from float. ``` >>> import time >>> ts = int(time.time()) >>> print(ts) 1389177318 ``` At least that's the concept.
Does Python's time.time() return the local or UTC timestamp?
13,890,935
217
2012-12-15T09:14:57Z
20,035,913
18
2013-11-17T20:41:30Z
[ "python", "time", "timezone" ]
Does `time.time()` in the Python time module return the system's time or the time in UTC?
The answer could be neither or both. * neither: `time.time()` returns approximately the number of seconds elapsed since the Epoch. The result doesn't depend on timezone so it is neither UTC nor local time. Here's [POSIX defintion for "Seconds Since the Epoch"](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V...
fatal error 'stdio.h' Python 2.7.3 on Mac OS X 10.7.5
13,891,056
2
2012-12-15T09:30:59Z
14,027,700
8
2012-12-25T04:32:24Z
[ "python", "mysql", "osx", "python-2.7" ]
I was told that this question is better suited here at Stack Overflow ( and not ServerFault ) So here it goes: I have this weird issue on my Mac OS X 10.7.5 ``` /Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/Python.h:33:10: fatal error: 'stdio.h' file not found ``` What caused the above error? ...
I figured out. Just need to install the command line tools found in Xcode and the problems will be solved. Cheers.
Is there a more pythonic way of exploding a list over a function's arguments?
13,891,559
3
2012-12-15T10:57:49Z
13,891,575
8
2012-12-15T11:00:05Z
[ "python", "list", "function", "parameters", "arguments" ]
``` def foo(a, b, c): print a+b+c i = [1,2,3] ``` Is there a way to call foo(i) without explicit indexing on i? Trying to avoid foo(i[0], i[1], i[2])
Yes, use [`foo(*i)`](http://docs.python.org/2.7/tutorial/controlflow.html#unpacking-argument-lists): ``` >>> foo(*i) 6 ``` You can also use `*` in function definition: `def foo(*vargs)` puts all non-keyword arguments into a tuple called `vargs`. and the use of `**`, for eg., `def foo(**kargs)`, will put all keyword a...
ValueError: need more than 0 values to unpack (python lists)
13,891,813
10
2012-12-15T11:36:43Z
13,891,831
21
2012-12-15T11:38:36Z
[ "python" ]
I'm learning python from Google code class. I'm trying out the exercises. ``` def front_x(words): x_list, ord_list = [] for word in words: if word[0] == 'x': x_list.append(word) else: ord_list.append(word) return sorted(x_list) + sorted(ord_list) ``` I believe the error is thrown because of ...
You are trying to use tuple assignment: ``` x_list, ord_list = [] ``` you probably meant to use multiple assignment: ``` x_list = ord_list = [] ``` which will not do what you expect it to; use the following instead: ``` x_list, ord_list = [], [] ``` or, best still: ``` x_list = [] ord_list = [] ``` When using a...
python xlutils : formatting_info=True not yet implemented
13,892,307
12
2012-12-15T12:46:34Z
13,914,953
15
2012-12-17T13:18:21Z
[ "python", "python-2.7", "xlrd", "xlwt", "xlutils" ]
I've got simple code to copy files with xlutils, xlrd, xlwt (downloaded new libraries from python-excel.org) with not loosing formatting. I've got an error as below: ``` from xlwt.Workbook import * from xlwt.Style import * from xlrd import open_workbook from xlutils.copy import copy import xlrd style = XFStyle() rb =...
According to [this thread](https://groups.google.com/d/msg/python-excel/w2AoQkX3TZc/1qjT1KzwoUsJ) the flag ``` formatting_info=True ``` is only working for xls-files, but not for xlsx yet (Version xlrd-0.8.0). As a workaround you could convert the workbook to xls using Excel or OpenOffice. It seems that a commandli...
Vectorized look-up of values in Pandas dataframe
13,893,227
18
2012-12-15T14:51:27Z
13,893,632
35
2012-12-15T15:47:22Z
[ "python", "pandas", "vectorization" ]
I have two pandas dataframes one called 'orders' and another one called 'daily\_prices'. daily\_prices is as follows: ``` AAPL GOOG IBM XOM 2011-01-10 339.44 614.21 142.78 71.57 2011-01-13 342.64 616.69 143.92 73.08 2011-01-26 340.82 616.50 155.74 75.89 2011-02-02 341.29 612.00 1...
Use our friend `lookup`, designed precisely for this purpose: ``` In [17]: prices Out[17]: AAPL GOOG IBM XOM 2011-01-10 339.44 614.21 142.78 71.57 2011-01-13 342.64 616.69 143.92 73.08 2011-01-26 340.82 616.50 155.74 75.89 2011-02-02 341.29 612.00 157.93 79.46 2011-02-10 351.4...
Python print array with new line
13,893,399
4
2012-12-15T15:17:22Z
13,893,414
10
2012-12-15T15:19:17Z
[ "python" ]
I'm new to python and have a simple array: ``` op = ['Hello', 'Good Morning', 'Good Evening', 'Good Night', 'Bye'] ``` When i use pprint, i get this output: ``` ['Hello', 'Good Morning', 'Good Evening', 'Good Night', 'Bye'] ``` Is there anyway i can remove the quotes, commas and brackets and print on a seperate lin...
You could [`join`](http://docs.python.org/2/library/stdtypes.html#str.join) the strings with a newline, and print the resulting string: ``` print "\n".join(op) ```
Python: transposing uneven rows into columns
13,893,435
4
2012-12-15T15:21:43Z
13,893,475
10
2012-12-15T15:27:48Z
[ "python", "list-comprehension", "reportlab" ]
I have a list of lists with uneven numbers of elements: ``` [['a','b','c'], ['d','e'], [], ['f','g','h','i']] ``` I'm displaying a table in Reportlab, and I want to display those as columns. As I understand it, RL only takes data for tables (Platypus) in the row form that I have above. I can use a loop to make the s...
[`itertools.izip_longest()`](http://docs.python.org/2/library/itertools.html#itertools.izip_longest) takes a `fillvalue` argument. On Python 3, it's [`itertools.zip_longest()`](http://docs.python.org/3.3/library/itertools.html#itertools.zip_longest). ``` >>> l = [[1,2,3], [4,5], [], [6,7,8,9]] >>> import itertools >>>...
How to position and align a matplotlib figure legend?
13,894,345
16
2012-12-15T17:11:37Z
13,962,752
20
2012-12-19T23:06:46Z
[ "python", "matplotlib", "legend" ]
I have a figure with two subplots as 2 rows and 1 column. I can add a nice looking figure legend with ``` fig.legend((l1, l2), ['2011', '2012'], loc="lower center", ncol=2, fancybox=True, shadow=True, prop={'size':'small'}) ``` However, this legend is positioned at the center of the **figure** and not bel...
In this case, you can either use axes for figure `legend` methods. In either case, `bbox_to_anchor` is the key. As you've already noticed `bbox_to_anchor` specifies a tuple of coordinates (or a box) to place the legend at. When you're using `bbox_to_anchor` think of the `location` kwarg as controlling the horizontal an...
what does the comma mean in python's unpack?
13,894,350
5
2012-12-15T17:12:43Z
13,894,363
10
2012-12-15T17:14:20Z
[ "python", "comma", "unpack" ]
we can simply use: ``` crc = struct.unpack('>i', data) ``` why people like this: ``` (crc,) = struct.unpack('>i', data) ``` what does the comma mean?
The first variant returns a single-element tuple: ``` In [13]: crc = struct.unpack('>i', '0000') In [14]: crc Out[14]: (808464432,) ``` To get to the value, you have to write `crc[0]`. The second variant *unpacks* the tuple, enabling you to write `crc` instead of `crc[0]`: ``` In [15]: (crc,) = struct.unpack('>i',...
pyside connection Error "RuntimeError: Failed to connect signal clicked()"
13,894,866
2
2012-12-15T18:19:05Z
13,894,993
9
2012-12-15T18:35:25Z
[ "python", "pyside", "qt-designer" ]
``` from PySide.QtCore import * from PySide.QtGui import * import sys import stackwid class Dialog(QDialog,stackwid.Ui_Dialog): def __init__(self,parent = None): super(Dialog,self).__init__(parent) self.setupUi(self) self.camButton.clicked.connect(self.set()) def set(self): ...
You don't connect the signal to your `set()`-function, but to it's return value. You just need to remove the parenthesis, then it should work: ``` self.camButton.clicked.connect(self.set) ```
How to make a python decorator function in Flask with arguments (for authorization)
13,896,650
17
2012-12-15T22:06:57Z
13,900,209
17
2012-12-16T09:56:24Z
[ "python", "flask", "decorator" ]
I used a flask snippet for my flask-login that checks that a user is logged in: ``` from functools import wraps def logged_in(f): @wraps(f) def decorated_function(*args, **kwargs): if session.get('logged_in') is not None: return f(*args, **kwargs) else: flash('Please lo...
Here's how to do it: ``` from functools import update_wrapper def owns_hotdog(hotdog): def decorator(fn): def wrapped_function(*args, **kwargs): # First check if user is authenticated. if not logged_in(): return redirect(url_for('login')) # For authoriza...
Heroku push rejected, failed to compile Python/django app (Python 2.7)
13,896,736
4
2012-12-15T22:22:18Z
13,898,367
12
2012-12-16T03:32:16Z
[ "python", "django", "deployment", "heroku", "python-2.7" ]
I'm doing the Heroku walkthrough: <https://devcenter.heroku.com/articles/django#prerequisites> for python developers, and I get an error when trying to run "git push heroku master", which can be found under the "Deploy to Heroku" section about 1/3 of the way down the page. I get the following traceback: ``` Counting o...
I think the problem is in the encoding of your `requirements.txt` file. Probably, you unknowingly saved it in Unicode format. You should save it in ANSI format. See this link for more details: <http://georgik.sinusgear.com/2012/08/20/problems-with-deploying-heroku-django-app-from-windows/>
Create an anonymous class instance in python
13,897,205
17
2012-12-15T23:34:10Z
13,897,264
27
2012-12-15T23:43:16Z
[ "python", "instance", "anonymous-types" ]
Sometimes i need to create an anonymous class instance in python, just like c#: ``` var o= new {attr1="somehing", attr2=344}; ``` but in python i do it in this way: ``` class Dummy: pass o = Dummy() o.attr1 = 'something' o.attr2 = 344 #EDIT 1 print o.attr1, o.attr2 ``` how can do that in pythonic way in single stat...
``` o = type('Dummy', (object,), { "attr1": "somehing", "attr2": 344 }) ``` ``` o.attr3 = "test" print o.attr1, o.attr2, o.attr3 ```
Create an anonymous class instance in python
13,897,205
17
2012-12-15T23:34:10Z
21,550,072
9
2014-02-04T10:38:48Z
[ "python", "instance", "anonymous-types" ]
Sometimes i need to create an anonymous class instance in python, just like c#: ``` var o= new {attr1="somehing", attr2=344}; ``` but in python i do it in this way: ``` class Dummy: pass o = Dummy() o.attr1 = 'something' o.attr2 = 344 #EDIT 1 print o.attr1, o.attr2 ``` how can do that in pythonic way in single stat...
## type while this is not precisely a single statement I think creating a wrapper around the magic of the accepted answer makes it by far more readable. ``` import inspect # wrap the type call around a function # use kwargs to allow named function arguments def create_type(name, **kwargs): return type(name, (o...
python time subtraction
13,897,246
8
2012-12-15T23:40:44Z
13,897,261
19
2012-12-15T23:42:53Z
[ "python", "time" ]
I want to get the time in Python. With `time.ctime()`, there are lots of functions: I tried: ``` def write_time(): NUMBER_OF_MIN=40 #my offset obj=time.gmtime() print " D", obj.tm_mday, " M",obj.tm_mon, "Y",obj.tm_year, " time", obj.tm_hour+TIME_OFFSET,":", obj.tm_min-NUMBER_OF_MIN, ":",obj.tm_sec ``` ...
Check out the [`datetime`](http://docs.python.org/2/library/datetime.html) library, which provides much more flexibility for math using dates. For example: ``` import datetime print datetime.datetime.now() print datetime.datetime.now() - datetime.timedelta(minutes=2) print datetime.datetime.now() - datetime.timedelta...
Unexpected keyword argument when using **kwargs in constructor
13,897,896
8
2012-12-16T01:49:43Z
13,897,904
16
2012-12-16T01:51:15Z
[ "python" ]
I'm baffled. I'm trying to make a subclass that doesn't care about any keyword parameters -- just passes them all along as is to the superclass, and explicitly sets the one parameter that is required for the constructor. Here's a simplified version of my code: ``` class BaseClass(object): def __init__(self, requir...
``` def SubClass(BaseClass): ``` is a function, not a class. There's no error because `BaseClass` could be an argument name, and nested functions are allowed. Syntax is fun, isn't it? ``` class SubClass(BaseClass): ```
GAE SDK 1.7.4 and InvalidCertificateException
13,899,530
19
2012-12-16T07:51:24Z
14,565,784
35
2013-01-28T15:50:11Z
[ "python", "django", "google-app-engine" ]
Recently, I upgraded my GAE SDK to ver. 1.7.4 and it started to throw 'InvalidCertificateException' when I try to run development server. I searched about this error and some people said it goes away with time, but mine didn't. What should I look into to fix this problem? I am using python framework Django for my app i...
Quick workaround that I found: delete the file `google_appengine/lib/cacerts/cacerts.txt` from your installed SDK. Starting from the GoogleAppEngineLauncher: > GoogleAppEngineLauncher/Contents/Resources/GoogleAppEngineDefault.bundle/Content‌​s/Resources/google\_appengine/lib/cacerts/cacerts.txt EDIT # > as of g...
Is there a way to get the value of nested dict in Immutabledict sent via request of werkzeug(flask)?
13,899,635
6
2012-12-16T08:11:21Z
13,900,542
9
2012-12-16T10:49:20Z
[ "python", "request", "flask", "python-requests", "werkzeug" ]
I asked question in past, but still facing the problem. address\_dict = {'address': {'US': 'San Francisco', 'US': 'New York', 'UK': 'London'}} When above parameters was sent via requests, how can I get values in address key using request.form on Flask? ``` import requests url = 'http://example.com' params = {"addres...
You're sending complex nested data structure as HTML form, it won't work like you expect. Encode it as JSON: ``` import json import requests url = 'http://example.com/' payload = {"address": {"US": "San Francisco", "UK": "London", "CH": "Shanghai"}} data = json.dumps(payload) headers = {'Content-Type': 'application/j...
How can I access a classmethod from inside a class in Python
13,900,515
9
2012-12-16T10:47:01Z
13,900,861
9
2012-12-16T11:32:06Z
[ "python", "class-members" ]
I would like to create a class in Python that manages above all static members. These members should be initiliazed during definition of the class already. Due to the fact that there will be the requirement to reinitialize the static members later on I would put this code into a classmethod. My question: How can I cal...
At the time that `x=10` is executed in your example, not only does the class not exist, but the classmethod doesn't exist either. Execution in Python goes top to bottom. If `x=10` is above the classmethod, there is no way you can access the classmethod at that point, because it hasn't been defined yet. Even if you co...
kalman 2d filter in python
13,901,997
14
2012-12-16T13:58:37Z
13,903,992
26
2012-12-16T17:58:49Z
[ "python", "2d", "kalman-filter" ]
My input is 2d (x,y) time series of a dot moving on a screen for a tracker software. It has some noise I want to remove using Kalman filter. Does someone can point me for a python code for Kalman 2d filter? In scipy cookbook I found only a 1d example: <http://www.scipy.org/Cookbook/KalmanFiltering> I saw there is imple...
Here is my implementation of the Kalman filter based on the [equations given on wikipedia](http://en.wikipedia.org/wiki/Kalman_filter). Please be aware that my understanding of Kalman filters is very rudimentary so there are most likely ways to improve this code. (For example, it suffers from the numerical instability ...
Python: List of all unique characters in a string
13,902,805
11
2012-12-16T15:33:24Z
13,902,829
27
2012-12-16T15:36:04Z
[ "python", "performance", "data-structures" ]
I want to append characters to a string but I want to make sure all the letters in the final list will be **unique.** **Example:** "aaabcabccd" -> "abcd" Now of course I have two solutions in my mind. One is using a **list** that will map the characters with their **ASCII** codes. So whenever I encounter a letter it...
The simplest solution is probably: ``` In [10]: ''.join(set('aaabcabccd')) Out[10]: 'acbd' ``` Note that this doesn't guarantee the order in which the letters appear in the output, even though the example might suggest otherwise. You refer to the output as a "list". If a list is what you really want, replace `''.joi...
Python: List of all unique characters in a string
13,902,805
11
2012-12-16T15:33:24Z
13,902,835
8
2012-12-16T15:36:38Z
[ "python", "performance", "data-structures" ]
I want to append characters to a string but I want to make sure all the letters in the final list will be **unique.** **Example:** "aaabcabccd" -> "abcd" Now of course I have two solutions in my mind. One is using a **list** that will map the characters with their **ASCII** codes. So whenever I encounter a letter it...
Use an [OrderedDict](http://docs.python.org/2/library/collections.html#collections.OrderedDict). This will ensure that the order is preserved ``` >>> ''.join(OrderedDict.fromkeys( "aaabcabccd").keys()) 'abcd' ``` PS: I just timed both the OrderedDict and Set solution, and the later is faster. If order does not matter...
Python - "tuple index out of range"
13,903,427
5
2012-12-16T16:58:23Z
13,903,437
10
2012-12-16T16:59:24Z
[ "python", "table", "indexing" ]
I am writing a program to display information about countries in a table format. It worked perfectly fine when I had 3 countries, but changing it to 10 (and adjusting all necessary code accordingly) resulted in the error, "Tuple index out of range" in the line: ``` print("{0:^20}{1:^20}{2:^20}{3:^20}{4:^20}{5:^20}[6:^...
You need to pass in a matching number of arguments for your format slots. Your format string has 10 slots, but you are only passing in 3 values. Reduced to 4 format slots, with only 3 arguments to `.format()`, shows the same error: ``` >>> '{0:^20}{1:^20}{2:^20}{3:^20}'.format(1, 2, 3) Traceback (most recent call las...
What do the binary operators mean when applied to logicals?
13,903,773
4
2012-12-16T17:34:48Z
13,903,795
8
2012-12-16T17:37:37Z
[ "python" ]
My understanding is that `&` is the bitwise AND operator. So I would expect it to have no meaning when applied to logicals. However, I see that: ``` >>> False & False False >>> False & True False >>> True & True True ``` and so on. Likewise for the other bitwise operators. So, why do these operators even accept logi...
> So, why do these operators even accept logical operands? `bool` subclasses `int`, and overrides `__and__()` etc to return `bool` for `bool` operands. For details, see [PEP 285](http://www.python.org/dev/peps/pep-0285/). Specifically: ``` 6) Should bool inherit from int? => Yes In an ideal wo...
multinomial pmf in python scipy/numpy
13,903,922
13
2012-12-16T17:51:18Z
13,974,527
9
2012-12-20T14:39:08Z
[ "python", "numpy", "scipy", "probability", "scientific-computing" ]
Is there a built-in function in scipy/numpy for getting the PMF of a Multinomial? I'm not sure if `binom` generalizes in the correct way, e.g. ``` # Attempt to define multinomial with n = 10, p = [0.1, 0.1, 0.8] rv = scipy.stats.binom(10, [0.1, 0.1, 0.8]) # Score the outcome 4, 4, 2 rv.pmf([4, 4, 2]) ``` What is the ...
There's no built-in function that I know of, and the binomial probabilities do not generalize (you need to normalise over a different set of possible outcomes, since the sum of all the counts must be n which won't be taken care of by independent binomials). However, it's fairly straightforward to implement yourself, fo...
What is the % operator in Python's print statement called?
13,904,143
3
2012-12-16T18:14:52Z
13,904,162
9
2012-12-16T18:16:38Z
[ "python" ]
Consider: ``` print "%s is %d years old." % ('Meirav', 5) ``` What is the `%` operator between the string literal and the tuple called? Other than in the print statement, where else is it seen in Python?
[It's known as the "string formatting" or "interpolation" operator](http://docs.python.org/2/library/stdtypes.html#string-formatting-operations), and it's used anywhere you might want to interpolate formatted data into a string.
Django queryset filter for backwards related fields
13,904,316
4
2012-12-16T18:36:15Z
13,904,336
7
2012-12-16T18:38:41Z
[ "python", "django", "django-queryset" ]
How can you filter a model based on a model that relates to it? Example below...this works, but I think this hits the DB twice and is pretty inelegant. Is there a way to do it directly with querysets? Maybe somehow with `select_related()`, but haven't been able to figure that one out. I want to return a `QuerySet` of `...
Try this. I haven't tested it let me know if you have any issues ``` #Untested Code Project.objects.filter(action__person = person) ```