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
Unpack NumPy array by column
27,046,533
3
2014-11-20T18:07:35Z
27,047,043
8
2014-11-20T18:36:59Z
[ "python", "numpy", "argument-unpacking" ]
If I have a NumPy array, for example 5x3, is there a way to unpack it column by column all at once to pass to a function rather than like this: `my_func(arr[:, 0], arr[:, 1], arr[:, 2])`? Kind of like `*args` for list unpacking but by column.
You can unpack the transpose of the array in order to use the columns for your function arguments: ``` my_func(*arr.T) ``` Here's a simple example: ``` >>> x = np.arange(15).reshape(5, 3) array([[ 0, 5, 10], [ 1, 6, 11], [ 2, 7, 12], [ 3, 8, 13], [ 4, 9, 14]]) ``` Let's write a func...
Meaning of Stanford Spanish POS Tagger tags
27,047,450
3
2014-11-20T19:01:39Z
27,049,346
8
2014-11-20T20:52:35Z
[ "python", "stanford-nlp", "text-mining" ]
I am tagging Spanish text with the Stanford POS Tagger (via NLTK in Python). Here is my code: ``` import nltk from nltk.tag.stanford import POSTagger spanish_postagger = POSTagger('models/spanish.tagger', 'stanford-postagger.jar') spanish_postagger.tag('esta es una oracion de prueba'.split()) ``` The result is: ```...
This is a simplified version of the tagset used in the **[AnCora treebank](http://clic.ub.edu/corpus/en)**. You can find their tagset documentation here: <http://nlp.lsi.upc.edu/freeling/doc/tagsets/tagset-es.html> The "simplification" consists of nulling out many of the final fields which don't strictly belong in a p...
Python mock patch argument `new` vs `new_callable`
27,049,877
6
2014-11-20T21:27:34Z
27,051,595
10
2014-11-20T23:32:04Z
[ "python", "mocking" ]
From the documentation <http://www.voidspace.org.uk/python/mock/patch.html> ``` patch(target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) ``` > If new is omitted, then the target is replaced with a MagicMock. If patch is used as a decorator and new is omitted, the ...
`new` is an actual object; `new_callable` is a callable used to create an object. The two cannot be used together (you either specify the replacement or a function to create the replacement; it's an error to use both.) ``` >>> foo = 6 >>> with mock.patch('__main__.foo', new=7): ... print foo ... 7 >>> with mock.patc...
Convert numpy type to python
27,050,108
5
2014-11-20T21:42:32Z
27,050,186
14
2014-11-20T21:47:09Z
[ "python", "json", "numpy", "pandas" ]
I have a list of dicts in the following form that I generate from pandas. I want to convert it to a json format. ``` list_val = [{1.0: 685}, {2.0: 8}] output = json.dumps(list_val) ``` However, json.dumps throws an error: TypeError: 685 is not JSON serializable I am guessing it's a type conversion issue from numpy t...
It looks like you're correct: ``` >>> import numpy >>> import json >>> json.dumps(numpy.int32(685)) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/json/__init__.py", line 243, in dumps return _default_encoder.encode(obj) File "/usr/lib/python2.7/json/encoder.p...
Make an http POST request to upload a file using python urllib/urllib2
27,050,399
3
2014-11-20T22:00:26Z
27,050,525
8
2014-11-20T22:08:57Z
[ "python", "http", "post", "urllib2", "urllib" ]
I would like to make a POST request to upload a file to a web service (and get response) using python. For example, I can do the following POST request with `curl`: ``` curl -F "[email protected]" -F output=json http://jigsaw.w3.org/css-validator/validator ``` How can I make the same request with python urllib/urllib2?...
Personally I think you should consider the [requests](http://docs.python-requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file) library to post files. ``` url = 'http://jigsaw.w3.org/css-validator/validator' files = {'file': open('style.css')} response = requests.post(url, files=files) ``` Uploading f...
How can I use Django OAuth Toolkit with Python Social Auth?
27,051,209
29
2014-11-20T22:58:05Z
27,051,810
50
2014-11-20T23:49:15Z
[ "python", "django", "oauth-2.0", "django-rest-framework", "python-social-auth" ]
I'm building an API using Django Rest Framework. Later this API is supposed to be consumed by iOS and Android devices. I want to allow my users to sign-up with oauth2-providers like Facebook and Google. In this case, they shouldn't have to create an account with my platform at all. But users should also be able to sign...
A lot of the difficulty in implementing OAuth comes down to understanding how the authorization flow is supposed to work. This is mostly because this is the "starting point" for logging in, and when working with a third-party backend (using something like Python Social Auth) you are actually *doing this twice*: once fo...
Splitting a conftest.py file into several smaller conftest-like parts
27,064,004
7
2014-11-21T14:48:55Z
27,068,195
10
2014-11-21T18:45:40Z
[ "python", "py.test" ]
I've got a large conftest.py file that I wish to split into smaller parts, for two reasons: 1. The file is very large (~1000 lines, including documentation) 2. Some of the fixtures depend on other fixtures, and I have no reason to expose those other fixtures as part of the conftest "API" when users look for relevant f...
You can put your stuff in other modules and reference them using a `pytest_plugins` variable in your `conftest.py`: ``` pytest_plugins = ['module1', 'module2'] ``` This will also work if your `conftest.py` has [hooks](http://pytest.org/latest/plugins.html?highlight=hooks#pytest-hook-reference) on them.
Django check if a related object exists error: RelatedObjectDoesNotExist
27,064,206
11
2014-11-21T14:59:04Z
27,064,374
23
2014-11-21T15:08:17Z
[ "python", "django" ]
I have a method `has_related_object` in my model that needs to check if a related object exists ``` class Business(base): name = models.CharField(max_length=100, blank=True, null=True) def has_related_object(self): return (self.customers is not None) and (self.car is not None) class Customer(base):...
This is because the ORM has to go to the database to check to see if `customer` exists. Since it doesn't exist, it raises an exception. You'll have to change your method to the following: ``` def has_related_object(self): has_customer = False try: has_customer = (self.customers is not None) except...
Django RelatedObjectDoesNotExist error
27,064,909
8
2014-11-21T15:34:59Z
27,065,231
10
2014-11-21T15:50:43Z
[ "python", "django" ]
I cannot see to get this to work... I have a method `has_related_object` in my model that needs to check if a related object exists... ``` class Business(base): name = models.CharField(max_length=100, blank=True, null=True) def has_related_object(self): has_customer = False has_car = False try...
You're trapping `except Business.DoesNotExist` but that's not the exception that's being thrown. Per [this SO answer](http://stackoverflow.com/a/26270785/7376) you want to catch the general [`DoesNotExist`](https://docs.djangoproject.com/en/1.7/ref/exceptions/#objectdoesnotexist-and-doesnotexist) exception instead. ED...
Pandas merge giving error "Buffer has wrong number of dimensions (expected 1, got 2)"
27,065,133
7
2014-11-21T15:46:00Z
27,066,284
8
2014-11-21T16:45:36Z
[ "python", "data-structures", "pandas" ]
I am trying to do a pandas merge and get the above error from the title when I try to run it. I am using 3 columns to match on whereas just before I do similar merge on only 2 columns and it works fine. ``` df = pd.merge(df, c, how="left", left_on=["section_term_ps_id", "section_school_id", "state"], r...
As mentioned in the comments, you have a dupe column: ![enter image description here](http://i.stack.imgur.com/9kb4c.jpg)
django development server, how to stop it when it run in background
27,066,366
5
2014-11-21T16:50:49Z
27,070,134
14
2014-11-21T20:51:10Z
[ "python", "django", "server" ]
I use a clode server to test my django small project , I type in manage.py runserver & ,and then I log out my cloude server ,I can visit mysite normally but when I reload my cloude server , I don't know how to stop the development server, I had to kill the process to stop it, is there anyway to stop the development?
The answer is findable via Google -- and answered in other forums. Example solution (on sister StackOverflow site) is [here](http://unix.stackexchange.com/questions/104821/how-to-stop-a-background-process). To be explicit, you could do: ``` ps auxw | grep runserver kill (Process # from previous command) ```
Why should i use vagrant if i use virtualenv?
27,069,182
6
2014-11-21T19:49:32Z
27,069,348
11
2014-11-21T20:01:13Z
[ "python", "django", "virtual-machine", "vagrant", "virtualenv" ]
I read this question [Do I need to use virtualenv with Vagrant?](http://stackoverflow.com/questions/18270859/do-i-need-to-use-virtualenv-with-vagrant) but i would like to know the opposite. I program in and deploy to UNIX/Linux environments (respectively MAC OSX and Ubuntu) and I use virtualenv to keep environments is...
The difference between virtualenv and Vagrant is that virtualenv is only about separate Python installations whereas Vagrant is about the whole machine. * **virtualenv** isolates the Python interpreter and the Python dependencies on one machine so you can install multiple Python projects alongside each other with thei...
Why does the 'is' operator say these methods aren't the same?
27,069,448
11
2014-11-21T20:08:39Z
27,069,553
16
2014-11-21T20:16:01Z
[ "python", "class", "object", "methods", "identity" ]
Consider this code: ``` class Person(object): def sayHello(self): return 'Hello' print(Person().sayHello is Person().sayHello) ``` I would expect it to show True. Why does it show False?
Methods on are bound to instances at **runtime**. When you run the following code: ``` print(Person().sayHello is Person().sayHello) ``` you create two instances and each time you have a different memory address. ``` >>> Person().sayHello <bound method Person.sayHello of <__main__.Person object at 0x7fbe90640410>> >...
Yield from coroutine vs yield from task
27,076,577
15
2014-11-22T10:55:42Z
27,088,005
14
2014-11-23T10:36:07Z
[ "python", "python-3.x", "asynchronous", "concurrency", "python-asyncio" ]
Guido van Rossum, in his speech in 2014 on Tulip/Asyncio [shows the slide](http://youtu.be/aurOB4qYuFM?t=53m8s): > **Tasks vs coroutines** > > * Compare: > > + res = yield from some\_coroutine(...) > + res = yield from Task(some\_coroutine(...)) > * Task can make progress without waiting for it > > + As log as y...
For the calling side co-routine `yield from coroutine()` feels like a function call (i.e. it will again gain control when coroutine() finishes). `yield from Task(coroutine())` on the other hand feels more like creating a new thread. `Task()` returns almost instantly and very likely the caller gains control back before...
Yield from coroutine vs yield from task
27,076,577
15
2014-11-22T10:55:42Z
27,209,410
7
2014-11-30T02:34:51Z
[ "python", "python-3.x", "asynchronous", "concurrency", "python-asyncio" ]
Guido van Rossum, in his speech in 2014 on Tulip/Asyncio [shows the slide](http://youtu.be/aurOB4qYuFM?t=53m8s): > **Tasks vs coroutines** > > * Compare: > > + res = yield from some\_coroutine(...) > + res = yield from Task(some\_coroutine(...)) > * Task can make progress without waiting for it > > + As log as y...
The point of using `asyncio.Task(coro())` is for cases where you *don't* want to explicitly wait for `coro`, but you want `coro` to be executed in the background while you wait for other tasks. That is what Guido's slide means by > [A] `Task` can make progress without waiting for it...**as long as you wait > for somet...
How to use "setup.cfg" instead of setup.py with Python 2.7
27,077,355
11
2014-11-22T12:25:33Z
27,077,610
19
2014-11-22T12:54:08Z
[ "python", "python-2.7", "installation" ]
It seemed to me, that instead of the whole plethora of named keyword-arguments for the `distutils.core.setup` function, one can use a `setup.cfg` file in the same directory as the `setup.py` file and all these keywords will be read from the setup.cfg file. I thought i could simply create a `setup.cfg` with Python 2.7,...
The problem is that the *setup.cfg* file does not do what you want. It does not provide parameters to the `setup` function. It is used to supply parameters to the commands that *setup.py* makes available. You can list the supported commands with **setup.py --help-commands**. You should see something like: ``` (env) go...
TypeError: object() takes no parameters
27,078,742
5
2014-11-22T14:56:58Z
27,078,790
9
2014-11-22T15:02:23Z
[ "python", "object", "parameters" ]
My code generates the following error: `TypeError: object() takes no parameters` ``` class Graph(object): def vertices(self): return list(self.__graph_dict.keys()) if __name__ == "__main__": g = { "a" : ["d"], "b" : ["c"], "c" : ["b", "c", "d", "e"], "d" : ["a", "c"], ...
Your Graph class takes no arguments on `__init__` therefore when you call: > graph = Graph(g) You get an error because Graph doesn't know what to do with 'g'. I think what you may want is: ``` class Graph(object): def __init__(self, values): self.__graph_dict = values def vertices(self): ...
How to iterate into a list into a tuple
27,081,463
2
2014-11-22T19:21:13Z
27,081,514
9
2014-11-22T19:25:40Z
[ "python", "list", "python-3.x", "iteration", "tuples" ]
I am writing a program where I have a bunch of tuples in a list like this: `[('a01', '01-24-2011', 's1'), ('a03', '01-24-2011', 's2')` etc. The tuples are the format ``` (animal ID, date(month, day, year), station# ) ``` I do not know how to access the information about the month only. I have tried: ``` months = ...
``` L = [('a01', '01-24-2011', 's1'), ('a03', '01-24-2011', 's2')] for animal, date, station in L: month, day, year = date.split('-') print("animal ID {} in month {} at station {}".format(animal, month, station)) ``` Output: ``` animal ID a01 in month 01 at station s1 animal ID a03 in month 01 at station s2 `...
Matplotlib xticks not lining up with histogram
27,083,051
10
2014-11-22T22:02:59Z
27,084,005
18
2014-11-23T00:04:00Z
[ "python", "matplotlib" ]
I'm generating some histograms with matplotlib and I'm having some trouble figuring out how to get the xticks of a histogram to align with the bars. Here's a sample of the code I use to generate the histogram: ``` from matplotlib import pyplot as py py.hist(histogram_data, 49, alpha=0.75) py.title(column_name) py.xt...
**Short answer:** Use `plt.hist(data, bins=range(50))` instead to get left-aligned bins, `plt.hist(data, bins=np.arange(50)-0.5)` to get center-aligned bins, etc. Also, if performance matters, because you want counts of unique integers, there are a couple of slightly more efficient methods (`np.bincount`) that I'll sh...
Detect strings with non English characters in Python
27,084,617
8
2014-11-23T01:31:48Z
27,084,708
13
2014-11-23T01:45:31Z
[ "python", "regex", "non-english" ]
I have some strings that have a mix of English and none English letters. For example: ``` w='_1991_اف_جي2' ``` How can I recognize these types of string using Regex or any other fast method in Python? I prefer not to compare letters of the string one by one with a list of letters, but to do this in one shot and ...
You can just check whether the string can be encoded only with ASCII characters (which are Latin alphabet + some other characters). If it can not be encoded, then it has the characters from some other alphabet. Note the comment `# -*- coding: ....`. It should be there at the top of the python file (otherwise you would...
pycharm and flask autoreload and breakpoints not working
27,087,315
12
2014-11-23T09:12:06Z
27,285,643
11
2014-12-04T03:16:29Z
[ "python", "flask", "pycharm" ]
I'm using Pycharm 4, with flask 0.10.1, python 3.4 It seems that when running a flask application from inside pycharm, if I run it with: ``` app.run(debug=True) ``` My breakpoints are ignored. After some googling, I've found that in order to make PyCharm stop on breakpoints, I should run flask with: ``` app.run(deb...
I'm going to start with the short answer: No, what you want cannot be done with any releases of PyCharm up to 4.0.1. The problem is that when you use the reloader the Flask application runs in a child process, so the PyCharm debugger is attached to the master process and has no control over the child. The best way to...
Sorting a dictionary and outputting the key which corresponds to the highest value?
27,090,558
2
2014-11-23T15:22:26Z
27,090,664
7
2014-11-23T15:31:28Z
[ "python", "python-3.x", "dictionary" ]
I am trying to output the name of the pet which corresponds to the highest value: ``` import operator pets = {"Dog":3, "Cat":5, "Rabbit":0} sorted_pets = sorted(pets.items(), key=operator.itemgetter(1), reverse = True) print (sorted_pets[0]) ``` The code above outputs ['Cat', 5]. How can I change it so it just output...
Possibly a more pythonic alternative: ``` >>> max(pets, key=pets.get) 'Cat' ```
UnicodeEncodeError: 'charmap' codec can't encode characters
27,092,833
10
2014-11-23T18:47:01Z
27,093,194
32
2014-11-23T19:19:24Z
[ "python", "beautifulsoup", "urllib" ]
I'm trying to scrape a website, but it gives me an error. I'm using the following code: ``` import urllib.request from bs4 import BeautifulSoup get = urllib.request.urlopen("https://www.website.com/") html = get.read() soup = BeautifulSoup(html) print(soup) ``` And I'm getting the following error: ``` File "C:\P...
I fixed it by adding `.encode("utf-8")` to `soup`. That means that `print(soup)` becomes `print(soup.encode("utf-8"))`.
White lines in matplotlib's pcolor
27,092,991
7
2014-11-23T19:00:32Z
27,096,694
8
2014-11-24T01:42:01Z
[ "python", "matplotlib" ]
In some pdf viewers such as Preview on OSX, plots made with matplotlib's pcolor have white lines (see image below). How can I get rid of them? The source code is very simple (choose any data for x,y,z): ``` import matplotlib matplotlib.use("pdf") import matplotlib.pyplot as pl pl.figure() pl.pcolormesh(x,y,z,cmap="Bl...
The comments have a good solution that utilizes `imshow`. When `imshow` is not appropriate for the input data (e.g. it is not uniformly spaced) this generally solves this problem, ``` pcol = pl.pcolormesh(x,y,z,cmap="Blues",linewidth=0,) pcol.set_edgecolor('face') ``` If that approach does not reduce the lines suffic...
Python glutCreateWindow error 'wrong type'
27,093,037
2
2014-11-23T19:04:07Z
27,154,196
11
2014-11-26T16:28:09Z
[ "python", "glut", "glutcreatewindow" ]
I'm trying to create a window with glut in python and have the following code: ``` glutInit() glutInitWindowSize(windowWidth, windowHeight) glutInitWindowPosition(int(centreX - windowWidth/2), int(centreY - windowHeight/2)) glutCreateWindow("MyWindow") glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_...
I just encountered exactly the same problem and found this blog entry: <http://codeyarns.com/2012/04/27/pyopengl-glut-ctypes-error/> Basically you need to specify that you are passing byte data rather than a string using `b'Window Title'`
Python retreive DayOfWeek as integer
27,106,335
3
2014-11-24T13:45:36Z
27,106,387
8
2014-11-24T13:48:12Z
[ "python", "python-datetime" ]
I need to get the day of the week as integer. If i use the following for day of the month `mydate.day` i would like to do the same for weekday. i tried `mydate.weekday` but this does not give me the integer (0 for sunday to 6 for saturday). Any suggestions?
If you are using [`datetime.datetime`](https://docs.python.org/2/library/datetime.html#datetime-objects), use [`datetime.datetime.weekday` method](https://docs.python.org/2/library/datetime.html#datetime.datetime.weekday): ``` >>> d = datetime.datetime.now() >>> d datetime.datetime(2014, 11, 24, 22, 47, 3, 80000) >>> ...
Sklearn Linear Regression - "IndexError: tuple index out of range"
27,107,057
8
2014-11-24T14:25:43Z
27,109,606
12
2014-11-24T16:34:57Z
[ "python", "scikit-learn" ]
I have a ".dat" file in which are saved values of X and Y (so a tuple (n,2) where n is the number of rows). ``` import numpy as np import matplotlib.pyplot as plt import scipy.interpolate as interp from sklearn import linear_model in_file = open(path,"r") text = np.loadtxt(in_file) in_file.close() x = np.array(text[:...
**Linear Regression** expects `X` as an array with two dimensions and internally requires `X.shape[1]` to initialize an `np.ones` array. So converting `X` to an **nx1 array** would do the trick. So, replace: ``` regr.fit(x,y) ``` by: ``` regr.fit(x[:,np.newaxis],y) ``` This will fix the problem. Demo: ``` >>> from...
Is the right-hand side of an assignment always evaluated before the assignment?
27,112,647
2
2014-11-24T19:28:50Z
27,112,772
7
2014-11-24T19:37:45Z
[ "python", "python-2.7", "undefined-behavior" ]
Here is a code snippet. ``` x = {} x[1] = len(x) print x {1: 0} ``` Is this well defined? That is, could `x == {1: 1}` instead? Because I remember that an equivalent program in C++ '98 (if we use `std::map`) has undefined behaviour. The output of the program was different when compiled with VS compiler and G++.
As I mentioned in a comment, this test case can be reduced to: ``` x = {} x[1] = len(x) ``` The question then becomes, is `x[1] == 0`, or is `x[1] == 1`? ### Let's look at the relevant [2.x documentation](https://docs.python.org/2/reference/expressions.html#evaluation-order) and [3.x documentation](https://docs.pyth...
Pandas replace values
27,117,773
6
2014-11-25T02:24:42Z
27,117,982
12
2014-11-25T02:46:37Z
[ "python", "replace", "pandas" ]
I have the following dataframe: ``` col 0 pre 1 post 2 a 3 b 4 post 5 pre 6 pre ``` I want to replace all rows in the dataframe which do not contain 'pre' to become 'nonpre', so dataframe looks like: ``` col 0 pre 1 nonpre 2 nonpre 3 nonpre 4 nonpre 5 pre 6 pre ```...
As long as you're comfortable with the `df.loc[condition, column]` syntax that pandas allows, this is very easy, just do `df['col'] != 'pre'` to find all rows that should be changed: ``` df['col2'] = df['col'] df.loc[df['col'] != 'pre', 'col2'] = 'nonpre' df Out[7]: col col2 0 pre pre 1 post nonpre 2 ...
Sorting a text file alphabetically (Python)
27,123,125
3
2014-11-25T09:36:21Z
27,123,226
11
2014-11-25T09:41:02Z
[ "python", "sorting" ]
I would like to sort the file 'shopping.txt' in alphabetical order ``` shopping = open('shopping.txt') line=shopping.readline() while len(line)!=0: print(line, end ='') line=shopping.readline() #for eachline in myFile: # print(eachline) shopping.close() ```
An easy way to do this is using the `sort()` or `sorted()` functions. ``` lines = shopping.readlines() lines.sort() ``` Alternatively: ``` lines = sorted(shopping.readlines()) ``` The disadvantage is that you have to read the whole file into memory, though. If that's not a problem, you can use this simple code.
Sorting a text file alphabetically (Python)
27,123,125
3
2014-11-25T09:36:21Z
27,123,262
9
2014-11-25T09:42:37Z
[ "python", "sorting" ]
I would like to sort the file 'shopping.txt' in alphabetical order ``` shopping = open('shopping.txt') line=shopping.readline() while len(line)!=0: print(line, end ='') line=shopping.readline() #for eachline in myFile: # print(eachline) shopping.close() ```
Just to show something different instead of doing this in python, you can do this from a command line in Unix systems: ``` sort shopping.txt -o shopping.txt ``` and your file is sorted. Of course if you really want python for this: solution proposed by a lot of other people with reading file and sorting works fine
add columns different length pandas
27,126,511
5
2014-11-25T12:16:17Z
27,126,593
8
2014-11-25T12:21:00Z
[ "python", "pandas" ]
I have a problem with adding columns in pandas. I have DataFrame, dimensional is nxk. And in process I wiil need add columns with dimensional mx1, where m = [1,n], but I don't know m. When I try do it: ``` df['Name column'] = data # type(data) = list ``` result: ``` AssertionError: Length of values does not mat...
Use concat and pass `axis=1` and `ignore_index=True`: ``` In [38]: import numpy as np df = pd.DataFrame({'a':np.arange(5)}) df1 = pd.DataFrame({'b':np.arange(4)}) print(df1) df b 0 0 1 1 2 2 3 3 Out[38]: a 0 0 1 1 2 2 3 3 4 4 In [39]: pd.concat([df,df1], ignore_index=True, axis=1) Out[39]: 0 1 0 ...
Error "QObject::startTimer: QTimer can only be used with threads started with QThread" many times when closing application
27,131,294
3
2014-11-25T15:58:09Z
27,178,019
7
2014-11-27T20:01:52Z
[ "python", "qt", "pyqt", "pyqtgraph" ]
I know this has been asked many times before. I read all of those threads, and my case seems different. Everybody else who has this trouble has a few straightforward causes that I think I’ve ruled out, such as: * Starting a timer with no event loop running * Starting/stopping a timer from a thread other than the one...
There seem to be two closely-related issues in the example. The first one causes Qt to print the `QObject::startTimer: QTimer can only be used with threads started with QThread` messages on exit. The second one (which may not affect all users) causes Qt to print `QPixmap: Must construct a QApplication before a QPaint...
django application selenium testing no static files
27,138,094
12
2014-11-25T22:36:44Z
27,178,338
7
2014-11-27T20:33:52Z
[ "python", "django", "selenium" ]
I want to do some functional tests on my django app. I'm using selenium, tests works but the problem is with static files. The css/js status is not found. My tests is running on localhost:8081. Example bootstrap.css: ``` <h1>Not Found</h1><p>The requested URL /static/frontend/bootstrap/3.3.0/css/bootstrap.css was not ...
Ok I found the solution. First I had to add in setting ``` STATIC_ROOT = 'my static dir' ``` then: ``` ./manage.py collectstatic ```
django application selenium testing no static files
27,138,094
12
2014-11-25T22:36:44Z
28,309,801
23
2015-02-03T22:15:43Z
[ "python", "django", "selenium" ]
I want to do some functional tests on my django app. I'm using selenium, tests works but the problem is with static files. The css/js status is not found. My tests is running on localhost:8081. Example bootstrap.css: ``` <h1>Not Found</h1><p>The requested URL /static/frontend/bootstrap/3.3.0/css/bootstrap.css was not ...
Assuming you're using 1.7, you can use `StaticLiveServerTestCase` from `django.contrib.staticfiles.testing`, instead of `LiveServerTestCase` (from `django.test`).
How can JSON data with null value be converted to a dictionary
27,140,090
4
2014-11-26T01:55:57Z
27,140,103
12
2014-11-26T01:57:16Z
[ "python", "json", "dictionary", null ]
``` { "abc": null, "def": 9 } ``` I have JSON data which looks like this. If not for null (without quotes as a string), I could have used `ast` module's `literal_eval` to convert the above to a dictionary. A dictionary in Python cannot have `null` as value but can have `"null"` as a value. How do I convert the ab...
You should use the built-in [`json` module](https://docs.python.org/3/library/json.html), which was designed explicitly for this task: ``` >>> import json >>> data = ''' ... { ... "abc": null, ... "def": 9 ... } ... ''' >>> json.loads(data) {'def': 9, 'abc': None} >>> type(json.loads(data)) <class 'dict'> >>> ``` ...
count occurrences of number by column in pandas data frame
27,140,860
5
2014-11-26T03:30:37Z
27,140,944
10
2014-11-26T03:39:32Z
[ "python", "pandas" ]
I have a pandas data frame I want to count how often a number appears in a column for each column ``` a b c d e 0 2 3 1 5 4 1 1 3 2 5 4 2 1 3 2 5 4 3 2 4 1 5 3 4 2 4 1 5 3 ``` This is my code that does not work ``` def equalsOne(x): x[x.columns ...
You can do: ``` (df==1).sum() ``` `df==1` gives: ``` a b c d e 0 False False True False False 1 True False False False False 2 True False False False False 3 False False True False False 4 False False True False False ``` and the `sum()` treats `False` as `0`...
When does code in __init__.py get run?
27,144,872
7
2014-11-26T08:57:17Z
27,144,933
10
2014-11-26T09:01:15Z
[ "python" ]
I have read the documentation and there is something I'm still not sure about. Does all the initialisation code for the whole module in `__init__.py` get run if I do: ``` from mymodule import mything ``` or only if I do ``` import mymodule ``` What gets run from `__init__.py` and when does it get run? I'm sure I c...
The code in `__init__.py` is run whenever you import *anything* from the package. That includes importing other modules in that package. The style of import (`import packagename` or `from packagename import some_name`) doesn't matter here. Like all modules, the code is run just once, and entered into `sys.modules` un...
How to clean images in Python / Django?
27,147,300
8
2014-11-26T10:56:22Z
29,172,195
12
2015-03-20T17:12:06Z
[ "python", "django", "matplotlib" ]
I'm asking this question, because I can't solve one problem in `Python/Django` (actually in pure Python it's ok) which leads to `RuntimeError: tcl_asyncdelete async handler deleted by the wrong thread`. This is somehow related to the way how I render `matplotlib` plots in Django. The way I do it is: ``` ... import mat...
By default matplotlib uses TK gui toolkit, when you're rendering an image without using the toolkit (i.e. into a file or a string), matplotlib still instantiates a window that doesn't get displayed, causing all kinds of problems. In order to avoid that, you should use an Agg backend. It can be activated like so -- ```...
How to surround selected text in PyCharm like with Sublime Text
27,152,414
24
2014-11-26T15:04:29Z
27,168,576
49
2014-11-27T10:39:49Z
[ "python", "sublimetext2", "pycharm" ]
Is there a way to configure PyCharm to be able to surround selected code with parenthesis by just typing on the parenthesis key, like when we use SublimText 2?
I think you want something like `Preferences | Editor | General | Smart Keys` -> `Surround selection on typing quote or brace`
Unable to bind local host:8000 with Google App Engine
27,155,715
3
2014-11-26T17:46:28Z
27,155,821
7
2014-11-26T17:53:24Z
[ "python", "google-app-engine", "localhost" ]
I am trying to run a Python app in Google App Engine. The UI doesn't work so I tried using the command lines. I tried restarting my PC, I tried changing port with "dev\_appserver.py --port=9999 ." but it still says `Unable to bind localhost:8000`: ``` raise BindError('Unable to bind %s:%s' % self.bind_addr) google...
The app server starts **two** servers; one for your application, the other for the [development console](https://cloud.google.com/appengine/docs/python/tools/devserver#Python_The_Development_Console). It is that second server that is causing the problem here; it normally would be run on port 8000. Change the ip addres...
Delete a key and value from an OrderedDict
27,155,819
5
2014-11-26T17:53:15Z
27,155,843
12
2014-11-26T17:54:13Z
[ "python", "dictionary", "ordereddictionary" ]
I am trying to remove a key and value from an `OrderedDict` but when I use: ``` dictionary.popitem(key) ``` it removes the last key and value even when a different key is supplied. Is it possible to remove a key in the middle if the dictionary?
Yes, you can use [`del`](https://docs.python.org/3/reference/simple_stmts.html#grammar-token-del_stmt): ``` del dct[key] ``` Below is a demonstration: ``` >>> from collections import OrderedDict >>> dct = OrderedDict() >>> dct['a'] = 1 >>> dct['b'] = 2 >>> dct['c'] = 3 >>> dct OrderedDict([('a', 1), ('b', 2), ('c', ...
Python: Creating a 2D histogram from a numpy matrix
27,156,381
4
2014-11-26T18:26:05Z
27,156,707
9
2014-11-26T18:45:38Z
[ "python", "numpy", "matrix", "matplotlib", "histogram" ]
I'm new to python. I have a numpy matrix, of dimensions 42x42, with values in the range 0-996. I want to create a 2D histogram using this data. I've been looking at tutorials, but they all seem to show how to create 2D histograms from random data and not a numpy matrix. So far, I have imported: ``` import numpy as n...
If you have the raw data from the counts, you could use `plt.hexbin` to create the plots for you (IMHO this is better than a square lattice): Adapted from the example of [`hexbin`](http://matplotlib.org/1.4.0/examples/pylab_examples/hexbin_demo.html): ``` import numpy as np import matplotlib.pyplot as plt n = 100000 ...
How to delete a record by id in Flask-SQLAlchemy
27,158,573
26
2014-11-26T20:45:43Z
27,159,298
53
2014-11-26T21:35:37Z
[ "python", "flask-sqlalchemy" ]
I have `users` table in my MySql database. This table has `id`, `name` and `age` fields. How can I delete some record by `id`? Now I use the following code: ``` user = User.query.get(id) db.session.delete(user) db.session.commit() ``` But I don't want make any query before delete operation. Is there any way to do t...
You can do this, `User.query.filter_by(id=123).delete()` or `User.query.filter(User.id == 123).delete()` **Edit:** Make sure to commit for `delete()` to take effect.
Why do Ipython cells stop executing?
27,160,020
9
2014-11-26T22:29:55Z
34,639,159
8
2016-01-06T17:32:35Z
[ "python", "ipython", "ipython-notebook" ]
I'm sure this is a very newb question, so I apologize in advance. I'm trying to use ipython notebook for a group project. The program we are building is fairly large and pulls in a large number of external datasets. Much of the time, Ipython seems to stop working. I'll try to run a cell or multiple cells and nothing wi...
The asterisk next to a cell `[*]` indicates that the cell is currently executing. While IPython provides each notebook with it's own kernel, there is only *one* kernel per notebook. When that kernel is busy executing code (either a cell, or a series of cells) it cannot accept or run any further code until what it is cu...
Automated docstring and comments spell check
27,162,315
16
2014-11-27T02:51:14Z
27,162,411
16
2014-11-27T03:04:38Z
[ "python", "code-analysis", "pylint", "static-code-analysis" ]
Consider the following sample code: ``` # -*- coding: utf-8 -*- """Test module.""" def test(): """Tets function""" return 10 ``` `pylint` gives it 10 of 10, `flake8` doesn't find any warnings: ``` $ pylint test.py ... Global evaluation ----------------- Your code has been rated at 10.00/10 ... $ flake8 te...
Pylint just released 1.4.0, which includes a [`spell-checker`](https://bitbucket.org/logilab/pylint/src/ede9e9ebc2557f768e129f29aeb365608ae96ea2/ChangeLog?at=default#cl-31). Here is the initial [pull-request](http://www.bytebucket.org/logilab/pylint/pull-request/134/a-spelling-checker/diff). Note that, to make the che...
django migrate has error: Specify a USING expression to perform the conversion
27,163,724
8
2014-11-27T05:34:13Z
30,779,914
9
2015-06-11T11:47:31Z
[ "python", "django", "postgresql" ]
I change my model field from Charfiled() to GenericIPAddressField() ``` ip = models.GenericIPAddressField() ``` and use django 1.7 migrate ``` ./manage.py makemigrations core ./manage.py migrate ``` But there is error: ``` return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: column "ip" cannot...
one quick fix will be to drop and create the field: 1. delete the migration what is changing the field type. 2. delete/comment the field `ip` 3. make migrations 4. get back/uncomment the field `ip` with the new field type 5. make migrations 6. migrate I did this in production and restored the data with a previous csv...
ipython notebook pandas max allowable columns
27,163,830
7
2014-11-27T05:43:15Z
27,164,566
11
2014-11-27T06:45:23Z
[ "python", "pandas", "ipython", "ipython-notebook" ]
I have a simple csv file with ten columns! When I set the following option in the notebook and print my csv file (which is in a pandas dataframe) it doesn't print all the columns from left to right, it prints the first two, the next two underneath and so on. I used this option, why isn't it working? ``` pd.option_co...
I assume you want to display your data in the notebook than the following options work fine for me (IPython 2.3): ``` import pandas as pd from IPython.display import display data = pd.read_csv('yourdata.txt') ``` Either directly set the option ``` pd.options.display.max_columns = None display(data) ``` Or, use the ...
How do I subscribe someone to a list using the python mailchimp API v2.0?
27,168,034
4
2014-11-27T10:13:42Z
27,168,035
13
2014-11-27T10:13:42Z
[ "python", "mailchimp" ]
I want to subscribe a user to a list using the [Mailchimp API 2.0](https://apidocs.mailchimp.com/api/2.0/) and the [official mailchimp python package](https://pypi.python.org/pypi/mailchimp/2.0.9). I can't find any direct documentation for how.
Before you start, you'll need to get your API key and the list id by logging into Mailchimp. To get the API key, visit *Accounts > Extras* and generate an API key. To get the list id, visit *Lists > My list > Settings > List name and defaults*. Next, make sure you've installed the mailchimp python package: ``` pip i...
Renaming models(tables) in Django
27,175,106
4
2014-11-27T16:26:39Z
27,175,159
8
2014-11-27T16:28:59Z
[ "python", "django", "migrate", "renaming", "makemigrations" ]
so I've already created models in Django for my db, but now want to rename the model. I've change the names in the Meta class and then make migrations/migrate but that just creates brand new tables. I've also tried schemamigration but also not working, I'm using Django 1.7 Here's my model ``` class ResultType(models...
Django does not know, what you are trying to do. By default it will delete old table and create new. You need to create an empty migration, then use this operation (you need to write it by yourself): <https://docs.djangoproject.com/en/dev/ref/migration-operations/#renamemodel> Something like this: ``` class Migratio...
How to find the index of a value in 2d array in Python?
27,175,400
5
2014-11-27T16:40:54Z
27,175,491
9
2014-11-27T16:46:02Z
[ "python", "arrays", "numpy", "multidimensional-array" ]
I need to figure out how I can find all the index of a value in a 2d numpy array. For example, I have the following 2d array: ``` ([[1 1 0 0], [0 0 1 1], [0 0 0 0]]) ``` I need to find the index of all the 1's and 0's. ``` 1: [(0, 0), (0, 1), (1, 2), (1, 3)] 0: [(0, 2), (0, 3), (1, 0), (1, 1), (the entire all r...
You can use [`np.where`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html) to return a tuple of arrays of x and y indices where a given condition holds in an array. If `a` is the name of your array: ``` >>> np.where(a == 1) (array([0, 0, 1, 1]), array([0, 1, 2, 3])) ``` If you want a list of (x, ...
Calculate min of rows ignoring NaN values
27,180,115
2
2014-11-27T23:49:27Z
27,180,241
7
2014-11-28T00:07:57Z
[ "python", "numpy" ]
For example, I have this array and calculate mean of rows: ``` a = np.array([[1,2,3],[2,np.NaN,4]]) mins = np.min(a, axis = 1) ``` The problem is the output is: `[1. nan]`. How to ignore nan in a and get result `[1 2]`?
Another more concise and slightly faster alternative is to use the [`numpy.nanmin()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.nanmin.html) function, which does exactly what you asked for.
How to iterate over arguments
27,181,084
10
2014-11-28T02:28:34Z
27,181,165
13
2014-11-28T02:41:31Z
[ "python", "argparse" ]
I have such script: ``` import argparse parser = argparse.ArgumentParser( description='Text file conversion.' ) parser.add_argument("inputfile", help="file to process", type=str) parser.add_argument("-o", "--out", default="output.txt", help="output name") parser.a...
Please add 'vars' if you wanna iterate over namespace object: ``` for arg in vars(args): print arg, getattr(args, arg) ```
pip error: unrecognized command line option ‘-fstack-protector-strong’
27,182,042
7
2014-11-28T04:45:12Z
28,138,922
13
2015-01-25T16:56:42Z
[ "python", "pip", "lxml", "cython", "pyquery" ]
When I `sudo pip install pyquery`, `sudo pip install lxml`, and `sudo pip install cython`, I get very similar output with the same error that says: `x86_64-linux-gnu-gcc: error: unrecognized command line option ‘-fstack-protector-strong’` Here's the complete pip output for `sudo pip install pyquery`: ``` Require...
I ran into this problem when I attempted to upgrade my pandas version to 0.15.2 There are basically 2 ways to solve this issue: Install gcc-4.9 and compile with gcc-4.9 OR edit /usr/lib/python2.7/plat-x86\_64-linux-gnu/\_sysconfigdata\_nd.py as suggested by @user323094 If you install gcc-4.9 you are likely to stil...
ValueError: Incorrect timezone setting while migrating manage.py file in Django
27,182,557
6
2014-11-28T05:39:24Z
27,182,580
9
2014-11-28T05:41:31Z
[ "python", "django", "timezone", "django-timezone" ]
I am following the Django official documentation for writing first app using Django. Here, it has said that i have to set **TIME\_ZONE** to my time zone in the settings.py file. The default value of **TIME\_ZONE** was: "utc" And i have changed it to: "utc+6.00" After this edition while I try to migrate the **manage...
According to the [documentation](https://docs.djangoproject.com/en/dev/ref/settings/#time-zone): > `TIME_ZONE` > > Default: 'America/Chicago' > > A string representing the time zone for this installation, or None. Instead of `utc+6.00`, set the `TIME_ZONE` to `Asia/Dhaka`: ``` TIME_ZONE = 'Asia/Dhaka' ```
How can I lookup a named url in a view?
27,182,774
4
2014-11-28T06:01:55Z
27,182,809
10
2014-11-28T06:05:23Z
[ "python", "django", "django-forms", "django-views" ]
I want to fill out the `success_url` of a django form view using a named url: ``` class RegisterView(generic.edit.FormView): template_name = "cmmods/register.html" form_class = RegisterForm #success_url = reverse('complete-registration') success_url = "/cmmods/complete-registration" ``` When I type th...
That means the dependency has not been loaded yet. You can use `reverse_lazy` to defer the evaluation of the url pattern Like this: ``` success_url = reverse_lazy('complete-registration') ``` Documentation of [`reverse_lazy` can be found here](https://docs.djangoproject.com/en/1.7/ref/urlresolvers/#reverse-lazy)
Import with dot name in python
27,189,044
4
2014-11-28T12:49:53Z
27,189,110
7
2014-11-28T12:53:17Z
[ "python", "import" ]
How can I import a dotted name file in python? I don't mean a relative path, but a filename starting or containing a dot `"."` For example: `'.test.py'` is the filename. `import .test` will search for a `test` package with a `py` module in a parent package.
The situation is tricky, because dots mean subpackage structure to python. Never the less it is still kinda possible with `imp`: ``` import imp my_module = imp.load_source('my_module', '.test.py') ``` *note:* this is unorthodox and you are recommend to simply rename your modules instead.
Non blocking event scheduling in python
27,190,809
3
2014-11-28T14:29:09Z
27,190,867
7
2014-11-28T14:32:12Z
[ "python", "timer", "raspberry-pi", "scheduled-tasks", "nonblocking" ]
Is it possible to schedule a function to execute at every xx millisecs in python,without blocking other events/without using delays/without using sleep ? [What is the best way to repeatedly execute a function every x seconds in Python?](http://stackoverflow.com/questions/474528/what-is-the-best-way-to-repeatedly-execu...
You can "reschedule" the event by starting another `Timer` inside the callback function: ``` import threading def hello(): t = threading.Timer(10.0, hello) t.start() print "hello, world" t = threading.Timer(10.0, hello) t.start() ```
Import geographic plots from matplotlib to plotly
27,192,268
3
2014-11-28T15:58:21Z
27,193,024
7
2014-11-28T16:49:22Z
[ "python", "matplotlib", "plot", "plotly" ]
``` import mpl_toolkits import mpl_toolkits.basemap # # specify the map boundaries and projection type # mymap = mpl_toolkits.basemap.Basemap(llcrnrlon= -120, llcrnrlat=22, urcrnrlon=-58, urcrnrlat=48, projection="tmerc", lon_0 = -95, lat_0 = 35...
Unfortunately, Plotly does not support basemap conversions yet. That said, there is a work-around: <http://nbviewer.ipython.org/github/etpinard/plotly-misc-nbs/blob/etienne/plotly-maps.ipynb> In brief, you need to extract the x-y coordinates from the basemap object, attached them to a Plotly trace objects and call `...
What type is used to store byte strings in SQLAlchemy?
27,197,965
3
2014-11-29T01:33:22Z
27,204,495
7
2014-11-29T16:38:38Z
[ "python", "postgresql", "sqlalchemy" ]
I'm trying to store byte strings in a PostgreSQL database using SQLAlchemy. My model looks like this: ``` class UserAccount(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String) password_hash = db.Column(db.String) password_salt = db.Column(db.String) ``` I want `pas...
Use the [`LargeBinary`](http://docs.sqlalchemy.org/en/latest/core/type_basics.html#sqlalchemy.types.LargeBinary) type, which will use the [`bytea`](http://www.postgresql.org/docs/current/static/datatype-binary.html) type on PostgreSQL. You can also use the [`BYTEA`](http://docs.sqlalchemy.org/en/latest/dialects/postgre...
Python Queue.join()
27,200,674
2
2014-11-29T09:13:32Z
27,201,205
7
2014-11-29T10:25:24Z
[ "python", "queue" ]
Even if I do not set thread as Daemon, shouldn't the program exit itself once queue.join(), completes and unblocks? ``` #!/usr/bin/python import Queue import threading import time class workerthread(threading.Thread): def __init__(self,queue): threading.Thread.__init__(self) se...
When you call `queue.join()` in the main thread, all it does is block the main threads until the workers have processed everything that's in the queue. It does not stop the worker threads, which continue executing their infinite loops. If the worker threads are non-deamon, their continuing execution prevents the progr...
Convert large csv to hdf5
27,203,161
11
2014-11-29T14:08:35Z
27,203,245
11
2014-11-29T14:18:30Z
[ "python", "csv", "pandas", "hdf5", "pytables" ]
I have a 100M line csv file (actually many separate csv files) totaling 84GB. I need to convert it to a HDF5 file with a single float dataset. I used **h5py** in testing without any problems, but now I can't do the final dataset without running out of memory. How can I write to HDF5 without having to store the whole d...
[Use `append=True`](http://pandas.pydata.org/pandas-docs/version/0.15.1/io.html#id2) in the call to `to_hdf`: ``` import numpy as np import pandas as pd filename = '/tmp/test.h5' df = pd.DataFrame(np.arange(10).reshape((5,2)), columns=['A', 'B']) print(df) # A B # 0 0 1 # 1 2 3 # 2 4 5 # 3 6 7 # 4 8 9 ...
matplotlib.pyplot has no attribute 'style'
27,204,646
18
2014-11-29T16:55:18Z
27,204,738
18
2014-11-29T17:06:50Z
[ "python", "matplotlib" ]
I am trying to set a style in matplotlib as per tutorial <http://matplotlib.org/users/style_sheets.html> ``` import matplotlib.pyplot as plt plt.style.use('ggplot') ``` but what I get in return is: ``` AttributeError: 'module' object has no attribute 'style' ``` My matplotlib version is 1.1.1 (and I'm on a Mac runn...
> My matplotlib version is 1.1.1 There's your problem. [The `style` package was added in version 1.4](http://matplotlib.org/users/whats_new.html#style-package-added). You should update your version.
Professor used "The binary version of a function". Does that even exist?
27,206,149
3
2014-11-29T19:28:33Z
27,206,164
7
2014-11-29T19:30:27Z
[ "python", "function" ]
Our professor used this in the assignment. I don't think "The binary version of a function" exist after searching about it in Google. What do you think it means? > Say we have a function add that adds a bunch of numbers. Rather than > writing add(3, 5, 4, 1) we want to use currying to create an adder > function that c...
I think he means a function that accepts only two arguments, so it just adds two numbers. His example function `add(3, 5, 4, 1)` would be a function that accepts any number of arguments and adds them all, but `add2` would only accept two arguments, so `add2(3, 5)` would be 8. "The binary version of a function" in this ...
NaNs comparing equal in Numpy
27,207,088
6
2014-11-29T21:03:06Z
27,207,123
7
2014-11-29T21:07:18Z
[ "python", "numpy", null, "ieee-754", "multidimensional-array" ]
Consider the following script: ``` import numpy as np a = np.array([np.nan], dtype=float) b = np.array([np.nan], dtype=float) print a == b a = np.array([np.nan], dtype=object) b = np.array([np.nan], dtype=object) print a == b ``` On my machine this prints out ``` [False] [ True] ``` The first case is clear ([as p...
On newer versions of numpy you get this warning: ``` FutureWarning: numpy equal will not check object identity in the future. The comparison did not return the same result as suggested by the identity (`is`)) and will change. ``` my guess is that numpy is using `id` test as a shortcut, for `object` types before falli...
python nltk.sent_tokenize error ascii codec can't decode
27,212,912
3
2014-11-30T11:53:46Z
27,212,917
12
2014-11-30T11:54:13Z
[ "python", "nltk" ]
I could successfully read text into a variable but while trying to tokenize the texts im getting this strange error : ``` sentences=nltk.sent_tokenize(sample) UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 11: ordinal not in range(128) ``` I do know the cause of error is some special string/char...
You should try this: ``` sentences=nltk.sent_tokenize(sample.decode('utf-8')) ```
Round Function does not work in v2.6.6, but works in v3.4.2
27,214,184
2
2014-11-30T14:15:22Z
27,214,204
8
2014-11-30T14:18:27Z
[ "python", "python-3.x", "python-2.x" ]
My round function does not work in linux python 2.6.6, whereas it works fine in Windows 3.4.2 after using the following type of code: ``` Array[i] = round(math.e ** AnotherArray[i], 4) v.3.4.2: 0.0025999999999999999 => 0.0026 v.2.6.6: 0.0025999999999999999 => 0.0025999999999999999 ```
They both work the same, but Python 2.7 and up will round floating point numbers *when printing their `repr`esentations*, in order to not confuse users by the (language- and machine-independent) [limitations of floating point arithmetic](http://docs.python.org/3/tutorial/floatingpoint.html). The decimal number `0.0026...
TkInter keypress, keyrelease events
27,215,326
5
2014-11-30T16:19:43Z
27,215,461
8
2014-11-30T16:32:09Z
[ "python", "tkinter" ]
I understood that the Tk keypress and keyrelease events were supposed only to fire when the key was actually pressed or released? However with the following simple code, if I hold down the "a" key I get a continual sequence of alternating keypress/keyrelease events. Am I doing something wrong or is TkInter buggy? Thi...
Ok some more research found [this helpful post](http://computer-programming-forum.com/56-python/8a344bb91fc18a30.htm) which shows this is occuring because of X's autorepeat behaviour. You can disable this by using ``` os.system('xset r off') ``` and then reset it using "on" at the end of your script. The problem is t...
How to find if two numbers are consecutive numbers in gray code sequence
27,218,894
4
2014-11-30T22:14:11Z
27,332,721
17
2014-12-06T14:32:00Z
[ "java", "python", "c", "algorithm", "gray-code" ]
I am trying to come up with a solution to the problem that given two numbers, find if they are the consecutive numbers in the gray code sequence i.e., if they are gray code neighbors assuming that the gray code sequence is not mentioned. I searched on various forums but couldn't get the right answer. It would be great...
Actually, several of the other answers seem wrong: it's true that two *binary reflected Gray code* neighbours differ by only one bit (I assume that by « the » Gray code sequence, you mean the original binary reflected Gray code sequence as described by Frank Gray). However, that does not mean that two Gray codes di...
RuntimeError: working outside of request context
27,220,194
6
2014-12-01T00:42:45Z
27,224,426
8
2014-12-01T08:32:35Z
[ "python", "websocket", "flask", "flask-socketio" ]
I am trying to create a 'keepalive' websocket thread to send an emit every 10 seconds to the browser once someone connects to the page but getting an error and not sure how to get around it. Any idea how to make this work. And how would i kill this thread once a 'disconnect' is sent? Thanks! ``` @socketio.on('connect...
You wrote your background thread in a way that requires it to know who's the client, since you are sending a direct message to it. For that reason the background thread needs to have access to the request context. In Flask you can install a copy of the current request context in a thread using the `copy_current_request...
How to create mosaic plot from Pandas dataframe with Statsmodels library?
27,225,636
5
2014-12-01T09:49:39Z
27,227,053
9
2014-12-01T11:08:05Z
[ "python", "pandas", "statsmodels" ]
Using Python 3.4, Pandas 0.15 and Statsmodels 0.6.0, I try to create a [mosaic plot](http://en.wikipedia.org/wiki/Mosaic_plot) from a dataframe as described in the [Statsmodels documentation](http://statsmodels.sourceforge.net/stable/generated/statsmodels.graphics.mosaicplot.mosaic.html). However, I just don't understa...
I used your data and this code: ``` mosaic(myDataframe, ['size', 'length']) ``` and got the chart like this: ![mosaic chart](http://i.stack.imgur.com/VvaH2.png)
Conditional statements in a class, but outside of scope of the function
27,230,680
6
2014-12-01T14:35:52Z
27,230,748
9
2014-12-01T14:39:22Z
[ "python", "class", "scope", "conditional-statements" ]
We know that with notation: ``` class Foo(object): a = 1 def __init__(self): self.b = 2 def c(self): print('c') ``` we can create static variable `Foo.a`, 'normal' variable `b`, which will be available after creating and instance of `Foo`, and method `c` Today I was really surprised, t...
The class body is *just Python code*. It has specific scope rules, but anything goes otherwise. This means you can create functions conditionally: ``` class C: if some_condition: def optional_method(self): pass ``` or pull methods from elsewhere: ``` import some_module class D: method_na...
How to decode a QR-code image in (preferably pure) Python?
27,233,351
24
2014-12-01T16:58:42Z
27,294,041
38
2014-12-04T12:24:52Z
[ "python", "decode", "qr-code", "zxing", "zbar" ]
> **TL;DR**: I need a way to decode a QR-code from an image file using (preferable pure) Python. I've got a jpg file with a QR-code which I want to decode using Python. I've found a couple libraries which claim to do this: **PyQRCode** ([website here](http://pyqrcode.sourceforge.net/)) which supposedly can decode qr ...
You can try the following steps and code using `qrtools`: * Create a `qrcode` file, if not already existing + I used [`pyqrcode`](https://pypi.python.org/pypi/PyQRCode) for doing this, which can be installed using `pip install pyqrcode` + And then use the code: ``` >>> import pyqrcode >>> qr = pyqrco...
How to parse sentences based on lexical content (phrases) with Python-NLTK
27,234,280
9
2014-12-01T17:56:20Z
27,240,081
13
2014-12-02T00:50:36Z
[ "python", "nltk", "lexical" ]
Can Python-NLTK recognize input string and parse it not only based on white space but also on the content? Say, "computer system" became a phrases in this situation. Can anyone provide a sample code? --- **input String**: "A survey of user opinion of computer system response time" **Expected output**: ["A", "survey"...
The technology you're looking for is called multiple names from multiple sub-fields or sub-sub-fields of linguistics and computing. * **Keyphrase Extraction** + From Information Retrieval, mainly use for improving indexing/querying for sear + Read this recent survey paper: <http://www.hlt.utdallas.edu/~saidul/acl1...
django-admin.py startproject returns Could not import settings 'settings'
27,234,308
2
2014-12-01T17:57:47Z
28,001,362
7
2015-01-17T16:04:35Z
[ "python", "django" ]
``` virtualenv ./env source ./env/bin/activate pip install Django django-admin.py startproject src ``` And i get an error " ImportError: Could not import settings 'settings' (Is it on sys.path? Is there an import error in the settings file?): No module named settings" I use MacOs. Python version is 2.7.6. ``` userna...
You probably had settings env var from a previous project. ``` $ unset DJANGO_SETTINGS_MODULE ```
What does `ValueError: cannot reindex from a duplicate axis` mean?
27,236,275
23
2014-12-01T20:00:51Z
27,242,735
26
2014-12-02T05:50:08Z
[ "python", "pandas" ]
I am getting a `ValueError: cannot reindex from a duplicate axis` when I am trying to set an index to a certain value. I tried to reproduce this with a simple example, but I could not do it. Here is my session inside of `ipdb` trace. I have a DataFrame with string index, and integer columns, float values. However when...
This error usually rises when you join / assign to a column when the index has duplicate values. Since you are assigning to a row, I suspect that there is a duplicate value in `affinity_matrix.columns`, perhaps not shown in your question.
What does `ValueError: cannot reindex from a duplicate axis` mean?
27,236,275
23
2014-12-01T20:00:51Z
37,655,063
9
2016-06-06T10:26:39Z
[ "python", "pandas" ]
I am getting a `ValueError: cannot reindex from a duplicate axis` when I am trying to set an index to a certain value. I tried to reproduce this with a simple example, but I could not do it. Here is my session inside of `ipdb` trace. I have a DataFrame with string index, and integer columns, float values. However when...
As others have said, you've probably got duplicate values in your original index. To find them do this: `df[df.index.duplicated()]`
Django - URL routing issues (cannot import name 'urls')
27,236,866
2
2014-12-01T20:39:19Z
27,236,922
9
2014-12-01T20:42:50Z
[ "python", "django", "url", "routing", "django-urls" ]
I am following the Django tutorial on <https://docs.djangoproject.com/en/1.7/intro/tutorial03/>, and am trying to get the index view to show up. I've tried the code specified on the page verbatim but keep on getting errors. polls/urls.py: ``` from django.conf.urls import patterns, urls from polls import views ...
The problem is in your `import` statement - there is no `urls` function in `django.conf.urls` package. Replace: ``` from django.conf.urls import patterns, urls ``` with: ``` from django.conf.urls import patterns, url ```
What is the point of indexing in pandas?
27,238,066
6
2014-12-01T21:54:59Z
27,238,758
11
2014-12-01T22:44:25Z
[ "python", "pandas", "indexing" ]
Can someone point me to a link or provide an explanation of the benefits of indexing in pandas? I routinely deal with tables and join them based on columns, and this joining/merging process seems to re-index things anyway, so it's a bit cumbersome to apply index criteria considering I don't think I need to. Any though...
Like a dict, a DataFrame's index is backed by a hash table. Looking up rows based on index values is like looking up dict values based on a key. In contrast, the values in a column are like values in a list. Looking up rows based on index values is faster than looking up rows based on column values. For example, con...
Sending a file over TCP sockets in Python
27,241,804
17
2014-12-02T04:19:29Z
27,241,833
10
2014-12-02T04:21:41Z
[ "python", "file", "sockets", "python-2.7", "tcp" ]
I've successfully been able to copy the file contents (image) to a new file. However when I try the same thing over TCP sockets I'm facing issues. The server loop is not exiting. The client loop exits when it reaches the EOF, however the server is unable to recognize EOF. Here's the code: **Server** ``` import socke...
Client need to notify that it finished sending, using [`socket.shutdown`](https://docs.python.org/2/library/socket.html#socket.socket.shutdown) (not [`socket.close`](https://docs.python.org/2/library/socket.html#socket.socket.close) which close both reading/writing part of the socket): ``` ... print "Done Sending" s.s...
django bytesIO to base64 String & return as JSON
27,241,996
7
2014-12-02T04:42:10Z
27,242,568
8
2014-12-02T05:36:42Z
[ "python", "django", "python-3.x" ]
I am using python 3 & I have this code, trying to get base64 out of stream and returnn as json - but not working. ``` stream = BytesIO() img.save(stream,format='png') return base64.b64encode(stream.getvalue()) ``` in my view, I have: ``` hm =mymap() strHM = hm.generate(data) return HttpRespo...
In Python 3.x, [`base64.b64encode`](https://docs.python.org/3/library/base64.html#base64.b64encode) accepts a `bytes` object and returns a `bytes` object. ``` >>> base64.b64encode(b'a') b'YQ==' >>> base64.b64encode(b'a').decode() 'YQ==' ``` You need to convert it to `str` object, using [`bytes.decode`](https://docs.p...
Checking code for deprecation warnings
27,242,434
9
2014-12-02T05:25:29Z
27,336,824
7
2014-12-06T21:35:15Z
[ "python", "python-2.7", "static-code-analysis", "deprecation-warning" ]
Consider the following sample code: ``` data = [] try: print data[0] except IndexError as error: print error.message ``` There is nothing syntactically wrong (using Python2.7) with the code except that if you run python [with warnings turned on](https://docs.python.org/2/library/warnings.html#the-warnings-fil...
Since you want to do this statically, you can use the `ast` module to parse the code and then scan it for any occurrence of the deprecated code with a subclass of the `NodeVisitor` class. Like so: ``` import ast, sys class UsingMessageAttr(ast.NodeVisitor): error_object_names = [] def visit_Attribute(self, ...
Can Scrapy be replaced by pyspider?
27,243,246
14
2014-12-02T06:33:53Z
27,246,549
16
2014-12-02T09:59:38Z
[ "python", "web-scraping", "scrapy", "web-crawler", "pyspider" ]
I've been using `Scrapy` web-scraping framework pretty extensively, but, recently I've discovered that there is another framework/system called [`pyspider`](https://github.com/binux/pyspider), which, according to it's github page, is fresh, actively developed and popular. `pyspider`'s home page lists several things be...
pyspider and Scrapy have the same purpose, web scraping, but a different view about doing that. * spider should never stop till WWW dead. (information is changing, data is updating in websites, spider should have the ability and responsibility to scrape latest data. That's why pyspider has URL database, powerful sched...
How to patch a constant in python
27,252,840
3
2014-12-02T15:20:16Z
27,252,939
9
2014-12-02T15:25:25Z
[ "python", "testing", "mocking", "patch" ]
I have two different modules in my project. One is a config file which contains ``` LOGGING_ACTIVATED = False ``` This constant is used in the second module (lets call it main) like the following: ``` if LOGGING_ACTIVATED: amqp_connector = Connector() ``` In my test class for the main module i would like to pat...
If the `if LOGGING_ACTIVATED:` test happens at the *module level*, you need to make sure that that module is not yet imported first. Module-level code runs just once (the first time the module is imported anywhere), you cannot test code that won't run again. If the test is in a function, note that the global name used...
Why does the session cookie work when serving from a domain but not when using an IP?
27,254,013
2
2014-12-02T16:17:35Z
27,276,450
7
2014-12-03T16:12:25Z
[ "python", "session", "cookies", "flask" ]
I have a Flask application with sessions that works well on my local development machine. However, when I try to deploy it on an Amazon server, sessions do not seem to work. More specifically, the session cookie is not set. I can, however, set normal cookies. I made sure I have a static secure key, as others have indi...
This is a "bug" in Chrome, not a problem with your application. (It may also effect other browsers as well if they change their policies.) [RFC 2109](https://tools.ietf.org/html/rfc2109#section-4.3.2), which describes how cookies are handled, seems to indicate that cookie domains must be an FQDN with a TLD (.com, .net...
Python: find position of element in array
27,260,811
5
2014-12-02T23:13:35Z
27,260,971
10
2014-12-02T23:28:39Z
[ "python", "arrays", "numpy", "indexing" ]
I have a CSV containing weather data like max and min temperatures, precipitation, longitude and latitude of the weather stations etc. Each category of data is stored in a single column. I want to find the location of the maximum and minimum temperatures. Finding the max or min is easy: numpy.min(my\_temperatures\_col...
Have you thought about using Python list's [`.index(value)`](https://docs.python.org/2/tutorial/datastructures.html) method? It return the index in the list of where the first instance of the `value` passed in is found.
How to install Anaconda python for all users?
27,263,620
9
2014-12-03T04:23:50Z
27,364,203
7
2014-12-08T18:12:00Z
[ "python", "anaconda" ]
[Anaconda python distribution](https://store.continuum.io/cshop/anaconda/) is very convenient to deploy scientific computing env (SCE) and switch python versions as you want. By default, the installation will locate python into `~/anaconda` and the SCE can only benefit the local user. But what I need is to provide a c...
The installer lets you install anywhere. You can install it to a global location, like `/opt/anaconda`.
pandas: When cell contents are lists, create a row for each element in the list
27,263,805
8
2014-12-03T04:44:44Z
27,266,225
8
2014-12-03T07:44:29Z
[ "python", "pandas" ]
I have a dataframe where some cells contain lists of multiple values. Rather than storing multiple values in a cell, I'd like to expand the dataframe so that each item in the list gets its own row (with the same values in all other columns). So if I have: ``` import pandas as pd import numpy as np df = pd.DataFrame( ...
A bit longer than I expected: ``` >>> df samples subject trial_num 0 [-0.07, -2.9, -2.44] 1 1 1 [-1.52, -0.35, 0.1] 1 2 2 [-0.17, 0.57, -0.65] 1 3 3 [-0.82, -1.06, 0.47] 2 1 4 [0.79, 1.35, -0.09] 2 2 5 [1.17, 1.1...
Import psycopg2 Library not loaded: libssl.1.0.0.dylib
27,264,574
25
2014-12-03T05:49:24Z
27,339,209
29
2014-12-07T03:17:12Z
[ "python", "database", "postgresql", "python-2.7", "postgresql-9.3" ]
When I try to run the command: ``` import psycopg2 ``` I get the error: ``` ImportError: dlopen(/Users/gwulfs/anaconda/lib/python2.7/site-packages/psycopg2/_psycopg.so, 2): Library not loaded: libssl.1.0.0.dylib Referenced from: /Users/gwulfs/anaconda/lib/python2.7/site-packages/psycopg2/_psycopg.so Reason: imag...
***EDIT: potentially dangerous, read comments first!*** See a much safer answer below: <http://stackoverflow.com/a/30726895/308315> --- I ran into this exact issue about an hour after you posted it and just figured it out. I am using Mac OS X Yosemite, Python 2.7, and the Postgresql app. There seems to be a non-wor...
Import psycopg2 Library not loaded: libssl.1.0.0.dylib
27,264,574
25
2014-12-03T05:49:24Z
30,726,895
43
2015-06-09T08:34:31Z
[ "python", "database", "postgresql", "python-2.7", "postgresql-9.3" ]
When I try to run the command: ``` import psycopg2 ``` I get the error: ``` ImportError: dlopen(/Users/gwulfs/anaconda/lib/python2.7/site-packages/psycopg2/_psycopg.so, 2): Library not loaded: libssl.1.0.0.dylib Referenced from: /Users/gwulfs/anaconda/lib/python2.7/site-packages/psycopg2/_psycopg.so Reason: imag...
Instead of playing with symlinks in system library dirs, set the `$DYLD_FALLBACK_LIBRARY_PATH` to include the anaconda libraries. eg: ``` export DYLD_FALLBACK_LIBRARY_PATH=$HOME/anaconda/lib/:$DYLD_FALLBACK_LIBRARY_PATH ```
Import psycopg2 Library not loaded: libssl.1.0.0.dylib
27,264,574
25
2014-12-03T05:49:24Z
36,063,405
9
2016-03-17T14:26:05Z
[ "python", "database", "postgresql", "python-2.7", "postgresql-9.3" ]
When I try to run the command: ``` import psycopg2 ``` I get the error: ``` ImportError: dlopen(/Users/gwulfs/anaconda/lib/python2.7/site-packages/psycopg2/_psycopg.so, 2): Library not loaded: libssl.1.0.0.dylib Referenced from: /Users/gwulfs/anaconda/lib/python2.7/site-packages/psycopg2/_psycopg.so Reason: imag...
conda install psycopg works for me. It updates the following packages The following packages will be UPDATED: ``` conda: 3.19.1-py27_0 --> 4.0.5-py27_0 openssl: 1.0.2f-0 --> 1.0.2g-0 pip: 8.0.2-py27_0 --> 8.1.0-py27_0 setuptools: 19.6.2-py27_0 --> 20.2.2-py27_0 wheel: 0.26.0-py27_1 --> 0.29.0...
Import psycopg2 Library not loaded: libssl.1.0.0.dylib
27,264,574
25
2014-12-03T05:49:24Z
36,872,624
12
2016-04-26T18:09:44Z
[ "python", "database", "postgresql", "python-2.7", "postgresql-9.3" ]
When I try to run the command: ``` import psycopg2 ``` I get the error: ``` ImportError: dlopen(/Users/gwulfs/anaconda/lib/python2.7/site-packages/psycopg2/_psycopg.so, 2): Library not loaded: libssl.1.0.0.dylib Referenced from: /Users/gwulfs/anaconda/lib/python2.7/site-packages/psycopg2/_psycopg.so Reason: imag...
After bashing my head against the wall for a couple hours, these two solutions are guaranteed to work: **Option 1.** This solves our problem without messing around with environment variables. Run this in your shell: ``` brew install --upgrade openssl brew unlink openssl && brew link openssl --force ``` Boom! This up...
How to run Debug server for Django project in PyCharm Community Edition?
27,269,574
18
2014-12-03T10:42:14Z
28,256,637
48
2015-01-31T21:19:39Z
[ "python", "django", "configuration", "ide", "pycharm" ]
Has anyone had issues setting up a debug configuration for Django project in PyCharm Community Edition? Community Edition of the IDE is lacking the project type option on project setup and then when I am setting up Debug or Run config it asks me for a script it should run. What script would it be for Django, manage.py?...
Yes you can. 1. In Run -> Edit Configurations create new configuration 2. Script: path\_to/manage.py 3. Script parameters: runserver
TypeError: coercing to Unicode: need string or buffer, int found
27,274,705
11
2014-12-03T14:52:25Z
27,274,835
16
2014-12-03T14:57:30Z
[ "python", "api", "unicode", "buffer", "typeerror" ]
I have 2 APIs. I am fetching data from them. I want to assign particular code parts to string so that life became easier while coding. Here is the code: ``` import urllib2 import json urlIncomeStatement = 'http://dev.c0l.in:8888' apiIncomeStatement = urllib2.urlopen(urlIncomeStatement) dataIncomeStatement = json.load...
The problem might have to do with the fact that you are adding ints to strings here ``` if item['sector'] == 'technology': name + "'s interest payable - " + interestPayable name + "'s interest receivable - " + interestReceivable name + "'s interest receivable - " + sales name + "'s ...
Python pandas best way to select all columns starting with X
27,275,236
6
2014-12-03T15:15:54Z
27,275,344
10
2014-12-03T15:21:28Z
[ "python", "pandas", "selection" ]
I have a dataframe: ``` import pandas as pd import numpy as np df = pd.DataFrame({'foo.aa': [1, 2.1, np.nan, 4.7, 5.6, 6.8], 'foo.fighters': [0, 1, np.nan, 0, 0, 0], 'foo.bars': [0, 0, 0, 0, 0, 1], 'bar.baz': [5, 5, 6, 5, 5.6, 6.8], 'foo....
Just perform a list comprehension to create your columns: ``` In [28]: filter_col = [col for col in list(df) if col.startswith('foo')] filter_col Out[28]: ['foo.aa', 'foo.bars', 'foo.fighters', 'foo.fox', 'foo.manchu'] In [29]: df[filter_col] Out[29]: foo.aa foo.bars foo.fighters foo.fox foo.manchu 0 1.0 ...
How does this Python import work?
27,275,983
5
2014-12-03T15:51:11Z
27,276,142
8
2014-12-03T15:58:06Z
[ "python" ]
I have two files in the same directory, and there are no `__init__.py` files anywhere: ``` c:\work\test>tree . |-- a | `-- a | |-- a1.py | `-- a2.py `-- b ``` one file imports the other: ``` c:\work\test>type a\a\a1.py print 'a1-start' import a2 print 'a1-end' c:\work\test>type a\a\a2.py print 'a2' ``...
A quote from the [module docs](https://docs.python.org/2/tutorial/modules.html) (emphasis mine): "When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. s...
Python: Random System time seed
27,276,135
7
2014-12-03T15:57:49Z
27,276,285
8
2014-12-03T16:04:42Z
[ "python", "random", "time" ]
In python, and assuming I'm on a system which has a random seed generator, how do I get random.seed() to use system time instead? (As if /dev/urandom did not exist)
``` import random from datetime import datetime random.seed(datetime.now()) ```
Unsupported operation :not writeable python
27,278,755
3
2014-12-03T18:13:31Z
27,278,821
7
2014-12-03T18:17:03Z
[ "python", "python-3.x" ]
Email validation ``` #Email validator import re f= open ('ValidEmails.txt', 'w') def is_email(): email=input("Enter your email") pattern = '[\.\w]{1,}[@]\w+[.]\w+' file = open('ValidEmails.txt','r') if re.match(pattern, email): file.write(email) file.close print("Valid Email"...
You open the variable "file" as a read only then attempt to write to it. Use the 'w' flag. ``` file = open('ValidEmails.txt','w') ... file.write(email) ```
Returning the truthiness of a variable rather than its value?
27,284,465
2
2014-12-04T00:54:34Z
27,284,468
8
2014-12-04T00:55:27Z
[ "python", "boolean" ]
Consider this code: ``` test_string = 'not empty' if test_string: return True else: return False ``` I know I could construct a conditional expression to do it: ``` return True if test_string else False ``` However, I don't like testing if a boolean is true or false when I'd rather just return the boolean....
You can use [`bool`](https://docs.python.org/3/library/functions.html#bool): ``` return bool(test_string) ``` Demo: ``` >>> bool('abc') True >>> bool('') False >>> ```
Python: where is random.random() seeded?
27,284,943
3
2014-12-04T01:52:40Z
27,286,733
7
2014-12-04T05:12:11Z
[ "python", "random", "cryptography", "random-seed" ]
Say I have some python code: ``` import random r=random.random() ``` Where is the value of r seeded from in general? And what if my OS has no random, then where is it seeded? Why isn't this recommended for cryptography? Is there some way to know what the random number is?
Follow *da code*. To see where the `random` module "lives" in your system, you can just do in a terminal: ``` >>> import random >>> random.__file__ '/usr/lib/python2.7/random.pyc' ``` That gives you the path to the `.pyc` ("compiled") file, which is usually located side by side to the original `.py` where readable c...