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
access scope of variable in for loop
7,715,297
8
2011-10-10T15:41:38Z
7,715,350
10
2011-10-10T15:46:36Z
[ "python" ]
I have searched the SO before I post this question here and hopefully this is not a duplicated one. ``` def print_me(): a_list = range(1, 10) for idx, aa in enumerate(a_list): pass print(idx) if __name__ == '__main__' : print_me() ``` Output is as follows: > 8 I came from C++ world and could no...
`for` loop doesn't create any scope. This is the reason. In this particular code `idx` is a local variable of the `print_me` function. **From [the docs](http://docs.python.org/reference/executionmodel.html#naming-and-binding):** The following are blocks: * a module * a function body * a class definition **Update**...
How can I efficiently transform a numpy.int8 array in-place to a value-shifted numpy.uint8 array?
7,715,406
4
2011-10-10T15:51:06Z
7,715,461
9
2011-10-10T15:54:51Z
[ "python", "numpy" ]
I have a large numpy array of signed bytes (`dtype int8`). It contains values in the full range -128 to +127. I'd like to convert the efficiently to an array of unsigned bytes (`dtype uint8`) by adding 128 to each element, such that -128 → 0, 0 → 128, +127 → 255, *etc.* so of course the results still fit into an ...
``` import numpy as np a = np.array([-128, -1, 0, 1, 127], dtype=np.int8) a = a.view(np.uint8) a += 128 print a # -> array([ 0, 127, 128, 129, 255], dtype=uint8) ``` This creates no copies, and all operations are in-place. **EDIT**: safer to cast first to uint --- unsigned wrap-around is defined. **EDIT2**: s/numpy/...
PIL image show() doesn't work on windows 7
7,715,501
11
2011-10-10T15:57:47Z
7,715,851
11
2011-10-10T16:30:12Z
[ "python", "windows-7", "python-imaging-library", "show" ]
I would like to show an image using python on windows and other platforms. When I do: ``` from PIL import Image im = Image.open('image.png') im.show() ``` my default viewer opens up and tells me that `Windows Photo Viewer can't open this picture because either this file was deleted` , etc. The file is probably delet...
Ok, found a solution [here](http://www.daniweb.com/software-development/python/threads/308081): ``` import webbrowser webbrowser.open('image.png') ``` It opens the default viewer, not the browser, on my machine. Also, there is `os.startfile`.
How to reset cursor to the beginning of the same line in Python
7,715,594
12
2011-10-10T16:06:40Z
7,715,670
12
2011-10-10T16:13:13Z
[ "python" ]
Most of questions related to this topics here in SO is as follows: > How to print some information on the same line without introducing a > new line [Q1](http://stackoverflow.com/questions/3249524) [Q2](http://stackoverflow.com/questions/493386). Instead, my question is as follows: I expect to see the following eff...
``` import sys, time for i in xrange(0, 101, 10): print '\r>> You have finished %d%%' % i, sys.stdout.flush() time.sleep(2) print ``` The `\r` is the carriage return. You need the comma at the end of the `print` statement to avoid automatic newline. Finally `sys.stdout.flush()` is needed to flush the buffer out...
Calculating arithmetic mean (average) in Python
7,716,331
136
2011-10-10T17:19:17Z
7,716,358
160
2011-10-10T17:22:04Z
[ "python", "math", "statistics", "average", "mean" ]
Is there a built-in or standard library method in Python to calculate the arithmetic mean (average) of a list of numbers?
I am not aware of anything in the standard library. However, you could use something like: ``` def mean(numbers): return float(sum(numbers)) / max(len(numbers), 1) >>> mean([1,2,3,4]) 2.5 >>> mean([]) 0.0 ``` In numpy, there's [`numpy.mean()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html).
Calculating arithmetic mean (average) in Python
7,716,331
136
2011-10-10T17:19:17Z
13,869,415
114
2012-12-13T22:12:28Z
[ "python", "math", "statistics", "average", "mean" ]
Is there a built-in or standard library method in Python to calculate the arithmetic mean (average) of a list of numbers?
NumPy has a [`numpy.mean`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html) which is an arithmetic mean. Usage is as simple as this: ``` >>> import numpy >>> a = [1, 2, 4] >>> numpy.mean(a) 2.3333333333333335 ```
Calculating arithmetic mean (average) in Python
7,716,331
136
2011-10-10T17:19:17Z
18,292,047
28
2013-08-17T18:29:51Z
[ "python", "math", "statistics", "average", "mean" ]
Is there a built-in or standard library method in Python to calculate the arithmetic mean (average) of a list of numbers?
You don't even need numpy or scipy... ``` >>> a = [1, 2, 3, 4, 5, 6] >>> print(sum(a) / len(a)) 3 ```
Calculating arithmetic mean (average) in Python
7,716,331
136
2011-10-10T17:19:17Z
20,820,148
82
2013-12-28T22:38:12Z
[ "python", "math", "statistics", "average", "mean" ]
Is there a built-in or standard library method in Python to calculate the arithmetic mean (average) of a list of numbers?
In Python 3.4, there is a new [`statistics`](http://docs.python.org/3.4/library/statistics.html) module. You can now use [`statistics.mean`](http://docs.python.org/3.4/library/statistics.html#statistics.mean): ``` import statistics print(statistics.mean([1,2,4])) # 2.3333333333333335 ``` For 3.1-3.3 users, the origin...
usr/bin/env: bad interpreter Permission Denied --> how to change the fstab
7,716,357
3
2011-10-10T17:22:03Z
7,716,407
8
2011-10-10T17:26:54Z
[ "python", "permissions", "cygwin" ]
I'm using cygwin on windows 7 to run a bash script that activates a python script, and I am getting the following error: `myscript.script: /cydrive/c/users/mydrive/folder/myscript.py: usr/bin/env: bad interpreter: Permission Denied.` I'm a total newbie to programming, so I've looked around a bit, and I think this mea...
You script should start with: ``` #! /usr/bin/env whateverelse ... ^ this first one is important ```
Python+LDAP+SSL
7,716,562
10
2011-10-10T17:40:14Z
7,810,308
25
2011-10-18T16:06:36Z
[ "python", "ssl", "active-directory", "python-ldap" ]
Good day. In advance to apologize for my English, my national forums and resources did not help. There was a need in the script that changes (or creates) a user password in AD. After studying the issue, it became clear that 1. Password to assign or change can only establish an encrypted connection to the server 2. ...
After studying like this, I found a solution on their own ``` ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) l = ldap.initialize("ldaps://ldap:636") l.set_option(ldap.OPT_REFERRALS, 0) l.set_option(ldap.OPT_PROTOCOL_VERSION, 3) l.set_option(ldap.OPT_X_TLS,ldap.OPT_X_TLS_DEMAND) l.set_option( ldap.O...
Which is faster and why? Set or List?
7,717,011
11
2011-10-10T18:25:58Z
7,717,046
25
2011-10-10T18:30:46Z
[ "python", "list", "graph", "set" ]
Lets say that I have a graph and want to see if `b in N[a]`. Which is the faster implementation and why? ``` a, b = range(2) N = [set([b]), set([a,b])] ``` OR ``` N= [[b],[a,b]] ``` This is obviously oversimplified, but imagine that the graph becomes really dense.
Membership testing in a set is vastly faster, especially for large sets. That is because the set uses a [hash function](http://en.wikipedia.org/wiki/Hash_function) to map to a bucket. Since Python implementations automatically resize that hash table, the speed can be constant ([`O(1)`](http://en.wikipedia.org/wiki/O_no...
What's a better way of overriding nested class members in Python?
7,717,089
5
2011-10-10T18:35:36Z
7,717,149
11
2011-10-10T18:42:07Z
[ "python", "class", "inheritance", "syntax", "nested-class" ]
I need to “override” some of the base class' nested class members, while keeping the rest intact. This is what I do: ``` class InternGenericForm(ModelForm): class Meta: model = Intern exclude = ('last_achievement', 'program',) widgets = { 'name': TextInput(...
``` class InternGenericForm(ModelForm): class Meta: model = Intern exclude = ('last_achievement', 'program',) widgets = { 'name': TextInput(attrs={'placeholder': 'Имя и фамилия' }), } class InternApplicationForm(InternGenericForm): class Me...
how to convert 2d list to 2d numpy array?
7,717,380
33
2011-10-10T19:03:32Z
7,717,418
42
2011-10-10T19:07:36Z
[ "python", "numpy" ]
I have a 2D list something like ``` a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] ``` and I want to convert it to a 2d numpy array. Can we do it without allocating memory like ``` numpy.zeros((3,3)) ``` and then storing values to it?
Just pass the list to `np.array`: ``` a = np.array(a) ``` You can also take this opportunity to set the `dtype` if the default is not what you desire. ``` a = np.array(a, dtype=...) ```
Maximum Likelihood Estimate pseudocode
7,718,034
11
2011-10-10T20:05:45Z
7,718,431
14
2011-10-10T20:42:50Z
[ "python", "statistics", "machine-learning", "pseudocode" ]
I need to code a Maximum Likelihood Estimator to estimate the mean and variance of some toy data. I have a vector with 100 samples, created with `numpy.random.randn(100)`. The data should have zero mean and unit variance Gaussian distribution. I checked Wikipedia and some extra sources, but I am a little bit confused ...
If you do maximum likelihood calculations, the first step you need to take is the following: Assume a distribution that depends on some parameters. Since you `generate` your data (you even know your parameters), you "tell" your program to assume Gaussian distribution. However, you don't tell your program your parameter...
Maximum Likelihood Estimate pseudocode
7,718,034
11
2011-10-10T20:05:45Z
18,348,384
17
2013-08-21T03:26:44Z
[ "python", "statistics", "machine-learning", "pseudocode" ]
I need to code a Maximum Likelihood Estimator to estimate the mean and variance of some toy data. I have a vector with 100 samples, created with `numpy.random.randn(100)`. The data should have zero mean and unit variance Gaussian distribution. I checked Wikipedia and some extra sources, but I am a little bit confused ...
I just came across this, and I know its old, but I'm hoping that someone else benefits from this. Although the previous comments gave pretty good descriptions of what ML optimization is, no one gave pseudo-code to implement it. Python has a minimizer in Scipy that will do this. Here's pseudo code for a linear regressio...
Can I use Python 3 super() in Python 2.5.6?
7,718,684
11
2011-10-10T21:06:11Z
7,718,808
13
2011-10-10T21:18:55Z
[ "python", "python-3.x", "super", "python-2.5" ]
Can I use clean Python 3 [`super()`](http://www.python.org/dev/peps/pep-3135/) syntax in Python 2.5.6? Maybe with some kind of `__future__` import?
You cannot use a bare `super()` call that contains no type/class. Nor can you implement a replacement for it that will work. Python 3.x contains special support to enable bare `super()` calls (it places a `__class__` cell variable in all functions defined within a class - see PEP [3135](http://www.python.org/dev/peps/p...
Can I use Python 3 super() in Python 2.5.6?
7,718,684
11
2011-10-10T21:06:11Z
30,159,479
10
2015-05-11T04:01:51Z
[ "python", "python-3.x", "super", "python-2.5" ]
Can I use clean Python 3 [`super()`](http://www.python.org/dev/peps/pep-3135/) syntax in Python 2.5.6? Maybe with some kind of `__future__` import?
I realize this question is old, and the selected answer may have been correct at the time, but it's no longer complete. You still can't use `super()` in 2.5.6, but [`python-future`](http://python-future.org/) provides a [back-ported implementation](http://python-future.org/reference.html#super) for 2.6+: ``` % pip ins...
python setup.py sdist error: Operation not permitted
7,719,380
16
2011-10-10T22:26:19Z
7,719,634
9
2011-10-10T23:00:43Z
[ "python", "unix", "ubuntu", "virtualbox", "distutils" ]
I'm trying to create a python source package, but it fails when creating hard links for files. ``` $ python setup.py sdist running sdist running check reading manifest template 'MANIFEST.in' writing manifest file 'MANIFEST' making hard links in foo-0.1... hard linking README.txt -> foo-0.1 error: Operation not permit...
It is unclear from your question what step is failing. Might be the hard linking right before the error. You can try strace to see what system call is failing. That should give a better picture of the problem at least. [This python bug report](http://bugs.python.org/issue8876) looks like they're not going to fix this ...
python setup.py sdist error: Operation not permitted
7,719,380
16
2011-10-10T22:26:19Z
8,870,890
16
2012-01-15T15:34:41Z
[ "python", "unix", "ubuntu", "virtualbox", "distutils" ]
I'm trying to create a python source package, but it fails when creating hard links for files. ``` $ python setup.py sdist running sdist running check reading manifest template 'MANIFEST.in' writing manifest file 'MANIFEST' making hard links in foo-0.1... hard linking README.txt -> foo-0.1 error: Operation not permit...
I ran into the same issues. I was able to get it working by moving the python sources from the virtual box shared folder to my debian home folder. No error on sdist anymore. I hope it helps.
python setup.py sdist error: Operation not permitted
7,719,380
16
2011-10-10T22:26:19Z
22,147,112
15
2014-03-03T12:42:02Z
[ "python", "unix", "ubuntu", "virtualbox", "distutils" ]
I'm trying to create a python source package, but it fails when creating hard links for files. ``` $ python setup.py sdist running sdist running check reading manifest template 'MANIFEST.in' writing manifest file 'MANIFEST' making hard links in foo-0.1... hard linking README.txt -> foo-0.1 error: Operation not permit...
Same issue. I am using vagrant, my host OS is Windows while the Gust OS is Ubuntu. I am not a vim fan, so @simo's answer does not help me much because I really rely on virtual box shared folders to sync changes made by sublime editor to the Ubuntu virtual machine. Thanks to Fabian Kochem, he found a quick and dirty wo...
python setup.py sdist error: Operation not permitted
7,719,380
16
2011-10-10T22:26:19Z
27,778,454
8
2015-01-05T11:20:56Z
[ "python", "unix", "ubuntu", "virtualbox", "distutils" ]
I'm trying to create a python source package, but it fails when creating hard links for files. ``` $ python setup.py sdist running sdist running check reading manifest template 'MANIFEST.in' writing manifest file 'MANIFEST' making hard links in foo-0.1... hard linking README.txt -> foo-0.1 error: Operation not permit...
Looks like this was fixed in Python version 2.7.9 - <https://hg.python.org/cpython/raw-file/v2.7.9/Misc/NEWS> `Issue #8876: distutils now falls back to copying files when hard linking doesn't work. This allows use with special filesystems such as VirtualBox shared folders`
Why is set(None) invalid in python
7,719,419
2
2011-10-10T22:31:28Z
7,719,445
9
2011-10-10T22:34:07Z
[ "python", "types", "set" ]
``` >>> set(None) *** TypeError: 'NoneType' object is not iterable ``` is a problem but not this: ``` >>> a=set() >>> a.add(None) ``` Why?
As the error message tells you, `set()` expects an iterable. ``` set([None]) ``` Note: the same is true for `list`, `tuple`, ...
How to convert a string to a function in python?
7,719,466
9
2011-10-10T22:37:32Z
7,719,486
24
2011-10-10T22:40:39Z
[ "python", "string", "function" ]
For example, if I have a function called add like ``` def add(x,y): return x+y ``` and I want the ability to convert a string or an input to direct to that function like ``` w=raw_input('Please input the function you want to use') ``` or ``` w='add' ``` Is there any way to use w to refer to the function add?
Since you are taking user input, the safest way is to define exactly what is valid input: ``` dispatcher={'add':add} w='add' try: function=dispatcher[w] except KeyError: raise ValueError('invalid input') ``` If you want to evaluate strings like `'add(3,4)'`, you could use [safe eval](http://lybniz2.sourceforg...
JSON to model a class using Django
7,719,864
8
2011-10-10T23:37:17Z
7,719,928
8
2011-10-10T23:46:50Z
[ "python", "django", "json", "object" ]
I'm trying to get a JSON object like: ``` { "username": "clelio", "name": "Clelio de Paula", } ``` and transform it in: ``` class User(models.Model): name = models.CharField(max_length=30) username = models.CharField(max_length=20) def jsonToClass(s): aux = json.dumps(s, self) ...
You probably want to look at Django's [(de)serialization framework](https://docs.djangoproject.com/en/1.3/topics/serialization/). Given JSON like: ``` [ { "model": "myapp.user", "pk": "89900", "fields": { "name": "Clelio de Paula" } } ] ``` you can save it like this: ``` from django.core im...
operator precedence: not and comparisons
7,721,541
4
2011-10-11T04:57:40Z
7,721,558
7
2011-10-11T04:59:41Z
[ "python" ]
I'm trying to understand python better and the lack of parentheses can be a bit confusing for some reason. how is `(not a < b < c)` evaluated? Is it `(not a) < b < c`? or `not (a < b < c)`? According to the [reference manual](http://docs.python.org/reference/expressions.html#evaluation-order), does `not` have a lower...
What you're seeing in the 2.7 manual is all *relational* operators, including `not in` and `is not`, at the same precedence; boolean `not` is still one level lower in precedence and as such the relational comparison happens first.
Developing a web application in python with neo4j
7,721,737
7
2011-10-11T05:30:05Z
7,721,801
12
2011-10-11T05:39:19Z
[ "python", "django", "neo4j", "recommendation-engine" ]
I'm planning to implement a recommendation engine, of which details are given [here](http://stackoverflow.com/questions/7554873/neural-network-based-ranking-of-documents). 'Python' is my preferred choice along with 'neo4j' Database. Can anyone please point out, how integration of 'neo4j' with any web framework like 'dj...
I dont see why not. You can integrate this with Django & serve requests through it... 1. [Modeling Categories in Graph Database](http://blog.neo4j.org/2010/03/modeling-categories-in-graph-database.html) 2. [Neo4J shop categories example](https://github.com/neo4j-examples/python-shop-categories) 3. [Neo4j and django mo...
When do you use 'self' in Python?
7,721,920
10
2011-10-11T05:59:29Z
7,722,353
13
2011-10-11T06:51:51Z
[ "python", "self" ]
Are you supposed to use `self` when referencing a member function in Python (within the same module)? More generally, I was wondering when it is required to use `self`, not just for methods but for variables as well.
Adding an answer because Oskarbi's isn't explicit. You use `self` when: 1. Defining an instance method. It is passed automatically as the first parameter when you call a method on an instance, and it is the instance on which the method was called. 2. Referencing a *class or instance* attribute from inside an instance...
How to add custom permission to the User model in django?
7,724,265
14
2011-10-11T09:57:53Z
13,360,809
8
2012-11-13T12:30:09Z
[ "python", "django", "django-permissions" ]
in django by default when syncdb is run with django.contrib.auth installed, it creates default permissions on each model... like foo.can\_change , foo.can\_delete and foo.can\_add. To add custom permissions to models one can add class Meta: under the model and define permissions there, as explained here <https://docs.d...
You could do something like this: in the `__init__.py` of your Django app add: ``` from django.db.models.signals import post_syncdb from django.contrib.contenttypes.models import ContentType from django.contrib.auth import models as auth_models from django.contrib.auth.models import Permission # custom user related ...
Set multiplicity for user defined classes
7,724,737
3
2011-10-11T10:42:29Z
7,724,798
9
2011-10-11T10:47:15Z
[ "python" ]
I want to use sets on some classes I've made. I want those sets to restrict the multiplicity of my objects of that class. However I have a problem. Consider this toy example: ``` class Thing(object): def __init__(self, value): self.value = value def __eq__(self, other): return self.value == o...
You need to define the `__hash__` method of your class to return a hashcode based on `value`. In other words, you need to make your class *[hashable](http://docs.python.org/glossary.html#term-hashable)*. ``` class Thing(object): def __init__(self, value): self.value = value def __eq__(self, other): ...
Python - Using regex to find multiple matches and print them out
7,724,993
15
2011-10-11T11:03:25Z
7,725,094
25
2011-10-11T11:09:57Z
[ "python", "regex" ]
I need to find content of forms from HTML source file, I did some searching and found very good method to do that, but the problem is that it prints out only first found, how can I loop through it and output all form contents, not just first one? ``` line = 'bla bla bla<form>Form 1</form> some text...<form>Form 2</for...
[**Do not use regular expressions to parse HTML.**](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) But if you ever need to find all regexp matches in a string, use the [`findall`](http://docs.python.org/library/re.html#re.findall) function. ``` line ...
Python - Using regex to find multiple matches and print them out
7,724,993
15
2011-10-11T11:03:25Z
7,726,095
12
2011-10-11T12:34:12Z
[ "python", "regex" ]
I need to find content of forms from HTML source file, I did some searching and found very good method to do that, but the problem is that it prints out only first found, how can I loop through it and output all form contents, not just first one? ``` line = 'bla bla bla<form>Form 1</form> some text...<form>Form 2</for...
Instead of using `re.search` use `re.findall` it will return you all matches in a `List`. Or you could also use `re.finditer` (which i like most to use) it will return an `Iterator Object` and you can just use it to iterate over all found matches. ``` line = 'bla bla bla<form>Form 1</form> some text...<form>Form 2</fo...
Suds Error: BadStatusLine in httplib
7,725,693
3
2011-10-11T11:58:36Z
8,562,410
8
2011-12-19T13:59:30Z
[ "python", "soap", "suds", "httplib" ]
I am using suds 0.3.6. When creating a suds client, I randomly get an error: httplib.py, \_read\_status(), line 355, class httplib.BadStatusLine' Here is the code used to create the client: ``` imp = Import('http://www.w3.org/2001/XMLSchema') imp.filter.add('http://tempuri.org/encodedTypes') imp.filter.add('http://t...
I had the same problem. To troubleshoot the problem, I turned on full suds logging: ``` logging.basicConfig(level=logging.INFO) logging.getLogger("suds.client").setLevel(logging.DEBUG) logging.getLogger("suds.transport").setLevel(logging.DEBUG) logging.getLogger("suds.xsd.schema").setLevel(logging.DEBUG) logging.getLo...
How to use a (random) *.otf or *.ttf font in matplotlib?
7,726,852
25
2011-10-11T13:31:33Z
7,728,665
42
2011-10-11T15:36:00Z
[ "python", "matplotlib", "fonts" ]
How can I use any type of font in my font library on my computer (e.g. `*otf` or `*ttf`) in all my `matplotlib` figures?
See the example here: <http://matplotlib.sourceforge.net/examples/api/font_file.html> In general, you'd do something like this if you're wanting to use a specific `.ttf` file. (Keep in mind that pointing to a specific font file is usually a bad idea!) ``` import matplotlib.font_manager as fm import matplotlib.pyplot ...
Nose ignores test with custom decorator
7,727,678
20
2011-10-11T14:29:14Z
7,727,905
21
2011-10-11T14:45:22Z
[ "python", "decorator", "ignore", "nose" ]
I have some relatively complex integration tests in my Python code. I simplified them greatly with a custom decorator and I'm really happy with the result. Here's a simple example of what my decorator looks like: ``` def specialTest(fn): def wrapTest(self): #do some some important stuff pass r...
If I remember correctly, nose loads the test based on their names (functions whose name begins with test\_). In the snippet you posted, you do not copy the `__name__` attribute of the function in your wrapper function, so the name of the function returned is `wrapTest` and nose decides it's not a test. An easy way to ...
python and tkinter: using scrollbars on a canvas
7,727,804
14
2011-10-11T14:38:13Z
7,734,187
19
2011-10-12T00:57:25Z
[ "python", "tkinter", "scrollbar", "tkinter-canvas" ]
I'm trying to make a canvas scrollable. However, once I try to set up scrollbars to work with the canvas, tkinter seems to completely ignore the dimensions I initially set for my canvas. I've tried packing them all in a frame, setting the canvas to fill the frame and then setting the frame size, but that presents the s...
Your scrollbars need to have the Frame as a parent, not the Canvas: ``` from tkinter import * root=Tk() frame=Frame(root,width=300,height=300) frame.grid(row=0,column=0) canvas=Canvas(frame,bg='#FFFFFF',width=300,height=300,scrollregion=(0,0,500,500)) hbar=Scrollbar(frame,orient=HORIZONTAL) hbar.pack(side=BOTTOM,fill=...
Python unittest and test discovery
7,728,371
6
2011-10-11T15:18:14Z
7,728,426
20
2011-10-11T15:21:41Z
[ "python", "unit-testing", "python-2.7" ]
What *exactly* I need to do to make python's `unittest` work? I checked the official documentation, SO questions and even tried using `nose`, but nothing worked so far. What I'm doing wrong? ``` bash:~/path/to/project/src/tests$ ls -l total 8 -rw-r--r-- 1 myuser myuser 342 Out 11 11:51 echo_test.py -rw-r--r-- 1 myuser...
You need to rename the methods to begin with the word "test". As seen on <http://docs.python.org/library/unittest.html> : > A testcase is created by subclassing unittest.TestCase. The three individual tests are defined with methods whose names start with the letters test. This naming convention informs the test runne...
How to ForwardAgent yes using fabric?
7,729,301
22
2011-10-11T16:24:18Z
10,211,889
46
2012-04-18T14:45:04Z
[ "python", "deployment", "automation", "fabric" ]
I am successfully `run()`ning commands on remote server with my private key pair. However, I'd like to do `git clone ssh://private/repo` on remote server using my local key (or using local ssh agent I'm in). How to do it using fabric?
Since version 1.4 `fabric` has [environment option](http://docs.fabfile.org/en/1.4.1/usage/env.html?highlight=forwarding#forward-agent) that enables agent forwarding. ``` env.forward_agent = True ``` **UPD**: This feature [was buggy](https://github.com/fabric/fabric/issues/562) before `fabric` 1.4.2
How can I print and display subprocess stdout and stderr output without distortion?
7,729,336
5
2011-10-11T16:27:00Z
7,730,201
8
2011-10-11T17:45:14Z
[ "python", "subprocess" ]
Maybe there's someone out in the ether that can help me with this one. (I have seen a number of similar questions to this on SO, but none deal with both standard out and standard error or deal with a situation quite like mine, hence this new question.) I have a python function that opens a subprocess, waits for it to ...
Make the pipes non-blocking by using [`fcntl.fcntl`](http://docs.python.org/library/fcntl.html#fcntl.fcntl), and use [`select.select`](http://docs.python.org/library/select.html#select.select) to wait for data to become available in either pipe. For example: ``` # Helper function to add the O_NONBLOCK flag to a file d...
Are there libraries for packing and minifying multiple CSS and JS files into one file each?
7,730,346
6
2011-10-11T17:57:52Z
7,730,392
7
2011-10-11T18:01:10Z
[ "javascript", "python", "css", "minify" ]
According to O'Reilly's [High Performance Web Sites](http://shop.oreilly.com/product/9780596529307.do) (pages 15-16), it's highly recommended to make as few HTTP requests as is possible for high-performance. Thus, is there a library for combining multiple JS files into one file, and a library to do this for CSS as well...
What you are looking for is a css and javascript pipeline. Its becoming a standard for frameworks to provide this kind of tools. For instance, Rails 3.1 has its own asset pipeline built-in. Not only it will merge your css and javascripts into a single pack, but it will also compress them for even further performance b...
Numpy C-Api example gives a SegFault
7,730,717
7
2011-10-11T18:30:38Z
7,732,174
11
2011-10-11T20:37:29Z
[ "python", "c", "numpy", "python-c-api" ]
I'm trying to understand how the Python C- Api works, and I want to exchange numpy arrays between Python and a C Extension. So, I started this tutorial: <http://dsnra.jpl.nasa.gov/software/Python/numpydoc/numpy-13.html> Tried to do the first example there, a C module that calculates the trace of a 2d numpy array, was...
Your init function for the module needs to call ``` import_array(); ``` after ``` (void) Py_InitModule("trace", TraceMethods); ``` It mentions this in the tutorial near the top, but it is easy to miss. Without this, it segfaults on `PyArray_ContiguousFromObject`.
pydev: find all references to a function
7,731,324
28
2011-10-11T19:20:42Z
7,742,529
33
2011-10-12T15:28:15Z
[ "python", "pydev" ]
This has probably been asked before but I can't seem to find the answer. I've moved from windows to Linux and started using PyDev (Aptana) recently but what I cannot seem to find is how to find all references to a function.
Ctrl+Shift+G will find all the references to a function in PyDev (F3 will go to the definition of a function).
How can I check the data transfer on a network interface in python?
7,731,411
5
2011-10-11T19:28:03Z
7,791,143
7
2011-10-17T08:28:11Z
[ "python", "linux", "networking", "snmp", "pysnmp" ]
There is a socket method for getting the IP of a given network interface: ``` import socket import fcntl import struct def get_ip_address(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('2...
The best way to poll ethernet interface statistics is through SNMP... * It looks like you're using linux... if so, load up your `snmpd` with these options... after installing [`snmpd`](http://www.net-snmp.org/), in your **/etc/defaults/snmpd** (make sure the line with `SNMPDOPTS` looks like this): `SNMPDOPTS='-Lsd ...
add module to pythonpath - nothing works
7,731,947
4
2011-10-11T20:14:37Z
7,731,964
11
2011-10-11T20:16:46Z
[ "python", "linux", "module" ]
I don't have root access so I installed psycopg2 module to /opt (I have permission for that directory): ``` $python setup.py install --prefix=/opt ``` I've tried several methods: ``` #.bashrc PATH=$PATH:$HOME/bin:/opt/lib/python2.4/site-packages/psycopg2/ export PATH ``` or ``` #.bash_profile PATH=$PATH:...
Try `$PYTHONPATH` instead of `$PATH` in your bash configuration file. For more info look at the official documentation on [this](http://docs.python.org/tutorial/modules.html) topic.
Clear text from textarea with selenium
7,732,125
59
2011-10-11T20:32:23Z
7,809,907
85
2011-10-18T15:38:34Z
[ "python", "selenium", "selenium-webdriver" ]
I've got some tests where I'm checking that the proper error message appears when text in certain fields are invalid. One check for validity is that a certain textarea element is not empty. If this textarea already has text in it, how can I tell selenium to clear the field? something like: ``` driver.get_element_by_...
``` driver.find_element_by_id('foo').clear() ```
Clear text from textarea with selenium
7,732,125
59
2011-10-11T20:32:23Z
26,091,144
10
2014-09-29T00:52:34Z
[ "python", "selenium", "selenium-webdriver" ]
I've got some tests where I'm checking that the proper error message appears when text in certain fields are invalid. One check for validity is that a certain textarea element is not empty. If this textarea already has text in it, how can I tell selenium to clear the field? something like: ``` driver.get_element_by_...
In the most recent Selenium version, use: ``` driver.find_element_by_id('foo').clear() ```
Clear text from textarea with selenium
7,732,125
59
2011-10-11T20:32:23Z
27,799,120
14
2015-01-06T12:55:23Z
[ "python", "selenium", "selenium-webdriver" ]
I've got some tests where I'm checking that the proper error message appears when text in certain fields are invalid. One check for validity is that a certain textarea element is not empty. If this textarea already has text in it, how can I tell selenium to clear the field? something like: ``` driver.get_element_by_...
You can use ``` webElement.clear(); ``` [JavaDoc](https://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/WebElement.html#clear%28%29): If this element is a text entry element, this will clear the value. Note that the events fired by this event may not be as you'd expect. In particular, we don'...
Python: String of 1s and 0s -> binary file
7,732,496
4
2011-10-11T21:05:45Z
7,732,676
8
2011-10-11T21:21:50Z
[ "python", "binary" ]
I have a string of 1's and 0's in Python and I would like to write it to a binary file. I'm having a lot of trouble with finding a good way to do this. Is there a standard way to do this that I'm simply missing?
If you want a binary file, ``` >>> import struct >>> myFile=open('binaryFoo','wb') >>> myStr='10010101110010101' >>> x=int(myStr,2) >>> x 76693 >>> struct.pack('i',x) '\x95+\x01\x00' >>> myFile.write(struct.pack('i',x)) >>> myFile.close() >>> quit() ``` ``` $ cat binaryFoo �+$ ``` Is this what you are looking for?
python local modules
7,732,685
4
2011-10-11T21:22:50Z
7,733,761
9
2011-10-11T23:38:03Z
[ "python", "python-module" ]
I have several project directories and want to have libraries/modules that are specific to them. For instance, I might have a directory structure like such: ``` myproject/ mymodules/ __init__.py myfunctions.py myreports/ mycode.py ``` Assuming there is a function called `add` in `myfunctions.py`, I ca...
Don't mess around with `execfile` or `sys.path.append` unless there is some very good reason for it. Rather, just arrange your code into [proper python packages](http://docs.python.org/distutils/) and do your importing as you would any other library. If your `mymodules` is in fact a part of one large project, then set...
Find specific link w/ beautifulsoup
7,732,694
8
2011-10-11T21:23:57Z
7,732,827
8
2011-10-11T21:35:44Z
[ "python", "regex", "beautifulsoup" ]
Hi I cannot figure out how to find links which begin with certain text for the life of me. findall('a') works fine, but it's way too much. I just want to make a list of all links that begin with <http://www.nhl.com/ice/boxscore.htm?id=> Can anyone help me? Thank you very much
First set up a test document and open up the parser with BeautifulSoup: ``` >>> from BeautifulSoup import BeautifulSoup >>> doc = '<html><body><div><a href="something">yep</a></div><div><a href="http://www.nhl.com/ice/boxscore.htm?id=3">somelink</a></div><a href="http://www.nhl.com/ice/boxscore.htm?id=7">another</a></...
Expanding tuple into number repeated X times in a list (python)
7,733,033
2
2011-10-11T21:58:39Z
7,733,047
8
2011-10-11T22:01:29Z
[ "python" ]
This seems simple, but I can't figure it out. I have ten categories and scores assigned to each of them. In an intermediate step, I am storing results as ["score", repeats] pairs, as in: ``` [20,3] [40,7] [50,2] ``` ... What I want to do in the end is expand these pairs into repeats of numbers, then merge and averag...
You can do this: ``` >>> a = [20,3] >>> [a[0]] * a[1] [20, 20, 20] ``` However, this step isn't really necessary. To get the weighted average, you can multiply the values by the weights, sum them, and then divide by the sum of the weights, such as: ``` float(20*3 + 40*7 + 50*2) / (3 + 7 + 2) ``` The conversion to f...
How to build sphinx documentation for django project
7,733,577
11
2011-10-11T23:08:31Z
8,195,773
14
2011-11-19T17:16:24Z
[ "python", "django", "documentation", "documentation-generation", "python-sphinx" ]
I have a django project, which I document using reST in docstrings to do the following: 1. Help diagloags within IDE 2. Later on to build HTML documentation using Sphinx My documentation shows up properly within IDE (PyCharm), however I can't configure Sphinx to generate HTML documentation for me. Here is the struct...
Add the following to your conf.py and you will not need to set DJANGO\_SETTINGS\_MODULE each time: ``` import sys, os sys.path.append('/path/to/your/project') # The directory that contains settings.py # Set up the Django settings/environment from django.core.management import setup_environ from myproject import sett...
How to build sphinx documentation for django project
7,733,577
11
2011-10-11T23:08:31Z
24,369,625
10
2014-06-23T15:23:20Z
[ "python", "django", "documentation", "documentation-generation", "python-sphinx" ]
I have a django project, which I document using reST in docstrings to do the following: 1. Help diagloags within IDE 2. Later on to build HTML documentation using Sphinx My documentation shows up properly within IDE (PyCharm), however I can't configure Sphinx to generate HTML documentation for me. Here is the struct...
With Django 1.6, I couldn't use the answer by @MikeRyan since `from django.core.management import setup_environ` has been deprecated. Instead, I went to my **conf.py** file and added the following: ``` import sys import os sys.path.append(os.path.join(os.path.dirname(__file__), '..')) os.environ['DJANGO_SETTINGS_MODU...
How to build sphinx documentation for django project
7,733,577
11
2011-10-11T23:08:31Z
33,753,374
9
2015-11-17T09:32:01Z
[ "python", "django", "documentation", "documentation-generation", "python-sphinx" ]
I have a django project, which I document using reST in docstrings to do the following: 1. Help diagloags within IDE 2. Later on to build HTML documentation using Sphinx My documentation shows up properly within IDE (PyCharm), however I can't configure Sphinx to generate HTML documentation for me. Here is the struct...
The migration features introduced in Django 1.7 prevents the previous answers from working on newer versions. Instead you will have to do a manual setup. Analogous to all previous answers you'll first have to make sure Django can find your settings, and then call `django.setup()` which will load the settings and setup ...
matplotlib: overlay plots with different scales?
7,733,693
27
2011-10-11T23:27:29Z
7,734,614
68
2011-10-12T02:26:57Z
[ "python", "matplotlib" ]
So far I have the following code: ``` colors = ('k','r','b') ax = [] for i in range(3): ax.append(plt.axes()) plt.plot(datamatrix[:,0],datamatrix[:,i],colors[i]+'o') ax[i].set(autoscale_on=True) ``` With the `autoscale_on=True` option for each axis, I thought each plot should have its own y-axis limits, b...
It sounds like what you're wanting is subplots... What you're doing now doesn't make much sense (Or I'm very confused by your code snippet, at any rate...). Try something more like this: ``` import matplotlib.pyplot as plt import numpy as np fig, axes = plt.subplots(nrows=3) colors = ('k', 'r', 'b') for ax, color i...
different foreground colors for each line in wxPython wxTextCtrl
7,734,028
5
2011-10-12T00:26:35Z
7,736,087
10
2011-10-12T06:26:59Z
[ "python", "wxpython" ]
I have a multiline ``` wx.TextCtrl() ``` object which I set it's forground and Background colors for writing strings.I need to write different lines with different colors , ``` wx.TextCtrl.setForgroundcolor() ``` changes all previous lines colors as well.Is there a way around this?
There are several methods in wx.Python to get colored text. * `wx.TextCtrl` with `wx.TE_RICH`, `wx.TE_RICH2` styles * `wx.stc.StyledTextCtrl` * `wx.richtext.RichTextCtrl` * `wx.HtmlWindow` (inserting color tags in your text) * `wx.ListCrtl` You can get examples of all of them in the wxPython demo For example, you ca...
How do I remove a query string from URL using Python
7,734,569
3
2011-10-12T02:19:38Z
7,734,686
27
2011-10-12T02:42:25Z
[ "python", "http", "cgi", "urlparse" ]
Example: ``` http://example.com/?a=text&q2=text2&q3=text3&q2=text4 ``` After removing "**q2**", it will return: ``` http://example.com/?q=text&q3=text3 ``` In this case, there were multiple "**q2**" and all have been removed. Thank you,
``` #!/usr/bin/env python from urllib import urlencode from urlparse import urlparse, urlunparse, parse_qs url = 'http://example.com/?a=text&q2=text2&q3=text3&q2=text4' u = urlparse(url) query = parse_qs(u.query) query.pop('q2', None) u = u._replace(query=urlencode(query, True)) print(urlunparse(u)) ```
Python: TypeError: 'tuple' object does not support item assignment
7,735,838
16
2011-10-12T05:52:34Z
7,735,850
30
2011-10-12T05:53:52Z
[ "python" ]
I am writing a simple sort program in python and encounter this error. I want to swap list elements but it returns an error. I am attaching the error and program in question below. ``` list[i+1] = list[i] TypeError: 'tuple' object does not support item assignment ``` ``` def my_sort(list): for index in range(1,l...
Evaluating "1,2,3" results in `(1, 2, 3)`, a `tuple`. As you've discovered, tuples are immutable. Convert to a list before processing.
python: Counting the amount of vowels or consonants in a user input word
7,736,211
3
2011-10-12T06:41:24Z
7,736,325
7
2011-10-12T06:54:11Z
[ "python" ]
I'm a freshman in college, who's taking a python coding class. Currently I'm working on making a program count the amount of vowels or consonants based on a user's input to determine the mode. currently, I've made two lists, and I'm trying to find out how to program python to count the vowels/consonants. This is what...
``` number_of_consonants = sum(word.count(c) for c in consonants) number_of_vowels = sum(word.count(c) for c in vowels) ```
identifying the format of files
7,736,480
4
2011-10-12T07:13:06Z
7,736,508
7
2011-10-12T07:16:59Z
[ "python", "file", "identification" ]
In linux, we have a utility called “file”, which helps us to determine the identification of a file. Is there any python module that can do the same job? I don't prefer to use `subprocess.Popen(['file', 'blah.blah'])`, because it is platform dependent. For instance, windows do not have “file” (although it can ...
[`magic`](http://pypi.python.org/pypi/python-magic/) Don't forget [the DLL](http://gnuwin32.sourceforge.net/packages/file.htm).
Python assignment operator associativity
7,738,122
10
2011-10-12T09:43:56Z
7,738,155
11
2011-10-12T09:46:18Z
[ "python", "operators" ]
Consider the following Python3 program: ``` a = [0, 0] i = 0 a[i] = i = 1 print(a, i) a = [0, 0] i = 0 i = a[i] = 1 print(a, i) ``` I expected the output to be: ``` [0, 1] 1 [1, 0] 1 ``` But instead I got: ``` [1, 0] 1 [0, 1] 1 ``` My question is: is there anything in the Python language specificat...
**Short answer:** the code is well defined; the order is left-to-right. **Long answer:** First of all, let's get the terminology right. Unlike in some other languages, assignment in Python is a *statement*, not an *operator*. This means that you can't use assignment as part of another expression: for example `i = (j ...
Is Python DBM really fast?
7,738,272
4
2011-10-12T09:56:37Z
7,739,056
11
2011-10-12T11:04:28Z
[ "python", "nosql", "database", "dbm" ]
I was thinking that native DBM of Python should be quite faster than NOSQL databases such as Tokyo Cabinet, MongoDB, etc (as Python DBM has lesser features and options; i.e. a simpler system). I tested with a very simple write/read example as ``` #!/usr/bin/python import time t = time.time() import anydbm count = 0 wh...
Python doesn't have a built-in DBM implementation. It bases its DBM functions on a wide range of DBM-style third party libraries, like AnyDBM, Berkeley DBM and GNU DBM. Python's dictionary implementation is really fast for key-value storage, but not persistent. If you need high-performance runtime key-value lookups, y...
Walking/iterating over a nested dictionary of arbitrary depth (the dictionary represents a directory tree)
7,738,402
7
2011-10-12T10:08:24Z
7,738,774
9
2011-10-12T10:39:20Z
[ "python", "recursion", "dictionary", "tree", "iteration" ]
I am almost certain there is a simple solution to this, but I have spent hours now reading and rereading the same set of related results that don't quite answer my problem. **Context of this question (included for completion but feel free to skip this)** This came up because I want a user to be able to select a group...
Here is a function that prints all your file names. It goes through all the keys in the dictionary, and if they map to things that are not dictionaries (in your case, the filename), we print out the name. Otherwise, we call the function on the dictionary that is mapped to. ``` def print_all_files(directory): for ...
Python SOAP Client - use SUDS or something else?
7,739,613
49
2011-10-12T11:49:27Z
7,852,994
41
2011-10-21T17:23:28Z
[ "python", "soap", "suds" ]
I am currently looking into implementing a client which will use an existing extensive SOAP management API. I looked into different SOAP implementations like [pysimplesoap](http://code.google.com/p/pysimplesoap/) and [SUDS](https://fedorahosted.org/suds/). While the first had problems parsing the WSDL because of too m...
While there isn't a certified standard, if you must use SOAP, Suds is your best choice. Suds can be slow on large WSDLs, and that is something they are working on. In the meantime, if you don't expect your WSDL to change often, you have two options that can buy you a lot of speed: 1. Downloading your WSDL to localhos...
Logical or of Django many to many queries returns duplicate results
7,740,356
6
2011-10-12T12:52:29Z
7,740,807
11
2011-10-12T13:27:25Z
[ "python", "sql", "django", "many-to-many" ]
I have models with many to many relationships like this: ``` class Contact(models.Model): name = models.TextField() address = models.TextField() class Mail(models.Model): to = models.ManyToManyField(Contact, related_name='received_mails') cc = models.ManyToManyField(Contact, related_name='cced_mails')...
As SQL returns all matching records, Django dutifully maps them to objects. What you're looking for is the `.distinct()` queryset method that makes SQL collapse all duplicate rows into one.
How to test equivalence of ranges
7,740,796
6
2011-10-12T13:26:38Z
7,740,828
10
2011-10-12T13:28:54Z
[ "python", "unit-testing", "python-3.x" ]
One of my unittests checks to see if a range is set up correctly after reading a log file, and I'd like to just test `var == range(0,10)`. However, `range(0,1) == range(0,1)` evaluates to `False` in Python 3. Is there a straightforward way to test the equivalence of ranges in Python 3?
In Python3, `range` returns an iterable of type `range`. Two `range`s are equal if and only if they are identical (i.e. share the same `id`.) To test equality of its contents, convert the `range` to a `list`: ``` list(range(0,1)) == list(range(0,1)) ``` This works fine for short ranges. For very long ranges, [Charles...
Build a list using specific keys in a dict (python)?
7,741,662
4
2011-10-12T14:27:59Z
7,741,801
7
2011-10-12T14:36:23Z
[ "python", "list", "search", "dictionary", "dijkstra" ]
I'm implementing the Dijkstra search algorithm in Python. At the end of the search, I reconstruct the shortest path using a predecessor map, starting with the destination node's predecessor. For example: ``` path = [] path.append(destination) previous = predecessor_map[destination] while previous != origin: path.a...
The only suggestion that I have is to get rid of the slight code duplication: ``` path = [] previous = destination while previous != origin: path.append(previous) previous = predecessor_map[previous] ``` Beyond that, I think your code is actually very clear and is unlikely to benefit from any attempts to shor...
How to apply numpy.linalg.norm to each row of a matrix?
7,741,878
31
2011-10-12T14:41:43Z
7,741,976
44
2011-10-12T14:48:44Z
[ "python", "numpy" ]
I have a 2D matrix and I want to take norm of each row. But when I use numpy.linalg.norm(X) directly, it takes the norm of the whole matrix. I can take norm of each row by using a for loop and then taking norm of each X[i] but it takes a huge time since I have 30k rows. Any suggestions to find a quicker way? Or is it...
Note that, as [perimosocordiae shows](http://stackoverflow.com/a/19794741/190597), as of NumPy version 1.9, `np.linalg.norm(x, axis=1)` is the fastest way to compute the L2-norm. --- If you are computing an L2-norm, you could compute it directly (using the `axis=-1` argument to sum along rows): ``` np.sum(np.abs(x)*...
How to apply numpy.linalg.norm to each row of a matrix?
7,741,878
31
2011-10-12T14:41:43Z
19,794,741
27
2013-11-05T17:10:15Z
[ "python", "numpy" ]
I have a 2D matrix and I want to take norm of each row. But when I use numpy.linalg.norm(X) directly, it takes the norm of the whole matrix. I can take norm of each row by using a for loop and then taking norm of each X[i] but it takes a huge time since I have 30k rows. Any suggestions to find a quicker way? Or is it...
Resurrecting an old question due to a numpy update. As of the 1.9 release, `numpy.linalg.norm` now accepts an `axis` argument. [[code](https://github.com/numpy/numpy/pull/3387), [documentation](http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.linalg.norm.html)] This is the new fastest method in town: ```...
Python After 5:00pm
7,742,605
2
2011-10-12T15:32:47Z
7,742,669
7
2011-10-12T15:36:55Z
[ "python" ]
When a function runs I need it to check the current system time and if its past 5:00pm to do something. ``` current_time = datetime.datetime.now() if current_time > {code to represent 17:00 hours}: do stuff ``` Edit for clarification: Orders are being sent into my software which handles the picking/packing of ord...
``` if datetime.datetime.now().hour >= 17: pass ```
NLTK/NLP buliding a many-to-many/multi-label subject classifier
7,742,894
8
2011-10-12T15:52:50Z
7,752,752
9
2011-10-13T10:28:14Z
[ "python", "statistics", "nlp", "machine-learning", "nltk" ]
I have a human tagged corpus of over 5000 subject indexed documents in XML. They vary in size from a few hundred kilobytes to a few hundred megabytes. Being short articles to manuscripts. They have all been subjected indexed as deep as the paragraph level. I am lucky to have such a corpus available, and I am trying to ...
> What sort of classifier would be appropriate for this task. Was I wrong can a Bayes be used for more than a true/false sort of operation. You can easily build a multilabel classifier by [building a separate binary classifier for each class](http://nlp.stanford.edu/IR-book/html/htmledition/classification-with-more-th...
command line python app and frameworks
7,743,913
5
2011-10-12T17:15:43Z
10,394,333
17
2012-05-01T06:25:46Z
[ "python", "frameworks" ]
I'm going to be writing a fairly sophisticated command line app in python. I'd like to leverage something other than just pure python, maybe a framework or something that makes the services and code management within the app easier. I guess in my mind, I'm thinking MVC, as the app will have several different commands (...
This is a bit late, however posting for anyone else who stumbles across this: Cement is an Advanced CLI Application Framework for Python. Getting started is easy, and it is extremely flexible for customizing almost every piece of it from logging to config file parsing. Cement2 (code name portland) is currently in beta...
Pymongo keeps refusing the connection at 27017
7,744,147
21
2011-10-12T17:35:50Z
8,036,450
27
2011-11-07T12:23:47Z
[ "python", "pymongo" ]
I am trying to run a simple connection to pymongo but it keeps returning that the connection was refused Here is what I tried: ``` >>>from pymongo import Connection >>>connection = Connection('localhost',27017) ``` here is what I get ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/...
Removing mongod.lock from ``` /var/lib/mongodb ``` And then restarting the service should do it. For example, in my Ubuntu installation, restarting the server is something like: ``` sudo service mongod start ```
Pymongo keeps refusing the connection at 27017
7,744,147
21
2011-10-12T17:35:50Z
24,410,282
7
2014-06-25T13:37:53Z
[ "python", "pymongo" ]
I am trying to run a simple connection to pymongo but it keeps returning that the connection was refused Here is what I tried: ``` >>>from pymongo import Connection >>>connection = Connection('localhost',27017) ``` here is what I get ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/...
Just try following commands in given order : ``` sudo rm /var/lib/mongodb/mongod.lock sudo mongod --repair sudo service mongodb start sudo service mongodb status ``` That's it now you could see following as output of last command: `mongodb start/running, process 2796`
How to remove trailing whitespace in PyDev plugin for Eclipse
7,744,258
30
2011-10-12T17:46:59Z
7,744,283
35
2011-10-12T17:49:11Z
[ "python", "eclipse", "pydev" ]
Ideally, eclipse should remove all trailing whitespace when I save the file. I know there is option for this in C++/Java plugins for eclipse, but I couldnt find one for PyDev. Is there one? If not, whats the easiest way to achieve this?
Check in: Preferences > PyDev > Editor > Code Style > Code Formatter and check the "Right trim lines?" check box.
How to remove trailing whitespace in PyDev plugin for Eclipse
7,744,258
30
2011-10-12T17:46:59Z
7,744,294
8
2011-10-12T17:50:07Z
[ "python", "eclipse", "pydev" ]
Ideally, eclipse should remove all trailing whitespace when I save the file. I know there is option for this in C++/Java plugins for eclipse, but I couldnt find one for PyDev. Is there one? If not, whats the easiest way to achieve this?
i stumbled accros this usefull [site][1] [1]: <http://andrei.gmxhome.de/anyedit/> hope this could help
How can I implement multiple URL parameters in a Tornado route?
7,744,454
11
2011-10-12T18:04:38Z
7,759,671
31
2011-10-13T19:52:22Z
[ "python", "routing", "tornado" ]
I'm trying to figure out how to implement a URL with up to 3 (optional) url parameters. I figured out how to do this in ASP.NET MVC 3, but the constraints of the current project eliminated it. So, here's what I'm looking for: `base/{param1}/{param2}/{param3}` where param2 and param3 are optional. Is this simply a reg...
I'm not sure if there is a *nice* way to do it, but this should work: ``` import tornado.web import tornado.httpserver class TestParamsHandler(tornado.web.RequestHandler): def get(self, param1, param2, param3): param2 = param2 if param2 else 'default2' param3 = param3 if param3 else 'default3' ...
Printing unescaped white space to shell
7,744,518
4
2011-10-12T18:09:16Z
7,744,546
12
2011-10-12T18:11:53Z
[ "python", "escaping" ]
Consider this line of Python code: ``` s = "This string has \n\r whitespace" ``` How do I make `print s` give me `This string has \n\r whitespace` *instead of* ``` This string has whitespace ``` as it does now.
do you want a raw string ? ``` s = r"This string has \n\r whitespace" ``` or to transform special characters to it's representation? ``` repr(s) ```
Printing unescaped white space to shell
7,744,518
4
2011-10-12T18:09:16Z
7,744,550
7
2011-10-12T18:12:07Z
[ "python", "escaping" ]
Consider this line of Python code: ``` s = "This string has \n\r whitespace" ``` How do I make `print s` give me `This string has \n\r whitespace` *instead of* ``` This string has whitespace ``` as it does now.
``` print s.encode('string-escape') ```
How to show two figures using matplotlib?
7,744,697
12
2011-10-12T18:25:29Z
7,744,803
15
2011-10-12T18:35:06Z
[ "python", "matplotlib" ]
I have some troubles while drawing two figures at the same time, not shown in a single plot. But according to the documentation, I wrote the code and only the figure one shows. I think maybe I lost something important. Could anyone help me to figure out? Thanks. (The \*tlist\_first\* used in the code is a list of data....
You should call `plt.show()` only at the end after creating all the plots.
How to show two figures using matplotlib?
7,744,697
12
2011-10-12T18:25:29Z
7,744,882
18
2011-10-12T18:41:23Z
[ "python", "matplotlib" ]
I have some troubles while drawing two figures at the same time, not shown in a single plot. But according to the documentation, I wrote the code and only the figure one shows. I think maybe I lost something important. Could anyone help me to figure out? Thanks. (The \*tlist\_first\* used in the code is a list of data....
Alternatively to calling `plt.show()` at the end of the script, you can also control each figure separately doing: ``` f = plt.figure(1) plt.hist........ ............ f.show() g = plt.figure(2) plt.hist(........ ................ g.show() raw_input() ``` In this case you must call `raw_input` to keep the figures ali...
Cant Create tables in access with pyodbc
7,744,742
7
2011-10-12T18:30:21Z
7,744,776
8
2011-10-12T18:33:04Z
[ "python", "ms-access", "pyodbc" ]
I am trying to create tables in a MS Access DB with python using pyodbc but when I run my script no tables are created and no errors are given. My code: ``` #!/usr/bin/env python import pyodbc con = pyodbc.connect(r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=Z:\Data\Instruments\testDB.accdb; Provider=MSDAS...
You need to commit the transaction: ``` import pyodbc con = pyodbc.connect(r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=Z:\Data\Instruments\testDB.accdb; Provider=MSDASQL;') cur = con.cursor() string = "CREATE TABLE TestTable(symbol varchar(15), leverage double, shares integer, price double)" cur.execute(s...
Multiple context `with` statement in Python 2.6
7,745,164
17
2011-10-12T19:04:42Z
7,745,206
20
2011-10-12T19:08:03Z
[ "python" ]
I like the convenience of the multiple context `with` statement in Python 2.7: ``` with open('a.txt') as a, open('b.txt') as b: do_many_amazing_things(a, b) ``` However, I need to maintain compatibility with 2.6. `with` was brought to 2.5 via `__future__`, but I am unable to find anything about the multiple conte...
If no backward-compatible equivalent of this is possible, I would handle it by making the multiple-context `with` statement a set of single-context, nested `with` statements. ``` with open('a.txt') as a: with open('b.txt') as b: do_many_amazing_things(a, b) ``` EDIT to address your edit: If you insist o...
Appending to 2D lists in Python
7,745,562
18
2011-10-12T19:37:27Z
7,745,585
32
2011-10-12T19:40:05Z
[ "python", "list" ]
I've encountered what I think is a strange behavior in Python, and I'd like somebody to explain it if possible. I've created an empty 2D list ``` listy = [[]]*3 print listy [[], [], []] ``` The following works as I'd expect: `listy[1] = [1,2]` yields `[[], [1,2], []]` `listy[1].append(3)` yields `[[], [1,2,3], [...
You haven't created three *different* empty lists. You've created *one* empty list, and then created a new list with three references to that *same* empty list. To fix the problem use this code instead: ``` listy = [[] for i in range(3)] ``` Running your example code now gives the result you probably expected: ``` >...
Appending to 2D lists in Python
7,745,562
18
2011-10-12T19:37:27Z
7,745,587
10
2011-10-12T19:40:20Z
[ "python", "list" ]
I've encountered what I think is a strange behavior in Python, and I'd like somebody to explain it if possible. I've created an empty 2D list ``` listy = [[]]*3 print listy [[], [], []] ``` The following works as I'd expect: `listy[1] = [1,2]` yields `[[], [1,2], []]` `listy[1].append(3)` yields `[[], [1,2,3], [...
`[[]]*3` is not the same as `[[], [], []]`. It's as if you'd said ``` a = [] listy = [a, a, a] ``` In other words, all three list references refer to the same list instance.
Formating Complex Numbers
7,746,143
11
2011-10-12T20:27:19Z
14,548,149
14
2013-01-27T14:05:34Z
[ "python", "formatting", "complex-numbers" ]
For a project in one of my classes we have to output numbers up to five decimal places.It is possible that the output will be a complex number and I am unable to figure out how to output a complex number with five decimal places. For floats I know it is just: `print "%0.5f"%variable_name` Is there something similar f...
``` >>> n = 3.4+2.3j >>> n (3.4+2.3j) >>> '({0.real:.2f} + {0.imag:.2f}i)'.format(n) '(3.40 + 2.30i)' >>> '({c.real:.2f} + {c.imag:.2f}i)'.format(c=n) '(3.40 + 2.30i)' ``` To handle both positive and negative imaginary portions properly you would need a even more complicated formatting operation: ``` >>> n = 3.4-2.3j...
In bash, "which" gives an incorrect path - Python versions
7,746,240
9
2011-10-12T20:36:28Z
7,747,378
13
2011-10-12T22:35:13Z
[ "python", "osx", "bash", "which" ]
Can anyone explain how python 2.6 could be getting run by default on my machine? It looks like `python` points to 2.7, so it seems like `which` isn't giving me correct information. ``` ~> python --version Python 2.6.5 ~> which python /opt/local/bin/python ~> /opt/local/bin/python --version Python 2.7.2 ~> ls -l /opt/l...
Bash uses an [internal hash table](http://www.cyberciti.biz/tips/how-linux-or-unix-understand-which-program-to-run-part-i.html#hashtables) to optimize `$PATH` lookups. When you install a new program with the same name as an existing program (`python` in this case) earlier in your `$PATH`, Bash doesn't know about it and...
how play mp3 with pygame
7,746,263
9
2011-10-12T20:38:04Z
8,415,875
9
2011-12-07T13:13:58Z
[ "python", "pygame" ]
``` import pygame file = 'some.mp3' pygame.init() pygame.mixer.init() pygame.mixer.music.load(file) pygame.mixer.music.play() ``` Process finished with exit code 0. but it not play anything, how can resolve problem
The play function starts the music playing, but returns immediately. Then your program reaches it's end, and the pygame object is automatically destroyed which causes the music to stop. As you commented, it does play the music if you wait for it before exiting - because then the pygame object isn't destroyed until the...
Is Pro Django book still relevant?
7,746,344
12
2011-10-12T20:44:31Z
7,746,386
7
2011-10-12T20:48:18Z
[ "python", "django", "metaprogramming" ]
I want to dig deeper into Django's internals and the official online documentation only goes so far toward that end. The reviews for Marty Alchin's Pro Django are fantastic (I've read Pro Python and really enjoyed it). However, the book is from 2008 and is based on Django v1.0. My company builds off v1.3. Is this boo...
Yes, it's definitely still relevant. Although a lot has changed in Django since version 1, the internal parts and the concepts that Pro Django deals with are mostly the same. I'd have no hesitation in recommending the book - it's a really useful insight into how Django works and teaches some very useful methods as well...
Is Pro Django book still relevant?
7,746,344
12
2011-10-12T20:44:31Z
7,747,777
23
2011-10-12T23:29:22Z
[ "python", "django", "metaprogramming" ]
I want to dig deeper into Django's internals and the official online documentation only goes so far toward that end. The reviews for Marty Alchin's Pro Django are fantastic (I've read Pro Python and really enjoyed it). However, the book is from 2008 and is based on Django v1.0. My company builds off v1.3. Is this boo...
It's not my place to speak about its worth or recommendations, but I wrote the book with Django 1.0 in mind precisely to make sure it stayed relevant as long as possible. The aspects of Django that I documented are still present and functional, and the general aspects of Python are also still valid. They may have grown...
Python join all combinations of elements within each list
7,746,777
4
2011-10-12T21:24:08Z
7,746,812
7
2011-10-12T21:27:14Z
[ "python" ]
I have a list of tuples each with two elements: `[('1','11'),('2','22'),('3','33'),...n]` How would I find all the combinations of each tuple with only selecting one element of the tuple at a time? The example results: > > [[1,2,3],[11,2,3],[11,2,3],[11,22,33],[11,2,33],[11,22,3],[1,22,3],[1,22,33],[1,2,33]]` itert...
Use [itertools.product](http://docs.python.org/library/itertools.html#itertools.product): ``` In [88]: import itertools as it In [89]: list(it.product(('1','11'),('2','22'),('3','33'))) Out[89]: [('1', '2', '3'), ('1', '2', '33'), ('1', '22', '3'), ('1', '22', '33'), ('11', '2', '3'), ('11', '2', '33'), ('11', ...
Scraping and parsing Google search results using Python
7,746,832
17
2011-10-12T21:28:46Z
7,746,905
9
2011-10-12T21:36:33Z
[ "python", "screen-scraping", "web-scraping", "google-search-api" ]
I asked a [question](http://stackoverflow.com/questions/7722876/web-mining-or-scraping-or-crawling-what-tool-library-should-i-use) on realizing a general idea to crawl and save webpages. Part of the original question is: how to crawl and save a lot of "About" pages from the Internet. With some further research, I got ...
You may find [xgoogle](http://www.catonmat.net/blog/python-library-for-google-search/) useful... much of what you seem to be asking for is there...
python xlwt set custom background colour of a cell
7,746,837
18
2011-10-12T21:29:40Z
15,230,844
11
2013-03-05T17:59:11Z
[ "python", "excel", "format", "xlwt" ]
I am using python 2.7 and xlwt module for excel export I would like to set backgroung colour of a cell i know i can use ``` style1 = xlwt.easyxf('pattern: pattern solid, fore_colour red;') ``` but I would like to set custom color smth. like #8a8eef or is there a palette of possible colors, because light blue is not ...
If you are not using `easyxf()` and instead are building `XFStyle` object step by step, here is another way of using user friendly color names: ``` import xlwt style = xlwt.XFStyle() pattern = xlwt.Pattern() pattern.pattern = xlwt.Pattern.SOLID_PATTERN pattern.pattern_fore_colour = xlwt.Style.colour_map['dark_purple'...
python xlwt set custom background colour of a cell
7,746,837
18
2011-10-12T21:29:40Z
21,012,266
16
2014-01-09T05:29:52Z
[ "python", "excel", "format", "xlwt" ]
I am using python 2.7 and xlwt module for excel export I would like to set backgroung colour of a cell i know i can use ``` style1 = xlwt.easyxf('pattern: pattern solid, fore_colour red;') ``` but I would like to set custom color smth. like #8a8eef or is there a palette of possible colors, because light blue is not ...
Nowadays, there is a way (originally proposed [here](https://groups.google.com/forum/#!topic/python-excel/HmGnhYpV094)) to define and use custom colour using `add_palette_colour()` and `set_colour_RGB()`. Here's an example: ``` import xlwt book = xlwt.Workbook() # add new colour to palette and set RGB colour value...
Python reference to callback in dictionary
7,747,611
4
2011-10-12T23:06:12Z
7,747,690
8
2011-10-12T23:17:18Z
[ "python", "callback" ]
I have a class that specifies a set of callback functions (shown here as `cb1` and `cb2`). I keep a map of these which I want to call after some event. ``` class Foo: cb1 = None cb2 = None def test(self, input): for (name, callback) in map: if name == input: if callback...
Why not make your class explicitly handle registration? ``` import collections class Foo(object): handlers = None def __init__(self): self.handlers = collections.defaultdict(set) def register(self, event, callback): self.handlers[event].add(callback) def fire(self, event, **kwargs):...
(Very) basic Python client socket example
7,749,341
23
2011-10-13T04:03:58Z
7,749,381
7
2011-10-13T04:12:45Z
[ "python", "sockets", "networking" ]
I've been trying to wrap my head around how sockets work, and I've been trying to pick apart some sample code I found at [this page](http://www.pythonprasanna.com/Papers%20and%20Articles/Sockets/tcpclient_py.txt) for a very simple client socket program. Since this is basic sample code, I assumed it had no errors, but w...
It's trying to connect to the computer it's running on on port 5000, but the connection is being refused. Are you sure you have a server running? If not, you can use [`netcat`](https://en.wikipedia.org/wiki/Netcat) for testing: ``` nc -l -k -p 5000 ``` Some implementations may require you to omit the `-p` flag.
(Very) basic Python client socket example
7,749,341
23
2011-10-13T04:03:58Z
18,297,623
58
2013-08-18T09:23:21Z
[ "python", "sockets", "networking" ]
I've been trying to wrap my head around how sockets work, and I've been trying to pick apart some sample code I found at [this page](http://www.pythonprasanna.com/Papers%20and%20Articles/Sockets/tcpclient_py.txt) for a very simple client socket program. Since this is basic sample code, I assumed it had no errors, but w...
Here is the simplest python socket example. Server side: ``` import socket serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversocket.bind(('localhost', 8089)) serversocket.listen(5) # become a server socket, maximum 5 connections while True: connection, address = serversocket.accept() bu...
How do I get JSON data from RESTful service using Python?
7,750,557
41
2011-10-13T07:07:48Z
7,750,945
67
2011-10-13T07:45:48Z
[ "python", "json", "rest", "kerberos" ]
Is there any standard way of getting JSON data from RESTful service using Python? I need to use kerberos for authentication. some snippet would help.
I would give the [requests](http://docs.python-requests.org) library a try for this. Essentially just a much easier to use wrapper around the standard library modules (i.e. urllib2, httplib2, etc.) you would use for the same thing. For example, to fetch json data from a url that requires basic authentication would look...
How do I get JSON data from RESTful service using Python?
7,750,557
41
2011-10-13T07:07:48Z
7,750,946
49
2011-10-13T07:46:21Z
[ "python", "json", "rest", "kerberos" ]
Is there any standard way of getting JSON data from RESTful service using Python? I need to use kerberos for authentication. some snippet would help.
Something like this should work unless I'm missing the point: ``` import json import urllib2 json.load(urllib2.urlopen("url")) ```
How do I get JSON data from RESTful service using Python?
7,750,557
41
2011-10-13T07:07:48Z
7,751,010
16
2011-10-13T07:53:18Z
[ "python", "json", "rest", "kerberos" ]
Is there any standard way of getting JSON data from RESTful service using Python? I need to use kerberos for authentication. some snippet would help.
You basically need to make a HTTP request to the service, and then parse the body of the response. I like to use httplib2 for it: ``` import httplib2 as http import json try: from urlparse import urlparse except ImportError: from urllib.parse import urlparse headers = { 'Accept': 'application/json', ...
Can Python's map function call object member functions?
7,750,982
15
2011-10-13T07:49:47Z
7,751,029
27
2011-10-13T07:55:03Z
[ "python" ]
I need to do something that is functionally equivalent to this: ``` for foo in foos: bar = foo.get_bar() # Do something with bar ``` My first instinct was to use `map`, but this did not work: ``` for bar in map(get_bar, foos): # Do something with bar ``` Is what I'm trying to accomplish possible with `m...
either with `lambda`: ``` for bar in map(lambda foo: foo.get_bar(), foos): ``` or with `methodcaller`: ``` import operator get_bar = operator.methodcaller('get_bar') for bar in map(get_bar, foos): ``` or with a generator expression: ``` for bar in (foo.get_bar() for foo in foos): ```