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
How can I remove the ANSI escape sequences from a string in python
14,693,701
23
2013-02-04T19:07:04Z
33,925,425
19
2015-11-25T20:02:03Z
[ "python", "string", "escaping", "ansi-escape" ]
This is my string: ``` 'ls\r\n\x1b[00m\x1b[01;31mexamplefile.zip\x1b[00m\r\n\x1b[01;31m' ``` I was using code to retrieve the output from a SSH command and I want my string to only contain 'examplefile.zip' What I can use to remove the extra escape sequences?
The accepted answer to this question only considers color and font effects. There are a lot of sequences that do not end in 'm', such as cursor positioning, erasing, and scroll regions. The complete regexp for Control Sequences (aka ANSI Escape Sequences) is ``` /(\x9B|\x1B\[)[0-?]*[ -\/]*[@-~]/ ``` Refer to [ECMA-4...
How to parse positional arguments with leading minus sign (negative numbers) using argparse
14,693,718
11
2013-02-04T19:07:51Z
14,693,744
17
2013-02-04T19:09:49Z
[ "python", "argparse" ]
I would like to parse a required, positional argument containing a comma-separated list of integers. If the first integer contains a leading minus ('-') sign, argparse complains: ``` import argparse parser = argparse.ArgumentParser() parser.add_argument('positional') parser.add_argument('-t', '--test', action='store_t...
You need to insert a `--` into your command-line arguments: ``` $ python example.py --test -- -1,2,3,4 Namespace(positional='-1,2,3,4', test=True) ``` The double-dash stops argparse looking for any more optional switches; it's the defacto standard way of handling exactly this use case for command-line tools.
RuntimeError: main thread is not in main loop
14,694,408
9
2013-02-04T19:51:19Z
14,695,007
10
2013-02-04T20:26:46Z
[ "python", "multithreading", "tkinter" ]
When I call self.client = ThreadedClient() in my Python program, I get the error **"RuntimeError: main thread is not in main loop"**. I have already done some googling, but I am making an error somehow ... Can someone please help me out? Full error: ``` Exception in thread Thread-1: Traceback (most recent call la...
You're running your main GUI loop in a thread besides the main thread. You cannot do this. The docs mention offhandedly in a few places that Tkinter is not quite thread safe, but as far as I know, never quite come out and say that you can only talk to Tk from the main thread. The reason is that the truth is somewhat c...
Converting html to text with Python
14,694,482
15
2013-02-04T19:55:10Z
14,694,669
21
2013-02-04T20:06:25Z
[ "python", "web-scraping", "beautifulsoup" ]
I am trying to convert an html block to text using Python. **Input:** ``` <div class="body"><p><strong></strong></p> <p><strong></strong>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa</p> <p>Consectetuer adipiscing elit. <a href="http://example.com/" target="_...
What am I missing? `soup.get_text()` gives exactly the same output you wanted... ``` from bs4 import BeautifulSoup soup = BeautifulSoup(html) print soup.get_text() ``` output ``` Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa Consectetuer adipiscing elit. Som...
matplotlib: Delete a subplot
14,694,501
17
2013-02-04T19:56:42Z
14,694,683
35
2013-02-04T20:07:10Z
[ "python", "matplotlib" ]
I'm trying to figure out a way of deleting (dynamically) subplots in matplotlib. I see they have a `remove` method, but I get the error ``` NotImplementedError: cannot remove artist ``` I'm surprised that I can't find this anywhere. Does anyone know how to do this?
Wow, ok well I feel really stupid :P ``` fig.delaxes(ax) plt.draw() ``` In case anyone else needs it.
Why isn't 'list' a reserved word in Python?
14,694,559
4
2013-02-04T20:00:07Z
14,694,572
13
2013-02-04T20:00:33Z
[ "python", "python-2.7" ]
I just got bit by a bug that would have been prevented if `list` were a reserved word in Python. (Dumbery on my part, to be sure.) So why isn't list (or dict or float or any of the types) a reserved word? It seems easier to add an interpreter error than to try and remember a rule. (I also know Eclipse/PyDev has a set...
Only [keywords](http://docs.python.org/2/reference/lexical_analysis.html#keywords) are reserved. `list` is not a keyword but a built-in type, as are `str`, `set`, `dict`, `unicode`, `int`, `float`, etc. There is no point in reserving each and every possible built-in type; python is a dynamic language and if you want ...
Why does Celery NOT throw an Exception when the underlying task throws one
14,694,771
20
2013-02-04T20:12:32Z
24,243,137
21
2014-06-16T11:54:22Z
[ "python", "exception-handling", "celery" ]
Celery doesn't seem to be handling exceptions properly. If I have task: ``` def errorTest(): raise Exception() ``` and then I call ``` r = errorTest.delay() In [8]: r.result In [9]: r.state Out[9]: 'PENDING' ``` And it will hang like this indefinitely. Going and checking the logs shows that the error IS gett...
If you are running Celery with the CELERY\_ALWAYS\_EAGER set to True, then make sure you include this line in your settings too: ``` CELERY_EAGER_PROPAGATES_EXCEPTIONS = True ``` <http://docs.celeryproject.org/en/latest/configuration.html#celery-eager-propagates-exceptions>
How to insert strings with quotes and newlines into sqlite db with Python?
14,695,134
7
2013-02-04T20:34:59Z
14,695,158
15
2013-02-04T20:36:20Z
[ "python", "mysql", "sql", "database", "sqlite" ]
I'm trying to insert strings read from a file into an `sqlite` database in Python. The strings have whitespace (newline, tab characters, and spaces) and also have appearances of single or double quotes. Here's how I try to do it: ``` import sqlite3 conn = sqlite3.connect('example.db') c = conn.cursor() # Create table...
You use SQL parameters instead of string formatting: ``` c.execute("INSERT INTO test VALUES (?, 'bar')", (testfield,)) ``` When using SQL parameters you let the database library handle the quoting, and even better, give the database to optimize the query and reuse the optimized query plan for multiple executions of t...
Python packages not installing in virtualenv using pip
14,695,278
24
2013-02-04T20:43:36Z
14,695,504
47
2013-02-04T20:58:11Z
[ "python", "twisted", "virtualenv", "pip" ]
**I'm having trouble installing twisted** ``` pip --version ``` > pip 1.1 from > /home/chris/GL/GLBackend/glenv/lib/python2.7/site-packages/pip-1.1-py2.7.egg > (python 2.7) **Create a virtual environment** ``` chris@chris-mint ~/GL/GLBackend $ sudo virtualenv -p python2.7 glenv ``` > Running virtualenv with interp...
The problem here is that you're using `sudo` when you shouldn't be. And that's causing `pip` to try to install into `/usr/local/lib` instead of `~/glenv/lib`. (And, because you used `sudo`, it's successfully doing so, but that doesn't help you, because you're not allowing system site-packages in your venv.) There are ...
Most efficient way to filter a long time series Python
14,695,367
7
2013-02-04T20:48:13Z
14,702,381
8
2013-02-05T07:40:08Z
[ "python", "numpy", "python-2.7", "signal-processing", "scientific-computing" ]
I have a large time series, say 1e10, that results from recording neural activity, i.e. voltages. Before doing further analysis I want to band pass filter that data between 300 Hz and 7000 Hz. Below, I post the code for the Butterworth filter I designed. **How do I make this filter faster? It takes too long to run.** ...
First, your data sample is in a proprietary format, am I right? Even using the biosig toolbox for Python this format cannot be read. Maybe I'm wrong, but I didn't succeed to read it. Thus, I'll base my answer on artificial data, generated from a Rössler-oscillator. It is a chaotic, 3d-oscillator, often used in the fi...
unzipping a file with Python and returning all the directories it creates
14,696,158
3
2013-02-04T21:41:02Z
14,696,259
8
2013-02-04T21:48:03Z
[ "python", "compression", "zipfile", "decompression" ]
How can I unzip a `.zip` file with Python into some directory `output_dir` and fetch a list of all the directories made by the unzipping as a result? For example, if I have: `unzip('myzip.zip', 'outdir')` `outdir` is a directory that might have other files/directories in it. When I unzip `myzip.zip` into it, I'd like...
You can read the contents of the zip file with the `namelist()` method. Directories will have a trailing path separator: ``` >>> import zipfile >>> zip = zipfile.ZipFile('test.zip') >>> zip.namelist() ['dir2/', 'file1'] ``` You can do this before *or* after extracting contents. Depending on your operating environmen...
Object identity in JavaScript
14,696,626
3
2013-02-04T22:10:37Z
14,696,685
8
2013-02-04T22:13:49Z
[ "javascript", "python" ]
How to check that two variables point to the same object? Meaning that if I mutate it—the value pointed to by both variables will change. In Python there is `is` operator, what about JavaScript?
the strict equality operator (`===`) will evaluate to true if references are the same without doing any type conversion: ``` var a, b, c; a = {}; b = {}; c = a; console.log( a === b ); //false console.log( a === c ); //true ``` --- After shooting down two posts that have made the same mistakes, I think I should poin...
Faster way of polygon intersection with shapely
14,697,442
13
2013-02-04T23:07:16Z
14,804,366
24
2013-02-11T00:37:55Z
[ "python", "numpy", "shapely" ]
I have a large number of polygons (~100000) and try to find a smart way of calculating their intersecting area with a regular grid cells. Currently, I am creating the polygons and the grid cells using shapely (based on their corner coordinates). Then, using a simple for-loop I go through each polygon and compare it to...
Consider using [Rtree](http://pypi.python.org/pypi/Rtree/) to help identify which grid cells that a polygon may intersect. This way, you can remove the for loop used with the array of lat/lons, which is probably the slow part. Structure your code something like this: ``` from shapely.ops import cascaded_union from rt...
Switching kivy widgets
14,699,280
7
2013-02-05T02:38:40Z
14,710,823
8
2013-02-05T15:19:09Z
[ "python", "widget", "kivy" ]
I am using the Kivy python library. I have two widgets defined. When the program runs, I run the first widget. When that widgets button is pressed, I want it to dissapear and be replaced with the second widget. Here is the .kv for the two widgets ``` #uitest.kv <TestForm>: canvas: Rectangle: ...
My suggestion is to have an interface manager widget, then you can have various widgets for your UI forms. ``` import kivy from kivy.uix.label import Label from kivy.uix.button import Button from kivy.uix.boxlayout import BoxLayout from kivy.app import App class InterfaceManager(BoxLayout): def __init__(self, **...
AUTH_USER_MODEL refers to model .. that has not been installed and created AbstractUser models not able to login
14,699,598
14
2013-02-05T03:14:19Z
14,720,448
11
2013-02-06T02:08:11Z
[ "python", "django", "django-1.5" ]
**`AUTH_USER_MODEL` error solved in EDIT3. Passwords still will not save on user creation via form.** I'm using Django 1.5 playing around with the new user override/extension features, and I am not able to register new users via my registration form - only via the Admin. When registering via the registration form, I g...
Ok there were three issues here for me, so I'm going to address all of them since I am pretty sure the first two will come up for someone else. * `Manager isn't available; User has been swapped for 'poker.PokerUser'` This was due to using but not recreating the `UserCreationForm`. When using custom models in 1.5, som...
How do I set a proxy for phantomjs/ghostdriver in python webdriver?
14,699,718
21
2013-02-05T03:30:20Z
16,353,584
56
2013-05-03T07:13:34Z
[ "python", "proxy", "webdriver", "phantomjs", "ghostdriver" ]
I'm trying to figure out how to route my requests through an HTTP proxy. I'm initializing webdriver like this: ``` user_agent = 'my user agent 1.0' DesiredCapabilities.PHANTOMJS['phantomjs.page.settings.userAgent'] = user_agent driver = webdriver.PhantomJS() ``` I've gone through the docs and the source and can't se...
Below is the example of how to set proxy for PhantomJs in Python. You may change proxy type: socks5/http. ``` service_args = [ '--proxy=127.0.0.1:9999', '--proxy-type=socks5', ] browser = webdriver.PhantomJS('../path_to/phantomjs',service_args=service_args) ```
Transport exception
14,701,608
3
2013-02-05T06:40:54Z
16,220,464
7
2013-04-25T16:50:26Z
[ "python", "hadoop", "hbase", "thrift" ]
I'm trying to import happybase but gets the following error message while connecting. I have Hadoop pseudonode cluster and Hbase already running. Version of the components installed are as follows, Hadoop version - 1.0.4 Hbase version - 0.94.4 happybase -0.4 Can someone have a look into the exceptions below and let me...
make sure you have thrift server started before you try to connect. ``` hbase thrift start -threadpool ```
Multiprocessing or os.fork, os.exec?
14,701,901
2
2013-02-05T07:03:41Z
14,702,396
7
2013-02-05T07:41:45Z
[ "python" ]
I am using multiprocessing module to fork child processes. Since on forking, child process gets the address space of parent process, I am getting the same logger for parent and child. I want to clear the address space of child process for any values carried over from parent. I got to know that multiprocessing does fork...
Since `multiprocessing` is running a function from your program as if it were a thread function, it definitely needs a full copy of your process' state. That means doing `fork()`. Using a higher-level interface provided by `multiprocessing` is generally better. At least you should not care about the `fork()` return co...
How can I get a Python decorator to run after the decorated function has completed?
14,703,310
19
2013-02-05T08:46:55Z
14,703,332
17
2013-02-05T08:48:14Z
[ "python", "decorator", "python-decorators" ]
I want to use a decorator to handle auditing of various functions (mainly Django view functions, but not exclusively). In order to do this I would like to be able to audit the function **post-execution** - i.e. the function runs as normal, and if it returns without an exception, then the decorator logs the fact. Somet...
Decorators usually return a wrapper function; just put your logic in the wrapper function after invoking the wrapped function. ``` def audit_action(action): def decorator_func(func): def wrapper_func(*args, **kwargs): # Invoke the wrapped function first retval = func(*args, **kwargs...
plotting a smooth curve in matplotlib graphs
14,705,062
6
2013-02-05T10:16:36Z
14,705,423
12
2013-02-05T10:33:59Z
[ "python", "matplotlib", "netcdf" ]
i am reading a netcdf file using python and need to plot a graphs using matplotlib library in python . the netcdf file is containing 3 variables u v and w components . i have to draw these 3 components on a vertical scale. since these data is going to be used in a weather forecasting radar's . i need to plot these grap...
A simple solution is to do interpolation with splines, as explained in a [nice Scipy tutorial](http://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html). Here is an example: ![enter image description here](http://i.stack.imgur.com/KKHC2.png)
python matplotlib dash-dot-dot - how to?
14,710,221
30
2013-02-05T14:46:59Z
14,710,446
44
2013-02-05T14:58:57Z
[ "python", "matplotlib", "linestyle" ]
I am using python and matplotlib to generate graphical output. Is there a simple way to generate a dash-dot-dot line-style? I am aware of the `'--'`, `'-.'`, and `':'` options. Unfortunately, `'-..'` does not result in a dash-dot-dot line. I have looked at the `set_dashes` command, but that seems to control the l...
You can define [custom dashes](http://matplotlib.org/1.2.1/examples/pylab_examples/dash_control.html): ``` import matplotlib.pyplot as plt line, = plt.plot([1,5,2,4], '-') line.set_dashes([8, 4, 2, 4, 2, 4]) plt.show() ``` ![enter image description here](http://i.stack.imgur.com/5OtjP.png) `[8, 4, 2, 4, 2, 4]` mea...
Search directory for specific string
14,710,918
5
2013-02-05T15:24:01Z
14,711,127
7
2013-02-05T15:33:59Z
[ "python", "file", "directory" ]
I'm trying to search through a specific directory full of header files, and look through each header file, and if any file has a string "struct" in it, I just want the program to print which file has it. I have this so far, but it's not working correctly, can you help me figure it out: ``` import glob import os os.ch...
It seems you are interested in the file name, not the line, so we can speed thing up by reading the whole file and search: ``` ... for file in glob.glob('*.h'): with open(file) as f: contents = f.read() if 'struct' in contents: print file ``` Using the `with` construct ensures the file to be c...
Perform a logical exclusive OR on a Django Q object
14,711,203
4
2013-02-05T15:38:18Z
21,220,712
7
2014-01-19T18:19:45Z
[ "python", "django", "django-queryset", "django-q" ]
I would like to perform a logical exclusive OR ([XOR](http://en.wikipedia.org/wiki/Exclusive_disjunction)) on django.db.models.Q objects, using [operator](http://docs.python.org/2/library/operator.html) module to limit the choices of a model field to a subset of foreignkey. I am doing this in Django 1.4.3 along with Py...
You could add an `__xor__()` method to Q that uses and/or/not to do the XOR logic. ``` from django.db.models import Q class QQ: def __xor__(self, other): not_self = self.clone() not_other = other.clone() not_self.negate() not_other.negate() x = self & not_other ...
External javascript file is not getting added when runs on flask
14,711,552
12
2013-02-05T15:56:41Z
14,711,572
29
2013-02-05T15:57:43Z
[ "javascript", "python", "flask", "external" ]
I have a HTML file named showMap.html ``` <!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> <title>Map</title> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> ...
Serve the `map.js` file as a [static resource](http://flask.pocoo.org/docs/quickstart/#static-files): * move the file to a `static/` subdirectory of your package * generate a static URL for it in a Jinja2 template like so: ``` <script type="text/javascript" src="{{ url_for('static', filename='map.js') }}"></scrip...
How to prevent numbers being changed to exponential form in Python matplotlib figure
14,711,655
31
2013-02-05T16:01:19Z
14,711,866
47
2013-02-05T16:11:56Z
[ "python", "graph", "matplotlib", "figure" ]
I'm using Matplotlib in Python to plot simple x-y datasets. This produces really nice-looking graphs, although when I "zoom in" too close on various sections of the plotted graph using the Figure View (which appears when you execute plt.show(), the x-axis values change from standard number form (1050, 1060, 1070 etc.) ...
The formatting of tick labels is controlled by a `Formatter` object, which assuming you haven't done anything fancy will be a `ScalerFormatter`[by default](http://matplotlib.org/api/ticker_api.html#matplotlib.ticker.ScalarFormatter). This formatter will use a constant shift if the fractional change of the values visibl...
How to prevent numbers being changed to exponential form in Python matplotlib figure
14,711,655
31
2013-02-05T16:01:19Z
28,847,212
8
2015-03-04T05:24:43Z
[ "python", "graph", "matplotlib", "figure" ]
I'm using Matplotlib in Python to plot simple x-y datasets. This produces really nice-looking graphs, although when I "zoom in" too close on various sections of the plotted graph using the Figure View (which appears when you execute plt.show(), the x-axis values change from standard number form (1050, 1060, 1070 etc.) ...
You can use something like: ``` from matplotlib.ticker import ScalarFormatter, FormatStrFormatter ax.xaxis.set_major_formatter(FormatStrFormatter('%.0f')) ```
Pymongo cursor limit(1) returns more than 1 result
14,712,402
8
2013-02-05T16:38:17Z
14,712,656
10
2013-02-05T16:51:57Z
[ "python", "mongodb", "pymongo" ]
These are all documents in my collection: ``` { "_id" : ObjectId("5110291e6ee1c31d5b275d01"), "d" : 24, "s" : [ 1, 2, 3 ] } { "_id" : ObjectId("511029266ee1c31d5b275d02"), "d" : 24, "s" : [ 4, 5, 6 ] } { "_id" : ObjectId("5110292e6ee1c...
The [docs](http://api.mongodb.org/python/current/api/pymongo/cursor.html#pymongo.cursor.Cursor.__getitem__) says about index access of a cursor: > Any limit previously applied to this cursor will be ignored.
Using inlineCallbacks
14,712,752
7
2013-02-05T16:56:03Z
14,734,728
8
2013-02-06T17:05:22Z
[ "python", "twisted", "deferred" ]
I'm new to Twisted and I'm trying to write a simple resource which displays a list of names from a database, here's a part of my code: ``` #code from my ContactResource class def render_GET(self, request): def print_contacts(contacts, request): for c in contacts: request.write(c.name) i...
A `render_GET` method may not return a `Deferred`. It may only return a string or `NOT_DONE_YET`. Any method decorated with `inlineCallbacks` will return a `Deferred`. So, you may not decorate `render_GET` with `inlineCallbacks`. Of course, nothing stops you from calling any other function you want in `render_GET`, in...
what is the best way to generate a reset token in python?
14,713,757
9
2013-02-05T17:52:22Z
14,714,020
22
2013-02-05T18:07:01Z
[ "python", "registration", "password-recovery" ]
I'm trying to make a validation process for a password reset, what i've used are two values: the epoch time, and i want to use the users's old password (pbkdf2) as a key, Since i dont want to get non ASCII characters, i've used [SimpleEncode library](http://code.google.com/p/python-simpleencode/) because it's fast sin...
Not sure it's the best way, but I'd probably just generate a UUID4, which can be used in a URL to reset the password and expire it after 'n' amount of time. ``` >>> import uuid >>> uuid.uuid4().hex '8c05904f0051419283d1024fc5ce1a59' ``` You could use something like <http://redis.io> to hold that key, with a value of ...
what is the best way to generate a reset token in python?
14,713,757
9
2013-02-05T17:52:22Z
14,717,974
16
2013-02-05T22:10:59Z
[ "python", "registration", "password-recovery" ]
I'm trying to make a validation process for a password reset, what i've used are two values: the epoch time, and i want to use the users's old password (pbkdf2) as a key, Since i dont want to get non ASCII characters, i've used [SimpleEncode library](http://code.google.com/p/python-simpleencode/) because it's fast sin...
Easiest way by far is to use the [ItsDangerous](http://packages.python.org/itsdangerous/) library: > You can serialize and sign a user ID for unsubscribing of newsletters into URLs. This way you don’t need to generate one-time tokens and store them in the database. Same thing with any kind of activation link for acc...
Conditional Logic on Pandas DataFrame
14,714,181
11
2013-02-05T18:17:37Z
14,714,452
14
2013-02-05T18:35:28Z
[ "python", "pandas" ]
How to apply conditional logic to a Pandas DataFrame. See DataFrame shown below, ``` data desired_output 0 1 False 1 2 False 2 3 True 3 4 True ``` My original data is show in the 'data' column and the desired\_output is shown next to it. If the number in 'data...
``` In [1]: df Out[1]: data 0 1 1 2 2 3 3 4 ``` You want to apply a function that conditionally returns a value based on the selected dataframe column. ``` In [2]: df['data'].apply(lambda x: 'true' if x <= 2.5 else 'false') Out[2]: 0 true 1 true 2 false 3 false Name: data ``` You can...
Conditional Logic on Pandas DataFrame
14,714,181
11
2013-02-05T18:17:37Z
14,717,374
14
2013-02-05T21:34:52Z
[ "python", "pandas" ]
How to apply conditional logic to a Pandas DataFrame. See DataFrame shown below, ``` data desired_output 0 1 False 1 2 False 2 3 True 3 4 True ``` My original data is show in the 'data' column and the desired\_output is shown next to it. If the number in 'data...
Just compare the column with that value: ``` In [9]: df = pandas.DataFrame([1,2,3,4], columns=["data"]) In [10]: df Out[10]: data 0 1 1 2 2 3 3 4 In [11]: df["desired"] = df["data"] > 2.5 In [11]: df Out[12]: data desired 0 1 False 1 2 False 2 3 True 3 4 True ```
Convert transposed NumPy array to CvMat type in Python using cv.fromarray
14,714,881
3
2013-02-05T19:00:54Z
14,715,221
7
2013-02-05T19:20:36Z
[ "python", "opencv", "numpy" ]
I am having a problem where some numpy arrays don't convert to cvMat using cv.fromarray(). It appears the problem occurs whenever the numpy array has been transposed. ``` import numpy as np import cv # This works fine: b = np.arange(6).reshape(2,3).astype('float32') B = cv.fromarray(b) print(cv.GetSize(B)) # But thi...
You can check your arrays using the `flags.contiguous` attribute, and if they are not, make them be using `copy()`: ``` >>> a = np.arange(16).reshape(4,4) >>> a.flags.contiguous True >>> b = a.T >>> b.flags.contiguous False >>> b = b.copy() >>> b.flags.contiguous True ``` When you ask for a transpose, numpy doesn't a...
PyCrypto - How does the Initialization Vector work?
14,716,338
7
2013-02-05T20:30:35Z
14,724,042
12
2013-02-06T07:52:10Z
[ "python", "python-3.x", "pycrypto", "initialization-vector" ]
I'm trying to understand how PyCrypto works to use in a project but I'm not fully understanding the significance of the Initialization Vector (IV). I've found that I can use the wrong IV when decoding a string and I still seem to get the message back except for the first 16 bytes (the block size). Am simply using it wr...
The behavior you see is specific to the CBC mode. With CBC, decryption can be visualized in the following way (from wikipedia): ![CBC decryption](http://i.stack.imgur.com/P0TAV.png) You can see that IV only contributes to the first 16 bytes of plaintext. If the IV is corrupted while it is in transit to the receiver, ...
How do I find the string between two special characters?
14,716,342
6
2013-02-05T20:30:54Z
14,716,372
12
2013-02-05T20:32:44Z
[ "python", "string", "special-characters" ]
For example, I need everything in between the two square brackets. File1 ``` [Home sapiens] [Mus musculus 1] [virus 1 [isolated from china]] ``` So considering the above example, I need everything in between the first and last square brackets.
You can use a greedy regex: ``` re.search(r'\[(.*)\]', your_string).group(1) ```
How do I find the string between two special characters?
14,716,342
6
2013-02-05T20:30:54Z
14,716,544
11
2013-02-05T20:42:05Z
[ "python", "string", "special-characters" ]
For example, I need everything in between the two square brackets. File1 ``` [Home sapiens] [Mus musculus 1] [virus 1 [isolated from china]] ``` So considering the above example, I need everything in between the first and last square brackets.
Regular expressions are the most flexible option. For another approach, you can try string's [partition](http://docs.python.org/2/library/stdtypes.html#str.partition) and [rpartition](http://docs.python.org/2/library/stdtypes.html#str.rpartition) methods: ``` >>> s = "[virus 1 [isolated from china]]" >>> s.partition(...
How to read Json object with a python wsgi application
14,716,457
2
2013-02-05T20:37:45Z
14,716,537
7
2013-02-05T20:41:40Z
[ "python", "json", "post", "python-2.7", "mod-wsgi" ]
I need to develop a python (v2.7) wsgi application to receive and parse data in json object posted from another web. The format of an example JSON object is as below. ``` { "BuildId":"4c53575f-36f48a7f1f37", "EventId":1, "EventName":"Archiving Complete", "EventDescription":"Fired each time the build products ...
Use the stdlib [`json` library](http://docs.python.org/2/library/json.html) to parse the data, the result is a python dictionary: ``` def application(environ, start_response): try: request_body_size = int(environ.get('CONTENT_LENGTH', 0)) except (ValueError): request_body_size = 0 request_...
adding extra axis ticks using matplotlib
14,716,660
13
2013-02-05T20:51:29Z
14,716,726
24
2013-02-05T20:56:42Z
[ "python", "matplotlib" ]
I have a simple plot code as ``` plt.plot(x,y) plt.show() ``` I want to add some extra ticks on the x-axis in addition to the current ones, let's say at ``` extraticks=[2.1, 3, 7.6] ``` As you see I do not have a pattern for ticks so I do not want to increase the tick frequency for the whole axis; just keep the ori...
Yes, you can try something like: ``` plt.xticks(list(plt.xticks()[0]) + extraticks) ``` The function to use is [`xticks()`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.xticks). When called without arguments, it returns the current ticks. Calling it with arguments, you can set the tick positions and, o...
How can I tell which python implementation I'm using?
14,718,135
10
2013-02-05T22:22:56Z
14,718,168
22
2013-02-05T22:25:19Z
[ "python", "cpython" ]
Python has a few different implementations: CPython, Jython, PyPy, etc. I want to programmatically determine which implementation my code is running on. How can I do that? To be specific, write a function called `get_implementation_name()` for me: ``` impl_name = get_implementation_name() if impl_name == "CPython": ...
``` In [50]: import platform In [52]: platform.python_implementation() Out[52]: 'CPython' ```
Behavior of "and" with sets in Python
14,718,332
8
2013-02-05T22:38:12Z
14,718,367
14
2013-02-05T22:40:52Z
[ "python", "set" ]
I know that if I want to get the intersection of two sets (or frozensets) I should use the ampersand `&`. Out of curiosity I tried to use the word 'and' ``` a = set([1,2,3]) b = set([3,4,5]) print(a and b) #prints set([3,4,5]) ``` I am just curious why? what does this `and` represent when used with lists?
`x and y` just treats the whole `x` and `y` expressions as boolean values. If `x` is false, it returns `x`. Otherwise, it returns `y`. See [the docs](http://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not) for details. Both `set`s (as in your example) and `list`s (as in your question) are false i...
Unit tests for Query in SQLAlchemy
14,719,507
3
2013-02-06T00:27:11Z
14,719,663
9
2013-02-06T00:43:17Z
[ "python", "unit-testing", "sqlalchemy" ]
How does one go about testing queries in SQLAlchemy? For example suppose we have this `models.py` ``` from sqlalchemy import ( Column, Integer, String, ) from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Panel(Base): __tablename__ = 'Panels' id =...
your original test is on the right track, you just have to do one of two things: either make sure that two `Panel` objects of the same primary key identity compare as `True`: ``` class Panel(Base): # ... def __eq__(self, other): return isinstance(other, Panel) and other.id == self.id ``` or you can o...
Compute the similarity between two lists
14,720,324
4
2013-02-06T01:54:57Z
14,720,386
8
2013-02-06T02:00:29Z
[ "python", "algorithm", "set", "similarity" ]
I'd like to compute the similarity between two lists of various lengths. eg: ``` listA = ['apple', 'orange', 'apple', 'apple', 'banana', 'orange'] # (length = 6) listB = ['apple', 'orange', 'grapefruit', 'apple'] # (length = 4) ``` as you can see, a single item can appear multiple times in a list, and the lengths ar...
Use [`collections.Counter()`](http://docs.python.org/2/library/collections.html#collections.Counter) perhaps; those are multi-sets, or bags, in datatype parlance: ``` from collections import Counter counterA = Counter(listA) counterB = Counter(listB) ``` Now you can compare these by entries or frequencies: ``` >>> ...
How to generate random colors in matplotlib?
14,720,331
14
2013-02-06T01:55:29Z
14,720,445
20
2013-02-06T02:07:50Z
[ "python", "matplotlib" ]
What's the trivial example of how to generate random colors for passing to plotting functions? I'm calling scatter inside a loop and want each plot in a different color. > c: > a color. c can be a single color format string, or a sequence of color specifications of length N, or a sequence of N numbers to be mapped to...
``` for X,Y in data: scatter(X, Y, c=numpy.random.rand(3,1)) ```
How to generate random colors in matplotlib?
14,720,331
14
2013-02-06T01:55:29Z
14,720,550
7
2013-02-06T02:20:37Z
[ "python", "matplotlib" ]
What's the trivial example of how to generate random colors for passing to plotting functions? I'm calling scatter inside a loop and want each plot in a different color. > c: > a color. c can be a single color format string, or a sequence of color specifications of length N, or a sequence of N numbers to be mapped to...
When less than 9 datasets: ``` colors = "bgrcmykw" color_index = 0 for X,Y in data: scatter(X,Y, c=colors[color_index]) color_index += 1 ```
How to generate random colors in matplotlib?
14,720,331
14
2013-02-06T01:55:29Z
25,628,397
32
2014-09-02T16:45:29Z
[ "python", "matplotlib" ]
What's the trivial example of how to generate random colors for passing to plotting functions? I'm calling scatter inside a loop and want each plot in a different color. > c: > a color. c can be a single color format string, or a sequence of color specifications of length N, or a sequence of N numbers to be mapped to...
> I'm calling scatter inside a loop and want each plot in a different color. Based on that, and on your answer: It seems to me that you actually want `N` *distinct* colors for your datasets; **you want to map the integer indices `0, 1, ... N-1` to distinct RGB colors.** Something like: ![mapping index to color](http:...
How to generate random colors in matplotlib?
14,720,331
14
2013-02-06T01:55:29Z
28,222,930
9
2015-01-29T19:25:00Z
[ "python", "matplotlib" ]
What's the trivial example of how to generate random colors for passing to plotting functions? I'm calling scatter inside a loop and want each plot in a different color. > c: > a color. c can be a single color format string, or a sequence of color specifications of length N, or a sequence of N numbers to be mapped to...
elaborating @john-mee 's answer, if you don't need strictly unique colors but have arbitrarily long data: ``` from itertools import cycle cycol = cycle('bgrcmk').next for X,Y in data: scatter(X, Y, c=cycol()) ``` this has the advantage that the colors are easy to control and that it's short.
How to get numbers from /dev/random using Python?
14,720,799
2
2013-02-06T02:52:50Z
14,720,865
7
2013-02-06T03:12:20Z
[ "python" ]
I'm trying to write a python script to test the randomness of /dev/random, but I can't get it to give me any number. My code looks like this with open("/dev/random", 'rb') as file: print f.read(10) which I believe is supposed to print out 10 bytes from /dev/random, but instead of numbers, it prints out weird characte...
You are getting 10 bytes. Python won't automatically turn them into numbers. I recommend you grab the bytes in multiples of 4, then turn them into 32-bit unsigned integers, then scale them to whatever you need. EDIT: the old code showed the idea but was poorly divided into functions. Here is the same basic idea but n...
Combining Multiple Sets of Letters in Python
14,721,104
3
2013-02-06T03:43:30Z
14,721,154
8
2013-02-06T03:47:15Z
[ "python" ]
I am trying to figure out how to print all the combinations there are for multiple sets of letters without repetition. An example: A,B,C and X,Y,Z The combinations would be: AX AY AZ BX BY BZ CX CY CZ
You can use [`itertools.product`](http://docs.python.org/2/library/itertools.html#itertools.product) to get what you want. ``` from itertools import product a = ['A', 'B', 'C'] b = ['X', 'Y', 'Z'] for i in product(a, b): print ''.join(i) ```
Pythonic way to determine whether not null list entries are 'continuous'
14,721,406
45
2013-02-06T04:13:14Z
14,721,490
25
2013-02-06T04:20:52Z
[ "python", "list", null, "slice" ]
**I'm looking for a way to easily determine if all not None items in a list occur in a single continuous slice.** I'll use integers as examples of not None items. For example, the list `[None, None, 1, 2, 3, None, None]` meets my requirements for continuous integer entries. By contrast, `[1, 2, None, None, 3, None]` i...
Good 'ol `itertools.groupby` to the rescue: ``` from itertools import groupby def contiguous(seq): return sum(1 for k,g in groupby(seq, lambda x: x is not None) if k) == 1 ``` gives ``` >>> contiguous([1,2,3,None,None]) True >>> contiguous([None, 1,2,3,None]) True >>> contiguous([None, None, 1,2,3]) True >>> co...
Pythonic way to determine whether not null list entries are 'continuous'
14,721,406
45
2013-02-06T04:13:14Z
14,721,498
12
2013-02-06T04:21:17Z
[ "python", "list", null, "slice" ]
**I'm looking for a way to easily determine if all not None items in a list occur in a single continuous slice.** I'll use integers as examples of not None items. For example, the list `[None, None, 1, 2, 3, None, None]` meets my requirements for continuous integer entries. By contrast, `[1, 2, None, None, 3, None]` i...
You could use something like `itertools.groupby`: ``` from itertools import groupby def are_continuous(items): saw_group = False for group, values in groupby(items, lambda i: i is not None): if group: if saw_group: return False else: saw_group =...
Pythonic way to determine whether not null list entries are 'continuous'
14,721,406
45
2013-02-06T04:13:14Z
14,721,500
7
2013-02-06T04:21:27Z
[ "python", "list", null, "slice" ]
**I'm looking for a way to easily determine if all not None items in a list occur in a single continuous slice.** I'll use integers as examples of not None items. For example, the list `[None, None, 1, 2, 3, None, None]` meets my requirements for continuous integer entries. By contrast, `[1, 2, None, None, 3, None]` i...
This may not be the best way to go about doing it, but you can look for the first non-None entry and the last `non-None` entry and then check the slice for `None`. e.g.: ``` def is_continuous(seq): try: first_none_pos = next(i for i,x in enumerate(seq) if x is not None) #need the or None on the nex...
Pythonic way to determine whether not null list entries are 'continuous'
14,721,406
45
2013-02-06T04:13:14Z
14,721,700
44
2013-02-06T04:41:02Z
[ "python", "list", null, "slice" ]
**I'm looking for a way to easily determine if all not None items in a list occur in a single continuous slice.** I'll use integers as examples of not None items. For example, the list `[None, None, 1, 2, 3, None, None]` meets my requirements for continuous integer entries. By contrast, `[1, 2, None, None, 3, None]` i...
``` def contiguous(seq): seq = iter(seq) all(x is None for x in seq) # Burn through any Nones at the beginning any(x is None for x in seq) # and the first group return all(x is None for x in seq) # everthing else (if any) should be None. ``` Here are a couple of examples. You can use `nex...
Pythonic way to determine whether not null list entries are 'continuous'
14,721,406
45
2013-02-06T04:13:14Z
14,727,068
7
2013-02-06T10:44:18Z
[ "python", "list", null, "slice" ]
**I'm looking for a way to easily determine if all not None items in a list occur in a single continuous slice.** I'll use integers as examples of not None items. For example, the list `[None, None, 1, 2, 3, None, None]` meets my requirements for continuous integer entries. By contrast, `[1, 2, None, None, 3, None]` i...
The natural way to consume sequence elements is to use `dropwhile`: ``` from itertools import dropwhile def continuous(seq): return all(x is None for x in dropwhile(lambda x: x is not None, dropwhile(lambda x: x is None, seq))) ``` We can express this without nested fun...
AttributeError: 'Manager' object has no attribute 'get_by_natural_key' error in Django?
14,723,099
9
2013-02-06T06:41:37Z
14,724,828
22
2013-02-06T08:44:10Z
[ "python", "django", "django-authentication", "django-1.5", "django-managers" ]
I am using Django `'1.5c1'`. I have this line in my settings.py: ``` AUTH_USER_MODEL = 'fileupload.galaxyuser' ``` Here's my `Galaxyuser` model: ``` class GalaxyUser(models.Model): id = models.IntegerField(primary_key=True) create_time = models.DateTimeField(null=True, blank=True) update_time = models.Da...
You have created a new user model but you have not yet specified a manager for that model. If you're not yet familiar with managers in Django I suggest reading the [documentation on that](https://docs.djangoproject.com/en/1.5/topics/db/managers/) first. As the Django 1.5 say ([source](https://docs.djangoproject.com/en/...
How do I convert a hexadecimal to a string in Python?
14,723,553
2
2013-02-06T07:15:03Z
14,723,647
9
2013-02-06T07:21:33Z
[ "python", "hex" ]
Using Python, ``` h = 0x11012 # ... ??? result = '11012' ``` What intermediary steps do I have to take to go from h -> result?
Python 2.7 and later: ``` >>> "{:x}".format(0x11012) '11012' ``` Python 2.6: ``` >>> "{0:x}".format(0x11012) '11012' ``` Python 2.5 and earlier: ``` >>> "%x" % 0x11012 '11012' ```
Web2py Custom Validators
14,724,584
4
2013-02-06T08:28:47Z
14,729,851
8
2013-02-06T13:06:40Z
[ "python", "table", "web2py", "customvalidator", "custom-validators" ]
**Hi.... I am new too Web2py and am trying to use a custom validator** class IS\_NOT\_EMPTY\_IF\_OTHER(Validator): ``` def __init__(self, other, error_message='must be filled because other value ' 'is present'): self.other = other self.error_message = error_message def...
save the code on /modules/customvalidators.py ``` from gluon.validators import is_empty from gluon.validators import Validator class IS_NOT_EMPTY_IF_OTHER(Validator): def __init__(self, other, error_message='must be filled because other value ' 'is present'): ...
Convex Hull and SciPy
14,724,933
5
2013-02-06T08:50:47Z
14,725,542
8
2013-02-06T09:25:55Z
[ "python", "geometry", "scipy", "computational-geometry", "convex-hull" ]
I'm trying to use scipy (0.10.1) for a quick hack to visualize the convex hull. I can get the convex hull using the following code: ``` vecs = [[-0.094218, 51.478927], [-0.09348, 51.479364], [-0.094218, 51.478927], ... [-0.094218, 51.478927], [-0.094321, 51.479918], [-0.094218, 51.478927], [-...
So this code seems to do the trick, but could be simpler... Essentially, I first collect the vertex numbers from the hull. Then I compute the mean, recenter the dataset and sort it by the angle from the mean. ``` ps = set() for x, y in hull: ps.add(x) ps.add(y) ps = numpy.array(list(ps)) center = vecs[ps].mean...
How to make PyQt window state to maximised in pyqt
14,726,296
5
2013-02-06T10:07:02Z
14,726,363
14
2013-02-06T10:10:08Z
[ "python", "pyqt4", "maximize" ]
I am using PyQt4 for GUI in my application. I want to know how can make my window maximized by default. I goggled but did not found an alternate. I tried using below code, but its not for maximized instead it resizes the window to desktop screen size. But i need the effect which we will see when we press the maximi...
From [the docs](http://qt-project.org/doc/qt-4.8/qwidget.html#showMaximized): ``` self.showMaximized() ```
How can I change the default Mysql connection timeout when connecting through python?
14,726,789
22
2013-02-06T10:30:38Z
14,726,944
31
2013-02-06T10:38:22Z
[ "python", "mysql", "corpus" ]
I connected to a mysql database using python `con = _mysql.connect('localhost', 'dell-pc', '', 'test')` The program that I wrote takes a lot of time in full execution i.e. around 10 hours. Actually, I am trying to read distinct words from a corpus. After reading was finished there was a timeout error. I checked Mysql ...
You change default value in MySQL configuration file (option **connect\_timeout** in *mysqld* section) - ``` [mysqld] connect_timeout=100 ``` If this file is not accessible for you, then you can set this value using this statement - ``` SET GLOBAL connect_timeout=100; ```
How can I change the default Mysql connection timeout when connecting through python?
14,726,789
22
2013-02-06T10:30:38Z
19,610,568
13
2013-10-26T18:50:12Z
[ "python", "mysql", "corpus" ]
I connected to a mysql database using python `con = _mysql.connect('localhost', 'dell-pc', '', 'test')` The program that I wrote takes a lot of time in full execution i.e. around 10 hours. Actually, I am trying to read distinct words from a corpus. After reading was finished there was a timeout error. I checked Mysql ...
Do: ``` con.query('SET GLOBAL connect_timeout=28800') con.query('SET GLOBAL wait_timeout=28800') con.query('SET GLOBAL interactive_timeout=28800') ```
Can Javascript call a Django method/function?
14,727,224
2
2013-02-06T10:51:55Z
14,727,341
11
2013-02-06T10:57:35Z
[ "javascript", "python", "django", "model-view-controller", "jquery" ]
Imagine a simple page with a counter and two buttons. The value displayed by the counter is a read/stored in a model's field. I want that when I press the "green" button the counter is incremented by one and when I press the "red" button the counter is decreased by one. What's the best way to implement such behavior: ...
JavaScript in browser-side is sitting on the front end, while Django is serving on the backend(server-side). The former neither can nor need directly call the latter's functions. The interface between them is typically web service APIs, namely, browser makes AJAX calls with URLs defined in web services, which are backe...
I want Python argparse to throw an exception rather than usage
14,728,376
23
2013-02-06T11:50:13Z
14,728,477
40
2013-02-06T11:54:51Z
[ "python", "argparse" ]
I don't think this is possible, but I want to handle exceptions from argparse myself. For example: ``` import argparse parser = argparse.ArgumentParser() parser.add_argument('--foo', help='foo help', required=True) try: args = parser.parse_args() except: do_something() ``` When I run it: ``` $ myapp.py usag...
You can subclass `ArgumentParser` and override the `error` method to do something different when an error occurs: ``` class ArgumentParserError(Exception): pass class ThrowingArgumentParser(argparse.ArgumentParser): def error(self, message): raise ArgumentParserError(message) parser = ThrowingArgumentPar...
Marking classes and/or methods as deprecated in Sphinx
14,729,943
12
2013-02-06T13:11:17Z
14,729,992
11
2013-02-06T13:14:14Z
[ "python", "documentation", "deprecated", "python-sphinx" ]
Is there any way to mark a class and/or method as deprecated in Sphinx? I can only find a deprecated option for modules. Using a generic admonition would work, but wouldn't carry the semantic meaning.
I think you're looking for [`deprecated`](http://sphinx-doc.org/markup/para.html#directive-deprecated).
Is the shortcircuit behaviour of Python's any/all explicit?
14,730,046
20
2013-02-06T13:16:57Z
14,730,284
8
2013-02-06T13:28:41Z
[ "python" ]
Prompted by the discussion [here](http://stackoverflow.com/a/14721700/174728) The [docs](http://docs.python.org/2/library/functions.html#all) suggest some equivalent code for the behaviour of [`all`](http://docs.python.org/2/library/functions.html#all) and [`any`](http://docs.python.org/2/library/functions.html#any) ...
The docs say > "Return True if any element of the iterable is true. If the iterable is empty, return False. **EQUIVALENT TO:**" (emphasis mine) ... ``` def any(iterable): for element in iterable: if element: return True return False ``` If `any` didn't short circuit, it wouldn't be **EQUI...
Is the shortcircuit behaviour of Python's any/all explicit?
14,730,046
20
2013-02-06T13:16:57Z
14,866,380
21
2013-02-14T01:29:39Z
[ "python" ]
Prompted by the discussion [here](http://stackoverflow.com/a/14721700/174728) The [docs](http://docs.python.org/2/library/functions.html#all) suggest some equivalent code for the behaviour of [`all`](http://docs.python.org/2/library/functions.html#all) and [`any`](http://docs.python.org/2/library/functions.html#any) ...
**The behaviour is guaranteed**. I've contributed a [patch](http://bugs.python.org/file29131/mywork.patch), which was accepted and [merged](http://bugs.python.org/issue17255) recently, so if you grab the latest sources you will see that the short-circuiting behaviour is now explicitly enforced. ``` hg clone http://hg....
Duck typing to allow tuples, lists, or something that can be treated like one
14,730,383
4
2013-02-06T13:33:10Z
14,730,416
8
2013-02-06T13:35:18Z
[ "python", "duck-typing" ]
``` def foo(spam, obj_of_interest): """Pass a _____ and an object of interest, and return [something that does something worthwhile] """ name = spam[0] quest = spam[1] fav_color = spam[2] # ... interesting code return obj_of_interest ``` You'll note that `foo()` can function perfectly regardless of...
You say, ``` """spam is an object that supports indexing.""" ```
Accessing Python dict keys with or without dict.keys()
14,730,481
4
2013-02-06T13:38:51Z
14,730,599
11
2013-02-06T13:45:35Z
[ "python", "loops", "dictionary" ]
Usually I access `dict` keys using `keys()` method: ``` d = {'a':1, 'b':2, 'c':3} for k in d.keys(): print k ``` But sometimes I see this code: ``` for k in d: print k ``` Is this code correct? safe?
To answer your explicit question, Yes, it is safe. To answer the question you didn't know you had: in python 2.x: `dict.keys()` returns a list of keys. But doing `for k in dict` iterates over them. Iterating is faster than constructing a list. in python 3+ explicitly calling `dict.keys()` is not slower because it ...
Replace element with a list in python
14,731,228
3
2013-02-06T14:16:50Z
14,731,283
11
2013-02-06T14:19:29Z
[ "python", "list" ]
In python, what is the best way to replace an element in a list with the elements from another list? For example, I have: ``` a = [ 1, 'replace_this', 4 ] ``` I want to replace `replace_this` with `[2, 3]`. After replacing it must be: ``` a = [ 1, 2, 3, 4 ] ``` **Update** Of course, it is possible to do with slic...
You can just use slicing: ``` >>> a = [ 1, 'replace_this', 4 ] >>> a[1:2] = [2, 3] >>> a [1, 2, 3, 4] ``` And as @mgilson points out - if you don't happen to know the position of the element to replace, then you can use `a.index` to find it... (see his comment) **update related to not using slicing** Using `itertoo...
Value Error when Slicing in Pandas
14,731,714
5
2013-02-06T14:42:12Z
14,731,958
14
2013-02-06T14:54:18Z
[ "python", "pandas" ]
I have a DataFrame that I would like to use the 'str.contrains()' method. I believed I had found how to do this when I read [pandas + dataframe - select by partial string](http://stackoverflow.com/questions/11350770/pandas-dataframe-select-by-partial-string). However, I keep getting a value error. My DataFrame is as f...
Your string search still returns nan values whereas the slicing operation works with booleans only. It appears 'na=False' is not working (in this case?), i can replicate it on my machine with the latest (released) Pandas version. You can workaround it by first applying the .fillna() function to the results like: ``` ...
Django HTTP 500 Error
14,731,988
6
2013-02-06T14:55:39Z
14,732,375
7
2013-02-06T15:15:54Z
[ "python", "django", "http", "templates" ]
I am creating a custom HTTP 500 error template. Why is it Django shows it when i raise an exception and not when I return HttpResponseServerError (I just get the default browser 500 error)? I find this behaviour strange...
The `HttpResponseServerError` inherits from `HttpResponse` and is actually quite simple: ``` class HttpResponseServerError(HttpResponse): status_code = 500 ``` So let's look at the `HttpResponse` constructor: ``` def __init__(self, content='', *args, **kwargs): super(HttpResponse, self).__init__(*args, **kwa...
NLTK Tagging spanish words using a corpus
14,732,465
8
2013-02-06T15:19:25Z
14,742,406
13
2013-02-07T02:12:06Z
[ "python", "nltk" ]
I am trying to learn how to tag spanish words using NLTK. From the [nltk book](http://nltk.org/book/ch05.html), It is quite easy to tag english words using their example. Because I am new to nltk and all language processing, I am quite confused on how to proceeed. I have downloaded the `cess_esp` corpus. Is there a w...
First you need to **read the tagged sentence from a corpus.** NLTK provides a nice interface to no bother with different formats from the different corpora; you can simply import the corpus use the corpus object functions to access the data. See <http://nltk.googlecode.com/svn/trunk/nltk_data/index.xml> . Then you hav...
Multi Index Sorting in Pandas
14,733,871
27
2013-02-06T16:24:31Z
14,734,148
35
2013-02-06T16:36:27Z
[ "python", "sorting", "pandas", "multi-index" ]
I have a dataset with multi-index columns in a pandas df that I would like to sort by values in a specific column. I have tried using sortindex and sortlevel but haven't been able get the results I am looking for. My dataset looks like: ``` Group1 Group2 A B C A B C 1 1 0 3 2 5 7 2 5 6 9 1 0...
When sorting by a MultiIndex you need to contain the tuple describing the column inside a list\*: ``` In [11]: df.sort([('Group1', 'C')], ascending=False) Out[11]: Group1 Group2 A B C A B C 2 5 6 9 1 0 0 1 1 0 3 2 5 7 3 7 0 2 0 3 5 ``` \* *so as...
How to access pandas groupby dataframe by key
14,734,533
51
2013-02-06T16:55:54Z
14,734,627
69
2013-02-06T17:00:27Z
[ "python", "group-by", "dataframe", "pandas" ]
How do I access the corresponding groupby dataframe in a groupby object by the key? With the following groupby: ``` rand = np.random.RandomState(1) df = pd.DataFrame({'A': ['foo', 'bar'] * 3, 'B': rand.randn(6), 'C': rand.randint(0, 20, 6)}) gb = df.groupby(['A']) ``` I can itera...
You can use the [`get_group`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.get_group.html) method: ``` In [21]: gb.get_group('foo') Out[21]: A B C 0 foo 1.624345 5 2 foo -0.528172 11 4 foo 0.865408 14 ``` *Note: This doesn't require creating an intermediar...
How to access pandas groupby dataframe by key
14,734,533
51
2013-02-06T16:55:54Z
17,302,673
38
2013-06-25T16:27:52Z
[ "python", "group-by", "dataframe", "pandas" ]
How do I access the corresponding groupby dataframe in a groupby object by the key? With the following groupby: ``` rand = np.random.RandomState(1) df = pd.DataFrame({'A': ['foo', 'bar'] * 3, 'B': rand.randn(6), 'C': rand.randint(0, 20, 6)}) gb = df.groupby(['A']) ``` I can itera...
Wes McKinney (pandas' author) in Python for Data Analysis provides the following recipe: ``` groups = dict(list(gb)) ``` which returns a dictionary whose keys are your group labels and whose values are DataFrames, i.e. ``` groups['foo'] ``` will yield what you are looking for: ``` A B C 0 foo 1.62...
How to access pandas groupby dataframe by key
14,734,533
51
2013-02-06T16:55:54Z
28,847,219
12
2015-03-04T05:25:09Z
[ "python", "group-by", "dataframe", "pandas" ]
How do I access the corresponding groupby dataframe in a groupby object by the key? With the following groupby: ``` rand = np.random.RandomState(1) df = pd.DataFrame({'A': ['foo', 'bar'] * 3, 'B': rand.randn(6), 'C': rand.randint(0, 20, 6)}) gb = df.groupby(['A']) ``` I can itera...
Rather than ``` gb.get_group('foo') ``` I prefer using `gb.groups` ``` df.loc[gb.groups['foo']] ``` Because in this way you can choose multiple columns as well. for example: ``` df.loc[gb.groups['foo'],('A','B')] ```
How to split a word into letters in Python
14,737,222
6
2013-02-06T19:31:06Z
14,737,242
19
2013-02-06T19:32:29Z
[ "python" ]
I was wondering if there is a straightforward way to do the following: Input string: ``` input = 'Hello' ``` Output string: ``` output = 'H,e,l,l,o' ``` I understand you can do `list(input)`, but that returns a list and I wanted to get the string rather than the list. Any suggestions?
``` In [1]: ','.join('Hello') Out[1]: 'H,e,l,l,o' ``` This makes use of the fact that strings are iterable and yield the individual characters when iterated over.
Get pip to work with git and github repository
14,737,500
6
2013-02-06T19:49:07Z
14,928,126
11
2013-02-18T01:11:47Z
[ "python", "django", "git", "github", "pip" ]
I'm writting a python app that depends on another one that is hosted on a github repository (never in pypi) for development reasons. Lets call them: * App being written: `AppA` * App in github: `AppB` In App A, the setup.py is like: ``` # coding=utf-8 import sys try: from setuptools import setup, find_packages ...
The problem is not with `pip`, is with `setuptools`. The responsible for the `setup()` call is `setuptools` package (setuptools or distribute project). Neither `setuptools` or `distribute` understand that kind of url, they understand tarballs/zip files. Try pointing to Github's download url - usually a zip file. You...
How to I delete all Flask sessions?
14,737,531
10
2013-02-06T19:50:47Z
14,737,616
16
2013-02-06T19:56:12Z
[ "python", "session", "flask" ]
How do I delete all sessions and cookies set by my Flask/python app. So that when users return they have to re-login. I want to do this each time I push a new version of the code to production otherwise.
Best way I found is to invalidate the secret key like so ``` app.secret_key = os.urandom(32) ``` The key is secure enough, and each time you launch your system the key changes invalidating all sessions.
Effective implementation of one-to-many relationship with Python NDB
14,739,044
10
2013-02-06T21:22:24Z
14,740,062
7
2013-02-06T22:25:28Z
[ "python", "google-app-engine", "app-engine-ndb" ]
I would like to hear your opinion about the effective implementation of one-to-many relationship with Python NDB. (e.g. Person(one)-to-Tasks(many)) In my understanding, there are three ways to implement it. 1. Use 'parent' argument 2. Use 'repeated' Structured property 3. Use 'repeated' Key property I choose a way b...
A key thing you are missing: How are you reading the data? If you are displaying all the tasks for a given person on a request, 2 makes sense: you can query the person and show all his tasks. However, if you need to query say a list of all tasks say due at a certain time, querying for repeated structured properties i...
How to grab most recently modified file
14,739,062
5
2013-02-06T21:23:24Z
14,739,115
9
2013-02-06T21:26:09Z
[ "python" ]
I have a folder with a bunch of files. Is there a way to select the file that is the most recently updated? For example: ``` FTP_FOLDER = os.path.join(os.getcwd(), 'ftp_folder') xml_files = [file for file in glob.glob(os.path.join(FTP_FOLDER, '*.xml'))] ``` Now, how to get the most recent xml\_file?
Use `os.path.getmtime` to get the file modification time: ``` import os xml_files.sort(key=os.path.getmtime) print xml_files[-1] # most recent file ```
Concatenating column vectors using numpy arrays
14,741,061
15
2013-02-06T23:45:08Z
14,753,067
34
2013-02-07T14:07:15Z
[ "python", "vector", "numpy", "concatenation" ]
I'd like to concatenate 'column' vectors using numpy arrays but because numpy sees all arrays as row vectors by default, `np.hstack` and `np.concatenate` along any axis don't help (and neither did `np.transpose` as expected). ``` a = np.array((0, 1)) b = np.array((2, 1)) c = np.array((-1, -1)) np.hstack((a, b, c)) # ...
I believe [numpy.column\_stack](http://docs.scipy.org/doc/numpy/reference/generated/numpy.column_stack.html) should do what you want. Example: ``` >>> a = np.array((0, 1)) >>> b = np.array((2, 1)) >>> c = np.array((-1, -1)) >>> numpy.column_stack((a,b,c)) array([[ 0, 2, -1], [ 1, 1, -1]]) ``` It is essential...
Python os.environ["HOME"] works on idle but not in a script
14,742,064
10
2013-02-07T01:29:57Z
14,742,225
13
2013-02-07T01:48:58Z
[ "python", "python-2.7", "cmd" ]
I am working on a simple Python (2.7.3) script, but I have to get the user's Home Folder. I tried: ``` import os home_folder = os.environ["HOME"] ``` And it works fine when I'm running this code on IDLE, but if I launch it from the cmd, it gives me: `«KeyError: 'HOME'»` Can someone tell me why? How can I solve thi...
Windows uses `USERPROFILE`, instead of `HOME`. Windows doesn't have `HOME` and other OSs don't have `USERPROFILE`, so using either of these drops platform independence. To keep platform independence, you can use `expanduser` from `os.path`, like so: ``` import os.path home_folder = os.path.expanduser('~') ``` On a s...
Time a while loop python
14,742,089
3
2013-02-07T01:32:13Z
14,742,193
7
2013-02-07T01:44:11Z
[ "python", "time", "while-loop" ]
I'm trying to time a while loop within a while loop, total time it takes to execute, and record the time it takes to do so, every time it loops. I need a way to achieve this using my code if possible, or open to different concepts I may not know of yet. ``` import random import time import sys def main(): loope...
When you set start outside your initial loop you are guaranteeing that you are getting the incorrect time it takes for the while loop to execute. It would be like saying: ``` program_starts = time.time() while(True): now = time.time() print("It has been {0} seconds since the loop started".format(now - program_...
How to check if an element exists in a Python array (Equivalent of PHP in_array)?
14,743,156
8
2013-02-07T03:43:53Z
14,743,170
21
2013-02-07T03:45:24Z
[ "python", "arrays", "lookup" ]
I'm new to Python and I'm looking for a standard function that would tell me if an element is present in an array. I found the `index` method but it throws an exception if the element is not found. I just need some simple function that would return `true` if the element is in the array or `false` if not. Basically an ...
``` >>> 1 in [0, 1, 2, 3, 4, 5] True ```
Counting values in dictionary
14,743,454
4
2013-02-07T04:17:00Z
14,743,473
13
2013-02-07T04:18:39Z
[ "python", "dictionary" ]
I have a dictionary as follows. ``` dictA = { 'a' : ('duck','duck','goose'), 'b' : ('goose','goose'), 'c' : ('duck','duck','duck'), 'd' : ('goose'), 'e' : ('duck','duck') } ``` I'm hoping to loop through dictA and output a list that will show me the keys in dictA that have more than one ...
``` [k for (k, v) in dictA.iteritems() if v.count('duck') > 1] ```
Python super(Class, self).method vs super(Parent, self).method
14,743,787
3
2013-02-07T04:51:18Z
14,743,879
9
2013-02-07T04:59:17Z
[ "python", "inheritance", "parent", "super" ]
This question is derive from the following [question](http://stackoverflow.com/questions/14739809/django-overwriting-modelform-save-causes-recursion), let's say `class B` extends `class A` ``` class A(object): def do_work(self): print 123 class B(A): def do_work(self): super(B,self).do_work() # versus the...
``` super(B,self).do_work() ``` will call the `do_work` function as seen by the parent class of `B` - that is, `A.do_work`. --- ``` super(A,self).do_work() ``` will call the `do_work` function as seen by the parent class of `A` - that is, `object.do_work` (which probably doesn't exist, and thus would likely raise a...
Prepend a level to a pandas MultiIndex
14,744,068
14
2013-02-07T05:16:07Z
14,746,845
33
2013-02-07T08:37:45Z
[ "python", "pandas" ]
I have a DataFrame with a MultiIndex created after some grouping: ``` import numpy as np import pandas as p from numpy.random import randn df = p.DataFrame({ 'A' : ['a1', 'a1', 'a2', 'a3'] , 'B' : ['b1', 'b2', 'b3', 'b4'] , 'Vals' : randn(4) }).groupby(['A', 'B']).sum() df Output> Vals Output> A ...
You can first add it as a normal column and then append it to the current index, so: ``` df['Firstlevel'] = 'Foo' df.set_index('Firstlevel', append=True, inplace=True) ``` And change the order if needed with: ``` df.reorder_levels(['Firstlevel', 'A', 'B']) ``` Which results in: ``` Vals First...
Parse XML with (X)HTML entities
14,744,945
13
2013-02-07T06:23:58Z
14,786,514
15
2013-02-09T09:03:47Z
[ "python", "xml", "python-3.x", "elementtree" ]
Trying to parse XML, with ElementTree, that contains undefined entity (i.e. `&nbsp;`) raises: `ParseError: undefined entity &nbsp;` In Python 2.x XML entity dict can be updated by creating parser ([documentation](http://effbot.org/elementtree/elementtree-xmlparser.htm#tag-ET.XMLParser.entity)): ``` parser = ET.XMLPa...
The issue here is that the only valid mnemonic entities in XML are `quot`, `amp`, `apos`, `lt` and `gt`. This means that almost all (X)HTML named entities must be defined in the DTD using the [entity declaration markup](http://www.w3.org/TR/2006/REC-xml11-20060816/#sec-entity-decl) defined in the [XML 1.1 spec](http://...
Pandas DataFrame, how do i split a column into two
14,745,022
18
2013-02-07T06:30:11Z
14,745,484
24
2013-02-07T07:03:46Z
[ "python", "dataframe", "pandas" ]
I have a data frame with one column and i'd like to split it into two columns, with one column header as '`fips'` and the other `'row'` My datFrame df looks like this currently ``` row 0 00000 UNITED STATES 1 01000 ALABAMA 2 01001 Autauga County, AL 3 01003 Baldwin County, AL 4 01005 Barbour ...
There might be a better way, but this here's one approach: ``` In [34]: import pandas as pd In [35]: df Out[35]: row 0 00000 UNITED STATES 1 01000 ALABAMA 2 01001 Autauga County, AL 3 01003 Baldwin County, AL 4 01005 Barbour County, AL In [36]: df = pd.DataFrame(df.row.s...
Pandas DataFrame, how do i split a column into two
14,745,022
18
2013-02-07T06:30:11Z
21,296,915
18
2014-01-23T00:20:07Z
[ "python", "dataframe", "pandas" ]
I have a data frame with one column and i'd like to split it into two columns, with one column header as '`fips'` and the other `'row'` My datFrame df looks like this currently ``` row 0 00000 UNITED STATES 1 01000 ALABAMA 2 01001 Autauga County, AL 3 01003 Baldwin County, AL 4 01005 Barbour ...
You can [extract](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html) the different parts out quite neatly using a regex pattern: ``` In [11]: df.row.str.extract('(?P<fips>\d{5})((?P<state>[A-Z ]*$)|(?P<county>.*?), (?P<state_code>[A-Z]{2}$))') Out[11]: fips 1 ...
Pandas DataFrame, how do i split a column into two
14,745,022
18
2013-02-07T06:30:11Z
32,850,652
11
2015-09-29T17:52:36Z
[ "python", "dataframe", "pandas" ]
I have a data frame with one column and i'd like to split it into two columns, with one column header as '`fips'` and the other `'row'` My datFrame df looks like this currently ``` row 0 00000 UNITED STATES 1 01000 ALABAMA 2 01001 Autauga County, AL 3 01003 Baldwin County, AL 4 01005 Barbour ...
If you don't want to create a new dataframe, or if your dataframe has more columns than just the ones you want to split, you could: ``` df["flips"], df["row_name"] = zip(*df["row"].str.split().tolist()) del df["row"] ```
How to merge two tuples in Python?
14,745,199
9
2013-02-07T06:44:46Z
14,745,503
12
2013-02-07T07:04:34Z
[ "python" ]
How to convert the following tuple: from: ``` (('aa', 'bb', 'cc'), 'dd') ``` to: ``` ('aa', 'bb', 'cc', 'dd') ```
``` l = (('aa', 'bb', 'cc'), 'dd') l = l[0] + (l[1],) ``` This will work for your situation, however [gnibbler's solution](http://stackoverflow.com/a/14745275/1907098) is better for general cases.
post request using python to asp.net page
14,746,750
8
2013-02-07T08:32:07Z
14,747,275
15
2013-02-07T09:04:28Z
[ "python", "http-post", "web-scraping" ]
i want scrap the PINCODEs from "<http://www.indiapost.gov.in/pin/>", i am doing with following code written. ``` import urllib import urllib2 headers = { 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Origin': 'http://www.indiapost.gov.in', 'User-Agent': 'Mozilla/5.0 (Windows ...
Where did you get the value `viewstate` and `eventvalidation`? On one hand, they shouldn't end with "...", you must have omitted something. On the other hand, they shouldn't be hard-coded. One solution is like this: 1. Retrieve the page via URL "<http://www.indiapost.gov.in/pin/>" without any form data 2. Parse and r...
Generate a set of sorted random numbers from a specific range
14,748,910
3
2013-02-07T10:31:40Z
14,748,975
8
2013-02-07T10:34:35Z
[ "python", "random", "generator" ]
I'd like to generate a set of x unique random numbers and sort them in Python. For example: range(1000, 10000) x = 100 I've figured out to import random and use the random.randrange method, then loop to get 100 random numbers and in the end sort them. However, I don't know how to get unique numbers (such that they do...
Use [`random.sample`](http://docs.python.org/3/library/random.html#random.sample) ``` numbers = random.sample(xrange(1000, 10000), 100) # or `range` in Python 3 ``` The sorting part is easy - use the [`list.sort`](http://docs.python.org/3/library/stdtypes.html#list.sort) method. ``` numbers.sort() ``` By default t...
Python: how to check whether optional function parameter is set
14,749,328
27
2013-02-07T10:52:05Z
14,749,388
18
2013-02-07T10:54:58Z
[ "python", "function", "optional-parameters" ]
Is there an easy way in Python to check whether the value of an optional parameter comes from its default value, or because the user has set it explicitly at the function call?
Not really. The standard way is to use a default value that the user would not be expected to pass, e.g. an `object` instance: ``` DEFAULT = object() def foo(param=DEFAULT): if param is DEFAULT: ... ``` Usually you can just use `None` as the default value, if it doesn't make sense as a value the user woul...
Python multiprocessing memory usage
14,749,897
4
2013-02-07T11:21:03Z
14,750,086
8
2013-02-07T11:31:54Z
[ "python", "linux", "memory-management", "multiprocessing" ]
I have writen a program that can be summarized as follows: ``` def loadHugeData(): #load it return data def processHugeData(data, res_queue): for item in data: #process it res_queue.put(result) res_queue.put("END") def writeOutput(outFile, res_queue): with open(outFile, 'w') as f ...
The `multiprocessing` module is effectively based on the `fork` system call which creates a copy of the current process. Since you are loading the huge data before you `fork` (or create the `multiprocessing.Process`), the child process inherits a copy of the data. However, if the operating system you are running on im...
Delete letters from string
14,750,675
7
2013-02-07T12:03:45Z
14,750,758
8
2013-02-07T12:08:22Z
[ "python" ]
I have strings like '12454v', '346346z'. I want to delete all letters from strings. Re works fine: ``` import re str='12454v' re.sub('[^0-9]','', str) #return '12454' ``` Is there a way to do this without using regular expressions?
``` >>> ''.join(filter(str.isdigit, '12454v')) '12454' ```
Catch python 'ImportError' if import from source directory
14,750,711
10
2013-02-07T12:05:43Z
14,750,951
8
2013-02-07T12:18:43Z
[ "python", "exception-handling", "importerror" ]
When one tries to import a module `foo` while being in the source directory, one gets an rather confusing `ImportError` message: `ImportError: No module named foo`. How can I easily catch this case and return a more informative message, e.g. 'Please do not load module foo from the source directory'? Having the `__ini...
`ImportError: No module named foo` actually means the module `foo.py` or package `foo/__init__.py` could not be found in any of the directories in the search path (`sys.path` list). Since `sys.path` usually contains `.` (the current directory), that's probably what you meant by *being in the source directory*. You are...
Computer Vision: Masking a human hand
14,752,006
6
2013-02-07T13:14:10Z
14,756,351
9
2013-02-07T16:44:14Z
[ "python", "opencv", "computer-vision" ]
I'd like to detect my hand from a live video stream and create a mask of my hand. However I'm reaching quite a poor result, as you can see from the picture. My goal is to track the hand movement, so what I did was convert the video stream from BGR to HSV color space then I thresholded the image in order to isolate the...
There are many ways to perform pixel-wise threshold to separate "skin pixels" from "non-skin pixels", and there are papers based on virtually any colorspace (even with RGB). So, my answer is simply based on the paper Face Segmentation Using Skin-Color Map in Videophone Applications by Chai and Ngan. They worked with th...
Python 3: using %s and .format()
14,753,844
20
2013-02-07T14:45:24Z
14,753,974
22
2013-02-07T14:50:58Z
[ "python", "string", "string-formatting" ]
I have finally switched from `%` to the `.format()` string formatting operator in my 2.x code in order to make it easier to migrate to 3.x in future. It was a bit surprising to find out that not only the `%`-style formatting remains in Py3, but it is widely used in the standard library code. It seems logical, because w...
Python 3.2 documentation said that, `%` will eventually go away. <http://docs.python.org/3.2/tutorial/inputoutput.html#old-string-formatting> > Since `str.format()` is quite new, a lot of Python code still uses the `%` > operator. However, because this old style of formatting will > eventually be removed from the lan...