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
matplotlib interactive graphing (manually drawing lines on a graph)
9,136,938
8
2012-02-03T23:38:07Z
9,226,239
8
2012-02-10T10:24:32Z
[ "python", "matplotlib" ]
I have succesfully plotted a set of date sequenced data (X axis is date) using matplotlib. However, I want to be able to **manually** draw lines from one (date1, y1) to another (date2, y2) on the plotted graph. I can't seem to find any examples that show how to do this - or indeed if it is even posible. To summarize,...
I would write something like this: ``` import matplotlib.pyplot as plt class LineDrawer(object): lines = [] def draw_line(self): ax = plt.gca() xy = plt.ginput(2) x = [p[0] for p in xy] y = [p[1] for p in xy] line = plt.plot(x,y) ax.figure.canvas.draw() ...
Python edge detection and curvature calculation
9,137,216
6
2012-02-04T00:14:39Z
9,173,965
9
2012-02-07T09:42:04Z
[ "python", "image-processing", "computer-vision" ]
I know the edge detection problem has been posted before (in Java: [Count the number of objects in an Image](http://stackoverflow.com/questions/2952165/count-the-number-of-objects-in-an-image), language independent: [Image edge detection](http://stackoverflow.com/questions/3540910/image-edge-detection)), but I want to ...
We have segmentation and edge detection algorithms in the actively developed `scikit-image` that you may find useful: [Scikit Images Examples](http://scikit-image.org/docs/dev/auto_examples/)
How can I calculate or monitor the training of a neural network in pybrain?
9,137,463
7
2012-02-04T00:54:33Z
9,344,722
8
2012-02-18T22:24:29Z
[ "python", "neural-network", "pybrain" ]
I have a neural network n pybrain,with two inputs,a hidden layer and a output layer.I use the following to train: ``` trainer = BackpropTrainer(net,ds) trainer.trainUntilConvergence() ``` net is the neural network and ds is the train data. My question is if and how I can calculate the time needed to complete the tra...
You could always subclass `BackpropTrainer` (source code [here](https://github.com/pybrain/pybrain/blob/master/pybrain/supervised/trainers/backprop.py)) and override `trainUntilConvergence` if using `maxEpochs` , track the percentage of completeness using the ratio between epochs and epochs. If not using `maxEpochs` y...
Looping over a list in Python
9,138,112
3
2012-02-04T03:17:49Z
9,138,132
9
2012-02-04T03:21:52Z
[ "python", "list" ]
I have a list with sublists in it. i want to print all the sublists with length equal to 3. I am doing the following in python: ``` for x in values[:]: if len(x)==3: print x ``` 'values' is the original list. Does the above code print all the sublist with length equal to 3 for each value of x? I want to ...
Try this, `x in mylist` is better and more readable than `x in mylist[:]` and your `len(x)` should be equal to `3`. ``` >>> mylist = [[1,2,3],[4,5,6,7],[8,9,10]] >>> for x in mylist: ... if len(x)==3: ... print x ... [1, 2, 3] [8, 9, 10] ``` or if you need more pythonic use [list-comprehensions](http://d...
Using map function with a multi-variable function
9,139,062
5
2012-02-04T07:01:33Z
9,139,097
9
2012-02-04T07:08:46Z
[ "python", "dictionary" ]
I have a multi-variable function and i would like to use the map() function with it. Example: ``` def f1(a, b, c): return a+b+c map(f1, [[1,2,3],[4,5,6],[7,8,9]]) ```
[`itertools.starmap`](http://docs.python.org/library/itertools.html#itertools.starmap) made for this: ``` import itertools def func1(a, b, c): return a+b+c print list(itertools.starmap(func1, [[1,2,3],[4,5,6],[7,8,9]])) ``` Output: ``` [6, 15, 24] ```
Python: storing print output from different module's function
9,139,525
2
2012-02-04T08:28:59Z
9,139,765
7
2012-02-04T09:16:55Z
[ "python" ]
I'm trying to store the print output from a function of another module imported, as a string and write it into a file. However, that function does not return a string, it only prints the output. so I need something like: ``` import someModule ...... f.open('test.v','w') out = storetheprintoutputasstring(someModule.mai...
I think what you're asking to do is a bit of a hack, so I assume you *have* to do it this way. Here is how you could redirect `stdout` to a file using the `with` statement: ``` import sys from contextlib import contextmanager @contextmanager def redirected(stdout): saved_stdout = sys.stdout sys.stdout = open...
How to set default value to all keys of a dict object in python?
9,139,897
24
2012-02-04T09:41:36Z
9,139,961
46
2012-02-04T09:52:34Z
[ "python", "dictionary" ]
I know you can use setdefault(key, value) to set default value for a given key, but is there a way to set default values of all keys to some value after creating a dict ? Put it another way, I want the dict to return the specified default value for every key I didn't yet set.
You can replace your old dictionary with a [`defaultdict`](http://docs.python.org/py3k/library/collections.html#collections.defaultdict): ``` >>> from collections import defaultdict >>> d = {'foo': 123, 'bar': 456} >>> d['baz'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'baz' >>...
How to get rows which match a list of 3-tuples conditions with SQLAlchemy
9,140,015
5
2012-02-04T10:04:08Z
9,140,163
7
2012-02-04T10:28:32Z
[ "python", "sql", "sqlalchemy" ]
Having a list of 3-tuples : ``` [(a, b, c), (d, e, f)] ``` I want to retrieve all the rows from a table where 3 columns matches the tuples. FOr this example, the query `WHERE` clause could be something like this : ``` (column_X = a AND column_Y = b AND column_Z = c) OR (column_X = d AND column_Y = e AND column_Z ...
Easiest way would be using SQLAlchemy-provided [tuple\_](http://docs.sqlalchemy.org/en/latest/core/sqlelement.html?highlight=tuple_#sqlalchemy.sql.expression.tuple_) function: ``` from sqlalchemy import tuple_ session.query(Foo).filter(tuple_(Foo.a, Foo.b, Foo.c).in_(items)) ``` **This works with PostgreSQL, but bre...
Ploting an x-y graph with "four" axes
9,140,643
5
2012-02-04T11:51:52Z
9,141,890
7
2012-02-04T15:19:55Z
[ "python", "matplotlib" ]
Generally, I'm trying to understand whether *matplotlib* actually has this capability. I have a ***speed*** (on x axis) in mph vs. ***power*** (on y axis) in kW graph, to which I need to add a ***rotations*** (on second y axis, **to the right**) and another ***speed*** (on second x axis, **up on the top**) in km/h. P...
Looking for [twinx](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.twinx) and [twiny](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.twiny)? ``` import matplotlib.pyplot as plt x = range(1,21) plt.xlabel('1st X') plt.ylabel('1st Y') plt.plot(x,x,'r') # against 1st x, 1...
Numpy error: invalid value encountered in power
9,140,744
6
2012-02-04T12:10:54Z
9,141,054
14
2012-02-04T12:57:33Z
[ "python", "numpy", "runtime-error" ]
I have the following code: ``` import numpy def numpysum(n): a = numpy.arange(n) ** 2 b = numpy.arange(n) ** 3 c = a + b return c size = 3000 c = numpysum(size) ``` When running, I get the error: > D:\Work\programming\python\test\_1\src\test1\_numpy.py:6: RuntimeWarning: invalid value encountered in p...
numpy is actually looking out for you on this one. Unlke in standard Python, its integer operations don't work on arbitrary-precision objects. I'd guess you were running a 32-bit python, because the same operations don't overflow for me: ``` >>> sys.maxsize 9223372036854775807 >>> size = 3000 >>> c = numpysum(size) >>...
OOP python - removing class instance from a list
9,140,857
3
2012-02-04T12:27:45Z
9,140,906
9
2012-02-04T12:33:28Z
[ "python", "list", "object" ]
I have a list where I save the objects created by a specific class. I would like to know, cause I can't manage to solve this issue, how do I delete an instance of the class from the list? This should happen based on knowing one attribute of the object.
Iterate through the list, find the object and its position, then delete it: ``` for i, o in enumerate(obj_list): if o.attr == known_value: del obj_list[i] break ```
How does numpy.histogram() work?
9,141,732
59
2012-02-04T14:56:40Z
9,141,822
84
2012-02-04T15:09:38Z
[ "python", "numpy", "histogram" ]
While reading up on numpy, I encountered the function [`numpy.histogram()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html). What is it for and **how does it work?** In the docs they mention **bins**: What are they? Some googling led me to the [definition of Histograms in general](http://en....
A bin is range that represents the width of a single bar of the histogram along the X-axis. You could also call this the interval. (Wikipedia defines them more formally as "disjoint categories".) The Numpy `histogram` function doesn't draw the histogram, but it computes the occurrences of input data that fall within e...
How does numpy.histogram() work?
9,141,732
59
2012-02-04T14:56:40Z
9,141,911
30
2012-02-04T15:23:04Z
[ "python", "numpy", "histogram" ]
While reading up on numpy, I encountered the function [`numpy.histogram()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html). What is it for and **how does it work?** In the docs they mention **bins**: What are they? Some googling led me to the [definition of Histograms in general](http://en....
``` import numpy as np hist, bin_edges = np.histogram([1, 1, 2, 2, 2, 2, 3], bins = range(5)) ``` Below, `hist` indicates that there are 0 items in bin #0, 2 in bin #1, 4 in bin #3, 1 in bin #4. ``` print(hist) # array([0, 2, 4, 1]) ``` `bin_edges` indicates that bin #0 is the interval [0,1), bin #1 is [1,2), .....
What is the Python best practice concerning dicts vs objects for simple key-value storage?
9,142,050
4
2012-02-04T15:44:50Z
9,142,105
8
2012-02-04T15:51:40Z
[ "javascript", "python", "object", "dictionary", "associative-array" ]
After some time programming in Javascript I have grown a little fond of the duality there between objects and associative arrays (dictionaries): ``` //Javascript var stuff = { a: 17, b: 42 }; stuff.a; //direct access (good sugar for basic use) stuff['a']; //key based access (good for flexibility and for foreach...
Not sure about "established best practices", but what I do is: 1. If the value types are homogenous – i.e. all values in the mappings are numbers, use a dict. 2. If the values are heterogenous, and if the mapping always has a given more or less constant set of keys, use an object. (Preferrably use an actual class, s...
Python regex match literal asterisk
9,142,736
3
2012-02-04T17:14:26Z
9,142,758
8
2012-02-04T17:17:06Z
[ "python", "regex" ]
Given the following string: ``` s = 'abcdefg*' ``` How can I match it or any other string only made of lowercase letters and *optionally* ending with an asterisk? I thought the following would work, but it does not: ``` re.match(r"^[a-z]\*+$", s) ``` It gives `None` and not a match object.
> How can I match it or any other string only made of lowercase letters and optionally ending with an asterisk? The following will do it: ``` re.match(r"^[a-z]+[*]?$", s) ``` 1. The `^` matches the start of the string. 2. The `[a-z]+` matches one or more lowercase letters. 3. The `[*]?` matches zero or one asterisks...
Django HTTP Request get vs getlist behavior
9,143,872
3
2012-02-04T19:35:53Z
9,411,632
7
2012-02-23T10:55:48Z
[ "python", "django" ]
I had a Django form that submitted a list of values to my view. I first tried retrieving the list using the **get** method but discovered that it only returned the last one and I should be using **getlist**. After some stumbling around I found a [closed Django bug](https://code.djangoproject.com/ticket/1130) that expla...
HTTP requests do support multiple values assigned to a one parameter (key). That's why people can use them and do (sometimes) use them. That's also why Django introduced the [`MultiValueDict`](http://djangoapi.quamquam.org/trunk/django.utils.datastructures.MultiValueDict-class.html) structure. Division into `get()` an...
Changing the class type of a class after inserted data
9,143,948
5
2012-02-04T19:44:55Z
9,143,995
11
2012-02-04T19:50:38Z
[ "python", "class", "python-3.x" ]
I want to create a class in python, which should work like this: 1. Data assigned, maybe bound to a variable (eg `a = exampleclass(data)` or just `exampleclass(data)`) 2. Upon being inserted data, it should automatically determine some properties of the data, and if some certain properties are fullfilled, it will auto...
Why not using a factory method? This one will decide which class to instanciate depending on the passed data. Using your example: ``` def create_number(number): if number < 1000: return SmallNumber(number) return BigNumber(number) ```
Changing the class type of a class after inserted data
9,143,948
5
2012-02-04T19:44:55Z
9,144,000
8
2012-02-04T19:50:58Z
[ "python", "class", "python-3.x" ]
I want to create a class in python, which should work like this: 1. Data assigned, maybe bound to a variable (eg `a = exampleclass(data)` or just `exampleclass(data)`) 2. Upon being inserted data, it should automatically determine some properties of the data, and if some certain properties are fullfilled, it will auto...
Don't. Use a factory function instead. ``` def create_number(source): if source < 1000: return Small_number(source) else: return Big_number(source) a = create_number(50) b = create_number(234234) c = create_number(2) ```
Changing the class type of a class after inserted data
9,143,948
5
2012-02-04T19:44:55Z
9,144,059
7
2012-02-04T19:58:58Z
[ "python", "class", "python-3.x" ]
I want to create a class in python, which should work like this: 1. Data assigned, maybe bound to a variable (eg `a = exampleclass(data)` or just `exampleclass(data)`) 2. Upon being inserted data, it should automatically determine some properties of the data, and if some certain properties are fullfilled, it will auto...
Using a [factory method](http://en.wikipedia.org/wiki/Factory_method_pattern) is the usual way to solve this, *especially* since instantiating a class is indistinguishable from calling a function in Python. However, if you *really* want, you can assign to `self.__class__`: ``` THRESHOLD = 1000 class Small(object): ...
Code to Generate e one Digit at a Time
9,144,154
3
2012-02-04T20:13:42Z
9,147,276
9
2012-02-05T06:03:04Z
[ "python", "algorithm", "math" ]
I am trying to make a constant random number generators (I mean a RNG that outputs a series of numbers that doesn't repeat, but stays the same every time it starts from the beginning). I have one for pi. I need an algorithm to generate e digit by digit to feed into the RNG, preferably in form of Python iterator or gene...
Yes! I did it with continued fraction! I found these code from [Generating digits of square root of 2](http://stackoverflow.com/questions/5187664/generating-digits-of-square-root-of-2) ``` def z(contfrac, a=1, b=0, c=0, d=1): for x in contfrac: while a > 0 and b > 0 and c > 0 and d > 0: t = a ...
Unknown encoding: idna in Python Requests
9,144,724
5
2012-02-04T21:30:24Z
13,057,751
8
2012-10-24T21:07:25Z
[ "python", "character-encoding", "python-requests", "http-request" ]
I'm using Python Requests. All works great but today I get this strange error: ``` [...] File "/usr/local/Cellar/python/2.7.2/lib/python2.7/site-packages/requests/models.py", line 321, in full_url netloc = netloc.encode('idna').decode('utf-8') LookupError: unknown encoding: idna ``` Any ideas what could be wrong?...
Try adding: ``` import encodings.idna ``` in various places to sift out other errors. I ran into this same problem working on a port of python to a new platform. We had only partial library support and `unicodedata` was missing which was causing imports of the idna module to fail. Once we ported `unicodedata` this er...
Calling private function within the same class python
9,145,499
7
2012-02-04T23:20:04Z
9,145,524
11
2012-02-04T23:25:01Z
[ "python", "function", "call", "private" ]
How can i call a private function from some other function within the same class? ``` class Foo: def __bar(arg): #do something def baz(self, arg): #want to call __bar ``` Right now, when i do this: ``` __bar(val) ``` from baz(), i get this: ``` NameError: global name '_Foo__createCodeBehind' is not def...
There is no implicit `this->` in Python like you have in C/C++ etc. You have to call it on `self`. ``` class Foo: def __bar(self, arg): #do something def baz(self, arg): self.__bar(arg) ``` --- These methods are not *really* private though. When you start a method name with two underscore...
Executing a Python script in Apache2
9,145,517
8
2012-02-04T23:23:38Z
9,145,915
15
2012-02-05T00:34:47Z
[ "python", "apache", "cgi" ]
I am trying to execute a Python program using Apache. However, Apache will only serve the file and not actually execute it. The permissions on the file are r/w/x and it is in `/var/www`. I will post the contents of `httpd.conf` and the program code after. I also tried to running the python script as a `.cgi` file but t...
The first line of httpd.conf: `AddHandler cgi-script .cgi .pl` is irrelevant, since you're testing python scripts and not perl scripts. And you should define those directives within the location of your python script, and tell apache that it should execute cgi scripts in that location: `Options +ExecCGI`. This snippet ...
how to limit/offset sqlalchemy orm relation's result?
9,148,316
7
2012-02-05T09:52:36Z
11,158,656
8
2012-06-22T14:52:22Z
[ "python", "orm", "sqlalchemy" ]
in case i have a user Model and article Model, user and article are one-to-many relation. so i can access article like this ``` user = session.query(User).filter(id=1).one() print user.articles ``` but this will list user's all articles, what if i want to limit articles to 10 ? in rails there is an `all()` method whi...
The solution is to use a `dynamic` relationship as described in the [collection configuration techniques](http://docs.sqlalchemy.org/en/rel_0_7/orm/collections.html) section of the SQLAlchemy documentation. By specifying the relationship as ``` class User(...): # ... articles = relationship('Articles', order_...
How do I add a module to the ipython autocomplete?
9,151,003
6
2012-02-05T16:46:18Z
9,151,043
10
2012-02-05T16:51:23Z
[ "python", "autocomplete", "module", "ipython" ]
I have just installed the `sqlalchemy` module in my computer but when I type `import sql` and `TAB` in the ipython prompt the autocomplete only suggests me the builtin `sqlite3` module. How do I get ipython to also suggest `sqlalchemy` on the import autocomplete?
Based on this message, ``` In [1]: import sq[TAB] Caching the list of root modules, please wait! (This will only be done once - type '%rehashx' to reset cache!) ``` have you tried `%rehashx` ?
How to iterate through a list of lists in python?
9,151,104
6
2012-02-05T16:59:46Z
9,151,126
20
2012-02-05T17:03:28Z
[ "python" ]
I have a list of lists like this. ``` documents = [['Human machine interface for lab abc computer applications','4'], ['A survey of user opinion of computer system response time','3'], ['The EPS user interface management system','2']] ``` Now i need to iterate through the above list and outp...
The simplest solution for doing exactly what you specified is: ``` documents = [sub_list[0] for sub_list in documents] ``` This is basically equivalent to the iterative version: ``` temp = [] for sub_list in documents: temp.append(sub_list[0]) documents = temp ``` This is however not really a general way of ite...
Installing scrapy/pyopenssl in Windows' virtualenv
9,151,268
16
2012-02-05T17:23:50Z
9,151,430
13
2012-02-05T17:41:53Z
[ "python", "windows", "virtualenv", "scrapy", "pyopenssl" ]
I am trying to [install scrapy](http://doc.scrapy.org/en/0.14/intro/install.html) on Windows XP (32bit) virtualenv: ``` pip install scrapy ``` The installer spits out this ambiguous error message: ``` error: Only found improper OpenSSL directories: ['E:\\cygwin', 'E:\\Program Files\\Git'] ``` How should I configure...
Apparently pyopenssl installation expects the binaries and libs to be laid out exactly as installed by [OpenSSL windows binaries](http://www.slproweb.com/products/Win32OpenSSL.html). Installing it from there (and not using cygwin's openssl for example), and adding the bin directory to the path solved this issue.
Python nltk: Find collocations without dot-separated words
9,151,326
5
2012-02-05T17:29:48Z
9,183,525
8
2012-02-07T20:39:00Z
[ "python", "nltk" ]
I am trying to find collocations with NLTK in a text by using the built-in method. Now I am having the following example text (*test* and *foo* follow each other, but there is a **sentence border** in between): ``` content_part = """test. foo 0 test. foo 1 test. foo 2 test. foo 3 test. foo 4 test. foo...
You could use WordPunctTokenizer to separate the punctuation from words and later filter out the bigrams with punctuation with apply\_word\_filter(). Same thing may be used for trigrams for not finding collocations over sentence borders. ``` from nltk import bigrams from nltk import collocations from nltk import Freq...
Iterating over list of dictionaries
9,152,431
7
2012-02-05T19:51:40Z
9,152,486
11
2012-02-05T19:58:00Z
[ "python" ]
I have a list -myList - where each element is a dictionary. I wish to iterate over this list but I am only interesting in one attribute - 'age' - in each dictionary each time. I am also interested in keeping count of the number of iterations. I do: ``` for i, entry in enumerate(myList): print i; print entry['...
You could use a generator to only grab ages. ``` # Get a dictionary myList = [{'age':x} for x in range(1,10)] # Enumerate ages for i, age in enumerate(d['age'] for d in myList): print i,age ``` And, yeah, don't use semicolons.
Sphinx values for attributes reported as None
9,153,473
10
2012-02-05T22:04:56Z
14,503,035
8
2013-01-24T13:56:13Z
[ "python", "python-sphinx" ]
When I use Sphinx autodoc to document a class, the values for the attributes are always reported, (as it says it should [here](http://sphinx.pocoo.org/latest/changes.html), under #437) but always as "= None" ``` Attribute = None Some Documentation ``` I include it like ``` .. autoclass:: core.SomeClass :membe...
There will be an `:annotation:` option (see [pull-request](https://bitbucket.org/birkenfeld/sphinx/pull-request/109)) in the upcoming version 1.2 of sphinx (and in the second beta). For `autodata`/`autoattribute` you can then force a specific value or suppress it. So in order to print no value for the attribute you wo...
Import module in another directory from a "parallel" sub-directory
9,153,527
6
2012-02-05T22:09:46Z
9,153,630
7
2012-02-05T22:21:50Z
[ "python" ]
I want to have a hierarchy that looks like this (and it has to look like this) ``` main_folder\ main.py domain_sub_directory\ __init__.py domain.py ui_sub_direcotory\ __init__.py menu.py ``` I need to activate ui.py frome main.py but then acces domain.py from menu.py. How c...
You asked the difference in the import statements. Its partially a matter of the namespace for which the object will be imported under, and also a way to limit the exact amount of code that is imported. ``` import os from os import path ``` Both os and os.path are modules. The first imports the entire os module and a...
Regex/code for removing "FWD", "RE", etc, from email subject
9,153,629
10
2012-02-05T22:21:40Z
9,154,184
12
2012-02-05T23:44:24Z
[ "python", "regex", "email" ]
Given an email subject line, I'd like to clean it up, getting rid of the "Re:", "Fwd", and other junk. So, for example, "[Fwd] Re: Jack and Jill's Wedding" should turn into "Jack and Jill's Wedding". Someone must've done this before, so I'm hoping you can point me to battle tested regex or code. Here are some example...
Try this one (replace with ''): ``` /([\[\(] *)?(RE|FWD?) *([-:;)\]][ :;\])-]*|$)|\]+ *$/igm ``` (If you put each subject through as its own string then you don't need the `m` modifier; this is just so that `$` matches end of line, not just end of string, for multiline string inputs). See it in action [here](http://...
python and XML: how to place two documents into a single document
9,153,844
6
2012-02-05T22:52:15Z
9,181,241
7
2012-02-07T17:53:27Z
[ "python", "xml", "dom" ]
Here's my code: ``` def extract_infos(i): blabla... blabla calculate v... dom = xml.dom.minidom.parseString(v) return dom doc = xml.dom.minidom.Document() for i in range(1,100): dom = extract_infos(i) for child in dom.childNodes: doc.appendChild(child.cloneNode(True)) ``` The two last...
Here is how XML documents can be appended to a single master root element using minidom. ``` from xml.dom import minidom, getDOMImplementation XML1 = """ <sub1> <foo>BAR1</foo> </sub1>""" XML2 = """ <sub2> <foo>BAR2</foo> </sub2>""" impl = getDOMImplementation() doc = impl.createDocument(None, "root", None) for ...
getting the index while interating a list
9,154,528
3
2012-02-06T00:49:15Z
9,154,548
8
2012-02-06T00:53:52Z
[ "python", "list", "loops" ]
while i'm interating a list, how can i get the id of the current item to reference it to list methods? ``` xl = [1,2,3] # initial list yl = [3,2] # list used to remove items from initial list for x in xl[:]: for y in yl: if x == y: xl.pop(x) # problem break print x, y pri...
The general way to do this is with `enumerate`. ``` for idx, item in enumerate(iterable): pass ``` But for your use case, this is not very pythonic way to do what you seem to be trying. Iterating over a list and modifying it at the same time should be avoided. Just use a list comprehension: ``` xl = [item for item...
Import a class variable from another module
9,155,079
7
2012-02-06T02:46:07Z
9,155,099
7
2012-02-06T02:52:18Z
[ "python", "import" ]
I'm trying to import just a variable inside a class from another module: ``` import module.class.variable # ImportError: No module named class.variable from module.class import variable # ImportError: No module named class from module import class.variable # SyntaxError: invalid syntax (the . is highlighted) ``` ...
``` variable = __import__('module').class.variable ```
How do I get SQLAlchemy to correctly insert a unicode ellipsis into a mySQL table?
9,155,264
13
2012-02-06T03:29:14Z
9,157,305
26
2012-02-06T08:20:59Z
[ "python", "mysql", "unicode", "sqlalchemy", "feedparser" ]
I am trying to parse an RSS feed with feedparser and insert it into a mySQL table using SQLAlchemy. I was actually able to get this running just fine but today the feed had an item with an ellipsis character in the description and I get the following error: UnicodeEncodeError: 'latin-1' codec can't encode character u'...
The error message ``` UnicodeEncodeError: 'latin-1' codec can't encode character u'\u2026' in position 35: ordinal not in range(256) ``` seems to indicate that some Python language code is trying to convert the character `\u2026` into a Latin-1 (ISO8859-1) string, and it is failing. Not surprising, that character is...
How to try-except an illegal matrix operation due to singularity in NumPy
9,155,478
8
2012-02-06T04:08:46Z
9,155,489
18
2012-02-06T04:10:59Z
[ "python", "numpy", "linear-algebra" ]
In NumPy, I'm trying to use `linalg` to compute matrix inverses at each step of a Newton-Raphson scheme (the problem size is small intentionally so that we can invert analytically computed Hessian matrices). However, after I get far along towards convergence, the Hessian gets close to singular. Is there any method wit...
The syntax would be like this: ``` import numpy try: # your code that will (maybe) throw except numpy.linalg.linalg.LinAlgError as err: if 'Singular matrix' in err.message: # your error handling block else: raise ```
regexp: match character group or end of line
9,155,590
14
2012-02-06T04:30:02Z
9,155,707
16
2012-02-06T04:51:32Z
[ "python", "regex" ]
How do you match `^` (begin of line) and `$` (end of line) in a `[]` (character group)? --- simple example haystack string: `zazty` rules: 1. match any "z" or "y" 2. if preceded by 1. an "a", "b"; or 2. at the beginning of the line. pass: match the first two "z" a regexp that would work is: `(?:^|[aAbB])...
You can't match a `^` or `$` within a `[]` because the only characters with special meaning inside a character class are `^` (as in "everything but") and `-` (as in "range") (and the character classes). `\A` and `\Z` just don't count as character classes. This is for all (standard) flavours of regex, so you're stuck w...
Valid JSON giving JSONDecodeError: Expecting , delimiter
9,156,417
7
2012-02-06T06:34:04Z
9,156,466
16
2012-02-06T06:39:51Z
[ "python", "json" ]
I'm trying to parse a json response data from youtube api but i keep getting an error. Here is the snippet where it choking: ``` data = json.loads("""{ "entry":{ "etag":"W/\"A0UGRK47eCp7I9B9WiRrYU0.\"" } }""") ``` ..and this happens: ``` JSONDecodeError: Expecting , delimiter: line 1 column 23 (char 23) ``` I've c...
You'll need a `r` before """, or replace all `\` with `\\`. This is not something you should care about when read the json from somewhere else, but something in the string itself. `data = json.loads(r"""{ "entry":{ "etag":"W/\"A0UGRK47eCp7I9B9WiRrYU0.\"" } }""")` see [here](http://docs.python.org/reference/lexical_an...
Hierarchical clustering of 1 million objects
9,156,961
16
2012-02-06T07:40:25Z
9,157,685
12
2012-02-06T08:59:00Z
[ "python", "machine-learning", "cluster-analysis", "data-mining", "hierarchical-clustering" ]
Can anyone point me to a hierarchical clustering tool (preferable in python) that can cluster ~1 Million objects? I have tried [`hcluster`](http://code.google.com/p/scipy-cluster/) and also [Orange](http://orange.biolab.si/). `hcluster` had trouble with 18k objects. Orange was able to cluster 18k objects in seconds, b...
The problem probably is that they will try to compute the full 2D distance matrix (about 8 GB naively with double precision) and then their algorithm will run in `O(n^3)` time anyway. You should seriously consider using a *different* clustering algorithm. Hierarchical clustering is slow and the results are not at all ...
Hierarchical clustering of 1 million objects
9,156,961
16
2012-02-06T07:40:25Z
9,466,570
7
2012-02-27T14:22:32Z
[ "python", "machine-learning", "cluster-analysis", "data-mining", "hierarchical-clustering" ]
Can anyone point me to a hierarchical clustering tool (preferable in python) that can cluster ~1 Million objects? I have tried [`hcluster`](http://code.google.com/p/scipy-cluster/) and also [Orange](http://orange.biolab.si/). `hcluster` had trouble with 18k objects. Orange was able to cluster 18k objects in seconds, b...
To beat O(n^2), you'll have to first reduce your 1M points (documents) to e.g. 1000 piles of 1000 points each, or 100 piles of 10k each, or ... Two possible approaches: * build a hierarchical tree from say 15k points, then add the rest one by one: time ~ 1M \* treedepth * first build 100 or 1000 flat clusters, t...
How do I raise the same Exception with a custom message in Python?
9,157,210
45
2012-02-06T08:07:56Z
9,157,277
39
2012-02-06T08:16:49Z
[ "python", "exception", "message" ]
I have this `try` block in my code: ``` try: do_something_that_might_raise_an_exception() except ValueError as err: errmsg = 'My custom error message.' raise ValueError(errmsg) ``` Strictly speaking, I am actually raising *another* `ValueError`, not the `ValueError` thrown by `do_something...()`, which is...
Update: **For Python 3, check Ben's answer** --- To attach a message to the current exception and re-raise it: (the outer try/except is just to show the effect) For python 2.x where x>=6: ``` try: try: raise ValueError # something bad... except ValueError as err: err.message=err.message+" hello...
How do I raise the same Exception with a custom message in Python?
9,157,210
45
2012-02-06T08:07:56Z
29,442,282
23
2015-04-04T03:06:49Z
[ "python", "exception", "message" ]
I have this `try` block in my code: ``` try: do_something_that_might_raise_an_exception() except ValueError as err: errmsg = 'My custom error message.' raise ValueError(errmsg) ``` Strictly speaking, I am actually raising *another* `ValueError`, not the `ValueError` thrown by `do_something...()`, which is...
I realize this question has been around for awhile, but once you're lucky enough to only support python 3.x, this really becomes a thing of beauty :) ### raise from We can chain the exceptions using [raise from](https://docs.python.org/3/reference/simple_stmts.html#raise). ``` try: 1 / 0 except ZeroDivisionError...
Python - write data into csv format as string (not file)
9,157,314
37
2012-02-06T08:21:49Z
9,157,338
22
2012-02-06T08:23:39Z
[ "python", "csv" ]
I want to cast data like `[1,2,'a','He said "what do you mean?"']` to a csv-formatted string. Normally one would use `csv.writer()` for this, because it handles all the crazy edge cases (comma escaping, quote mark escaping, CSV dialects, etc.) The catch is that `csv.writer()` expects to output to a file object, not to...
You could use [`StringIO`](http://docs.python.org/library/stringio.html) instead of your own `Dummy_Writer`: > This module implements a file-like class, `StringIO`, that reads and writes a string buffer (also known as memory files). There is also [`cStringIO`](http://docs.python.org/library/stringio.html#module-cStri...
Python - write data into csv format as string (not file)
9,157,314
37
2012-02-06T08:21:49Z
9,157,370
45
2012-02-06T08:27:11Z
[ "python", "csv" ]
I want to cast data like `[1,2,'a','He said "what do you mean?"']` to a csv-formatted string. Normally one would use `csv.writer()` for this, because it handles all the crazy edge cases (comma escaping, quote mark escaping, CSV dialects, etc.) The catch is that `csv.writer()` expects to output to a file object, not to...
In Python 3: ``` >>> import io >>> import csv >>> output = io.StringIO() >>> csvdata = [1,2,'a','He said "what do you mean?"',"Whoa!\nNewlines!"] >>> writer = csv.writer(output, quoting=csv.QUOTE_NONNUMERIC) >>> writer.writerow(csvdata) 59 >>> output.getvalue() '1,2,"a","He said ""what do you mean?""","Whoa!\nNewlines...
Python easy_install throws chmod-error
9,157,759
2
2012-02-06T09:07:40Z
12,681,269
8
2012-10-01T21:20:24Z
[ "python", "windows", "chmod", "easy-install" ]
I'm trying to install Python Fabric on Windows 7 using the guide from [Getting Python and Fabric Installed on Windows](http://www.jonnyreeves.co.uk/2011/08/getting-python-and-fabric-installed-on-windows/). To install PyCrypto and Fabric, i used easy\_install, as recommended in the guide, but both failed, returning an ...
[Download](http://sourceforge.net/projects/mingw/) and install `MinGW - Minimalist GNU for Windows`. To making some Unix commands accessible from the windows console, set in your `env` variables: ``` C:\MinGW\bin;C:\MinGW\mingw32\bin;C:\MinGW\msys\1.0\bin;C:\MinGW\msys\1.0\sbin ``` . Alternatively, from the console...
Good uses for mutable function argument default values?
9,158,294
14
2012-02-06T09:50:00Z
9,158,327
13
2012-02-06T09:54:30Z
[ "python", "arguments", "default-value", "mutable" ]
It is a common mistake to set a mutable object as the default value of an argument in a function. Here's an example taken from [this excellent write-up by David Goodger](http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html): ``` >>> def bad_append(new_item, a_list=[]): a_list.append(new_item) ...
You can use it to cache values between function calls: ``` def get_from_cache(name, cache={}): if name in cache: return name cache[name] = result = expensive_calculation() return result ``` but usually that sort of thing is done better with a class as you can then have additional attributes to clear the c...
Django/Python - Check a date is in current week
9,159,173
6
2012-02-06T11:04:18Z
9,159,217
16
2012-02-06T11:08:12Z
[ "python", "django", "datetime", "django-queryset" ]
I would like to do something like this: ``` entries = Entry.objects.filter(created_at__in = current_week()) ``` How to make it for good performance. Thanks! Edit: I still have no idea for `current_week()` function.
Use `__range`. You'll need to actually calculate the beginning and end of the week first: ``` import datetime date = datetime.date.today() start_week = date - datetime.timedelta(date.weekday()) end_week = start_week + datetime.timedelta(7) entries = Entry.objects.filter(created_at__range=[start_week, end_week]) ```
Can I add comments to a pip requirements file?
9,159,757
53
2012-02-06T11:59:20Z
9,160,112
52
2012-02-06T12:28:11Z
[ "python", "comments", "pip" ]
I'd like to add comments for a few packages in a pip requirements file. (Just to explain why that package is on the list.) Can I do this? I'm imagining something like ``` Babel==0.9.5 # translation CherryPy==3.2.0 # web server Creoleparser==0.7.1 # wiki formatting Genshi==0.5.1 # templating ```
Sure, you can, based on [`pip` docs](https://pip.pypa.io/en/latest/reference/pip_install.html#requirements-file-format): > A line that begins with # is treated as a comment and ignored. Whitespace followed by a # causes the # and the remainder of the line to be treated as a comment. Go ahead!
Can I add comments to a pip requirements file?
9,159,757
53
2012-02-06T11:59:20Z
9,160,135
8
2012-02-06T12:30:07Z
[ "python", "comments", "pip" ]
I'd like to add comments for a few packages in a pip requirements file. (Just to explain why that package is on the list.) Can I do this? I'm imagining something like ``` Babel==0.9.5 # translation CherryPy==3.2.0 # web server Creoleparser==0.7.1 # wiki formatting Genshi==0.5.1 # templating ```
[You can add comments (lines beginning with #)](http://stackoverflow.com/a/3665316/1128985)
Apache 2 + mod_wsgi + WSGIScriptAlias
9,160,105
4
2012-02-06T12:27:32Z
9,169,296
7
2012-02-07T00:15:04Z
[ "python", "django", "apache2", "mod-wsgi", "httpd.conf" ]
I am currently doing research whether Python and Django are fit for a project that I'm going to work on (so far it looks good). As a means of a test, I want to get python running on an actual server (apache2 on ubuntu), using mod\_wsgi, but I just can't make it work. Here is my httpd.conf (located at /etc/apache2/httpd...
Try: ``` WSGIScriptAlias /test/tc-test /var/www/stage/hello/tc-test/django.wsgi ``` You shouldn't have trailing slash on first argument.
What is the reason python handles locals() this way (in pairs)?
9,160,367
5
2012-02-06T12:50:07Z
9,160,431
8
2012-02-06T12:55:47Z
[ "python" ]
Get this simple python code, same matching with re.compile instance. I noticed that even though I am using the very same value, it creates two instances, and repeats them accordingly. I wonder if one can tell the reason for this behavior, * Why does it create the second instance at all? * Why only two? * And why each...
My *guess* is that this has something to do with the [return value being assigned](http://stackoverflow.com/questions/1538832/is-this-single-underscore-a-built-in-variable-in-python) to underscore (`_`) internally in the interactive python shell - i.e. since `_` is pointing to `<_sre.SRE_Match object at 0x23cb238>` 'ti...
Pythons platform.system() gives me str object has no attribute system but only in script
9,160,463
2
2012-02-06T12:58:36Z
9,160,515
8
2012-02-06T13:03:39Z
[ "python", "platform" ]
If I do like this in the python prompt: ``` import platform platform.system() ``` I get Linux as expected. However if I do like this in my script: ``` import platform if(platform.system() == "windows"): print x else: print y ``` I just get this error messsage. AttributeError: str object has no attribute system...
Somewhere in your script you have a variable called `platform` that shadows the module with the same name.
Format a string that has extra curly braces in it
9,161,355
9
2012-02-06T14:10:27Z
9,162,098
15
2012-02-06T15:02:07Z
[ "python", "escaping", "python-3.x", "string-formatting" ]
I have a LaTeX file I want to read in with Python 3 and format a value into the resultant string. Something like: ``` ... \textbf{REPLACE VALUE HERE} ... ``` But I have not been able to figure out how to do this since the new way of doing string formatting uses `{val}` notation and since it is a LaTeX document, there...
Method 1, which is what I'd actually do: use a [string.Template](http://docs.python.org/dev/library/string.html#template-strings) instead. ``` >>> from string import Template >>> Template(r'\textbf{This and that} plus \textbf{$val}').substitute(val='6') '\\textbf{This and that} plus \\textbf{6}' ``` Method 2: add ext...
Parse key value pairs in a text file
9,161,439
5
2012-02-06T14:15:01Z
9,161,513
9
2012-02-06T14:19:53Z
[ "python", "file" ]
I am a newbie with Python and I search how to parse a .txt file. My .txt file is a namelist with computation informations like : **myfile.txt** > var0 = 16 > var1 = 1.12434E10 > var2 = -1.923E-3 > var3 = 920 How to read the values and put them in `myvar0, myvar1, myvar2, myvar3` in python?
Try python standard module [configparser](http://docs.python.org/library/configparser.html)
Parse key value pairs in a text file
9,161,439
5
2012-02-06T14:15:01Z
9,161,531
20
2012-02-06T14:21:25Z
[ "python", "file" ]
I am a newbie with Python and I search how to parse a .txt file. My .txt file is a namelist with computation informations like : **myfile.txt** > var0 = 16 > var1 = 1.12434E10 > var2 = -1.923E-3 > var3 = 920 How to read the values and put them in `myvar0, myvar1, myvar2, myvar3` in python?
I suggest storing the values in a dictionary instead of in separate local variables: ``` myvars = {} with open("namelist.txt") as myfile: for line in myfile: name, var = line.partition("=")[::2] myvars[name.strip()] = float(var) ``` Now access them as `myvars["var1"]`. If the names are all valid p...
Submitting a form with mechanize (TypeError: ListControl, must set a sequence)
9,161,764
5
2012-02-06T14:37:34Z
9,162,633
8
2012-02-06T15:38:19Z
[ "python", "mechanize-python" ]
I'm trying to submit a form with mechanize but have run into an error (TypeError: ListControl, must set a sequence) After googling for some time and trying a couple of different solutions I haven't been able to solve the issue. I'm trying to submit all the fields. The form data fetched via mechanize (for f in br.forms...
`type` field expects a list of integers from you, but you provide just one integer. Change this: ``` br.form['type'] = '22' ``` to this: ``` br.form['type'] = ['22',] ```
Error installing pymssql on Mac OS X Lion
9,161,770
3
2012-02-06T14:37:55Z
9,624,507
11
2012-03-08T20:34:10Z
[ "python", "pymssql" ]
I have XCode installed and also FreeTDS. I tried to connect to my SQL Server and it works perfect. Now I have to develop an aplication on python that works with this SQL Server and I´m trying to install pymsql, but I got this error when I launche sudo python setup.py command: ``` ==> sudo python setup.py install run...
Unfortunately, pymssql's setup.py (as of version pymssql-2.0.0b1-dev-20111019) needs a bit of help to work properly on OSX Lion. The current setup.py tries to compile/link against some pre-built Linux FreeTDS libraries, and also tries to link against librt, which doesn't exist on OSX. Additionally, it only explicitly l...
How can I get Selenium Web Driver to wait for an element to be accessible, not just present?
9,161,773
23
2012-02-06T14:38:19Z
9,162,482
15
2012-02-06T15:28:25Z
[ "python", "selenium", "webdriver" ]
I am writing tests for a web application. Some commands pull up dialog boxes that have controls that are visible, but not available for a few moments. (They are greyed out, but webdriver still sees them as visible). How can I tell Selenium to wait for the element to be actually accessible, and not just visible? ``` ...
I assume the events timeline goes like this: 1. there are no needed elements on page. 2. needed element appears, but is disabled: `<input type="button" id="createFolderCreateBtn" disabled="disabled" />` 3. needed element becomes enabled: `<input type="button" id="createFolderCreateBtn" />` Currently you are...
How can I get Selenium Web Driver to wait for an element to be accessible, not just present?
9,161,773
23
2012-02-06T14:38:19Z
9,176,713
11
2012-02-07T13:01:28Z
[ "python", "selenium", "webdriver" ]
I am writing tests for a web application. Some commands pull up dialog boxes that have controls that are visible, but not available for a few moments. (They are greyed out, but webdriver still sees them as visible). How can I tell Selenium to wait for the element to be actually accessible, and not just visible? ``` ...
``` print time.time() try: print "about to look for element" def find(driver): e = driver.find_element_by_id("createFolderCreateBtn") if (e.get_attribute("disabled")=='true'): return False return e element = WebDriverWait(driver, 10).un...
Python Nose: Log tests results to a file with Multiprocess Plugin
9,162,224
11
2012-02-06T15:11:37Z
9,936,164
13
2012-03-30T02:24:01Z
[ "python", "logging", "multiprocessing", "nose" ]
Im trying to log my tests output to a file as well as running them concurrently. For this Im trying to use the multiprocess plugin and the xunit plugin. Im aware that they dont work together, xunit doesnt log anything because mutiprocess doesn't send the output directly. <https://github.com/nose-devs/nose/issues/2> ...
If you want to use basic redirection from the shell you can do ``` nosetests &> output.txt ``` But based on your question it seems you'd rather do something like: ``` $nosetests --processes 4 --with-xunit --xunit-file=test_output.xml ``` **Full example**: ``` $ls test_nose.py test_nose.pyc $cat test_nose.py i...
Highlighting python code blocks in vim
9,163,572
8
2012-02-06T16:34:37Z
9,164,272
8
2012-02-06T17:22:52Z
[ "python", "vim", "syntax-highlighting" ]
I wanted to highlight different indentation levels in vim, so I could identify large blocks of code more easily. I have some reasonable large nested for/while/with/try blocks and it gets hard to identify the block a am into, i.e. how many 'tabs' I have before the cursor. Is there a way to highlight tabs? This is what...
The [Indent Guides](https://github.com/nathanaelkane/vim-indent-guides) vim plug-in does exactly this kind of highlighting. I use it together with the `listchars` option (as Ackar pointed out).
python property getter/setter confusion
9,163,940
7
2012-02-06T16:58:22Z
9,164,034
15
2012-02-06T17:04:29Z
[ "python", "properties", "getter-setter" ]
I'm a bit confused about properties in python. Consider the following code ``` class A: @property def N(self): print("A getter") return self._N @N.setter def N(self,v): print("A setter") self._N = v def __init__(self): self._N = 1 class B: @property ...
A and B must be new-style classes in Python 2.x. [`property([fget[, fset[, fdel[, doc]]]])`](http://docs.python.org/glossary.html#term-new-style-class) > Return a property attribute for [new-style classes](http://docs.python.org/glossary.html#term-new-style-class) (classes that derive from [object](http://docs.python...
Custom columns using Django admin
9,164,610
8
2012-02-06T17:46:53Z
9,166,179
19
2012-02-06T19:42:34Z
[ "python", "django", "django-admin" ]
I have a model `Data`, associated to a table like this (The model `Data` is made up of only IntegerField): ``` subject | year | quarter | sales | ---------------------------------- 1 | 2010 | 1 | 20 | 1 | 2010 | 2 | 100 | 1 | 2010 | 3 | 100 | 1 | 2010 | 4 | 20 ...
You can use methods on your `Model` or your `ModelAdmin` as items for `list_display`. See: <https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display> Since these are methods that might be useful outside the admin, as well, I'd suggest adding them to your `Model`. ``` from ...
What are the upper and lower bound for Chinese char in UTF-8?
9,166,130
3
2012-02-06T19:37:56Z
9,169,489
10
2012-02-07T00:35:22Z
[ "python", "cjk" ]
I would like to make a set in python contains all the `ord()` of the Chinese chars: for English the equivalent is : ``` english = set(range(ord('a'),ord('z') + 1 ) + range(ord('A'),ord('Z') + 1 )) ```
From the Unicode Standard (v6.0, section 12.1), > Han ideographic characters are found in seven main blocks of the Unicode Standard, as shown in Table 12-2 ``` Table 12-2. Blocks Containing Han Ideographs Block | Range | Comment ----------------------------------------+-------...
Convert RGBA PNG to RGB with PIL
9,166,400
40
2012-02-06T19:58:12Z
9,166,671
8
2012-02-06T20:18:43Z
[ "python", "png", "jpeg", "python-imaging-library", "rgba" ]
I'm using PIL to convert a transparent PNG image uploaded with Django to a JPG file. The output looks broken. ### Source file ![transparent source file](http://i.stack.imgur.com/I2uNe.png) ### Code ``` Image.open(object.logo.path).save('/tmp/output.jpg', 'JPEG') ``` or ``` Image.open(object.logo.path).convert('RG...
The transparent parts mostly have RGBA value (0,0,0,0). Since the JPG has no transparency, the jpeg value is set to (0,0,0), which is black. Around the circular icon, there are pixels with nonzero RGB values where A = 0. So they look transparent in the PNG, but funny-colored in the JPG. You can set all pixels where A...
Convert RGBA PNG to RGB with PIL
9,166,400
40
2012-02-06T19:58:12Z
9,459,208
46
2012-02-27T02:03:07Z
[ "python", "png", "jpeg", "python-imaging-library", "rgba" ]
I'm using PIL to convert a transparent PNG image uploaded with Django to a JPG file. The output looks broken. ### Source file ![transparent source file](http://i.stack.imgur.com/I2uNe.png) ### Code ``` Image.open(object.logo.path).save('/tmp/output.jpg', 'JPEG') ``` or ``` Image.open(object.logo.path).convert('RG...
Here's a version that's much simpler - not sure how performant it is. Heavily based on some django snippet I found while building `RGBA -> JPG + BG` support for sorl thumbnails. ``` from PIL import Image png = Image.open(object.logo.path) png.load() # required for png.split() background = Image.new("RGB", png.size, ...
inheritance on class attributes (python)
9,166,523
5
2012-02-06T20:06:27Z
9,166,592
8
2012-02-06T20:12:17Z
[ "python", "inheritance", "override" ]
Is there a way to accomplish something like this? I work in Python, but I am not sure if there is a way to do it in any programming language... ``` class Parent(): class_attribute = "parent" @staticmethod def class_method(): print __class__.class_attribute class Child(Parent): class_attribute...
Er, sounds like you want a classmethod, which not surprisingly is done with the `classmethod` decorator: ``` class Parent(object): class_attribute = "parent" @classmethod def class_method(cls): print cls.class_attribute class Child(Parent): class_attribute = "child" >>> Parent.class_method(...
Python: Using a dictionary to select function to execute
9,168,340
4
2012-02-06T22:33:38Z
9,168,387
13
2012-02-06T22:37:10Z
[ "python", "function", "dictionary", "inspect" ]
Hello I am new in Python, I am trying to use functional programming to create a dictionary containing a key and a function to execute: ``` myDict={} myItems=("P1","P2","P3",...."Pn") def myMain(key): def ExecP1(): pass def ExecP2(): pass def ExecP3(): pass ... def ExecPn...
Simplify, simplify, simplify ``` def p1( args ): whatever def p2( more args): whatever myDict={ "P1": p1, "P2", p2, ... "Pn", pn } def myMain(name): myDict[name] ``` That's all you need.
Suppressing treatment of string as iterable
9,168,904
11
2012-02-06T23:27:57Z
9,168,967
7
2012-02-06T23:37:04Z
[ "string", "python-3.x", "python", "iterable" ]
**UPDATE:** An idea to make built-in strings non-iterable was [proposed on python.org in 2006](http://mail.python.org/pipermail/python-3000/2006-April/000759.html). My question differs in that I'm trying to only suppress this features once in a while; still this whole thread is quite relevant. Here are the critical [...
To expand, and make an answer out of it: No, you shouldn't do this. 1. It changes the functionality people expect from strings. 2. It means extra overhead throughout your program. 3. It's largely unnecessary. 4. Checking types is very unpythonic. You can do it, and the methods you have given are probably the best wa...
Suppressing treatment of string as iterable
9,168,904
11
2012-02-06T23:27:57Z
9,168,987
7
2012-02-06T23:39:07Z
[ "string", "python-3.x", "python", "iterable" ]
**UPDATE:** An idea to make built-in strings non-iterable was [proposed on python.org in 2006](http://mail.python.org/pipermail/python-3000/2006-April/000759.html). My question differs in that I'm trying to only suppress this features once in a while; still this whole thread is quite relevant. Here are the critical [...
There aren't any ways to do this automatically, unfortunately. The solution you propose (a `str` subclass that isn't iterable) suffers from the same problem as `isinstance()` ... namely, you have to remember to use it everywhere you use a string, because there's no way to make Python use it in place of the native class...
How can I add a python tuple to a YAML file using pyYAML?
9,169,025
6
2012-02-06T23:43:36Z
9,169,553
8
2012-02-07T00:43:06Z
[ "python", "pyyaml" ]
The title is fairly self-explanatory. When I save a tuple to a YAML file, I get something that looks like this: ``` ambient: !!python/tuple [0.3, 0.3 ,0.3] ``` When I try to load it with yaml.safe\_load(file\_object), I keep getting an error that reads: ``` yaml.constructor.ConstructorError: could not determine a...
In pyyaml, the SafeLoader does not include a loader for the python native types, only the types defined in the yaml spec. You can see the types for the `SafeLoader` and the `Loader` here in the interaction sample below. You can define a new Loader class that adds in the python tuple, but not other types, so it should ...
Partial coloring of text in matplotlib
9,169,052
24
2012-02-06T23:47:19Z
9,185,143
13
2012-02-07T22:42:42Z
[ "python", "matplotlib" ]
Is there a way in matplotlib to partially specify the color of a string? Example: ``` plt.ylabel("Today is cloudy.") ``` How can I show "today" as red, "is" as green and "cloudy." as blue? Thanks.
I only know how to do this non-interactively, and even then only with the 'PS' backend. To do this, I would use Latex to format the text. Then I would include the 'color' package, and set your colors as you wish. Here is an example of doing this: ``` import matplotlib matplotlib.use('ps') from matplotlib import rc ...
Partial coloring of text in matplotlib
9,169,052
24
2012-02-06T23:47:19Z
9,185,851
16
2012-02-07T23:48:30Z
[ "python", "matplotlib" ]
Is there a way in matplotlib to partially specify the color of a string? Example: ``` plt.ylabel("Today is cloudy.") ``` How can I show "today" as red, "is" as green and "cloudy." as blue? Thanks.
here's the interactive version (same one I posted to [the list](http://old.nabble.com/Partial-coloring-of-text-in-matplotlib-td33279901.html)) ``` import matplotlib.pyplot as plt from matplotlib import transforms def rainbow_text(x,y,ls,lc,**kw): """ Take a list of strings ``ls`` and colors ``lc`` and place t...
In python, how can I test if a path is a symbolic link?
9,170,015
4
2012-02-07T01:54:17Z
9,170,020
8
2012-02-07T01:55:15Z
[ "python" ]
In python, how can I test if a path *is* a symbolic link? I'm sure it has to do with the [os package](http://docs.python.org/library/os.html), but my searching of the documentation text didn't yield a result. I'm using version 2.7 at the moment.
Close, but no cigar. You want the [os.path module](http://docs.python.org/library/os.path.html). Check out [`os.path.islink()`](http://docs.python.org/library/os.path.html#os.path.islink).
Need to Pretty-Print Twitter JSON Data to a File using Python
9,170,288
17
2012-02-07T02:37:47Z
9,170,313
12
2012-02-07T02:41:22Z
[ "python", "json", "twitter", "pretty-print" ]
A project for class involves parsing Twitter JSON data. I'm getting the data and setting it to the file without much trouble, but it's all in one line. This is fine for the data manipulation I'm trying to do, but the file is ridiculously hard to read and I can't examine it very well, making the code writing for the dat...
You can parse the JSON, then output it again with indents like this: ``` import json mydata = json.loads(output) print json.dumps(mydata, indent=4) ``` See <http://docs.python.org/library/json.html> for more info.
Need to Pretty-Print Twitter JSON Data to a File using Python
9,170,288
17
2012-02-07T02:37:47Z
9,170,531
11
2012-02-07T03:14:33Z
[ "python", "json", "twitter", "pretty-print" ]
A project for class involves parsing Twitter JSON data. I'm getting the data and setting it to the file without much trouble, but it's all in one line. This is fine for the data manipulation I'm trying to do, but the file is ridiculously hard to read and I can't examine it very well, making the code writing for the dat...
``` header, output = client.request(twitterRequest, method="GET", body=None, headers=None, force_auth_header=True) # now write output to a file twitterDataFile = open("twitterData.json", "w") # magic happens here to make it pretty-printed twitterDataFile.write(simplejson.dumps(simplejson.lo...
How to partially set arguments to a function without running it?
9,170,430
4
2012-02-07T02:59:27Z
9,170,444
7
2012-02-07T03:00:48Z
[ "python", "function" ]
I'm trying to make life as easy as possible for my users while providing them with complete flexibility. I need to write functions for them to use, but the trick is that a user needs to pick the function before running it. Here's what I would like to do: ``` def standardGenerator(obj,param=8.0): # algorithm which g...
Well, another way to do this is to use [`functools.partial`](http://docs.python.org/library/functools.html#functools.partial).
surface plots in matplotlib
9,170,838
41
2012-02-07T04:02:45Z
9,170,879
44
2012-02-07T04:09:24Z
[ "python", "matplotlib" ]
I have a list of 3-tuples representing a set of points in 3D space. I want to plot a surface that covers all these points. The plot\_surface function in the mplot3d package requires as arguments X,Y and Z which are 2d arrays. Is plot\_surface the right function to plot surface and how do I transform my data in to the r...
For surfaces it's a bit different than a list of 3-tuples, you should pass in a grid for the domain in 2d arrays. If all you have is a list of 3d points, rather than some function `f(x, y) -> z`, then you will have a problem because there are multiple ways to triangulate that 3d point cloud into a surface. Here's a s...
How do you get the magnitude of a vector in Numpy?
9,171,158
56
2012-02-07T04:48:50Z
9,171,196
76
2012-02-07T04:54:44Z
[ "python", "numpy" ]
In keeping with the "There's only one obvious way to do it", how do you get the magnitude of a vector (1D array) in Numpy? ``` def mag(x): return math.sqrt(sum(i**2 for i in x)) ``` The above works, but I *cannot believe* that I must specify such a trivial and core function myself.
The function you're after is [`numpy.linalg.norm`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.norm.html). (I reckon it should be in base numpy as a property of an array -- say `x.norm()` -- but oh well). ``` import numpy as np x = np.array([1,2,3,4,5]) np.linalg.norm(x) ``` You can also feed in ...
How do you get the magnitude of a vector in Numpy?
9,171,158
56
2012-02-07T04:48:50Z
9,184,560
45
2012-02-07T21:52:18Z
[ "python", "numpy" ]
In keeping with the "There's only one obvious way to do it", how do you get the magnitude of a vector (1D array) in Numpy? ``` def mag(x): return math.sqrt(sum(i**2 for i in x)) ``` The above works, but I *cannot believe* that I must specify such a trivial and core function myself.
If you are worried at all about speed, you should instead use: ``` mag = np.sqrt(x.dot(x)) ``` Here are some benchmarks: ``` >>> import timeit >>> timeit.timeit('np.linalg.norm(x)', setup='import numpy as np; x = np.arange(100)', number=1000) 0.0450878 >>> timeit.timeit('np.sqrt(x.dot(x))', setup='import numpy as np...
How can I make this Project Euler solution execute in Python at the same speed as Java?
9,171,457
7
2012-02-07T05:33:21Z
9,171,661
7
2012-02-07T05:57:41Z
[ "java", "python", "performance" ]
Before anyone starts in, I know that talking about "speed" in a programming language isn't always the most... useful discussion. That said, speed is the issue here. I tackled [Project Euler problem 5](http://projecteuler.net/problem=5) in both languages and, while my implementations in both languages look fairly simil...
Python is a dynamically typed language, while Java is a statically typed language. This means that Java has more readily available information at compile time about what types your variables are, in particular numbers. Java's designers spent quite a bit of effort defining the JVM in such a way that 32-bit (`int`) and 6...
Spawning functions asynchronously using Gevents
9,171,471
5
2012-02-07T05:35:23Z
9,178,667
9
2012-02-07T15:10:44Z
[ "python", "asynchronous", "gevent" ]
I was undergoing Gevents ( python library for asych functionality ) and wrote a very small program to understand how it works , but the results were quite baffling. The below is the code ``` import gevent import time def mytime(t): time.sleep(t) print " i have slept for ",t,"secs" x = range (0,10) x.rever...
Your reaction to the tutorial seems to show that you've missed part of what it's trying to show. In the asynchronous part of the tutorial's code, the main reason that the tasks finish in a random order is because they've **slept for a random period of time**. They **still** sleep for a random period of time in the sy...
Using pyramid authentication with pyramid
9,171,519
9
2012-02-07T05:41:39Z
9,171,925
13
2012-02-07T06:28:45Z
[ "python", "authorization", "pyramid" ]
In the pyramid documentation, the Sqlalchemy Dispatch Tutorial uses dummy data in `security.py`. I needed to use mysql data so I implemented it like this: **My Login Code** ``` @view_config(route_name='login', renderer='json',permission='view') def user_login(request): session = DBSession username = request.p...
You have the idea right. Your groupfinder is broken right now. Notice you have a for-loop with a return statement inside. The groupfinder should return **at least** an empty list `[]` if the user is valid. Only return `None` if the user is invalid. Also an md5 of the password is pretty crappy these days. Look at the ...
Python OpenCV cv.WaitKey spits back weird output on Ubuntu modulo 256 maps correctly
9,172,170
9
2012-02-07T06:57:12Z
9,191,027
10
2012-02-08T09:57:24Z
[ "python", "opencv", "modulo" ]
I am running Ubuntu 11.10 (Lenovo T400) with OpenCV 2.2 (I believe as imports are done as import cv2.cv as cv). This problem also happens if i just 'import cv' instead. I recently started having this problem, and it's kind of a weird one. I don't know anything significant I did, I have restarted since it started happe...
The modulus works because the information about the key is stored in the **last 8 bits** of the return value. A `k & 255` will also pick the last 8 bits: ``` >>> k = 1048678 >>> chr(k & 255) 'f' ``` In Python, `chr(n)` will return the character corresponding to *n*. Unfortunately, OpenCV documentation [presents no in...
Setting up Vim for Python
9,172,802
51
2012-02-07T08:02:58Z
9,172,881
14
2012-02-07T08:10:55Z
[ "python", "vim", "configuration", "editor", "indentation" ]
I really like the Emacs editor for Python because of it's smart tabbing for instance if I have something like this ``` def foo(): if bar: blah [b]eep ``` and I press tab on the cursor (which is on the b of beep), it will not insert a new tab causing a syntax error but it would toggle through the...
Put the following in your `.vimrc` ``` autocmd BufRead *.py set smartindent cinwords=if,elif,else,for,while,try,except,finally,def,class autocmd BufRead *.py set nocindent autocmd BufWritePre *.py normal m`:%s/\s\+$//e `` filetype plugin indent on ``` See also the [detailed instructions](http://henry.precheur.org/vim...
Setting up Vim for Python
9,172,802
51
2012-02-07T08:02:58Z
9,173,643
80
2012-02-07T09:16:09Z
[ "python", "vim", "configuration", "editor", "indentation" ]
I really like the Emacs editor for Python because of it's smart tabbing for instance if I have something like this ``` def foo(): if bar: blah [b]eep ``` and I press tab on the cursor (which is on the b of beep), it will not insert a new tab causing a syntax error but it would toggle through the...
In general, vim is a very powerful **regular language** editor (macros extend this but we'll ignore that for now). This is because vim's a thin layer on top of ed, and ed isn't much more than a line editor that speaks regex. Emacs has the advantage of being built on top of ELisp; lending it the ability to easily parse ...
Setting up Vim for Python
9,172,802
51
2012-02-07T08:02:58Z
17,501,672
21
2013-07-06T09:43:50Z
[ "python", "vim", "configuration", "editor", "indentation" ]
I really like the Emacs editor for Python because of it's smart tabbing for instance if I have something like this ``` def foo(): if bar: blah [b]eep ``` and I press tab on the cursor (which is on the b of beep), it will not insert a new tab causing a syntax error but it would toggle through the...
For those arriving around summer 2013, I believe some of this thread is outdated. I followed [this howto](http://unlogic.co.uk/2013/02/08/vim-as-a-python-ide/) which recommends Vundle over Pathogen. After one days use I found installing plugins trivial. The klen/python-mode plugin deserves special mention. It provide...
How to add numbers in nested Python lists
9,172,919
2
2012-02-07T08:15:06Z
9,172,954
8
2012-02-07T08:18:51Z
[ "python", "nested-lists" ]
I have a list ``` [["Sunday", 7, 0], ["Sunday", 2, 0], ["Monday", 1, 5], ["Tuesday", 5, 0], ["Thursday", 2, 0], ["Friday", 3, 0], ["Friday", 1, 0], ["Saturday", 4, 0], ["Monday", 8, 0], ["Monday", 1, 0], ["Tuesday", 1, 0], ["Tuesday", 2, 0], ["Wednesday", 0, 5]] ``` Can I add the values in the lists to get sums like ...
This is precisely what [`reduce()`](http://docs.python.org/library/functions.html#reduce) is made for: ``` In [4]: reduce(lambda x,y:['',x[1]+y[1],x[2]+y[2]], l) Out[4]: ['', 37, 10] ``` where `l` is your list. This traverses the list just once, and naturally lends itself to having different -- possibly more complic...
Why isn't the 'insert' function adding rows using MySQLdb?
9,173,073
4
2012-02-07T08:28:23Z
9,173,122
11
2012-02-07T08:32:23Z
[ "python", "mysql", "sql", "insert", "mysql-python" ]
I'm trying to figure out how to use the MySQLdb library in Python (I am novice at best for both of them). I'm following the code [here](http://www.kitebird.com/articles/pydbapi.html), specifically: ``` cursor = conn.cursor () cursor.execute ("DROP TABLE IF EXISTS animal") cursor.execute (""" CREATE TABLE animal ...
You forget `commit` data changes, autocommit is disabled by default: ``` cursor.close () conn.commit () conn.close () ``` Quoting [Writing MySQL Scripts with Python DB-API](http://www.kitebird.com/articles/pydbapi.html) documentation: > "The connection object commit() method commits any outstanding changes ...
Inline for in expression evaluation
9,175,262
9
2012-02-07T11:16:26Z
9,175,305
11
2012-02-07T11:20:05Z
[ "python", "syntax", "for-loop", "list-comprehension" ]
Is there a way I could inline this for loop? ``` already_inserted = True for i in indexes: already_inserted = already_inserted and bitfield[i] ```
``` already_inserted = all(bitfield[i] for i in indexes) ```
Inline for in expression evaluation
9,175,262
9
2012-02-07T11:16:26Z
9,175,307
10
2012-02-07T11:20:08Z
[ "python", "syntax", "for-loop", "list-comprehension" ]
Is there a way I could inline this for loop? ``` already_inserted = True for i in indexes: already_inserted = already_inserted and bitfield[i] ```
How about: ``` already_inserted = all(bitfield[i] for i in indexes) ```
Python: unpack format characters
9,176,354
4
2012-02-07T12:34:04Z
9,177,145
7
2012-02-07T13:31:42Z
[ "python", "perl", "unpack" ]
I need the python analog for this perl string: ``` unpack ("nNccH*", string_val) ``` I need the `nNccH*` - data format in python format characters In perl it unpack binary data to 5 variables: * 16 bit value in "network" (big-endian) * 32 bit value in "network" (big-endian) * signed char (8-bit integer) value * sig...
The Perl format `"nNcc"` is equivalent to the Python format `"!HLbb"`. There is no direct equivalent in Python for Perl's `"H*"`. There are two problems. * Python's `struct.unpack` does not accept the wildcard character, `*` * Python's `struct.unpack` does not "hexlify" data strings The first problem can be worked-a...
Why does 1.__add__(1) yield a syntax error?
9,177,349
6
2012-02-07T13:46:26Z
9,177,414
11
2012-02-07T13:50:17Z
[ "python" ]
Why does ``` 1.__add__(1) ``` yield `SyntaxError: invalid syntax`? What do the extra brackets add? ``` (1).__add__(1) ```
This is an effect of the tokenizer: `1.__add__(1)` is split into the tokens `"1."`, `"__add__"`, `"("`, `"1"`, and `")"`, since the tokenizer always tries to built the longest possible token. The first token is a floating point number, directly followed by an identifier, which is meaningless to the parser, so it throws...
Updating XML Elements and Attribute values using Python etree
9,177,360
4
2012-02-07T13:46:58Z
9,183,367
7
2012-02-07T20:29:10Z
[ "python", "xml", "elementtree", "xml.etree" ]
I'm very new to Python scripting, I'm trying to use 2.7 ElementTree to parse an XML file then update/replace specific element attributes with values sourced from a test data file. The idea is to be able to use a base XML file to then load and populate fields with specific test data etc. then save out as a unique XML fi...
For this kind of work, I always recommend [`BeautifulSoup`](http://www.crummy.com/software/BeautifulSoup/) because it has a really easy to learn API: ``` from BeautifulSoup import BeautifulStoneSoup as Soup xml = """ <TrdCaptRpt RptID="10000001" TransTyp="0"> <RptSide Side="1" Txt1="XXXXX"> <Pty ID="XXXXX...
Python UTF-16 CSV reader
9,177,820
7
2012-02-07T14:16:31Z
9,177,937
24
2012-02-07T14:23:51Z
[ "python", "csv", "utf-16" ]
I have a UTF-16 CSV file which I have to read. Python csv module does not seem to support UTF-16. I am using python 2.7.2. CSV files I need to parse are huge size running into several GBs of data. Answers for John Machin questions below ``` print repr(open('test.csv', 'rb').read(100)) ``` Output with test.csv havin...
At the moment, the csv module does not support UTF-16. In Python 3.x, csv expects a text-mode file and you can simply use the encoding parameter of [`open`](http://docs.python.org/release/3.2/library/functions.html#open) to force another encoding: ``` # Python 3.x only import csv with open('utf16.csv', 'r', encoding=...
Reading formatted text using python
9,178,305
6
2012-02-07T14:48:23Z
9,178,414
8
2012-02-07T14:55:01Z
[ "python", "csv" ]
I would like to use python read and write files of the following format: ``` #h -F, field1 field2 field3 a,b,c d,e,f # some comments g,h,i ``` This file closely resembles a typical CSV, except for the following: 1. The header line starts with #h 2. The second element of the header line is a tag to denote the delimit...
You can parse the first line separately to find the delimiter and fieldnames: ``` firstline = next(f).split() delimiter = firstline[1][-1] fields = firstline[2:] ``` Note that `csv.DictReader` can take any iterable as its first argument. So to skip the comments, you can wrap `f` in an iterator (`skip_comm...
How do I remove PyDev debugger breakpoints from deleted files?
9,178,564
6
2012-02-07T15:04:31Z
9,182,438
9
2012-02-07T19:19:08Z
[ "python", "eclipse", "debugging", "pydev", "breakpoints" ]
Whenever I launch the debugger from PyDev it complaints about breakpoints on files that don't exists anymore: ``` pydev debugger: warning: trying to add breakpoint to file that does not exist: (some file path).py (will have no effect) ``` There are about a dozen of these phantom breakpoints on files that no longer ex...
The `Debug` perspective should give you access to a `Breakpoints` view (you can see its title bar in some of the screenshots in [this tutorial](http://pydev.org/manual_adv_debugger.html)). This view should list all your breakpoints, even if they relate to deleted files, and allow you to disable or remove them.
weird behaviour while removing duplicates in list
9,178,925
3
2012-02-07T15:26:58Z
9,178,948
8
2012-02-07T15:28:23Z
[ "python", "list", "duplicates" ]
I have a list of integers. What I would like to do is to sort them and remove all duplicates. I saw two different solutions on the internet. Both seem to give the same result which is not the one I expect. ``` a = integer_combinations(5, 5) print a >>[4, 8, 16, 32, 9, 27, 81, 243, 16, 64, 256, 1024, 25, 125, 625, 312...
Here is what I would use: ``` >>> a = [4, 8, 16, 32, 9, 27, 81, 243, 16, 64, 256, 1024, 25, 125, 625, 3125] >>> sorted(set(a)) [4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125] ``` The reason your code doesn't work as expected is that `dict` does not guarantee any particular ordering of its keys. Simi...
How to protect python class variables from an evil programmer?
9,179,225
5
2012-02-07T15:44:20Z
9,179,305
7
2012-02-07T15:48:30Z
[ "python", "class", "dictionary", "private", "protected" ]
How can I protect my variables from this kind of attack: ``` MyClass.__dict__ = {} MyClass.__dict__.__setitem__('_MyClass__protectedVariable','...but it is not') ``` The above changes the variable dictionary and after that it is childs play to change all the variables. The upper line is crucial for this to work. The ...
AFAIK there's not really a way to do this in Python. No matter what you do, anyone could always copy your source and remove your hacks, or (in most cases) either inherit from the class and override it or just directly reassign the methods. But: why do you care so much? If you name it `__whatever` that's very clear doc...