title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
python shuffling with a parameter to get the same result
19,306,976
8
2013-10-10T21:59:48Z
19,307,027
9
2013-10-10T22:04:01Z
[ "python" ]
``` import random x = [1, 2, 3, 4, 5, 6] random.shuffle(x) print x ``` I know how to shuffle a list, but is it possible to shuffle it with a parameter such that the shuffling produces the same result every time? Something like; ``` random.shuffle(x,parameter) ``` and the result is the same for this parameter. Say p...
Yes, `shuffle` accepts an optional argument that it calls to get its random number (which should be a float between 0 and 1, excluding 1). See the [docs](http://docs.python.org/2/library/random.html#random.shuffle). So you can compute the random number first, then do the shuffle: ``` >>> import random >>> r = random....
Non-ASCII identifiers for python 2.7
19,307,331
3
2013-10-10T22:30:08Z
19,307,398
7
2013-10-10T22:35:32Z
[ "python" ]
I know that in python 3.x I can use Non-ASCII identifiers (PEP 3131). ``` x1 = 2 x2 = 4 Δx = x2 - x1 print(Δx) ``` Is there such feature in python 2.7? Maybe, has anybody ported it to 2.x branch?
No, there is no such feature in Python 2; names are constricted to using ASCII letters and digits only. See the [Identifiers and Keywords](http://docs.python.org/2/reference/lexical_analysis.html#identifiers) section of the reference manual: > Identifiers (also referred to as names) are described by the following > l...
Execute terminal command from python in new terminal window?
19,308,415
7
2013-10-11T00:32:32Z
19,308,462
15
2013-10-11T00:36:58Z
[ "python", "shell", "terminal", "subprocess", "new-window" ]
The goal here is to run a new python file in a new shell from and existing python file in an existing shell. Say i have two files, aaa.py and bbb.py. Lets say for simplicity that all aaa.py does is... ``` subprocess.call('python bbb.py', shell=True) ``` ...and lets say that bbb.py does is... ``` print 'It worked' ``...
There's no way to do this in general from a shell. What you have to do is run the terminal program itself, or some launcher program that does so for you. And the way to do that is different for each terminal program. In some cases, [`os.startfile`](http://docs.python.org/2/library/os.html#os.startfile) will do what yo...
Why python is much slower than node.js on recursion
19,308,835
6
2013-10-11T01:25:33Z
19,309,104
12
2013-10-11T02:04:58Z
[ "python", "node.js" ]
I've wrote a simple fibonacci test program to compare the performance of node.js and python. It turns out python took 5s to finish the computation, while node.js ends in 200ms Why does python perform so poor on this case? python ``` import time beg = time.clock() def fib(n): if n <=2: return 1 return...
It is not really possible to set up a contrived benchmark like this and get results useful enough to make blanket statements about speed; benchmarking is extremely complex and in some cases runtimes can even factor out parts of your benchmark entirely because they realize there's a faster way to do what you tell it you...
How to (intermittently) skip certain cells when running IPython notebook?
19,309,287
11
2013-10-11T02:25:50Z
19,318,428
9
2013-10-11T12:41:45Z
[ "python", "ipython", "ipython-notebook", "ipython-magic" ]
I usually have to rerun (most parts of) a notebook when reopen it, in order to get access to previously defined variables and go on working. However, sometimes I'd like to skip some of the cells, which have no influence to subsequent cells (e.g., they might comprise a branch of analysis that is finished) and could tak...
Currently, there is no such feature included in the IPython notebook. Nevertheless, there are some possibilities to make your life easier, like: * use the `%store` or maybe better the `%%cache` magic (extension) to store the results of these intermittently cells, so they don't have to be recomputed (see <https://githu...
Getting original line number for exception in concurrent.futures
19,309,514
14
2013-10-11T02:54:08Z
24,457,608
7
2014-06-27T17:27:21Z
[ "python", "python-2.7", "concurrency", "concurrent.futures" ]
Example of using concurrent.futures (backport for 2.7): ``` import concurrent.futures # line 01 def f(x): # line 02 return x * x # line 03 data = [1, 2, 3, None, 5] # line 04 with concurrent.futures.ThreadPoolExecutor(len(data)) as executor: # line 05 futures = [executor.submit(f, n) for n in data] # lin...
I was in your same situation and I really needed to have the traceback of the raised exceptions. I was able to develop this workaround which consists in using the following subclass of the `ThreadPoolExecutor`. ``` import sys import traceback from concurrent.futures import ThreadPoolExecutor class ThreadPoolExecutorS...
python prime factorization performance
19,310,061
12
2013-10-11T04:03:35Z
19,310,394
11
2013-10-11T04:43:06Z
[ "python", "performance", "algorithm", "prime-factoring" ]
I'm relatively new to python and I'm confused about the performance of two relatively simple blocks of code. The first function generates a prime factorization of a number n given a list of primes. The second generates a list of all factors of n. I would have though `prime_factor` would be faster than `factors` (for th...
Without seeing what you used for `primes`, we have to guess (we can't run your code). But a big part of this is simply mathematics: there are (very roughly speaking) about `n/log(n)` primes less than `n`, and that's a lot bigger than `sqrt(n)`. So when you pass a prime, `prime_factor(n)` does a lot more work: it goes ...
Matplotlib - plot with a different color for certain data points
19,311,498
3
2013-10-11T06:19:28Z
19,311,870
7
2013-10-11T06:46:22Z
[ "python", "matplotlib", "scatter" ]
My question is similar to [this question](http://stackoverflow.com/questions/7881994/matplotlib-how-to-change-data-points-color-based-on-some-variable). I am plotting latitude vs longitude. If the value in a variable is 0, I want that lat/long value to be marked with a different color. How do I do that? This is my att...
You are indexing your `timeDiffInt` list with items from that list, if those are integers larger then the length of the list, it will show this error. Do you want your scatter to contain two colors? One colors for values of 0 and another colors for other values? You can use Numpy to change your list to zeros and ones...
Django rest-framework per action permission
19,313,314
10
2013-10-11T08:09:48Z
19,313,716
10
2013-10-11T08:35:16Z
[ "python", "django", "django-rest-framework", "django-permissions" ]
I'm a newbie in developing with Django + Django Rest-framework and I'm working on a project that provides REST Api access. I was wondering what is the best practice to assign a different permission to each action of a given ApiView or Viewset. Let's suppose I defined some permissions classes such as 'IsAdmin', 'IsRole...
You can create a [custom permission class](http://www.django-rest-framework.org/api-guide/permissions/#custom-permissions) extending DRF's `BasePermission`. You implement `has_permission` where you have access to the `request` and `view` objects. You can check `request.user` for the appropriate role and return `True`/...
Django rest-framework per action permission
19,313,314
10
2013-10-11T08:09:48Z
34,162,842
13
2015-12-08T18:01:31Z
[ "python", "django", "django-rest-framework", "django-permissions" ]
I'm a newbie in developing with Django + Django Rest-framework and I'm working on a project that provides REST Api access. I was wondering what is the best practice to assign a different permission to each action of a given ApiView or Viewset. Let's suppose I defined some permissions classes such as 'IsAdmin', 'IsRole...
In DRF documentation, > Note: The instance-level has\_object\_permission method will only be called if the view-level has\_permission checks have already passed Let's assume following permission about `user` object * List : staff only * Create : anyone * Retrieve : own self or staff * Update, Partial update : own se...
Python, SQLAlchemy pass parameters in connection.execute
19,314,342
3
2013-10-11T09:08:02Z
19,324,366
10
2013-10-11T17:53:09Z
[ "python", "sql", "sqlalchemy", "parameter-passing" ]
I am using SQLAlchemy connection.execute(sql) to transform select results to array of maps. Have following code ``` def __sql_to_data(sql): result = [] connection = engine.connect() try: rows = connection.execute(sql) for row in rows: result_row = {} for col in row.k...
[The tutorial](http://docs.sqlalchemy.org/en/rel_0_8/core/tutorial.html#using-text) gives a pretty good example for this: ``` >>> from sqlalchemy.sql import text >>> s = text( ... "SELECT users.fullname || ', ' || addresses.email_address AS title " ... "FROM users, addresses " ... "WHERE users.id =...
Why does scipy.optimize.curve_fit not fit correctly to the data?
19,314,402
2
2013-10-11T09:11:01Z
19,315,302
10
2013-10-11T09:56:24Z
[ "python", "numpy", "matplotlib", "curve-fitting", "data-fitting" ]
I've been trying to fit a function to some data for a while using `scipy.optimize.curve_fit` but I have real difficulty. I really can't see any reason why this wouldn't work. ``` # encoding: utf-8 from __future__ import (print_function, division, unicode_literals, ...
Firstly try not to increase `maxfev` so large, this is usually a sign something else is going wrong! Playing around I can get a fit by the following addition: ``` def f(x, b, a, k): return (b/(np.sqrt(1 + a*((k-x)**2)))) popt, pcov = curve_fit(f, x, y, p0=[20, 600.0, 35.0]) ``` Firstly give the fitting function ...
Working with google word2vec .bin files in gensim python
19,315,338
7
2013-10-11T09:58:14Z
20,102,707
7
2013-11-20T17:25:17Z
[ "python", "gensim", "word2vec" ]
I’m trying to get started by loading the pretrained .bin files from the google word2vec site ( freebase-vectors-skipgram1000.bin.gz) into the gensim implementation of word2vec. The model loads fine, using .. ``` model = word2vec.Word2Vec.load_word2vec_format('...../free....-en.bin', binary= True) ``` and creates a...
The words in '...../free....-en.bin' have the form of > en/boardwalk\_chapel > en/mutsu\_munemitsu > en/goffstown en/yaw\_axis > en/john\_e\_fogarty\_international\_center > en/francielle\_manoel\_alberto > en/shinji\_harada So when you look for 'girl' it is not there
csv writer in Python with custom quoting
19,315,366
9
2013-10-11T09:59:21Z
19,315,648
9
2013-10-11T10:15:11Z
[ "python", "csv", "quoting" ]
I'm looking for a way to define custom `quoting` with `csv.writer` in Python. There are 4 built-in ways to qoute values: ``` csv.QUOTE_ALL, csv.QUOTE_MINIMAL, csv.QUOTE_NONNUMERIC, csv.QUOTE_NONE ``` However I need a quoting mechanism which will emulate Postgres' `FORCE QUOTE *`, i.e. it will quote all non-None value...
Disable `csv` quoting and add the quotes yourself: ``` def quote(col): if col is None: return '' # uses double-quoting style to escape existing quotes return '"{}"'.format(str(col).replace('"', '""')) writer = csv.writer(fileobj, quoting=csv.QUOTE_NONE, escapechar='', quotechar='') for row in row...
Flask render template not working
19,315,567
4
2013-10-11T10:11:10Z
19,316,089
9
2013-10-11T10:37:27Z
[ "python", "flask", "jinja2" ]
I am new to Python and Flask. I have a templates folder in the the root of my application whic has two file. ``` <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}{% endblock title %}</title> <link href="http://netdna.bootstrapcdn.com/bootswatch/2.3.2/united/bootstrap.min.css" rel="style...
I modified the get accordingly. Setting the content type did the trick. ``` class AppointmentController(Resource): def __init__(self): pass def get(self): headers = {'Content-Type': 'text/html'} return make_response(render_template('index.html'),200,headers) ```
About variable scope?
19,316,985
5
2013-10-11T11:26:08Z
19,317,190
9
2013-10-11T11:35:38Z
[ "python" ]
I had a math test today and one of the extra credit questions on the test was ``` product = 1 for i in range(1,7,2): print i product = product * i print i print product ``` We were supposed to list out the steps of the loop which was easy; but it got me thinking, why does this program run? the second `print i...
The Devil is in the Details [Naming and binding](http://docs.python.org/2/reference/executionmodel.html) > A block is a piece of Python program text that is executed as a unit. > The following are blocks: a module, a function body, and a class > definition. Or in simple words, a `for loop` is not a block > A scope ...
Execute Shell Script from Python with multiple pipes
19,318,859
3
2013-10-11T13:03:13Z
19,318,923
7
2013-10-11T13:06:18Z
[ "python", "linux", "bash", "shell", "pipe" ]
I want to execute the following Shell Command in a python script: ``` dom=myserver cat /etc/xen/$myserver.cfg | grep limited | cut -d= -f2 | tr -d \" ``` I have this: ``` dom = myserver limit = subprocess.call(["cat /etc/xen/%s.cfg | grep limited | cut -d= -f2", str(dom)]) subprocess.call(['/root/bin/xen-limit'...
You can glue several subprocesses together: ``` c1 = ['ls'] p1 = subprocess.Popen(c1, stdout=subprocess.PIPE) c2 = ['wc'] p2 = subprocess.Popen(c2, stdin=p1.stdout, stdout=subprocess.PIPE) result = p2.stdout.read() ``` Notice how we've set the stdin of p2 to be the stdout of p1. EDIT: simplif...
How to get the content of a remote file without a local temporary file with fabric
19,319,014
7
2013-10-11T13:10:41Z
19,338,483
18
2013-10-12T19:47:17Z
[ "python", "fabric" ]
I want to get the content of a remote file with fabric, without creating a temporary file.
``` from StringIO import StringIO from fabric.api import get fd = StringIO() get(remote_path, fd) content=fd.getvalue() ```
How do you convert a python time.struct_time object into a ISO string?
19,319,370
13
2013-10-11T13:26:36Z
19,319,412
23
2013-10-11T13:28:36Z
[ "python", "datetime", "time" ]
I have a Python object: ``` time.struct_time(tm_year=2013, tm_mon=10, tm_mday=11, tm_hour=11, tm_min=57, tm_sec=12, tm_wday=4, tm_yday=284, tm_isdst=0) ``` And I need to get an [ISO string](http://www.w3.org/TR/NOTE-datetime): ``` '2013-10-11T11:57:12Z' ``` How can I do that?
Using [`time.strftime()`](http://docs.python.org/2/library/time.html#time.strftime) is perhaps easiest: ``` iso = time.strftime('%Y-%m-%dT%H:%M:%SZ', timetup) ``` Demo: ``` >>> import time >>> timetup = time.gmtime() >>> time.strftime('%Y-%m-%dT%H:%M:%SZ', timetup) '2013-10-11T13:31:03Z' ``` You can also use a `dat...
Twython search API with next_results
19,320,197
2
2013-10-11T14:06:09Z
21,644,346
11
2014-02-08T09:33:54Z
[ "python", "api", "twitter", "twython" ]
I'm a bit confused about the search API. Let's suppose I query for "foobar", the following code: ``` from twython import Twython api = Twython(...) r = api.search(q="foobar") ``` In this way I have 15 statuses and a `"next_results"` in `r["metadata"]`. Is there any way to bounce back those metadata to the Twython API...
petrux, "next\_results" is returned with metadata "max\_id" and since\_id which should be used to bounce back and loop through the timeline until we get desired number of tweets. Here is the update on it from twitter on how to do it: <https://dev.twitter.com/docs/working-with-timelines> Below is the sample code which...
Prevent Vim from indenting line when typing a colon (:) in Python
19,320,747
17
2013-10-11T14:31:30Z
21,820,207
17
2014-02-17T03:29:38Z
[ "python", "vim", "vi" ]
Whenever I append a `:` character in Vim in Python mode, it either: * indents the line * dedents the line * does nothing What is it even trying to do, and how do I get rid of this behavior?
Certain keys, when pressed, will trigger Vim's indent feature, which will attempt to set the correct amount of indentation on the current line. (You can manually trigger this by typing `==` in normal mode.) You can change which keys trigger this behavior, but first you need to know what indenting mode is being used. ...
how to kill zombie processes created by multiprocessing module?
19,322,129
11
2013-10-11T15:42:24Z
19,322,880
9
2013-10-11T16:23:50Z
[ "python", "linux", "multithreading" ]
I'm very new to `multiprocessing` module. And I just tried to create the following: I have one process that's job is to get message from RabbitMQ and pass it to internal queue (`multiprocessing.Queue`). Then what I want to do is : spawn a process when new message comes in. It works, but after the job is finished it lea...
A couple of things: 1. Make sure the parent `joins` its children, to avoid zombies. See [Python Multiprocessing Kill Processes](http://stackoverflow.com/questions/18477320/python-multiprocessing-kill-processes?lq=1) 2. You can check whether a child is still running with the `is_alive()` member function. See <http://do...
How do I find directory of the Python running script from inside the script?
19,322,836
3
2013-10-11T16:21:25Z
19,323,023
10
2013-10-11T16:31:40Z
[ "python", "directory" ]
How do I find the directory of the running Python script from inside Python [3.3]? I have tried what was suggested at: [Python: How to find script's directory](http://stackoverflow.com/questions/4934806/python-how-to-find-scripts-directory) , but I get "Invalid syntax" and directed to "os" (And I did import os). The c...
To get the directory that contains the module you are running: ``` import os path = os.path.dirname(os.path.realpath(__file__)) ``` Or if you want the directory from which the script was invoked: ``` import os path = os.getcwd() ``` From the [docs](http://docs.python.org/2/reference/datamodel.html#the-standard-type...
Heroku & Django: "OSError: No such file or directory: '/app/{myappname}/static'"
19,323,513
18
2013-10-11T16:59:14Z
19,323,823
33
2013-10-11T17:19:56Z
[ "python", "django", "git", "heroku", "django-staticfiles" ]
I have a Django app on Heroku. I am having some problems with static files (they are loading in one Heroku [environment](https://devcenter.heroku.com/articles/multiple-environments) but not another), so I tried the debug command recommended [here](https://devcenter.heroku.com/articles/django-assets#debugging). ``` $ h...
It's looking for a folder named 'static' that's next to the settings.py, i.e. in the project folder, not at the root of the git repo. ``` git root/ git root/{app name} git root/{app name}/settings.py git root/{app name}/static/ <- this is what you're missing ``` Note that empty folders aren't tracked by git, ...
Flask-Migrate not creating tables
19,323,990
10
2013-10-11T17:30:03Z
19,324,130
7
2013-10-11T17:37:53Z
[ "python", "flask", "flask-sqlalchemy", "flask-migrate" ]
I have the following models in file `listpull/models.py`: ``` from datetime import datetime from listpull import db class Job(db.Model): id = db.Column(db.Integer, primary_key=True) list_type_id = db.Column(db.Integer, db.ForeignKey('list_type.id'), nullable=False) list_type...
When you call the `migrate` command Flask-Migrate (or actually Alembic underneath it) will look at your `models.py` and compare that to what's actually in your database. The fact that you've got an empty migration script suggests you have updated your database to match your model through another method that is outside...
Add missing dates to pandas dataframe
19,324,453
16
2013-10-11T17:58:15Z
19,324,591
47
2013-10-11T18:08:29Z
[ "python", "date", "plot", "pandas", "dataframe" ]
[I've found quite of bit of talk on similar issues, but nothing on how I'm approaching this] I have a CSV file I'm parsing which could have multiple events on a given date. Sometimes there are NO events on a date. I take these events, get a count by date and plot them. However, when I plot them, my two series dont al...
You could use `Series.reindex`: ``` import pandas as pd idx = pd.date_range('09-01-2013', '09-30-2013') s = pd.Series({'09-02-2013': 2, '09-03-2013': 10, '09-06-2013': 5, '09-07-2013': 1}) s.index = pd.DatetimeIndex(s.index) s = s.reindex(idx, fill_value=0) print(s) ``` ...
Access a function variable outside the function without using `global`
19,326,004
8
2013-10-11T19:43:09Z
19,327,712
22
2013-10-11T21:42:39Z
[ "python", "local-variables" ]
I am trying to access a local function variable outside the function in Python. So, for example, ``` bye = '' def hi(): global bye something something bye = 5 sigh = 10 hi() print bye ``` The above works fine as it should. Since I want to find out if I can access `bye` outside `hi()` without usin...
You could do something along this lines: ``` def hi(): # something # something hi.bye = 5 sigh = 10 hi() print hi.bye ``` Functions are objects in Python and can have arbitrary attributes assigned to them.
Python except None
19,327,320
7
2013-10-11T21:10:23Z
19,327,342
7
2013-10-11T21:12:12Z
[ "python" ]
Are there any unexpected side effects of using "except None"? The behavior I expect is that nothing will be caught by that clause which a few small tests seem to confirm. Here is a rough outline of what I am trying to do. When no argument is provided to the function, exceptions=None which creates the "except None" cla...
Works fine here (under Python 2.x). ``` >>> try: ... foo ... except None as e: ... pass ... Traceback (most recent call last): File "<stdin>", line 2, in <module> NameError: name 'foo' is not defined ``` > For an except clause with an expression, that expression is evaluated, and the clause matches the excepti...
How to cache a Django Model in Memory
19,328,172
3
2013-10-11T22:22:33Z
19,328,863
7
2013-10-11T23:44:21Z
[ "python", "django", "caching", "django-models" ]
i have a Model in my app, that is used so much in my application, some views made something like 100 queries in that Table, I already have a tons of optimisations to make a better use of this Model, but the great part of that amount is caused by the Django **init** method of other classes, for personal reasons... So ac...
You can use [Django's provided caching](https://docs.djangoproject.com/en/dev/topics/cache/#the-low-level-cache-api). [This answer](http://stackoverflow.com/questions/4631865/caching-query-results-in-django/4632043#4632043) to a very similar question gets you on the right track.
Python - read text file with weird utf-16 format
19,328,874
3
2013-10-11T23:45:21Z
19,328,914
7
2013-10-11T23:50:06Z
[ "python", "numpy", "encoding", "utf-16le" ]
I'm trying to read a text file into python, but it seems to use some very strange encoding. I try the usual: ``` file = open('data.txt','r') lines = file.readlines() for line in lines[0:1]: print line, print line.split() ``` Output: ``` 0.0200197 1.97691e-005 ['0\x00.\x000\x002\x000\x000\x001\x009\x007\...
I'm willing to bet this is a UTF-16-LE file, and you're reading it as whatever your default encoding is. In UTF-16, each character takes two bytes.\* If your characters are all ASCII, this means the UTF-16 encoding looks like the ASCII encoding with an extra '\x00' after each character. To fix this, just decode the d...
Plotting animated quivers in Python
19,329,039
8
2013-10-12T00:11:41Z
19,338,495
9
2013-10-12T19:49:24Z
[ "python", "animation", "matplotlib" ]
I am trying to animate a vector such as wind in Python. I tried to use quiver function in pylab and in combination with matplotlib.animation from matplotlib. However, the result says `'QuiverKey' object is not subscriptable`. I think that it is because I don't understand fully about these two functions or just these tw...
Here's an example to get you started: ``` import numpy as np from matplotlib import pyplot as plt from matplotlib import animation X, Y = np.mgrid[:2*np.pi:0.2,:2*np.pi:0.2] U = np.cos(X) V = np.sin(Y) fig, ax = plt.subplots(1,1) Q = ax.quiver(X, Y, U, V, pivot='mid', color='r', units='inches') ax.set_xlim(-1, 7) a...
interactive shell debugging with pycharm
19,329,601
34
2013-10-12T01:49:02Z
19,346,029
8
2013-10-13T13:56:59Z
[ "python", "pycharm", "python-idle" ]
I am new in pycharm. I have been using IDLE for a long time. It is very convenient to use python objects after script execution in IDLE. Is there any way to use script objects after its execution with interactive python shell using pycharm? For example, we have got a 'test' project with one file 'test.py': ``` a = '...
You can simply use the Python Console inside both PyCharm 2 and PyCharm 3. And you can simply import since your project root is already added to your `PYTHONPATH`: So let me demonstrate through some screen shots: # 1. Making a `console.py` file in root directory ![enter image description here](http://i.stack.imgur.c...
interactive shell debugging with pycharm
19,329,601
34
2013-10-12T01:49:02Z
20,595,435
13
2013-12-15T14:10:28Z
[ "python", "pycharm", "python-idle" ]
I am new in pycharm. I have been using IDLE for a long time. It is very convenient to use python objects after script execution in IDLE. Is there any way to use script objects after its execution with interactive python shell using pycharm? For example, we have got a 'test' project with one file 'test.py': ``` a = '...
I found to previous answers from Piga-fetta, Games Brainiac and kobejohn ***useful, but not satisfying***. So I here provide a third option: **Loading selected code into the console** (my suggestion) Use `Shift` + `Alt` + `E` to load the selected code or the line in which the cursor is placed into the console and imm...
interactive shell debugging with pycharm
19,329,601
34
2013-10-12T01:49:02Z
22,894,745
49
2014-04-06T13:34:20Z
[ "python", "pycharm", "python-idle" ]
I am new in pycharm. I have been using IDLE for a long time. It is very convenient to use python objects after script execution in IDLE. Is there any way to use script objects after its execution with interactive python shell using pycharm? For example, we have got a 'test' project with one file 'test.py': ``` a = '...
It is already there. Just not very obvious how to enable it. 1. Set a breakpoint in your code and launch debug. 2. When the breakpoint is reached, click the *Console* tab, and then click the **Show command line** icon (see screenshot). This will enable a python shell (notice the green `>>>` on the screenshot) where y...
Extract historic leap seconds from tzdata
19,332,902
19
2013-10-12T09:58:01Z
19,647,860
10
2013-10-29T01:02:55Z
[ "python", "datetime", "astronomy", "tzinfo", "leap-second" ]
Is there a way to extract the moment of historic leap seconds from the time-zone database that is distributed on most linux distributions? I am looking for a solution in python, but anything that works on the command line would be fine too. My use case is to convert between gps-time (which is basically the number of s...
I just did `man 5 tzfile` and computed an offset that would find the leap seconds info, then read the leap seconds info. You can uncomment the "DEBUG:" print statements to see more of what it finds in the file. EDIT: program updated to now be correct. It now uses the file `/usr/share/zoneinfo/right/UTC` and it now fi...
In Python, what does '<function at ...>' mean?
19,333,598
2
2013-10-12T11:23:06Z
19,333,628
7
2013-10-12T11:25:29Z
[ "python", "function", "memory-address", "repr" ]
What does `<function at 'somewhere'>` mean? Example: ``` >>> def main(): ... pass ... >>> main <function main at 0x7f95cf42f320> ``` And maybe there is a way to somehow access it using **`0x7f95cf42f320`**?
You are looking at the default representation of a function object. It provides you with a name and a unique id, which in CPython *happens* to be a memory address. You cannot access it using the address; the memory address is only used to help you distinguish between function objects. In other words, if you have *two...
Python - converting a string of numbers into a list of int
19,334,374
4
2013-10-12T12:50:30Z
19,334,399
20
2013-10-12T12:52:46Z
[ "python", "string", "list", "integer" ]
I have a string of numbers, something like: ``` example_string = '0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11' ``` I would like to convert this into a list: ``` example_list = [0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11] ``` I tried something like ``` for i in example string: exa...
Split on commas, then map to integers: ``` map(int, example_string.split(',')) ``` Or use a list comprehension: ``` [int(s) for s in example_string.split(',')] ``` The latter works better on Python 3 if you want a list result. This works because `int()` tolerates whitespace: ``` >>> example_string = '0, 0, 0, 11,...
Creating seed data in a flask-migrate or alembic migration
19,334,604
18
2013-10-12T13:15:08Z
19,337,737
19
2013-10-12T18:33:35Z
[ "python", "flask", "flask-sqlalchemy", "alembic", "flask-migrate" ]
How can I insert some seed data in my first migration? If the migration is not the best place for this, then what is the best practice? ``` """empty message Revision ID: 384cfaaaa0be Revises: None Create Date: 2013-10-11 16:36:34.696069 """ # revision identifiers, used by Alembic. revision = '384cfaaaa0be' down_rev...
Migrations should be limited to schema changes only, and not only that, it is important that when a migration up or down is applied that data that existed in the database from before is preserved as much as possible. Inserting seed data as part of a migration may mess up pre-existing data. As most things with Flask, y...
Creating seed data in a flask-migrate or alembic migration
19,334,604
18
2013-10-12T13:15:08Z
19,338,319
32
2013-10-12T19:30:50Z
[ "python", "flask", "flask-sqlalchemy", "alembic", "flask-migrate" ]
How can I insert some seed data in my first migration? If the migration is not the best place for this, then what is the best practice? ``` """empty message Revision ID: 384cfaaaa0be Revises: None Create Date: 2013-10-11 16:36:34.696069 """ # revision identifiers, used by Alembic. revision = '384cfaaaa0be' down_rev...
Alembic has, as one of its operation, [`bulk_insert()`](http://alembic.zzzcomputing.com/en/latest/ops.html?highlight=insert#alembic.operations.Operations.bulk_insert). The documentation gives the following example (with some fixes I've included): ``` from datetime import date from sqlalchemy.sql import table, column f...
Cross Validation and Grid Search
19,335,165
7
2013-10-12T14:17:08Z
19,338,764
20
2013-10-12T20:15:21Z
[ "python", "classification", "scikit-learn", "cross-validation" ]
Is there someone who can explain me in really simple words what's the difference between cross validation and grid search?! How does it work and should i do first a cross valdiation and then a grid search?! my question cames by reading this doc [sklearn](http://scikit-learn.org/dev/auto_examples/grid_search_digits.ht...
Cross-validation is when you reserve part of your data to use in evaluating your model. There are different cross-validation methods. The simplest conceptually is to just take 70% (just making up a number here, it doesn't have to be 70%) of your data and use that for training, and then use the remaining 30% of the data...
Django: Reverse for 'detail' with arguments '('',)' and keyword arguments '{}' not found
19,336,076
6
2013-10-12T15:44:23Z
19,336,837
9
2013-10-12T17:01:02Z
[ "python", "django", "django-templates", "django-views" ]
I'm following the official tutorial to learn Django and using 1.5. I had this link as part of my index template, which was working fine: ``` <li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li> ``` however, this is hardcoded and the tutorial suggested a better way was to use: ``` <li><a href="{% url 'de...
In your `index.html` you gave `poll_id` as an argument, but that's just the name the argument will have within the `detail` function; it is not defined in your template. The actual value you want to call the function with is probably `poll.id`.
Using Sci-Kit learn to classify text with a large corpus
19,336,497
6
2013-10-12T16:21:35Z
19,361,467
8
2013-10-14T13:33:50Z
[ "python", "classification", "scikit-learn" ]
I have about 1600 articles in my database, with each article already pre-labeled with one of the following categories: ``` Technology Science Business World Health Entertainment Sports ``` I am trying to use sci-kit learn to build a classifier that would categorize new articles. (I guess i'll split my training data i...
I think you faced the same problem I did when I started to feed my own data to the classifiers. You can use the function `sklearn.datasets.load_files`, but to do so, you need to create this structure: ``` train ├── science │   ├── 0001.txt │   └── 0002.txt └── technology ├── ...
Post tweet with tweepy
19,337,672
3
2013-10-12T18:25:04Z
19,337,759
8
2013-10-12T18:35:36Z
[ "python", "twitter", "tweepy", "tweets" ]
I'm trying to post a tweet with the tweepy library. I use this code: ``` import tweepy CONSUMER_KEY ="XXXX" CONSUMER_SECRET = "XXXX" ACCESS_KEY = "XXXX" ACCESS_SECRET = "XXXX" auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_KEY, ACCESS_SECRET) api = tweepy.API(auth) api...
In the application's settings, set your Application Type to "Read and Write". Then renegotiate your access token.
How to find possible English words in long random string?
19,338,113
2
2013-10-12T19:10:42Z
19,338,766
7
2013-10-12T20:15:34Z
[ "python", "dictionary", "information-retrieval", "trie" ]
I'm doing an artistic project where I want to see if any information emerges from a long string of characters (~28,000). It's sort of like the problem one faces in solving a Jumble. Here's a snippet: > jfifddcceaqaqbrcbdrstcaqaqbrcrisaxohvaefqiygjqotdimwczyiuzajrizbysuyuiathrevwdjxbinwajfgvlxvdpdckszkcyrlliqxsdpunnvme...
I used this solution to find all words forwards and backwards from a corpus of 28,000 random characters in a dictionary of 100,000 words in .5 seconds. It runs in O(n) time. It takes a file called "words.txt" which is a dictionary that has words separated by some kind of whitespace. I used the default unix wordlist in ...
How to fix a : TypeError 'tuple' object does not support item assignment
19,338,209
3
2013-10-12T19:19:57Z
19,338,259
12
2013-10-12T19:24:35Z
[ "python", "pygame" ]
The following fragment of code from this tutorial: <http://www.raywenderlich.com/24252/beginning-game-programming-for-teens-with-python> ``` for badguy in badguys: if badguy[0]<-64: badguys.pop(index) badguy[0]-=7 index+=1 for badguy in badguys: screen.blit(badguyimg, ba...
Change this ``` badguy[0]-=7 ``` into this ``` badguy = list(badguy) badguy[0]-=7 badguy = tuple(badguy) ``` Alternatively, if you can leave `badguy` as a `list`, then don't even use tuples and you'll be fine with your current code (with the added change of using lists instead of tuples)
Python function to get the t-statistic
19,339,305
5
2013-10-12T21:18:44Z
19,339,372
9
2013-10-12T21:27:50Z
[ "python", "python-2.7", "statistics", "confidence-interval" ]
I am looking for a Python function (or to write my own if there is not one) to get the t-statistic in order to use in a confidence interval calculation. I have found tables that give answers for various probabilities / degrees of freedom like [this one](http://www.sussex.ac.uk/Users/grahamh/RM1web/t-testcriticalvalues...
Have you tried scipy? You will need to installl the scipy library...more about installing it here: <http://www.scipy.org/install.html> Once installed, you can replicate the Excel functionality like such: ``` from scipy import stats #Studnt, n=999, p<0.05, 2-tail #equivalent to Excel TINV(0.05,999) print stats.t.ppf(...
Find all products produced by 2 unique elements of an array (python)
19,341,265
4
2013-10-13T02:38:41Z
19,341,281
8
2013-10-13T02:40:37Z
[ "python", "arrays", "loops" ]
How do you determine the product/sum/difference/division of all the numbers in an array in python? For example for multiplication: ``` array=[1,2,3,4] ``` output will just be 1\*2, 1\*3, 1\*4, 2\*3, 2\*4, 3\*4: ``` [2,3,4,6,8,12] ``` I understand how "for" and "while" loops work but have been unable to figure out t...
Use [`itertools.combinations`](http://docs.python.org/2/library/itertools.html#itertools.combinations): ``` >>> from itertools import combinations >>> array = [1, 2, 3, 4] >>> [i * j for i, j in combinations(array, 2)] [2, 3, 4, 6, 8, 12] ```
Get HTTP Error code from requests.exceptions.HTTPError
19,342,111
13
2013-10-13T05:17:43Z
19,343,099
24
2013-10-13T08:10:15Z
[ "python", "http", "exception", "python-requests" ]
I am catching exceptions like this, ``` def get_url_fp(image_url, request_kwargs=None): response = requests.get(some_url, **request_kwargs) response.raise_for_status() return response.raw try: a = "http://example.com" fp = get_url_fp(a) except HTTPError as e: # Need to check its an 404, 503, 5...
The `HTTPError` carries the `Response` object with it: ``` def get_url_fp(image_url, request_kwargs=None): response = requests.get(some_url, **request_kwargs) response.raise_for_status() return response.raw try: a = "http://example.com" fp = get_url_fp(a) except HTTPError as e: # Need to che...
ord() and Unicode Table don't give the same number
19,342,115
4
2013-10-13T05:17:59Z
19,342,124
9
2013-10-13T05:19:18Z
[ "python" ]
According to the Python documentation, ord() gives the corresponding number in Unicode. When I entered ``` ord('A') ``` I got the number 65. However, when I checked the Unicode number for 'A' in the site called Unicode Table (<http://unicode-table.com/en>), it says the number is 41. Why is that happening? What is th...
"41" is in hexadecimal. ``` >>> ord("A") 65 >>> hex(ord("A")) '0x41' >>> int("41",base=16) 65 ``` Note that along the top of the page you linked, you see `0123456789ABCDEF`, which is giving you the last digit.
Django:No module named django.core.management
19,342,896
7
2013-10-13T07:36:32Z
19,342,951
7
2013-10-13T07:45:59Z
[ "python", "django" ]
I am a Django newbie and want to explore the power of this famous framework. After all setups I ran `sudo python manage.py syncdb`, and I get this error ``` Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line ImportError: No mo...
This first line its probably making it use your python from `/usr/bin/env`. You could try two things in this case: 1) If you didn't already, you should activate your virtualenv and then install Django: ``` source /home/myname/Envs/EnvName/bin/activate pip install django ``` 2) Remove first line of manage.py which I...
Pythonic alternatives to if/else statements
19,343,433
4
2013-10-13T08:56:58Z
19,343,446
11
2013-10-13T08:58:36Z
[ "python", "optimization", "if-statement", "data-structures" ]
I'm trying to avoid a complex web of if/elif/else statements. What pythonic approaches can I use to accomplish my goal. Here's what I want to achieve: My script will receive a slew of different urls, youtube.com, hulu.com, netflix.com, instagram.com, imgur.com, etc, etc possibly 1000s of different domains. I will ...
Use a dispatch dictionary mapping domain to function: ``` def default_handler(parsed_url): pass def youtube_handler(parsed_url): pass def hulu_handler(parsed_url): pass handlers = { 'www.youtube.com': youtube_handler, 'hulu.com': hulu_handler, } handler = handlers.get(urlParsed.netloc, d...
Problems with a shared mutable?
19,343,752
4
2013-10-13T09:36:55Z
19,343,762
9
2013-10-13T09:38:39Z
[ "python" ]
``` def set_if_not_there(d, fields, default_value=None): for field in fields: if not field in d: d[field] = default_value d = { } set_if_not_there(d, ['cnt1', 'cnt2'], 0) set_if_not_there(d, ['tags1', 'tags2'], []) d['cnt1'] += 1 d['tags1'].append('work') print d ``` The output is: ``` {'t...
Use a factory function instead of a default value: ``` def set_if_not_there(d, fields, default_factory=None): if default_factory is None: default_factory = lambda: None for field in fields: if not field in d: d[field] = default_factory() ``` and pass in callables (like functions or...
Python - Syntax error on colon in list
19,344,255
3
2013-10-13T10:41:54Z
19,344,276
7
2013-10-13T10:44:22Z
[ "python", "list", "syntax" ]
I've been trying to create a simple dictionary to define a word that the user inputs. After defining the dictionary and it's words, I'm trying to print the definition of the input'd word. For some reason, when I try to run this program there is a syntax error on the colon in the list. I'm not sure how to fix this probl...
You forgot a comma at the end of each entry in the dict. Dicts use curly braces "`{...}`" ``` dic1 = { 'bug':'A broken piece of code that causes a program to stop functioning', 'string':'A piece of text', 'integer':'A whole number', 'float':'A decimal number', 'function':'A block of organized and c...
Project Euler getting smallest multiple in python
19,348,430
2
2013-10-13T18:01:36Z
19,361,072
15
2013-10-14T13:12:39Z
[ "python", "algorithm" ]
I am doing problem five in Project Euler: "2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?" I have constructed the following code which finds the correct value 2...
If a problem is hard, trying solving a simpler version. Here, how to calculate the lowest common multiple of *two* numbers. If you've read any number theory book (or think about prime factors), you can do that using the greatest common divisor function (as implemented by the Euclidean algorithm). ``` from fractions im...
How to pad with zeros a tensor along some axis (Python)
19,349,410
7
2013-10-13T19:38:15Z
19,350,072
15
2013-10-13T20:42:45Z
[ "python", "numpy", "multidimensional-array" ]
I would like to pad a numpy tensor with 0 along the chosen axis. For instance, I have tensor `r` with shape `(4,3,2)` but I am only interested in padding only the last two axis (that is, pad only the matrix). Is it possible to do it with the one-line python code?
You can use [`np.pad()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.pad.html): ``` a = np.ones((4,3,2)) # npad is a tuple of (n_before, n_after) for each dimension npad = ((0,0), (1,2), (2,1)) b = np.pad(a, pad_width=npad, mode='constant', constant_values=0) print b # [[[ 0. 0. 0. 0. 0.] # [ 0. ...
What’s the difference between a project and an app in Django world?
19,350,785
13
2013-10-13T22:00:06Z
19,351,042
16
2013-10-13T22:29:01Z
[ "python", "django" ]
I am creating my first real website using Django but I am still struggling to understand the diff between a project and an app. For example, My website is a sports news website which will contain sections like articles, ranking tables and "fixtures and results", my question is should each one of these sections be in a...
A *project* refers to the entire application and all its parts. An *app* refers to a submodule of the application. It's, hopefully, self-contained and not intertwined with other apps in the project so that, in theory, you could pick it up and plop it down into another project without much, or any, modification. An *ap...
How is the Python grammar used internally?
19,351,065
10
2013-10-13T22:31:35Z
20,835,683
9
2013-12-30T08:03:12Z
[ "python", "python-3.x", "grammar", "language-design" ]
I'm trying to get a deeper understanding of how Python works, and I've been looking at the grammar shown at <http://docs.python.org/3.3/reference/grammar.html>. I notice it says you would have to change parsermodule.c also, but truthfully I'm just not following what's going on here. I understand that a grammar is a s...
A grammar is used to describe all possible strings in a language. It is also useful in specifying how a parser should parse the language. In this grammar it seems like they are using their own version of [EBNF](http://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_Form), where a non-terminal is any lowercase word ...
Read file with "variable=value" (Windows INI) format?
19,351,262
4
2013-10-13T22:53:57Z
19,351,277
10
2013-10-13T22:56:14Z
[ "python", "file" ]
I'm learning Python and as a starter developer I have few questions. I need read a file that have this format: ``` # This is the text file [label1] method=auto [label2] variable1=value1 variable2=ae56d491-3847-4185-97a0-36063d53ff2c variable3=value3 ``` Now I have the following code: ``` # This is the Python file ...
Use the [`configparser` module](http://docs.python.org/2/library/configparser.html) to handle this instead. That module parses this file format ( called the Windows INI format ) directly. ``` try: # Python 3 from configparser import ConfigParser except ImportError: # Python 2 from ConfigParser import C...
Embed Plotly graph into a webpage with Bottle
19,356,920
9
2013-10-14T09:11:42Z
19,797,851
10
2013-11-05T20:02:43Z
[ "python", "bottle", "plotly" ]
Hi i am using plotly to generate graphs using Python, Bottle. However, this returns me a url. Like: ``` https://plot.ly/~abhishek.mitra.963/1 ``` I want to paste the entire graph into my webpage instead of providing a link. Is this possible? My code is: ``` import os from bottle import run, template, get, post, req...
Yes, embedding is possible. Here's an iframe snippet you can use (with any Plotly URL): `<iframe width="800" height="600" frameborder="0" seamless="seamless" scrolling="no" src="https://plot.ly/~abhishek.mitra.963/1/.embed?width=800&height=600"></iframe>` The plot gets embedded at a URL that is made especially for em...
ConfigParser reads capital keys and make them lower case
19,359,556
28
2013-10-14T11:48:14Z
19,359,720
53
2013-10-14T11:57:09Z
[ "python", "python-2.7" ]
I found one interesting observation. I had written one config file read program as, ``` import ConfigParser class ConfReader(object): ConfMap = dict() def __init__(self): self.config = ConfigParser.ConfigParser() self.config.read('./Config.ini') self.__loadConfigMap() def __loadC...
`ConfigParser.ConfigParser()` is a subclass of [`ConfigParser.RawConfigParser()`](http://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser), which is documented to behave this way: > All option names are passed through the `optionxform()` method. Its default implementation converts option names ...
get_or_create throws Integrity Error
19,362,085
5
2013-10-14T14:04:02Z
19,362,177
15
2013-10-14T14:08:50Z
[ "python", "django", "django-forms" ]
Given that the whole point of object.get\_or\_create() is to get the object if it already exists, I fail to see why it's throwing an integrity error for this code: ``` class UserAdd(TemplateView): def post(self, request, *args, **kwargs): context = self.get_context_data(*args, **kwargs) form = UserAddForm(req...
The parameters sent into the `get_or_create` method need to match exactly, or django's ORM would try to create a new object, and since a primary key/unique column constraint would be violated, you are getting the error. Try this: ``` if form.is_valid(): first_name = form.cleaned_data['first_name'] last_name =...
My code nests too deep. Is there a better way?
19,363,527
6
2013-10-14T15:17:37Z
19,363,554
10
2013-10-14T15:19:00Z
[ "python" ]
This particular code I wrote in another question recently, and I'm not sure it's optimal. I couldn't find a less-indented way of doing this though. Is there? ``` def msg_generator(self): ''' Provides messages until bot dies ''' while self.alive: for msg in self.irc.recv(self.buffer).split(('\r\n').enco...
Off the top of my head, you can do this: ``` def msg_generator(self): ''' Provides messages until bot dies ''' while self.alive: for msg in self.irc.recv(self.buffer).split(('\r\n').encode()): if len(msg) <= 3: continue try: yield Message(msg.d...
Replace None value in list?
19,363,881
9
2013-10-14T15:36:02Z
19,363,894
22
2013-10-14T15:36:41Z
[ "python", "list", "replace" ]
I have: ``` d = [1,'q','3', None, 'temp'] ``` I want to replace None value to 'None' or any string expected effect: ``` d = [1,'q','3', 'None', 'temp'] ``` a try replace in string and for loop but I get error: ``` TypeError: expected a character buffer object ```
Use a simple list comprehension: ``` ['None' if v is None else v for v in d] ``` Demo: ``` >>> d = [1,'q','3', None, 'temp'] >>> ['None' if v is None else v for v in d] [1, 'q', '3', 'None', 'temp'] ``` Note the `is None` test to match the `None` singleton.
Python function to check for palindrome
19,365,008
2
2013-10-14T16:41:18Z
19,365,056
15
2013-10-14T16:43:53Z
[ "python", "palindrome" ]
Given below is the code to check if a list is a palindrome or not. It is giving correct output for 983. Where am I going wrong? ``` def palindrome(num): flag=0 r=num[::-1] for i in range (0, len(num)-1): if(r[i]==num[i]): flag=1 else: flag=0 return flag ```
You should return as soon as there is a mismatch. Also, you just need to iterate till half the length: ``` def function(...): ... for i in range (0, (len(num) + 1) / 2): if r[i] != num[i]: return False return True ``` --- BTW, you don't need that loop. You can simply do: ``` def pali...
PostgreSQL TypeError: not all arguments converted during string formatting
19,365,072
4
2013-10-14T16:45:10Z
19,365,362
8
2013-10-14T17:01:05Z
[ "python", "postgresql", "psycopg2" ]
I am executing a query in psycopg2 linked up to a PostgreSQL database. Here is the code in question: ``` with open('dataFile.txt', 'r') as f: lines = f.readlines() newLines = [line[:-1] for line in lines] curr=conn.cursor() lineString = ','.join(newLines) curr.execute("SELECT fields.fieldkey FROM f...
There must be a comma after `lines[0]` to make that a tuple. ``` curr.execute(""" SELECT fields.fieldkey FROM fields LEFT JOIN zone ON zone.fieldkey=fields.fieldkey WHERE zone.zonekey = %s; """, (lines[0],)) ``` Since the [`execute` method is expecting a sequence (or a mapping)](http://initd.org/psyco...
When is semicolon use in Python considered "good" or "acceptable"?
19,365,508
17
2013-10-14T17:09:26Z
19,366,094
9
2013-10-14T17:50:23Z
[ "python" ]
Python is a "whitespace delimited" language. However, the use of semicolons *are* allowed. For example, the following works but is frowned upon: ``` print "Hello!"; print "This is valid"; ``` I've been using python for several years now, and the only time I have ever used semicolons is in generating one-time command-...
[PEP 8](http://www.python.org/dev/peps/pep-0008/#other-recommendations) is the official style guide and says: > Compound statements (multiple statements on the same line) are generally discouraged. (See also the examples just after this in the PEP.) While I don't agree with everything PEP 8 says, if you're looking f...
How to add an extra row to a pandas dataframe
19,365,513
13
2013-10-14T17:09:43Z
19,368,360
22
2013-10-14T20:04:58Z
[ "python", "pandas" ]
If I have an empty dataframe as such: ``` columns = ['Date', 'Name', 'Action','ID'] df = pd.DataFrame(columns=columns) ``` is there a way to append a new row to this newly created dataframe? Currently I have to create a dictionary, populate it, then append the dictionary to the dataframe at the end. Is there a more d...
Upcoming pandas 0.13 version will allow to add rows through `loc` on non existing index data. Description is [here](http://pandas.pydata.org/pandas-docs/stable/indexing.html#setting-with-enlargement) and this new feature is called *Setting With Enlargement*.
How to add an extra row to a pandas dataframe
19,365,513
13
2013-10-14T17:09:43Z
25,376,997
22
2014-08-19T06:33:20Z
[ "python", "pandas" ]
If I have an empty dataframe as such: ``` columns = ['Date', 'Name', 'Action','ID'] df = pd.DataFrame(columns=columns) ``` is there a way to append a new row to this newly created dataframe? Currently I have to create a dictionary, populate it, then append the dictionary to the dataframe at the end. Is there a more d...
``` df.loc[len(df)]=['8/19/2014','Jun','Fly','98765'] ``` Try this
Set partitions in Python
19,368,375
9
2013-10-14T20:05:46Z
19,369,410
8
2013-10-14T21:13:19Z
[ "python", "arrays", "combinatorics" ]
I have an array of `[1,2,3]` I want to make all the possible combinations using all elements of the array: Result: ``` [[1], [2], [3]] [[1,2], [3]] [[1], [2,3]] [[1,3], [2]] [[1,2,3]] ```
Unlike my comments suggested, I was unable to quickly find an itertools based relatively fast solution! Edit: this is no longer quite true, I have a fairly short (but slow and unreadable) solution using itertools largely, see the end of the answer. This is what I got instead: The idea is that we find all the combinati...
Set partitions in Python
19,368,375
9
2013-10-14T20:05:46Z
30,134,039
11
2015-05-08T22:58:01Z
[ "python", "arrays", "combinatorics" ]
I have an array of `[1,2,3]` I want to make all the possible combinations using all elements of the array: Result: ``` [[1], [2], [3]] [[1,2], [3]] [[1], [2,3]] [[1,3], [2]] [[1,2,3]] ```
Since this nice question has been brought back to life, here's a fresh answer. The problem is solved recursively: If you already have a partition of *n-1* elements, how do you use it to partition *n* elements? Either place the *n*'th element in one of the existing subsets, or add it as a new, singleton subset. That's ...
Django + uwsgi + nginx . Import error: No module named py
19,368,606
4
2013-10-14T20:20:17Z
19,368,656
7
2013-10-14T20:23:44Z
[ "python", "django", "nginx" ]
I am trying to run my sample django application using uWSGI and nginx. But I am getting import error, no module named py. I am not sure where should I add the python path. I am running with the following command. ``` sudo uwsgi --socket mysite.socket --module wsgi.py --chmod-socket=666. ``` I even tried passing path...
The `--module` argument is presumably meant to be a Python module, not a file. So you probably just need `--module=wsgi`.
How to make a Button using the tkinter Canvas widget?
19,369,391
5
2013-10-14T21:11:55Z
19,369,991
9
2013-10-14T22:00:15Z
[ "python", "button", "tkinter", "tkinter-canvas" ]
I want to obtain a button out of a Canvas. I've tried to `pack` the canvas in the button widget, but that didn't work. Googling a bit, I've found (here: [How do you create a Button on a tkinter Canvas?](http://stackoverflow.com/questions/11980812/how-do-you-create-a-button-on-a-tkinter-canvas)) that the Canvas method `...
Tkinter doesn't allow you to directly draw on widgets other than the canvas, and canvas drawings will always be below embedded widgets. The simple solution is to create the effect of a button using just the canvas. There's really nothing special about doing this: just create a canvas, then add bindings for ButtonPress...
The right way to limit maximum number of threads running at once?
19,369,724
9
2013-10-14T21:37:44Z
19,369,877
11
2013-10-14T21:50:36Z
[ "python", "multithreading", "python-multithreading" ]
I'd like to create a program that runs multiple light threads, but limits itself to a constant, predefined number of concurrent running tasks, like this (but with no risk of race condition): ``` import threading def f(arg): global running running += 1 print("Spawned a thread. running=%s, arg=%s" % (runnin...
It sounds like you want to implement the producer/consumer pattern with eight workers. Python has a [`Queue`](http://docs.python.org/2/library/queue.html) class for this purpose, and it is thread-safe. Each worker should call `get()` on the queue to retrieve a task. This call will block if no tasks are available, caus...
O(n) Java algorithm to find odd-number-out in array (not odd numbers)
19,370,236
12
2013-10-14T22:20:59Z
19,370,315
15
2013-10-14T22:27:35Z
[ "java", "python", "arrays", "algorithm", "big-o" ]
I'm having a great deal of trouble trying to figure this question out, and the root of that trouble is creating an algorithm of `O(n)` complexity. Here's the question I'm struggling with: > An Array `A` of length `n` contains integers from the range `[0, .., n - 1]`. However, it only contains `n - 1` distinct numbers....
Iterate over the array twice: That is still O(n). Create a temporary array of booleans (or a Java BitSet) to hold which numbers you got. Second time you do the loop, check if there is a hole in the array of booleans.
O(n) Java algorithm to find odd-number-out in array (not odd numbers)
19,370,236
12
2013-10-14T22:20:59Z
19,370,421
32
2013-10-14T22:39:03Z
[ "java", "python", "arrays", "algorithm", "big-o" ]
I'm having a great deal of trouble trying to figure this question out, and the root of that trouble is creating an algorithm of `O(n)` complexity. Here's the question I'm struggling with: > An Array `A` of length `n` contains integers from the range `[0, .., n - 1]`. However, it only contains `n - 1` distinct numbers....
Suppose the number missing is `x` and the duplicate is `y`. If you add all numbers, the sum will be: ``` (n - 1) * n / 2 - x + y ``` From the above, you can find `(x - y)`.....(1) Similarly, sum the squares of the numbers. The sum will then be: > `(n - 1) * n * (2 * n - 1) / 6 - x2 + y2` From the above you get `(x...
Get Errno from Python Requests ConnectionError?
19,370,436
6
2013-10-14T22:40:41Z
19,370,547
18
2013-10-14T22:53:10Z
[ "python", "python-2.7", "exception-handling", "python-requests", "errno" ]
I'm catching and printing Python Requests ConnectionErrors fine with just this: ``` except requests.exceptions.ConnectionError as e: logger.warning(str(e.message)) ``` It prints out messages such as: ``` HTTPSConnectionPool(host='10.100.24.16', port=443): Max retries exceeded with url: /api/datastores/06651841-b...
I think you can access it using `e.args[0].reason.errno`. This is probably documented somewhere, but usually when I have to track down something like this I just try it at the console and dig around a little bit. (I use IPython so it's easy to do tab-inspection, but let's try it without). First, let's generate an err...
Python, TypeError: unhashable type: 'list'
19,371,358
14
2013-10-15T00:19:00Z
19,371,472
52
2013-10-15T00:33:22Z
[ "python", "python-3.x" ]
i'm reciving the following error in my program: Traceback: ``` Traceback (most recent call last): File "C:\Python33\Archive\PythonGrafos\Alpha.py", line 126, in <module> menugrafos() File "C:\Python33\Archive\PythonGrafos\Alpha.py", line 97, in menugrafos zetta = Beta.caminhografo(grafo,va,vb) File "C:\Python33\Archiv...
The problem is that you can't use a `list` as the key in a `dict`, since `dict` keys need to be immutable. Use a tuple instead. This is a list: ``` [x, y] ``` This is a tuple: ``` (x, y) ``` Note that in most cases, the `(` and `)` are optional, since `,` is what actually defines a tuple (as long as it's not surro...
python if elif else statement
19,371,643
8
2013-10-15T00:56:12Z
19,371,662
10
2013-10-15T00:59:06Z
[ "python", "if-statement", "nested" ]
I'm trying to create a program with python that calculate the cost for shipping. However, I can't run the program to where it works properly. What ever my total is the same amount comes out as $6 for US and $8 for Canada. I can't seem to get pass that. ``` total = raw_input('What is the total amount for your online ...
You can't compare Strings numerically. Instead convert to an int first and then compare. For example: ``` if int(total) < 50 ``` Variables to avoid duplication would help too.
python if elif else statement
19,371,643
8
2013-10-15T00:56:12Z
19,371,678
8
2013-10-15T01:00:35Z
[ "python", "if-statement", "nested" ]
I'm trying to create a program with python that calculate the cost for shipping. However, I can't run the program to where it works properly. What ever my total is the same amount comes out as $6 for US and $8 for Canada. I can't seem to get pass that. ``` total = raw_input('What is the total amount for your online ...
1. you should get integer from raw\_input, not string. use int(). 2. comparison values like 50, 100, 150, ... also should be integer below is fixed code. ``` total = int(raw_input('What is the total amount for your online shopping?')) country = raw_input('Shipping within the US or Canada?') if country == "US": i...
python: Open file from zip without temporary extracting it
19,371,860
17
2013-10-15T01:23:17Z
19,372,080
20
2013-10-15T01:52:20Z
[ "python", "zipfile" ]
How can I open files from a zip archive without extracting them first? I'm using pygame. To save disk space, I have all the images zipped up. Is it possible to load a given image directly from the zip file? For example: `pygame.image.load('zipFile/img_01')`
Vincent Povirk's answer won't work completely; ``` import zipfile archive = zipfile.ZipFile('images.zip', 'r') imgfile = archive.open('img_01.png') ... ``` You have to change it in: ``` import zipfile archive = zipfile.ZipFile('images.zip', 'r') imgdata = archive.read('img_01.png') ... ``` For details read the note...
Converting Unicode string to Chinese characters
19,371,953
2
2013-10-15T01:35:57Z
19,377,995
7
2013-10-15T09:44:20Z
[ "python", "python-2.7", "unicode" ]
How can I convert the following Unicode string to Chinese characters? The string is: ``` '\\u5982\\u679c\\u6211\\u662f\\u4e00\\u4e2a\\u4ece\\u524d\\u7684\\u54f2\\u4eba\\uff0c\\u6765\\u5230\\u4eca\\u5929\\u7684\\u4e16\\u754c\\uff0c\\u6211\\u4f1a\\u6700\\u6000\\u5ff5\\u4ec0\\u4e48\\uff1f' ``` And I want it to be: ```...
Decode it using `unicode-escape` will give you what you want. ## Python 2.7 ``` >>> print '\\u5982\\u679c\\u6211\\u662f\\u4e00\\u4e2a\\u4ece\\u524d\\u7684\\u54f2\\u4eba\\uff0c\\u6765\\u5230\\u4eca\\u5929\\u7684\\u4e16\\u754c\\uff0c\\u6211\\u4f1a\\u6700\\u6000\\u5ff5\\u4ec0\\u4e48\\uff1f'.decode('unicode-escape') 如æ...
Python CSV Module
19,372,111
2
2013-10-15T01:55:20Z
19,372,134
11
2013-10-15T01:57:55Z
[ "python", "csv" ]
I'm using the following code to learn how to read, write and analyze with a CSV file from this website <http://www.whit.com.au/blog/2011/11/reading-and-writing-csv-files/>. However, I get these errors, ``` Traceback (most recent call last): Files "csv_example.py", line 1, in <module? import csv File "C:\python27\csv....
This is a common error. Rename your script from csv.py to something else; it will try to import itself when you do `import csv`.
After passing open call as argument to another function, is the file object closed?
19,372,466
5
2013-10-15T02:44:05Z
19,372,598
7
2013-10-15T03:01:06Z
[ "python" ]
If I want to use a `file` object just once, normally I would still use the `with` block or explicitly close the `file` object when I'm done, because closing a file seems to be the right-thing-to-do: ``` with open('filename','r') as f: x = dosomething(f) ``` or ``` f = open('filename','r') x = dosomething(f) f.cl...
It's a poor practice. It has nothing to do with the open mode (read, write, read+write, append, binary mode, text mode ...). In CPython, "it almost always works" because file objects are automatically closed when they become garbage (unreachable), and CPython's reference counting **usually** collects (non-cyclic) garb...
Consequences of abusing nltk's word_tokenize(sent)
19,373,296
6
2013-10-15T04:27:10Z
19,373,464
7
2013-10-15T04:46:20Z
[ "python", "nltk" ]
I'm attempting to split a paragraph into words. I've got the lovely nltk.tokenize.word\_tokenize(sent) on hand, but help(word\_tokenize) says, "This tokenizer is designed to work on a sentence at a time." Does anyone know what could happen if you use it on a paragraph, i.e. max 5 sentences, instead? I've tried it on a...
`nltk.tokenize.word_tokenize(text)` is simply a thin [wrapper function](http://code.google.com/p/nltk/source/browse/trunk/nltk/nltk/tokenize/__init__.py) that calls the `tokenize` method of an instance of a [TreebankWordTokenizer](http://code.google.com/p/nltk/source/browse/trunk/nltk/nltk/tokenize/treebank.py) class, ...
Assigning a variable NaN in python without numpy
19,374,254
43
2013-10-15T06:02:06Z
19,374,296
56
2013-10-15T06:05:27Z
[ "python", "constants", null ]
Most languages have a NaN constant you can use to assign a variable the value NaN. Can python do this without using numpy?
Yes -- use `float('nan')` or `float('NaN')`. As of Python 3.5, you can also use [`math.nan`](https://docs.python.org/3.5/library/math.html#math.nan). ``` >>> a = float('nan') >>> print(a) nan >>> print(a + 2) nan >>> a == a False >>> import math >>> math.isnan(a) True >>> # Python 3.5+ >>> math.isnan(math.nan) True ``...
Assigning a variable NaN in python without numpy
19,374,254
43
2013-10-15T06:02:06Z
19,374,306
8
2013-10-15T06:05:56Z
[ "python", "constants", null ]
Most languages have a NaN constant you can use to assign a variable the value NaN. Can python do this without using numpy?
``` nan = float('nan') ``` And now you have the constant, `nan`. You can similarly create NaN values for decimal.Decimal.: ``` dnan = Decimal('nan') ```
What are these Python notations: `[ [] ] * n` and `(i,)`
19,375,008
4
2013-10-15T06:57:24Z
19,375,069
10
2013-10-15T07:00:56Z
[ "python", "syntax" ]
Can someone please clarify these 2 notations in Python: * `[ [] ] * n`: apparently this creates n references to the same object (in this case, an empty list). In which situations is this useful? * `(i,)`: I have seen some people use this "trailing comma" notation (example: [Generating all size k subsets of {0, 1, 2, ....
Yes, that does create references to the same object: ``` >>> L = [[]] * 3 >>> L [[], [], []] >>> L[0].append(1) >>> L [[1], [1], [1]] >>> map(id, L) [4299803320, 4299803320, 4299803320] ``` This could be useful for whenever you want to create objects with the same items. --- `(i,)` creates a tuple with the item `i`...
REST API in Google App Engine + Python?
19,375,085
15
2013-10-15T07:01:41Z
19,379,735
11
2013-10-15T11:09:37Z
[ "python", "google-app-engine", "rest", "google-cloud-endpoints" ]
How create a RESTful API using Google App Engine with Python? I've tried using Cloud Endpoints, but the documentation does not focus on a RESTful API. Is there something similar to django-tastypie for GAE?
The RESTful api can be build based on EndPoint API. There are some tools can help you make things easier: appengine rest server (not based on endpoints) > Drop-in server for Google App Engine applications which exposes your data model via a REST API with no extra work. <https://code.google.com/p/appengine-rest-serve...
Is IndentationError a syntax error in Python or not?
19,375,513
3
2013-10-15T07:29:07Z
19,375,533
12
2013-10-15T07:30:37Z
[ "python", "python-3.x", "syntax" ]
I have a simple question, Is `IndentationError` a `SyntaxError` in Python or not? I think it is not but since I am a beginner I would like to be sure. Are syntax errors only those which give me `SyntaxError` as a response in an interpreter? For example, if I type ``` 3f = 22 ``` I get ``` SyntaxError: invalid synt...
``` >>> issubclass(IndentationError, SyntaxError) True ``` It means yes More info [here](http://docs.python.org/3/library/exceptions.html#exception-hierarchy) and [here](http://docs.python.org/3/library/functions.html#issubclass)
Python 2.3 calling super class method
19,375,831
3
2013-10-15T07:47:39Z
19,375,847
15
2013-10-15T07:49:01Z
[ "python", "superclass", "super", "derived-class" ]
having trouble calling base class function in the following `Python 2.3` script. after reviewing this post: [Call a parent class's method from child class in Python?](http://stackoverflow.com/questions/805066/call-a-parent-classs-method-from-child-class-in-python) I've generate this small piece of code: ``` class Ba...
You should give `super` the derived class from which you want to step up, not the base class: ``` super(Derived, self).func() ``` Right now you are trying to access the func method of `Base`'s superclass, which may not even exist.
pip: cert failed, but curl works
19,377,045
22
2013-10-15T08:56:18Z
19,398,611
22
2013-10-16T08:33:04Z
[ "python", "curl", "ssl", "pip" ]
We installed the our root cert on the client, and the https connection works for `curl`. But if we try to use `pip`, it fails: ``` Could not fetch URL https://installserver:40443/pypi/simple/pep8/: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:499: error:14090086:SSL routines:SS...
Unfortunately pip does not use the system certs, but curl does. I found a solution: ``` pip --cert /etc/ssl/certs/FOO_Root_CA.pem install pep8 ``` This is not nice (curl and other libraries find the cert without adding a parameter) but works. If you don't want to use the command line argument, you can set the cert ...
pip: cert failed, but curl works
19,377,045
22
2013-10-15T08:56:18Z
20,874,741
16
2014-01-02T00:32:13Z
[ "python", "curl", "ssl", "pip" ]
We installed the our root cert on the client, and the https connection works for `curl`. But if we try to use `pip`, it fails: ``` Could not fetch URL https://installserver:40443/pypi/simple/pep8/: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:499: error:14090086:SSL routines:SS...
My solution is downloading `cacert.pem` from <http://curl.haxx.se/ca/cacert.pem> and add the path for `cacert.pem` to `~/.pip/pip.conf` as guettli suggested ``` [global] cert = /path/to/cacert.pem ```
How to make a histogram in ipython notebook using ggplot2 (for python)
19,377,371
8
2013-10-15T09:13:04Z
19,665,280
14
2013-10-29T17:32:34Z
[ "python", "ggplot2", "ipython", "ipython-notebook", "python-ggplot" ]
I'm trying to make a histogram of a simple list of numbers in python using [ipython notebook](http://ipython.org/notebook.html) and [ggplot for python](https://pypi.python.org/pypi/ggplot). Using pylab, it's easy enough, but I cannot get ggplot to work. I'm using this code (based on the diamond histogram example, whic...
If you just want to make a histogram of the numbers in your vector 'a', there are a couple of problems. First, ggplot accepts data in the form of a pandas Dataframe, so you need to build that first. ``` import pandas as pd a = [1, 1, 2, 1, 1, 4, 5, 6] df = pd.DataFrame(a, columns=['a']) ``` Second, the geom is `geom...
Combine two columns of text in dataframe in pandas/python
19,377,969
49
2013-10-15T09:42:52Z
19,378,497
50
2013-10-15T10:09:51Z
[ "python", "pandas", "dataframe" ]
I have a 20 x 4000 dataframe in python using pandas. Two of these columns are named Year and quarter. I'd like to create a variable called period that makes Year = 2000 and quarter= q2 into 2000q2 Can anyone help with that?
``` dataframe["period"] = dataframe["Year"].map(str) + dataframe["quarter"] ```
Combine two columns of text in dataframe in pandas/python
19,377,969
49
2013-10-15T09:42:52Z
32,529,152
25
2015-09-11T17:36:18Z
[ "python", "pandas", "dataframe" ]
I have a 20 x 4000 dataframe in python using pandas. Two of these columns are named Year and quarter. I'd like to create a variable called period that makes Year = 2000 and quarter= q2 into 2000q2 Can anyone help with that?
``` df = pd.DataFrame({'Year': ['2014', '2015'], 'quarter': ['q1', 'q2']}) df['period'] = df[['Year', 'quarter']].apply(lambda x: ''.join(x), axis=1) ``` Yields this dataframe ``` Year quarter period 0 2014 q1 2014q1 1 2015 q2 2015q2 ``` This method generalizes to an arbitrary number of string colu...
Combine two columns of text in dataframe in pandas/python
19,377,969
49
2013-10-15T09:42:52Z
35,850,749
16
2016-03-07T18:04:04Z
[ "python", "pandas", "dataframe" ]
I have a 20 x 4000 dataframe in python using pandas. Two of these columns are named Year and quarter. I'd like to create a variable called period that makes Year = 2000 and quarter= q2 into 2000q2 Can anyone help with that?
The method [`cat()` of the `.str` accessor](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.cat.html#pandas.Series.str.cat) works really well for this: ``` >>> import pandas as pd >>> df = pd.DataFrame([["2014", "q1"], ... ["2015", "q3"]], ... columns=('Yea...
Combine two columns of text in dataframe in pandas/python
19,377,969
49
2013-10-15T09:42:52Z
36,911,306
12
2016-04-28T10:02:08Z
[ "python", "pandas", "dataframe" ]
I have a 20 x 4000 dataframe in python using pandas. Two of these columns are named Year and quarter. I'd like to create a variable called period that makes Year = 2000 and quarter= q2 into 2000q2 Can anyone help with that?
yet another ways to do this: ``` df['period'] = df['Year'].astype(str) + df['quarter'] ``` or bit slower: ``` df['period'] = df[['Year','quarter']].astype(str).sum(axis=1) ``` Let's test it on 200K rows DF: ``` In [250]: df Out[250]: Year quarter 0 2014 q1 1 2015 q2 In [251]: df = pd.concat([df] * ...
Python: What's the use case for set.pop()?
19,378,718
4
2013-10-15T10:19:38Z
19,378,876
7
2013-10-15T10:26:45Z
[ "python" ]
The Python built-in type `set` has a method called [pop()](http://docs.python.org/2/library/stdtypes.html#set.pop), from the docs: > Remove and return an arbitrary element from the set. Raises KeyError > if the set is empty. I couldn't think of any use case for this feature, it seems to be an attempt to implement the...
You'd use it when you have a pool of jobs to process in no particular order. Jobs should only be executed once, but once executed can be added again: ``` jobs = set([job1, job2, job3]) while jobs: job = jobs.pop() job.process() ``` where `job.process()` potentially adds more jobs to the pile. Once all jobs h...
How to read a config file using python
19,379,120
8
2013-10-15T10:38:35Z
19,379,306
22
2013-10-15T10:47:47Z
[ "python" ]
I have a config file `abc.txt` which looks somewhat like: ``` path1 = "D:\test1\first" path2 = "D:\test2\second" path3 = "D:\test2\third" ``` I want to read these paths from the `abc.txt` to use it in my program to avoid hard coding.
In order to use my example,Your file "abc.txt" needs to look like: ``` [your-config] path1 = "D:\test1\first" path2 = "D:\test2\second" path3 = "D:\test2\third" ``` Then in your software you can use the config parser: ``` import ConfigParser ``` and then in you code: ``` configParser = ConfigParser.RawConfigParse...
How to read a config file using python
19,379,120
8
2013-10-15T10:38:35Z
19,379,480
7
2013-10-15T10:55:48Z
[ "python" ]
I have a config file `abc.txt` which looks somewhat like: ``` path1 = "D:\test1\first" path2 = "D:\test2\second" path3 = "D:\test2\third" ``` I want to read these paths from the `abc.txt` to use it in my program to avoid hard coding.
You need a section in your file: ``` [My Section] path1 = D:\test1\first path2 = D:\test2\second path3 = D:\test2\third ``` Then, read the properties: ``` import ConfigParser config = ConfigParser.ConfigParser() config.readfp(open(r'abc.txt')) path1 = config.get('My Section', 'path1') path2 = config.get('My Section...