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
Pandas ParserError EOF character when reading multiple csv files to HDF5
18,016,037
4
2013-08-02T11:40:37Z
29,857,126
15
2015-04-24T20:43:41Z
[ "python", "csv", "python-3.x", "pandas", "hdf5" ]
Using Python3, Pandas 0.12 I'm trying to write multiple csv files (total size is 7.9 GB) to a HDF5 store to process later onwards. The csv files contain around a million of rows each, 15 columns and data types are mostly strings, but some floats. However when I'm trying to read the csv files I get the following error:...
I had a similar problem. The line listed with the 'EOF inside string' had a string that contained within it a single quote mark. When I added the option quoting=csv.QUOTE\_NONE it fixed my problem. For example: ``` df = pd.read_csv(csvfile, header = None, delimiter="\t", quoting=csv.QUOTE_NONE, encoding='utf-8') ```
Save Matplotlib Animation
18,016,390
6
2013-08-02T12:00:47Z
18,016,676
8
2013-08-02T12:17:38Z
[ "python", "animation", "matplotlib" ]
I am trying to make an Animation of a wave package and save it as a movie. Everything except the saving is working. Can you please tell me what I am doing wrong? When going into the line `ani.save('MovWave.mp4')` he tells me: ``` writer = writers.list()[0] IndexError: list index out of range ``` I tried googling ...
Do you have `ffmpeg` or `mencoder` installed? Look at [this answer](http://stackoverflow.com/questions/13316397/matplotlib-animation-no-moviewriters-available/14574894#14574894) for help on installing ffmpeg.
python sort list based on key sorted list
18,016,827
8
2013-08-02T12:25:48Z
18,016,874
13
2013-08-02T12:27:39Z
[ "python", "list", "sorting" ]
I have a predefined list which indicates the order of some values: ``` ['id','name','age','height','weight',] ``` (can be very long) I want to sort any subset of this list: So if i get `['height','id']` It will become `['id','height']` or `['name','weight','height']` ---> `['name','height','weight']` Is there som...
The most efficient way would be to create a map from word to order: ``` ordering = {word: i for i, word in enumerate(predefined_list)} ``` then use that mapping in sorting: ``` somelist.sort(key=ordering.get) ``` The alternative is to use `.index()` on the list to scan through the list and find the index for each w...
How to stop a looping thread in Python?
18,018,033
17
2013-08-02T13:25:04Z
18,018,102
13
2013-08-02T13:28:25Z
[ "python", "multithreading", "wxpython" ]
What's the proper way to tell a looping thread to stop looping? I have a fairly simple program that pings a specified host in a separate `threading.Thread` class. In this class it sleeps 60 seconds, the runs again until the application quits. I'd like to implement a 'Stop' button in my `wx.Frame` to ask the looping t...
This has been asked before on Stack. See the following links: * [Is there any way to kill a Thread in Python?](http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python) * [Stopping A Thread (Python)](http://stackoverflow.com/questions/6524459/stopping-a-thread-python) Basically you just n...
Matplotlib Animation
18,019,226
2
2013-08-02T14:19:56Z
18,019,594
8
2013-08-02T14:35:44Z
[ "python", "animation", "matplotlib" ]
Can you please help me figuring out what the problem is here? I don't know what is going wrong. Single plots from `img` can be plotted just fine, but the animation module gives an error. The Traceback says: ``` Traceback (most recent call last): File "/home/ckropla/workspace/TAMM/Sandkasten.py", line 33, in <module>...
Each element in `img` needs to be a *sequence* of artists, not a single artist. If you change `img.append(plt.imshow(Z[i]))` to `img.append([plt.imshow(Z[i])])` then your code works fine.
How to do boolean algebra on missing values?
18,019,387
13
2013-08-02T14:26:39Z
18,022,411
8
2013-08-02T17:02:25Z
[ "python", "boolean-expression" ]
I want to replicate boolean `NA` values as they behave in R: > NA is a valid logical object. Where a component of x or y is NA, the result will be NA if the outcome is ambiguous. In other words NA & TRUE evaluates to NA, but NA & FALSE evaluates to FALSE. > <http://stat.ethz.ch/R-manual/R-devel/library/base/html/Logic...
As other have said, you can define your own class. ``` class NA_(object): instance = None # Singleton (so `val is NA` will work) def __new__(self): if NA_.instance is None: NA_.instance = super(NA_, self).__new__(self) return NA_.instance def __str__(self): return "NA" def _...
Python SyntaxError when using end argument with print function
18,020,849
4
2013-08-02T15:34:29Z
18,021,232
8
2013-08-02T15:52:37Z
[ "python" ]
I don't know why i get the error because i have done exactly as the book says ``` >>> os.getcwd() 'C:\\Users\\expoperialed\\Desktop\\Pyt…' >>> data = open('sketch.txt') >>> print(data.readline(),end="") SyntaxError: invalid syntax ```
Or, to use the print function like you want in Python 2: ``` >>> from __future__ import print_function ``` That will need to be at the top of your Python program though because of the way the `__future__` module works.
(Beginner)Python functions Codeacademy
18,020,967
4
2013-08-02T15:39:07Z
18,020,988
8
2013-08-02T15:40:03Z
[ "python" ]
I'm just learning to program on Codeacademy. I have an assignment, but cant figure out what I'm doing wrong. First I need to define a function that returns the cube of a value. Then I should define a second function that checks if a number is divisible by 3. If it is I need to return it, otherwise I need to return `Fa...
You are not catching the return value of the function `cube`. Do `b = cube(b)`. Or better yet, do `return cube(b)`. ``` def cube(c): return c**3 def by_three(b): if b % 3 == 0: b = cube(b) return b # Or simply return cube(b) and remove `b = cube(b)` else: return False ``` When...
Python Redis connection should be closed on every request? (flask)
18,022,767
3
2013-08-02T17:25:19Z
18,024,593
8
2013-08-02T19:17:46Z
[ "python", "database", "redis", "flask" ]
*I am creating flask app with Redis database. And I have one connection question* **I can have Redis connection global and keep non-closed all time:** ***init**.py* ``` import os from flask import Flask import redis app = Flask(__name__) db = redis.StrictRedis(host='localhost', port=6379, db=0) ``` **Also I can r...
By default [redis-py](https://github.com/andymccurdy/redis-py) uses connection pooling. The [github wiki](https://github.com/andymccurdy/redis-py#connection-pools) says: > Behind the scenes, redis-py uses a connection pool to manage connections to a Redis server. By default, each Redis instance you create will in turn...
Pandas index column title or name
18,022,845
61
2013-08-02T17:30:53Z
18,023,468
82
2013-08-02T18:08:39Z
[ "python", "pandas" ]
Does anyone know how to get the index column name in pandas? Here's an example dataframe of what I'm talking about: ``` Column 1 Index Title Apples 1 Oranges 2 Puppies 3 Ducks 4 ``` What I'm trying to do is get/set the index title. The only way...
You can just get/set the index via its `name` property ``` In [7]: df.index.name Out[7]: 'Index Title' In [8]: df.index.name = 'foo' In [9]: df.index.name Out[9]: 'foo' In [10]: df Out[10]: Column 1 foo Apples 1 Oranges 2 Puppies 3 Ducks 4 ```
Pandas index column title or name
18,022,845
61
2013-08-02T17:30:53Z
18,023,485
13
2013-08-02T18:09:26Z
[ "python", "pandas" ]
Does anyone know how to get the index column name in pandas? Here's an example dataframe of what I'm talking about: ``` Column 1 Index Title Apples 1 Oranges 2 Puppies 3 Ducks 4 ``` What I'm trying to do is get/set the index title. The only way...
`df.index.name` should do the trick. Python has a `dir` function that let's you query object attributes. `dir(df.index)` was helpful here.
Pandas index column title or name
18,022,845
61
2013-08-02T17:30:53Z
36,013,757
8
2016-03-15T14:12:42Z
[ "python", "pandas" ]
Does anyone know how to get the index column name in pandas? Here's an example dataframe of what I'm talking about: ``` Column 1 Index Title Apples 1 Oranges 2 Puppies 3 Ducks 4 ``` What I'm trying to do is get/set the index title. The only way...
From version `0.18.0` you can use [`rename_axis`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rename_axis.html): ``` print df Column 1 Index Title Apples 1.0 Oranges 2.0 Puppies 3.0 Ducks 4.0 ``` The new functionality works w...
Django unittest and mocking the requests module
18,023,350
5
2013-08-02T18:02:47Z
18,023,520
11
2013-08-02T18:11:13Z
[ "python", "unit-testing", "mocking", "python-requests" ]
I am new to Mock and am writing a unit test for this function: ``` # utils.py import requests def some_function(user): payload = {'Email': user.email} url = 'http://api.example.com' response = requests.get(url, params=payload) if response.status_code == 200: return response.json() ...
Patch `json` method instead of `content`. (`content` is not used in `some_function`) Try following code. ``` import unittest from mock import Mock, patch import utils class UtilsTestCase(unittest.TestCase): def test_some_function(self): user = self.user = Mock() user.email = '[email protected]' ...
Linear time v.s. Quadratic time
18,023,576
8
2013-08-02T18:15:15Z
18,023,609
19
2013-08-02T18:17:55Z
[ "python", "big-o", "complexity-theory", "time-complexity" ]
Often, some of the answers mention that a given solution is **linear**, or that another one is **quadratic**. How to make the difference / identify what is what? Can someone explain this, the easiest possible way, for the ones like me who still don't know?
They must be referring to run-time complexity also known as Big O notation. This is an extremely large topic to tackle. I would start with the article on wikipedia: <https://en.wikipedia.org/wiki/Big_O_notation> When I was researching this topic one of the things I learned to do is graph the runtime of my algorithm wi...
Linear time v.s. Quadratic time
18,023,576
8
2013-08-02T18:15:15Z
18,023,667
24
2013-08-02T18:22:20Z
[ "python", "big-o", "complexity-theory", "time-complexity" ]
Often, some of the answers mention that a given solution is **linear**, or that another one is **quadratic**. How to make the difference / identify what is what? Can someone explain this, the easiest possible way, for the ones like me who still don't know?
A method is linear when the time it takes increases linearly with the number of elements involved. For example, a for loop which prints the elements of an array is roughly linear: ``` for x in range(10): print x ``` because if we print range(100) instead of range(10), the time it will take to run it is 10 times l...
lambda *args, **kwargs: None
18,024,503
10
2013-08-02T19:12:07Z
18,024,605
23
2013-08-02T19:18:52Z
[ "python", "lambda", "default-arguments" ]
consider: ``` blank_fn = lambda *args, **kwargs: None def callback(x, y, z=''): print x, y, z def perform_task(callback=blank_fn): print 'doing stuff' callback('x', 'y', z='z' ) ``` The motivation for doing it this way is I don't have to put in logic to check if callback has been assigned because it def...
According to [PEP8](http://www.python.org/dev/peps/pep-0008/), you should "Always use a def statement instead of an assignment statement that binds a lambda expression directly to a name." So, one thing I would change is: ``` def blank_fn(*args, **kwargs): pass ``` However, I think a more pythonic way to do this ...
How to store formulas, instead of values, in pandas DataFrame
18,024,742
5
2013-08-02T19:26:02Z
18,025,179
11
2013-08-02T19:56:44Z
[ "python", "pandas" ]
Is it possible to work with pandas DataFrame as with an Excel spreadsheet: say, by entering a formula in a column so that when variables in other columns change, the values in this column change automatically? Something like: ``` a b c 2 3 =a+b ``` And so when I update 2 or 3, the column `c` also updates automati...
This will work in 0.13 (still in development) ``` In [19]: df = DataFrame(randn(10,2),columns=list('ab')) In [20]: df Out[20]: a b 0 0.958465 0.679193 1 -0.769077 0.497436 2 0.598059 0.457555 3 0.290926 -1.617927 4 -0.248910 -0.947835 5 -1.352096 -0.568631 6 0.009125 0.711511 7 -0.993082 -1...
Python argparse conditional requirements
18,025,646
9
2013-08-02T20:29:39Z
18,026,189
7
2013-08-02T21:10:01Z
[ "python", "python-2.7", "argparse" ]
How do I set up argparse as follows: ``` if -2 is on the command line, no other arguments are required if -2 is not on the command line, -3 and -4 arguments are required ``` For example, ``` -2 [good] -3 a -4 b [good] -3 a [not good, -4 required] -2 -5 c [good] -2 -3 a [good] ``` There are a number of similar quest...
A subparser (as suggested in comments) might work. Another alternative (since `mutually_exclusive_group` can't quite do this) is just to code it manually, as it were: ``` import argparse def main(): parser = argparse.ArgumentParser() parser.add_argument('-2', dest='two', action='store_true') parser.add_...
pygobject-2.28.6 won't configure: No package 'gobject-introspection-1.0' found, how do I resolve?
18,025,730
16
2013-08-02T20:37:54Z
18,027,346
26
2013-08-02T22:58:52Z
[ "python", "pygobject", "gobject", "gobject-introspection" ]
I'm trying to get pygobject-2.28.6 to compile in cygwin (version in repository is 2.28.4 which has some issues). Here is the tail of ./configure: ``` checking for GLIB - version >= 2.24.0... yes (version 2.34.3) checking for ffi... checking for FFI... yes checking for GIO... yes checking for GIOUNIX... yes checking fo...
You're probably missing the development package. The package name varies by distribution, but it's the one containing `/usr/lib/pkgconfig/gobject-introspection-1.0.pc` (or `/usr/lib64/pkgconfig/gobject-introspection-1.0.pc` for some 64-bit distros): * Fedora, CentOS, RHEL, *etc.*: **gobject-introspection-devel** * Deb...
pygobject-2.28.6 won't configure: No package 'gobject-introspection-1.0' found, how do I resolve?
18,025,730
16
2013-08-02T20:37:54Z
21,161,599
10
2014-01-16T12:19:20Z
[ "python", "pygobject", "gobject", "gobject-introspection" ]
I'm trying to get pygobject-2.28.6 to compile in cygwin (version in repository is 2.28.4 which has some issues). Here is the tail of ./configure: ``` checking for GLIB - version >= 2.24.0... yes (version 2.34.3) checking for ffi... checking for FFI... yes checking for GIO... yes checking for GIOUNIX... yes checking fo...
I got this to compile on cygwin. The package you need is: `libgirepository1.0-devel`. In Ubuntu it's called `libgirepository1.0-dev`
setting Chrome preferences w/ Selenium Webdriver in Python
18,026,391
11
2013-08-02T21:26:00Z
19,024,814
21
2013-09-26T09:46:09Z
[ "python", "python-2.7", "selenium-webdriver", "selenium-chromedriver" ]
I'm using Selenium Webdriver (in Python) to automate the downloading of thousands of files. I want to set Chrome's download folder programmatically. After reading [this](http://stackoverflow.com/questions/15165593/set-chrome-prefs-with-python-binding-for-selenium-in-chromedriver), I tried this: ``` chromepath = '/User...
The following worked for me: ``` chromeOptions = webdriver.ChromeOptions() prefs = {"download.default_directory" : "/some/path"} chromeOptions.add_experimental_option("prefs",prefs) chromedriver = "path/to/chromedriver.exe" driver = webdriver.Chrome(executable_path=chromedriver, chrome_options=chromeOptions) ``` Sour...
Make special diagonal matrix in Numpy
18,026,541
9
2013-08-02T21:41:02Z
18,026,924
12
2013-08-02T22:17:42Z
[ "python", "arrays", "numpy", "matrix", "toeplitz" ]
I am trying to make a numpy array that looks like this: ``` [a b c ] [ a b c ] [ a b c ] [ a b c ] ``` So this involves updating the main diagonal and the two diagonals above it. What would be an efficient way of doing this?
You can use `np.indices` to get the indices of your array and then assign the values where you want. ``` a = np.zeros((5,10)) i,j = np.indices(a.shape) ``` `i,j` are the line and column indices, respectively. ``` a[i==j] = 1. a[i==j-1] = 2. a[i==j-2] = 3. ``` will result in: ``` array([[ 1., 2., 3., 0., 0., 0...
Python setuptools: How can I list a private repository under install_requires?
18,026,980
21
2013-08-02T22:22:40Z
20,234,833
18
2013-11-27T05:47:32Z
[ "python", "github", "setuptools" ]
I am creating a `setup.py` file for a project which depends on private GitHub repositories. The relevant parts of the file look like this: ``` from setuptools import setup setup(name='my_project', ..., install_requires=[ 'public_package', 'other_public_package', 'private_repo_1', ...
Here's what worked for me: ``` install_requires=[ 'private_package_name==1.1', ], dependency_links=[ 'git+ssh://[email protected]/username/private_repo.git#egg=private_package_name-1.1', ] ``` Note that you have to have the version number in the egg name, otherwise it will say it can't find the packa...
Python is adding extra newline to the output
18,028,504
3
2013-08-03T01:56:03Z
18,028,521
9
2013-08-03T02:00:12Z
[ "python" ]
The input file: `a.txt` ``` aaaaaaaaaaaa bbbbbbbbbbb cccccccccccc ``` The python code: ``` with open("a.txt") as f: for line in f: print line ``` The problem: ``` [root@a1 0]# python read_lines.wsgi aaaaaaaaaaaa bbbbbbbbbbb cccccccccccc ``` as you can see the output has extra line between each item....
`print` appends a newline, and the input lines already end with a newline. A standard solution is to output the input lines verbatim: ``` import sys with open("a.txt") as f: for line in f: sys.stdout.write(line) ``` **PS**: I think that @abarnert's solution is more exhaustive and that for Python 3 (or ...
Python str vs unicode types
18,034,272
41
2013-08-03T15:15:25Z
18,034,277
18
2013-08-03T15:16:25Z
[ "python", "string", "unicode" ]
Working with Python 2.7, I'm wondering which real advantage has using type `unicode` instead of `str`, as both of them seem to be able to hold Unicode strings. Is there any special reason a part from being able to set Unicode codes in `unicode` strings using scape char `\`?: Executing a module with: ``` # -*- coding:...
Your terminal happens to be configured to UTF-8. The fact that printing `a` works is a coincidence; you are writing raw UTF-8 bytes to the terminal. `a` is a value of length *two*, containing two bytes, hex values C3 and A1, while `ua` is a unicode value of length *one*, containing a codepoint U+00E1. This difference...
Python str vs unicode types
18,034,272
41
2013-08-03T15:15:25Z
18,034,409
86
2013-08-03T15:32:53Z
[ "python", "string", "unicode" ]
Working with Python 2.7, I'm wondering which real advantage has using type `unicode` instead of `str`, as both of them seem to be able to hold Unicode strings. Is there any special reason a part from being able to set Unicode codes in `unicode` strings using scape char `\`?: Executing a module with: ``` # -*- coding:...
`unicode`, which is python 3's `str`, is meant to handle *text*. Text is a sequence of **code points** which *may be bigger than a single byte*. Text can be *encoded* in a specific encoding to represent the text as raw bytes(e.g. `utf-8`, `latin-1`...). Note that `unicode` *is not encoded*! The internal representation ...
Can the Python interpreter welcome message be suppressed?
18,037,916
7
2013-08-03T22:28:40Z
18,037,937
13
2013-08-03T22:32:01Z
[ "python" ]
Instead of: ``` $ python Python 2.7.2 (default, Oct 11 2012, 20:14:37) [GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> ``` I'd like, for example: ``` $ python --quiet >>> ```
You can try this: ``` $ python -ic "" >>> ```
filling a n*n matrix with n elements
18,038,245
3
2013-08-03T23:18:32Z
18,038,291
8
2013-08-03T23:28:22Z
[ "python" ]
I want to fill a nxn matrix with n elements, such that each row and each column has exactly 1 element. E.g. a 3x3 matrix can have following as possible solutions: ``` 1 0 0 0 1 0 0 0 1 0 1 0 1 0 0 1 0 0 0 0 1 0 0 1 0 1 0 ``` Following is the code i wrote: ``` arr=[[0 for x in xrange(...
> n\*n matrix with n elements, such that each row and each column has exactly 1 element. I assume you want a n\*n matrix having exactly one *non 0* element on each row/column --- Are you looking for a way to build a diagonal matrix? ``` >>> n = 5 >>> [[1 if j == i else 0 for j in range(n)] for i in range(n)] [[1, 0...
Python Pandas Error tokenizing data
18,039,057
48
2013-08-04T01:54:45Z
18,039,175
9
2013-08-04T02:24:35Z
[ "python", "csv", "pandas" ]
I try to use Pandas to manipulate a .csv files but I get this error: ``` pandas.parser.CParserError: Error tokenizing data. C error: Expected 2 fields in line 3, saw 12 ``` I have tried to read the Pandas doc, but found nothing. My code is simple: ``` path = 'GOOG Key Ratios.csv' #print(open(path).read()) data = p...
The parser is getting confused by the header of the file. It reads the first row and infers the number of columns from that row. But the first two rows aren't representative of the actual data in the file. Try it with `data = pd.read_csv(path, skiprows=2)`
Python Pandas Error tokenizing data
18,039,057
48
2013-08-04T01:54:45Z
18,129,082
70
2013-08-08T14:47:15Z
[ "python", "csv", "pandas" ]
I try to use Pandas to manipulate a .csv files but I get this error: ``` pandas.parser.CParserError: Error tokenizing data. C error: Expected 2 fields in line 3, saw 12 ``` I have tried to read the Pandas doc, but found nothing. My code is simple: ``` path = 'GOOG Key Ratios.csv' #print(open(path).read()) data = p...
you could also try; ``` data = pd.read_csv('file1.csv', error_bad_lines=False) ```
Python Pandas Error tokenizing data
18,039,057
48
2013-08-04T01:54:45Z
26,599,892
9
2014-10-28T02:18:23Z
[ "python", "csv", "pandas" ]
I try to use Pandas to manipulate a .csv files but I get this error: ``` pandas.parser.CParserError: Error tokenizing data. C error: Expected 2 fields in line 3, saw 12 ``` I have tried to read the Pandas doc, but found nothing. My code is simple: ``` path = 'GOOG Key Ratios.csv' #print(open(path).read()) data = p...
It might be an issue with * the delimiters in your data * the first row, as @TomAugspurger assiduously noted To solve it, try specifying the `sep` and/or `header` arguments when calling `read_csv`. For instance, ``` df = pandas.read_csv(fileName, sep='delimiter', header=None) ``` In the code above, `sep` defines yo...
Django - Get only date from datetime.strptime
18,039,680
19
2013-08-04T04:22:12Z
18,039,722
51
2013-08-04T04:31:35Z
[ "python", "django", "datetime" ]
I have start date field in database as date (not datetime). In my save method in forms.py I'm using `datetime.strptime(date_string, '%Y-%m-%d')` to convert string to date. The method returns me formatted date along with time, i.e, "2006-08-03 00:00:00". I want just the date and no time. Because I get an "invalid date ...
I think you need date object not datetime. Try converting datetime to date using date() method on datetime object ``` from datetime import datetime datetime.strptime('2014-12-04', '%Y-%m-%d').date() ```
Standard error ignoring NaN in pandas groupby groups
18,039,923
9
2013-08-04T05:14:33Z
18,042,914
8
2013-08-04T12:26:06Z
[ "python", "numpy", "pandas", "scipy", null ]
I have data loaded into a dataframe with that has a multi index for the columns headers. Currently I've been grouping the data by the columns indices to take the mean of the groups and calculate the 95% confidence intervals like this: ``` from pandas import * import pandas as pd from scipy import stats as st #Normali...
`count()` method of `Series` object will return no NaN value count: ``` import pandas as pd s = pd.Series([1,2,np.nan, 3]) print s.count() ``` output: ``` 3 ``` So, try: ``` ci = grouped.aggregate(lambda x: np.std(x) / x.count() * 1.96) ```
Define function as list element
18,040,190
4
2013-08-04T06:04:06Z
18,040,213
9
2013-08-04T06:07:09Z
[ "python" ]
``` >>> list=[None] >>> def list[0](x,y): File "<stdin>", line 1 def list[0](x,y): ^ SyntaxError: invalid syntax ``` How can I define a function as an element of a list?
``` def f(whatever): do_stuff() l[0] = f ``` The function definition syntax doesn't allow you to define a function directly into a data structure, but you can just create the function and then assign it wherever it needs to go.
Define function as list element
18,040,190
4
2013-08-04T06:04:06Z
18,040,234
11
2013-08-04T06:11:19Z
[ "python" ]
``` >>> list=[None] >>> def list[0](x,y): File "<stdin>", line 1 def list[0](x,y): ^ SyntaxError: invalid syntax ``` How can I define a function as an element of a list?
Python's `def` isn't flexible enough to handle generic [lvalues](http://dictionary.reference.com/browse/lvalue) such as `list[0]`. The language only allows you to use an *identifier* as function name. Here are the relevant parts of the [grammar rule for the def-statement](http://docs.python.org/2.7/reference/compound_s...
How to install PyQt5 on a new virtualenv and work on an IDLE
18,042,919
6
2013-08-04T12:26:33Z
18,446,391
9
2013-08-26T14:20:55Z
[ "python", "pyqt", "virtualenv", "pip", "pyqt5" ]
I installed PyQt5 globally on my win7 system (python 3.3), using the installer provided from the official riverbank website. Then i created a new `–no-site-packages` virtualenv, where the only things i see listed after typing `pip list`, are pip (1.4) and setuptools (0.9.7). The problem now however, is that i need ...
> Both "pip install sip" and "pip install PyQt5" inside the virtual enviroment are returning errors. If the errors you're referring to are: `Could not find any downloads that satisfy the requirement [pyqt5|sip]` and `No distributions at all found for [pyqt5|sip]` Then this [answer](http://stackoverflow.com/a/13662...
stop python in terminal on mac
18,047,657
10
2013-08-04T21:17:48Z
18,047,735
13
2013-08-04T21:25:23Z
[ "python", "osx", "terminal" ]
Using python in terminal on a Mac, type ``` ctrl-z ``` will stop the python, but not exit it, giving output like this: ``` >>> [34]+ Stopped python ``` As you can see, I have stopped 34 python calls. Although I could use ``` >>> exit() ``` to exit python, the questions are: 1. Is there a short...
`CTRL`+`d` -> Defines EOF (End of File). `CTRL`+`c` -> Will terminate most jobs. If, however you have written a python wrapper program that calls other python programs in turn, Ctrl-c will only stop the the job that is currently running. The wrapper program will keep running. Worst case scenario, you can do this: Op...
Satchmo clonesatchmo.py ImportError: cannot import name execute_manager
18,048,232
11
2013-08-04T22:26:31Z
18,048,990
11
2013-08-05T00:17:19Z
[ "python", "django", "django-models", "satchmo", "django-manage.py" ]
I get satchmo to try, but I have a great problem at first try, and I don't understand whats wrong. When I making `$ python clonesatchmo.py` into clear django project, it trows an error: ``` $ python clonesatchmo.py Creating the Satchmo Application Customizing the files Performing initial data synching Traceback (most ...
`execute_manager` was put on the deprecation path as part of the project layout refactor in Django 1.4 <https://docs.djangoproject.com/en/1.4/releases/1.4/#django-core-management-execute-manager>. Per the deprecation policy that means that the code for `execute_manager` has been completely removed in 1.6. If you are se...
Satchmo clonesatchmo.py ImportError: cannot import name execute_manager
18,048,232
11
2013-08-04T22:26:31Z
19,993,247
64
2013-11-15T03:55:49Z
[ "python", "django", "django-models", "satchmo", "django-manage.py" ]
I get satchmo to try, but I have a great problem at first try, and I don't understand whats wrong. When I making `$ python clonesatchmo.py` into clear django project, it trows an error: ``` $ python clonesatchmo.py Creating the Satchmo Application Customizing the files Performing initial data synching Traceback (most ...
Replace the contents of manage.py with the following (from a new django 1.6 project). ``` #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "<app>.settings") from django.core.management import execute_from_command_line execute_from_comm...
What's the difference between assigning a function with and without parentheses?
18,048,388
2
2013-08-04T22:50:21Z
18,048,395
11
2013-08-04T22:51:00Z
[ "python" ]
What's the difference in python between ``` value = getValue() ``` and ``` value = getValue ``` ?
Using parenthesis calls the function where as not using them creates a reference to that function. See below: ``` >>> def t(): ... return "Hi" ... >>> a = t >>> a <function t at 0x01BECA70> >>> a = t() >>> a 'Hi' >>> ``` Here is a good link to explain further: <http://docs.python.org/2/tutorial/controlflow.html>...
How to get stack trace string without raising exception in python?
18,049,548
13
2013-08-05T01:47:26Z
18,049,562
21
2013-08-05T01:49:15Z
[ "python", "stack-trace" ]
`traceback.format_exc()` can get it with raising an exception. `traceback.print_stack()` prints the stack without an exception needed, but it does not return a string. There doesn't seem to be a way to get the stack trace string without raising an exception in python?
It's `traceback.extract_stack()` if you want convenient access to module and function names and line numbers, or `''.join(traceback.format_stack())` if you just want a string that looks like the `traceback.print_stack()` output.
AttributeError: 'module' object (scipy) has no attribute *** Why does this error occur?
18,049,687
9
2013-08-05T02:09:48Z
18,049,731
10
2013-08-05T02:18:40Z
[ "python", "scipy" ]
In scipy, the error occurs quite often. ``` >>> import scipy >>> scipy.integrate.trapz(gyroSeries, timeSeries) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute 'integrate' >>> ``` **I figure out how to solve this problem by doing the following:*...
Most possibly because scipy is a library (package) that contains modules and to import a specific module from the scipy library, you need to specify it and import the module itself. As it's a separate module (sub-package), once you import it, it's attributes are available to you by using the regular scipy.module.attrib...
in python why if rank: is faster than if rank != 0:
18,049,909
5
2013-08-05T02:45:11Z
18,050,070
8
2013-08-05T03:11:11Z
[ "python", "performance", "numpy" ]
When I changed ``` for i in range(0, 100): rank = ranks[i] if rank != 0: pass ``` to: ``` for i in range(0, 100): rank = ranks[i] if rank: pass ``` I found the second code is much more efficient, why? bench mark it, and in my situation ranks is an numpy array of integer. The differe...
Distilling the checks to the core ``` for i in range(0,100): if i != 0: pass ``` and ``` for i in range(0,100): if i: pass ``` We see there is a difference ``` $ python -m timeit 'for i in range(0,100):' ' if i != 0:' ' pass' 100000 loops, best of 3: 4.69 usec per loop $ python -m timeit 'for i in ran...
Python 3 changing value of dictionary key in for loop not working
18,050,737
2
2013-08-05T04:46:47Z
18,050,753
11
2013-08-05T04:49:30Z
[ "python", "for-loop", "dictionary", "python-3.x", "key-value" ]
I have python 3 code that is not working as expected: ``` def addFunc(x,y): print (x+y) def subABC(x,y,z): print (x-y-z) def doublePower(base,exp): print(2*base**exp) def RootFunc(inputDict): for k,v in inputDict.items(): if v[0]==1: d[k] = addFunc(*v[1:]) elif v[0] ==2:...
`print` does not return a value. It returns `None`, so every time you call your functions, they're printing to standard output and returning `None`. Try changing all `print` statements to `return` like so: ``` def addFunc(x,y): return x+y ``` This will give the value `x+y` back to whatever called the function. ...
Why were True and False changed to keywords in Python 3
18,050,815
31
2013-08-05T04:55:45Z
18,050,980
37
2013-08-05T05:16:46Z
[ "python", "keyword" ]
In Python 2, we could reassign `True` and `False` (but not `None`), but all three (`True`, `False`, and `None`) were considered builtin variables. However, in Py3k all three were changed into keywords as per [the docs](http://docs.python.org/3.0/whatsnew/3.0.html). From my own speculation, I could only guess that it w...
Possibly because Python 2.6 not only allowed `True = False` but also allowed you to say funny things like: ``` __builtin__.True = False ``` which would reset `True` to `False` for the entire process. It can lead to really funny things happening: ``` >>> import __builtin__ >>> __builtin__.True = False >>> True False ...
Why were True and False changed to keywords in Python 3
18,050,815
31
2013-08-05T04:55:45Z
18,177,220
7
2013-08-11T22:12:13Z
[ "python", "keyword" ]
In Python 2, we could reassign `True` and `False` (but not `None`), but all three (`True`, `False`, and `None`) were considered builtin variables. However, in Py3k all three were changed into keywords as per [the docs](http://docs.python.org/3.0/whatsnew/3.0.html). From my own speculation, I could only guess that it w...
For two reasons, mainly: 1. So people don't do a `__builtin__.True = False` prank hidden on a random module. (as explayned by devnull) 2. Because keywords are faster than global builtins. In Python 2.x, the interpreter would have to resolve those variables' values before using them, which is a bit slower than keywords...
How can I execute shell command with a | pipe in it
18,050,937
5
2013-08-05T05:13:08Z
18,050,955
18
2013-08-05T05:14:56Z
[ "python", "shell" ]
I am using python's subprocess `call()` to execute shell command. It works for a single command. But what if my shell command calls a command and pipe it to another command. I.e. how can I execute this in python script? ``` grep -r PASSED *.log | sort -u | wc -l ``` I am trying to use the Popen way, but i always get...
Call with `shell=True` argument. For example, ``` import subprocess subprocess.call('grep -r PASSED *.log | sort -u | wc -l', shell=True) ``` --- ## Hard way ``` import glob import subprocess grep = subprocess.Popen(['grep', '-r', 'PASSED'] + glob.glob('*.log'), stdout=subprocess.PIPE) sort = subprocess.Popen(['s...
Replace '\' character in python
18,051,658
2
2013-08-05T06:16:10Z
18,051,679
7
2013-08-05T06:17:56Z
[ "python", "string" ]
I don't know why i can't find it, but i wanted to replace the special character `'\'` in python. I have a String within i have `'\'` characters but i confident find the solution, to replace it with '-'. This is what happening while i am trying to replace, ``` >>> x = 'hello\world' >>> x 'hello\\world' >>> x.replace('...
You need to escape it with another backslash: ``` x.replace('\\', '-') ``` Backslashes are special, in that they are used to introduce non-printing characters like newlines into a string. It's also how you add a `'` character to a `'`-quoted string, which is what Python thinks you were trying to do. It sees `\'` an...
how to create local own pypi repository index without mirror?
18,052,217
16
2013-08-05T06:58:25Z
18,071,247
10
2013-08-06T03:12:55Z
[ "python", "pip", "pypi" ]
We have several own python packages and want to create local pypi repository for them using simple interface like <https://pypi.python.org/simple/> This repository I want to create for local only without any mirrors due to security reason, and it will be put under apache's control The command `pypimirror` looks has t...
Since you asked to answer here: Take a look at [`pip2pi`](https://github.com/wolever/pip2pi), it seems to be exactly what you are looking for.
how to create local own pypi repository index without mirror?
18,052,217
16
2013-08-05T06:58:25Z
18,476,794
17
2013-08-27T22:55:26Z
[ "python", "pip", "pypi" ]
We have several own python packages and want to create local pypi repository for them using simple interface like <https://pypi.python.org/simple/> This repository I want to create for local only without any mirrors due to security reason, and it will be put under apache's control The command `pypimirror` looks has t...
We had a similar need at my company. Basically how can we upload "closed source" packages to an index while being able to install them as if they were on PyPI? We have sponsored a project called [devpi](https://pypi.python.org/pypi/devpi/1.0) which acts as a PyPI cache (packages you access from PyPI will be cached on ...
TypeError: not all arguments converted during string formatting python
18,053,500
60
2013-08-05T08:15:57Z
18,053,555
87
2013-08-05T08:19:49Z
[ "python", "string", "python-3.x", "typeerror", "output-formatting" ]
The program is supposed to take in two name and if they are the same length it check if they are the same word, if it's the same word it will print *"The names are the same"* if they are the same length but of different letters it will print *"The names are different but the same length"* The part I'm having a problem ...
You're mixing different format functions. The old-style `%` formatting uses `%` codes for formatting: ``` 'It will cost $%d dollars.' % 95 ``` The new-style `{}` formatting uses `{}` codes and the `.format` method ``` 'It will cost ${0} dollars.'.format(95) ``` Note that with old-style formatting, you have to spec...
TypeError: not all arguments converted during string formatting python
18,053,500
60
2013-08-05T08:15:57Z
18,053,723
15
2013-08-05T08:31:19Z
[ "python", "string", "python-3.x", "typeerror", "output-formatting" ]
The program is supposed to take in two name and if they are the same length it check if they are the same word, if it's the same word it will print *"The names are the same"* if they are the same length but of different letters it will print *"The names are different but the same length"* The part I'm having a problem ...
The error is in your string formatting. The correct way to use traditional string formatting using the '%' operator is to use a printf-style format string (Python documentation for this here: <http://docs.python.org/2/library/string.html#format-string-syntax>): ``` "'%s' is longer than '%s'" % (name1, name2) ``` How...
Python SQLAlchemy - "MySQL server has gone away"
18,054,224
5
2013-08-05T09:02:05Z
18,057,194
8
2013-08-05T11:37:22Z
[ "python", "mysql", "sqlalchemy" ]
Lets have a look at the next snippet - ``` @event.listens_for(Pool, "checkout") def check_connection(dbapi_con, con_record, con_proxy): cursor = dbapi_con.cursor() try: cursor.execute("SELECT 1") # could also be dbapi_con.ping(), # not sure what is better except exc.OperationalErr...
There was a talk about this, and this doc describes the problem pretty nicely, so I used their recommended approach to handle such errors: <http://discorporate.us/jek/talks/SQLAlchemy-EuroPython2010.pdf> It looks something like this: ``` from sqlalchemy import create_engine, event from sqlalchemy.exc import Disconnec...
How to use youtube-dl from a python program
18,054,500
27
2013-08-05T09:16:36Z
18,947,879
43
2013-09-22T19:28:17Z
[ "python", "youtube-dl" ]
I would like to access the result of the shell command: ``` youtube-dl -g "www.youtube.com..." ``` to print its output `direct url` to file; from within a python program: ``` import youtube-dl fromurl="www.youtube.com ...." geturl=youtube-dl.magiclyextracturlfromurl(fromurl) ``` Is that possible ? I tried to unders...
It's not difficult and [actually documented](https://github.com/rg3/youtube-dl/blob/master/README.md#embedding-youtube-dl): ``` import youtube_dl ydl = youtube_dl.YoutubeDL({'outtmpl': '%(id)s%(ext)s'}) with ydl: result = ydl.extract_info( 'http://www.youtube.com/watch?v=BaW_jenozKc', download=Fa...
How to use @pytest.mark with base classes?
18,055,439
10
2013-08-05T10:03:52Z
18,058,272
8
2013-08-05T12:34:00Z
[ "python", "py.test" ]
I'm using py.test 2.2.4 and my testcases are organised as follows: ``` import pytest class BaseTests(): def test_base_test(self): pass @pytest.mark.linuxonly class TestLinuxOnlyLocal(BaseTests): pass @pytest.mark.windowsonly class TestWindowsOnly(BaseTests): pass class TestEverywhere(BaseTests...
pytest takes a more function-oriented approach to testing than other Python testing frameworks (e.g. unittest), so classes are viewed mainly as a way to organise tests. In particular, markers applied to classes (or modules) are transferred to the test functions themselves, and since a non-overridden derived class meth...
When should I use setUpClass and when __init__?
18,056,464
5
2013-08-05T10:55:58Z
18,056,870
8
2013-08-05T11:18:00Z
[ "python", "oop", "unit-testing" ]
Is there any runtime-logic difference between these two methods? Or any behviour differences? If not, then should I forget about `__init__` and use only `setUpClass` thinking here about unittests classes like about namespaces instead of language OOP paradigm?
The two are quite different. `setUpClass` is a class method, for one, so it'll only let you set *class* attributes. They are also called at different times. The test runner creates *a new instance* for *every test*. If you test class contains 5 test methods, 5 instances are created and `__init__` is called 5 times. ...
Closing a program using python?
18,058,377
3
2013-08-05T12:38:32Z
18,058,565
7
2013-08-05T12:47:48Z
[ "python" ]
I am trying to use python to close VLC while it is recording audio. Currently I am using: ``` os.kill(pid,pid) ``` This works but is closing VLC abruptly and not allowing the recording file to close properly, thus corrupting it. If I manually close the VLC GUI instance than the recording file will not be corrupted. ...
You're using the function wrong, you'll likely want something like this: ``` from signal import SIGTERM os.kill(pid,SIGTERM) ``` The second parameter specifies the interrupt. Also often used is `SIGKILL` which is a hard kill, likely same as you had before. You can find more about the linux signals [here](https://www....
How to switch between python 2.7 to python 3 from command line?
18,058,389
3
2013-08-05T12:39:06Z
18,058,500
19
2013-08-05T12:45:06Z
[ "python", "windows", "command-line", "cmd" ]
I'm trying to find the best way to switch between the two python compilers 2.7 to 3.3 If I run python from cmd, I would you use something like > `python ex1.py` where I set "python" from window environment variable from my computer properties to point to either python 3.3 or 2.7 one or another. I am wondering there ...
For Windows 7, I just rename the `python.exe` from the Python 3 folder to `python3.exe` and add the path into the environment variables. Using that, I can execute `python test_script.py` and the script runs with Python 2.7 and when I do `python3 test_script.py`, it runs the script in Python 3. To add `Python 3` to the...
How to switch between python 2.7 to python 3 from command line?
18,058,389
3
2013-08-05T12:39:06Z
18,059,129
27
2013-08-05T13:17:02Z
[ "python", "windows", "command-line", "cmd" ]
I'm trying to find the best way to switch between the two python compilers 2.7 to 3.3 If I run python from cmd, I would you use something like > `python ex1.py` where I set "python" from window environment variable from my computer properties to point to either python 3.3 or 2.7 one or another. I am wondering there ...
No need for "tricks". Python 3.3 comes with PyLauncher "py.exe", installs it in the path, and registers it as the ".py" extension handler. With it, a special comment at the top of a script tells the launcher which version of Python to run: ``` #!python2 print "hello" ``` Or ``` #!python3 print("hello") ``` From the...
Python attributeError on __del__
18,058,730
8
2013-08-05T12:56:19Z
18,058,854
11
2013-08-05T13:02:27Z
[ "python", "class", "attributeerror", "del" ]
I have a python class object and I want to assign the value of one class variable ``` class Groupclass(Workerclass): """worker class""" count = 0 def __init__(self): """initialize time""" Groupclass.count += 1 self.membercount = 0; self.members = [] def __del__(self): ...
Your `__del__` method assumes that the class is still present by the time it is called. This assumption is incorrect. `Groupclass` has already been cleared when your Python program exits and is now set to `None`. Test if the global reference to the class still exists first: ``` def __del__(self): if Groupclass: ...
Flask app raises a 500 error with no exception
18,059,937
19
2013-08-05T13:53:38Z
18,063,897
32
2013-08-05T17:17:16Z
[ "python", "exception", "heroku", "flask" ]
I've been banging my head against this method in Flask for some time, and while it seems I'm making progress now, I've just happened upon something that baffles me to no end. Here is the method I'm calling: ``` @app.route('/facedata/<slug>', methods=["POST"]) def facedata(slug): if request.method == "POST": ...
After beating my head against this some more I finally figured it out thanks to the awesome people on the pocoo google group (I have since learned that there is a separate list for flask). Firstly, I needed to turn on the `PROPAGATE_EXCEPTIONS` option in my app configuration (<http://flask.pocoo.org/docs/config/#builti...
Naive Bayes probability always 1
18,060,232
4
2013-08-05T14:05:55Z
18,063,354
8
2013-08-05T16:43:35Z
[ "python", "scikit-learn", "text-classification" ]
I started using **sklearn.naive\_bayes.GaussianNB** for text classification, and have been getting fine initial results. I want to use the probability returned by the classifier as a measure of confidence, but the **predict\_proba()** method always returns "1.0" for the chosen class, and "0.0" for all the rest. I know...
> "...the probability outputs from predict\_proba are not to be taken too seriously" I'm the guy who wrote that. The point is that naive Bayes tends to predict probabilities that are almost always either very close to zero or very close to one; exactly the behavior you observe. Logistic regression (`sklearn.linear_mod...
Difference between asfreq and resample
18,060,619
10
2013-08-05T14:23:48Z
18,061,253
15
2013-08-05T14:54:40Z
[ "python", "pandas" ]
Can some please explain the difference between the asfreq and resample methods in pandas? When should one use what?
`resample` is more general than `asfreq`. For example, using `resample` I can pass an arbitrary function to perform binning over a `Series` or `DataFrame` object in bins of arbitrary size. `asfreq` is a concise way of changing the frequency of a `DatetimeIndex` object. It also provides padding functionality. As the pa...
Combining two Series into a DataFrame in pandas
18,062,135
65
2013-08-05T15:37:39Z
18,062,430
15
2013-08-05T15:53:14Z
[ "python", "pandas", "series", "dataframe" ]
I have two Series `s1` and `s2` with the same (non-consecutive) indices. How do I combine `s1` and `s2` to being two columns in a DataFrame and keep one of the indices as a third column?
Pandas will automatically align these passed in series and create the joint index They happen to be the same here. `reset_index` moves the index to a column. ``` In [2]: s1 = Series(randn(5),index=[1,2,4,5,6]) In [4]: s2 = Series(randn(5),index=[1,2,4,5,6]) In [8]: DataFrame(dict(s1 = s1, s2 = s2)).reset_index() Out...
Combining two Series into a DataFrame in pandas
18,062,135
65
2013-08-05T15:37:39Z
18,062,521
101
2013-08-05T15:57:31Z
[ "python", "pandas", "series", "dataframe" ]
I have two Series `s1` and `s2` with the same (non-consecutive) indices. How do I combine `s1` and `s2` to being two columns in a DataFrame and keep one of the indices as a third column?
I think [`concat`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.tools.merge.concat.html) is a nice way to do this. If they are present it uses the name attributes of the Series as the columns (otherwise it simply numbers them): ``` In [1]: s1 = pd.Series([1, 2], index=['A', 'B'], name='s1') In [2]: s2...
Drawing Diagonal Lines Across a Picture
18,064,041
6
2013-08-05T17:26:54Z
18,064,451
7
2013-08-05T17:49:32Z
[ "python", "coordinates", "draw", "jython", "jes" ]
I am trying to draw parallel lines diagonally from the top right corner to the bottom left corner of a picture. I want it to look like this (lovely paint pic) ![diag paint pic](http://i.stack.imgur.com/2o5js.png) ``` def diagTopLBottomR(): pic=makePicture(pickAFile()) w=getWidth(pic) h=getHeight(pic) x1=0 y...
In the first part, `y1` is set to 0 and `y2` increases from 0 in the loop, so `y1 < y2`. This is fine because you use ``` for y in range (y1,y2) ``` In the second part, `y3` is set to `h` (128 in your case, I guess) and `y4` increases from 0 in the loop, so `y3 > y4`. This is NOT fine because you use ``` for y in ra...
nose framework command line regex pattern matching doesnt work(-e,-m ,-i)
18,064,372
3
2013-08-05T17:45:19Z
18,389,494
8
2013-08-22T19:43:07Z
[ "python", "regex", "testing", "automated-tests", "nosetests" ]
the python nosetest framework has some command line options to include , exclude and match regex for tests which can be included/excluded and matched respectively. however they dont seem to be working correctly. > [kiran@my\_redhat test]$ nosetests -w cases/ -s -v -m='\_size' > > --- > > Ran 0 tests in 0.001s > > OK ...
Nosetests' -m argument is used to match directories, **filenames**, classes, and functions. ([See the nose docs explanation of this parameter](http://nose.readthedocs.org/en/latest/usage.html#cmdoption-m)) In your case, the filename of your test file (test\_case\_4.py) does not match the -m match expression (\_size), s...
How to create recalculating variables in Python
18,064,564
4
2013-08-05T17:55:59Z
18,064,632
7
2013-08-05T17:59:59Z
[ "python" ]
Suppose I have the code: ``` a = 2 b = a + 2 a = 3 ``` The question is: how to keep `b` updated on each change in `a`? E.g., after the above code I would like to get: `print(b)` to be `5`, not `4`. Of course, `b` can be a function of `a` via `def`, but, say, in IPython it's more comfortable to have simple variables....
You can do a lambda, which is basically a function... The only malus is that you have to do `b()` to get the value instead of just `b` ``` >>> a = 2 >>> b = lambda: a + 2 >>> b() 4 >>> a = 3 >>> b() 5 ```
Group by and aggregate the values of a list of dictionaries in Python
18,066,269
6
2013-08-05T19:36:11Z
18,066,479
10
2013-08-05T19:47:37Z
[ "python", "dictionary", "itertools" ]
I'm trying to write a function, in an elegant way, that will group a list of dictionaries and aggregate (sum) the values of like-keys. **Example:** ``` my_dataset = [ { 'date': datetime.date(2013, 1, 1), 'id': 99, 'value1': 10, 'value2': 10 }, { 'date': datetime.d...
You can use `collections.Counter` and `collections.defaultdict`. Using a dict this can be done in `O(N)`, while sorting requires `O(NlogN)` time. ``` from collections import defaultdict, Counter def solve(dataset, group_by_key, sum_value_keys): dic = defaultdict(Counter) for item in dataset: key = ite...
fastest way to search python dict with partial keyword
18,066,603
9
2013-08-05T19:55:10Z
18,066,632
16
2013-08-05T19:57:28Z
[ "python" ]
What is the fastest way to determine if a dict contains a key starting with a particular string? Can we do better than linear? How can we achieve an O(1) operation when we only know the start of a key? Here is the current solution: ``` for key in dict.keys(): if key.start_with(str): return True return Fal...
Without preprocessing the dict, `O(n)` is the best you can do. It doesn't have to be complicated, though: ``` any(key.startswith(mystr) for key in mydict) ``` (Don't use `dict` and `str` as variable names, those are already the names of two [built-in functions](http://docs.python.org/2/library/functions.html).) If y...
Create gantt Plot with python matplotlib
18,066,781
2
2013-08-05T20:07:42Z
18,072,543
9
2013-08-06T05:42:00Z
[ "python", "matplotlib" ]
How is ist possible with matplotlib to plot a graph with that data. The problem is to visualize the distance from column 2 to column 3. At the End it should look like a gant time graph. ``` 0 0 0.016 19.833 1 0 19.834 52.805 2 0 52.806 84.005 5 0 84.012 107.305 8 0 107.315 128.998 10 0 12...
If I have understood you correctly, you want to plot a horizontal line between the x-values of the 3rd and 4th column, with y-value equal that in column 0. To plot a horizontal line at a given y-value between two x-values, you could use [`hlines`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hlines). I b...
How do I generate a png file w/ selenium/phantomjs from a string?
18,067,021
5
2013-08-05T20:21:56Z
18,070,609
11
2013-08-06T01:54:53Z
[ "python", "selenium", "phantomjs" ]
I am using selenium/phantomjs to create png files of html in python. Is there a way to generate the png from an html string or filehandle (instead of a website)? I've searched through the selenium docs and googled but couldn't find an answer. I have: ``` htmlString = '<html><body><div style="background-color:red;heigh...
**PhantomJS** ``` var page = require('webpage').create(); page.open('http://github.com/', function () { page.render('github.png'); phantom.exit(); }); ``` This is how to get a screenshot in phantomJS, I've used phantomJS for some time now. You can find more information [here.](https://github.com/ariya/phanto...
Speedup virtualenv creation with numpy and pandas
18,067,073
13
2013-08-05T20:25:27Z
18,067,431
13
2013-08-05T20:47:21Z
[ "python", "numpy", "pandas", "virtualenv", "pip" ]
I have multiple virtualenvs on a single machine, but all of them need numpy and pandas. I want to have seperated copies for each virtualenv, but creation of those virtualenvs takes quite some time. Is there some well defined way to precompile numpy and pandas on my machine just once and then to do something like: ``` ...
You could make use of the [`wheel`](https://pypi.python.org/pypi/wheel) package. We do this over at [pandas](http://github.com/pydata/pandas) for our continuous integration builds so that we can basically download them and install them extremely fast. Take a look at [ci/speedpack/build.sh](https://github.com/pydata/pa...
Python psycopg2 not inserting into postgresql table
18,068,901
13
2013-08-05T22:31:53Z
18,068,953
12
2013-08-05T22:35:49Z
[ "python", "insert", "postgresql-9.2", "psycopg2" ]
I'm using the following to try and insert a record into a postgresql database table, but it's not working. I don't get any errors, but there are no records in the table. Do I need a commit or something? I'm using the postgresql database that was installed with the Bitnami djangostack install. ``` import psycopg2 try:...
Turns out I needed `conn.commit()` at the end
Python psycopg2 not inserting into postgresql table
18,068,901
13
2013-08-05T22:31:53Z
18,237,335
21
2013-08-14T16:33:21Z
[ "python", "insert", "postgresql-9.2", "psycopg2" ]
I'm using the following to try and insert a record into a postgresql database table, but it's not working. I don't get any errors, but there are no records in the table. Do I need a commit or something? I'm using the postgresql database that was installed with the Bitnami djangostack install. ``` import psycopg2 try:...
If don't want to have to commit each entry to the database, you can add the following line: ``` conn.autocommit = True ``` So your resulting code would be: ``` import psycopg2 try: conn = psycopg2.connect("dbname='djangostack' user='bitnami' host='localhost' password='password'") conn.autocommit = True exce...
Is it possible to have Jinja2 ignore sections of a template that have {} in them (for instance, inline javascript)
18,070,468
2
2013-08-06T01:35:40Z
18,070,527
8
2013-08-06T01:43:47Z
[ "python", "jinja2" ]
I added a facebook button to my page by copying/pasting the code they supply on their website. It looks like this: ``` "http://www.facebook.com/dialog/feed?app_id={{fbapp_id}}&link={{link_url}}&message={{share_message|urlencode}}&display=popup&redirect_uri={{link_url}} ``` As you can see, it's got the `{}` in there ...
You can usually find that information [in the documentation, under "Escaping"](http://jinja.pocoo.org/docs/templates/#escaping) or similar. In this case, you can either output the delimiter with a variable expression: ``` {{ '{{' }} ``` Or you can use the `raw` block, for longer stretches of code: ``` {% raw %} ...
The flow of a Recursive Call
18,071,450
2
2013-08-06T03:38:51Z
18,071,469
9
2013-08-06T03:41:18Z
[ "python", "python-2.7", "recursion" ]
I looked for answers for this question but most were given in programming languages other than Python. Now in this code: ``` def f(n): if n==0: return 1 else: m = f(n-1) s = n * m return s ``` I know that if I use n = 3 for instance, the fun...
The recursion level that is given `5` as a parameter will call itself *twice,* once with `4` and once with `3`, and the results of those two calls will be added together. Similarly, calling it with `4` will result in two calls, one with `3` and one with `2`. And so on down through the levels. So the recursion "tree" w...
python nested list comprehension
18,072,759
71
2013-08-06T06:02:43Z
18,072,788
23
2013-08-06T06:04:58Z
[ "python", "list", "list-comprehension" ]
I have a this list: ``` l = [['40', '20', '10', '30'], ['20', '20', '20', '20', '20', '30', '20'], ['30', '20', '30', '50', '10', '30', '20', '20', '20'], ['100', '100'], ['100', '100', '100', '100', '100'], ['100', '100', '100', '100']] ``` Now, what I want to do is convert each element in a list to float. My soluti...
``` >>> l = [['40', '20', '10', '30'], ['20', '20', '20', '20', '20', '30', '20'], ['30', '20', '30', '50', '10', '30', '20', '20', '20'], ['100', '100'], ['100', '100', '100', '100', '100'], ['100', '100', '100', '100']] >>> new_list = [float(x) for xs in l for x in xs] >>> new_list [40.0, 20.0, 10.0, 30.0, 20.0, 20.0...
python nested list comprehension
18,072,759
71
2013-08-06T06:02:43Z
18,072,799
104
2013-08-06T06:05:23Z
[ "python", "list", "list-comprehension" ]
I have a this list: ``` l = [['40', '20', '10', '30'], ['20', '20', '20', '20', '20', '30', '20'], ['30', '20', '30', '50', '10', '30', '20', '20', '20'], ['100', '100'], ['100', '100', '100', '100', '100'], ['100', '100', '100', '100']] ``` Now, what I want to do is convert each element in a list to float. My soluti...
Here is how you would do this with a nested list comprehension: ``` [[float(y) for y in x] for x in l] ``` This would give you a list of lists, similar to what you started with except with floats instead of strings. If you want one flat list then you would use `[float(y) for x in l for y in x]`.
Methods for speeding up build time in a project using bitbake?
18,074,979
10
2013-08-06T08:16:18Z
20,860,525
10
2013-12-31T16:46:15Z
[ "python", "build", "embedded", "openembedded", "bitbake" ]
I'm working in a project which has many bitbake recipes and takes a lot of time - up to 13 hours in some cases. I am new to bitbake and I'm asking for some way to: * check what packages take more to build * check very long dependencies (I have used bitbake -g already) * check if there are any circular dependencies and...
This is a very broad question! First, here is a summary on how to inspect your build performance and dependencies when using the openembedded/yocto project. This answers the first part of the question. ## What packages take more time to build? Use the **buildstats** with the **pybootchartgui** tool produce a build c...
Why Python’s function call semantics pass-in keyword arguments are not ordered?
18,077,265
3
2013-08-06T10:13:37Z
18,077,352
7
2013-08-06T10:16:58Z
[ "python" ]
Using the double star syntax in function definition, we obtain a regular dictionary. The problem is that it loose the user input order. Sometimes, we could want to know in which order keyword arguments where passed to the function. Since usually a function call do not involved many arguments, I don't think it is a pro...
Because dictionaries are not ordered by definition. I think it really is that simple. The point of `kwargs` is to take care of exactly those formal parameters which are not ordered. If you did know the order then you could receive them as 'normal' parameters or `*args`. Here is a dictionary definition. > CPython impl...
Python string to list best practice
18,077,309
5
2013-08-06T10:15:20Z
18,077,358
10
2013-08-06T10:17:14Z
[ "python", "string", "list" ]
I have a string like this `"['first', 'sec', 'third']"` What would be the best way to convert this to a list of strings ie. `['first', 'sec', 'third']`
I'd use [`literal_eval()`](http://docs.python.org/2/library/ast.html#ast.literal_eval), it's safe: > Safely evaluate an expression node or a string containing a Python > expression. The string or node provided may only consist of the > following Python literal structures: strings, numbers, tuples, lists, > dicts, bool...
python: hybrid between regular method and classmethod
18,078,744
5
2013-08-06T11:18:00Z
18,078,819
17
2013-08-06T11:21:48Z
[ "python", "methods", "class-method" ]
sometimes I have need to write class with static methods, however with possibility to initialized it and keep state (object) sth like: ``` class A: @classmethod def method(cls_or_self): # get reference to object when A().method() or to class when A.method() code ``` what I have now is: ``` class A: d...
Functions and `classmethod` objects act as [descriptors](http://docs.python.org/2/howto/descriptor.html); both return a wrapper that when called will in turn call the underlying function with an extra parameter. The only difference between how functions and `classmethod` objects behave is in what that extra parameter *...
what is the name of that in python
18,078,990
2
2013-08-06T11:30:27Z
18,079,032
8
2013-08-06T11:32:29Z
[ "python", "closures", "anonymous-function", "lambda" ]
I know what are closures and what are lambda functions but I want to know what is the name of that : ``` >>> def foo(a, b): >>> return a + b >>> >>> bar = foo >>> bar(1, 1) >>> 2 ``` I just want to know the fact of bind a function in a variable
This is called [first-class functions.](http://en.wikipedia.org/wiki/First-class_function) Quoting Wikipedia: > Specifically, this means the language supports passing functions as arguments to other functions, returning them as the values from other functions, and *assigning them to variables or storing them in data s...
Python: Return all values that corresponds to a given key inside a dictionary
18,079,087
3
2013-08-06T11:34:38Z
18,079,137
7
2013-08-06T11:37:00Z
[ "python", "dictionary", "key", "key-value" ]
I have the following dictionary, where the key of which corresponds to a value which inside of the rules of Rock Paper Scissors Lizard Spock it defeats. Ergo. 'scissors' defeats 'paper' and 'lizard'. ``` this_defeats_that = {'scissors': 'paper', 'paper': 'rock', 'rock': 'lizar...
You have to change the way you store the mapping. Dictionary in python is a key:value mapping, keys are unique. Consider making a list of values for each unique key instead: ``` >>> this_defeats_that = {'scissors': ['paper', 'lizard'], 'paper': ['rock', 'spock'], 'liz...
Finding the intersection between two series in Pandas
18,079,563
11
2013-08-06T11:58:31Z
18,079,695
16
2013-08-06T12:05:28Z
[ "python", "pandas", "series" ]
I have two series s1 and s2 in pandas/python and want to compute the intersection i.e. where all of the values of the series are common. How would I use the concat function to do this? I have been trying to work it out but have been unable to (I don't want to compute the intersection on the indices of s1 and S2, but o...
Place both series in the python set container. See documentation: <http://docs.python.org/2/library/sets.html> then use the set intersection method. s1.intersection(s2) and then transform back to list if needed. Just noticed pandas in the tag. Can translate back to that. ``` pd.Series(list(set(s1).intersection(set(...
Finding the intersection between two series in Pandas
18,079,563
11
2013-08-06T11:58:31Z
18,080,142
8
2013-08-06T12:26:44Z
[ "python", "pandas", "series" ]
I have two series s1 and s2 in pandas/python and want to compute the intersection i.e. where all of the values of the series are common. How would I use the concat function to do this? I have been trying to work it out but have been unable to (I don't want to compute the intersection on the indices of s1 and S2, but o...
If you are using Panda's, I assume you are also using NumPy. Numpy has a function `intersect1d` that will work with a Pandas' series. Example: ``` pd.Series(np.intersect1d(pd.Series([1,2,3,5,42]), pd.Series([4,5,6,20,42]))) ``` will return a Series with the values 5 and 42.
Finding the intersection between two series in Pandas
18,079,563
11
2013-08-06T11:58:31Z
21,175,114
10
2014-01-16T23:33:17Z
[ "python", "pandas", "series" ]
I have two series s1 and s2 in pandas/python and want to compute the intersection i.e. where all of the values of the series are common. How would I use the concat function to do this? I have been trying to work it out but have been unable to (I don't want to compute the intersection on the indices of s1 and S2, but o...
Setup: ``` s1 = pd.Series([4,5,6,20,42]) s2 = pd.Series([1,2,3,5,42]) ``` Timings: ``` %%timeit pd.Series(list(set(s1).intersection(set(s2)))) 10000 loops, best of 3: 57.7 µs per loop %%timeit pd.Series(np.intersect1d(s1,s2)) 1000 loops, best of 3: 659 µs per loop %%timeit pd.Series(np.intersect1d(s1.values,s2.v...
How to find parent elements by python webdriver?
18,079,765
19
2013-08-06T12:08:52Z
18,079,918
26
2013-08-06T12:16:29Z
[ "python", "selenium", "xpath", "selenium-webdriver", "parent-child" ]
Is there any methods for python+selenium to find parent elements, brother elements, or child elements just like `driver.find_element_parent?` or `driver.find_element_next?` or `driver.find_element_previous`? eg: ``` <tr> <td> <select> <option value=0, selected='selected'> </option> <opti...
You can find a parent element by using `..` xpath: ``` input_el = driver.find_element_by_name('A') td_p_input = input_el.find_element_by_xpath('..') ``` --- What about making a separate xpath for getting selected option, like this: ``` selected_option = driver.find_element_by_xpath('//option[@selected="selected"]')...
What is the easiest way to achieve realtime plotting in pyqtgraph
18,080,170
4
2013-08-06T12:27:50Z
18,081,255
10
2013-08-06T13:13:37Z
[ "python", "python-2.7", "pyqt", "pyqt4", "pyqtgraph" ]
I do not get how to achieve realtime plotting in pyqtgraph. The realisation of that is not implemented in the documentation yet. Could anyone please provide an easy example ?
Pyqtgraph only *enables* realtime plotting by being quick to draw new plot data. *How* to achieve realtime plotting is highly dependent on the details and control flow in your application. The most common ways are: 1. Plot data within a loop that makes calls to QApplication.processEvents(). ``` pw = pg.plot() ...
Python regex to remove all words which contains number
18,082,130
4
2013-08-06T13:51:29Z
18,082,240
9
2013-08-06T13:55:46Z
[ "python", "regex" ]
I am trying to make a Python regex which allows me to remove all worlds of a string containing a number. For example: ``` in = "ABCD abcd AB55 55CD A55D 5555" out = "ABCD abcd" ``` The regex for delete number is trivial: ``` print(re.sub(r'[1-9]','','Paris a55a b55 55c 555 aaa')) ``` But I don't know how to delete...
Do you need a regex? You can do something like ``` >>> words = "ABCD abcd AB55 55CD A55D 5555" >>> ' '.join(s for s in words.split() if not any(c.isdigit() for c in s)) 'ABCD abcd' ``` If you really want to use regex, you can try `\w*\d\w*`: ``` >>> re.sub(r'\w*\d\w*', '', words).strip() 'ABCD abcd' ```
Display None values in IPython
18,083,059
3
2013-08-06T14:30:34Z
18,083,138
7
2013-08-06T14:34:12Z
[ "python", "ipython", "nonetype" ]
By default, IPython doesn't seem to display `None` values: ``` In [1]: x = 1 In [2]: x Out[2]: 1 In [3]: y = None In [4]: y ``` I often end up writing `y is None` to be sure. How can I configure IPython to always show the value, even if it is `None`?
This is deliberate, since *all* expressions return something, even if it is only `None`. You'd see nothing *but* `None` in your interpreter. You can explicitly show the return value with `repr()` or `str()`, or by printing (which calls `str()` on results by default): ``` >>> y = None >>> repr(y) 'None' >>> str(y) 'No...
Check if a key exists in a Python list
18,084,263
6
2013-08-06T15:21:54Z
18,084,331
15
2013-08-06T15:25:13Z
[ "python", "list", "python-2.7" ]
Suppose I have a list that can have either one or two elements: ``` mylist=["important", "comment"] ``` or ``` mylist=["important"] ``` Then I want to have a variable to work as a flag depending on this 2nd value existing or not. What's the best way to check if the 2nd element exists? I already did it using `len(...
You can use the `in` operator: ``` 'comment' in mylist ``` or, if the *position* is important, use a slice: ``` mylist[1:] == ['comment'] ``` The latter works for lists that are size one, two or longer, and only is `True` if the list is length 2 *and* the second element is equal to `'comment'`: ``` >>> test = lamb...
Is there a way to use Python unit test assertions outside of a TestCase?
18,084,476
22
2013-08-06T15:32:55Z
18,084,492
20
2013-08-06T15:33:51Z
[ "python", "unit-testing" ]
I need to create a fake helper class to be used in unit tests (injected into tested classes). Is there some way to use TestCase assertions in such class? I would like to use the assertions for some common checks performed by the Fake class. Something like: ``` class FakeFoo(object): def do_foo(self, a, b): ass...
You can create a instance of `unittest.TestCase()` and call the methods on that, provided you pass in the name of an *existing* method on the class. `__init__` will do in this case: ``` tc = unittest.TestCase('__init__') tc.assertIsNotNone(a) ``` However, you are probably looking for a good [Mock library](http://en.w...
Why do I get a SyntaxError for a Unicode escape in my file path?
18,084,554
36
2013-08-06T15:37:38Z
18,084,594
56
2013-08-06T15:39:30Z
[ "python", "windows", "filenames" ]
The folder I want to get to is called python and is on my desktop. I get the following error when I try to get to it ``` >>> os.chdir('C:\Users\expoperialed\Desktop\Python') SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape ```
You need to use a *raw* string, double your slashes or use forward slashes instead: ``` r'C:\Users\expoperialed\Desktop\Python' 'C:\\Users\\expoperialed\\Desktop\\Python' 'C:/Users/expoperialed/Desktop/Python' ``` In regular python strings, the `\U` character combination signals a extended Unicode codepoint escape.
Read in large file and make dictionary
18,086,424
8
2013-08-06T17:13:23Z
18,142,414
7
2013-08-09T08:01:23Z
[ "python", "c", "performance", "pandas", "cython" ]
I have a large file which I need to read in and make a dictionary from. I would like this to be as fast as possible. However my code in python is too slow. Here is a minimal example that shows the problem. First make some fake data ``` paste <(seq 20000000) <(seq 2 20000001) > largefile.txt ``` Now here is a minima...
If you want the thing you said in the comment, then you can do it easily in pandas: Let's say you have a file with the same layout but the entries get duplicated, since in your example you add all the duplicates into a list: ``` 1 1 2 2 1 3 3 4 1 5 5 6 ``` Then you can read and manipulate the data: ``` In [1]: df = ...
How do we get an optional class attribute in Python?
18,087,030
3
2013-08-06T17:48:41Z
18,087,060
8
2013-08-06T17:50:10Z
[ "python" ]
For dictionary we can use `.get` method. What about a class's attribute and provide a default value?
You can use [`hasattr`](http://docs.python.org/2/library/functions.html#hasattr) and [`getattr`](http://docs.python.org/2/library/functions.html#getattr). For example: ``` hasattr(foo, 'bar') ``` would return `True` if `foo` has an attribute named `bar`, otherwise `False` and ``` getattr(foo, 'bar', 'quux') ``` wo...
Python: sharing common code among a family of scripts
18,087,122
13
2013-08-06T17:53:40Z
18,201,784
10
2013-08-13T06:05:05Z
[ "python", "python-module", "pythonpath" ]
I'm writing a family of Python scripts within a project; each script is within a subdirectory of the project, like so: ``` projectroot | |- subproject1 | | | |- script1.main.py | `- script1.merger.py | |- subproject2 | | | |- script2.main.py | |- script2.matcher.py | `- scrip...
I suggest putting trivial "launcher" scripts at the top level of your project, and making each of the subproject folders into packages. The modules in the packages can import each other or common code can be factored out into a `common` package. Here's what the structure would look like, if we assume the various `merg...
Append list of Python dictionaries to a file without loading it
18,087,397
4
2013-08-06T18:09:17Z
18,088,275
13
2013-08-06T18:55:11Z
[ "python", "json", "pickle" ]
Suppose I need to have a database file consisting of a list of dictionaries: file: ``` [ {"name":"Joe","data":[1,2,3,4,5]}, { ... }, ... ] ``` I need to have a function that receives a list of dictionaries as shown above and appends it to the file. Is there any way to achieve...
You can use json to dump the dicts, one per line. Now each line is a single json dict that you've written. You loose the outer list, but you can add records with a simple append to the existing file. ``` import json import os def append_record(record): with open('my_file', 'a') as f: json.dump(record, f) ...
Django Social Auth w/ Twitter: HTTP 401 Error (Unauthorized)
18,087,920
3
2013-08-06T18:35:17Z
20,302,399
10
2013-11-30T16:08:27Z
[ "python", "django", "twitter", "oauth" ]
I've followed a couple tutorials for using Django Social Auth Twitter authentication. I'm running Django 1.5 w/ SQLite. I keep getting a HTTP 401 Error (Unauthorized) when trying to log in. I'll paste code below and the error message below that: # settings.py: ``` LOGIN_URL = '/login/' LOGIN_REDIRECT_URL = '/members/...
First, stop what you're doing--you need to go on Twitter and reset your keys for the app because you appear to have placed your TWITTER\_APP\_KEY and TWITTER\_APP\_SECRET in your question. Update your settings.py with your new keys. Ok? Done? Good. Assuming you've got the proper auth keys in your application: Problem...