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
pip broke. how to fix DistributionNotFound error?
6,200,056
111
2011-06-01T10:58:08Z
6,200,314
28
2011-06-01T11:20:31Z
[ "python", "pip" ]
Whenever i try to use pip I get an error. For exampple: ``` $ sudo pip install gevent-websocket Traceback (most recent call last): File "/usr/local/bin/pip", line 5, in <module> from pkg_resources import load_entry_point File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 2675, in <module> parse_requirem...
I replaced 0.8.1 in 0.8.2 in /usr/local/bin/pip and everything worked again. ``` __requires__ = 'pip==0.8.2' import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.exit( load_entry_point('pip==0.8.2', 'console_scripts', 'pip')() ) ``` I installed pip through easy\_instal...
pip broke. how to fix DistributionNotFound error?
6,200,056
111
2011-06-01T10:58:08Z
11,788,373
221
2012-08-03T02:18:26Z
[ "python", "pip" ]
Whenever i try to use pip I get an error. For exampple: ``` $ sudo pip install gevent-websocket Traceback (most recent call last): File "/usr/local/bin/pip", line 5, in <module> from pkg_resources import load_entry_point File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 2675, in <module> parse_requirem...
I find this problem in my MacBook, the reason is because as @Stephan said, I use `easy_install` to install pip, and the mixture of both py package manage tools led to the `pkg_resources.DistributionNotFound` problem. The resolve is: ``` easy_install --upgrade pip ``` Remember: just use **one** of the above tools to m...
pip broke. how to fix DistributionNotFound error?
6,200,056
111
2011-06-01T10:58:08Z
29,609,088
11
2015-04-13T15:22:16Z
[ "python", "pip" ]
Whenever i try to use pip I get an error. For exampple: ``` $ sudo pip install gevent-websocket Traceback (most recent call last): File "/usr/local/bin/pip", line 5, in <module> from pkg_resources import load_entry_point File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 2675, in <module> parse_requirem...
I had this issue when I was using home-brew. Here is the solution from Issue [#26900](https://github.com/Homebrew/homebrew/issues/26900%20%22#26900) ``` python -m pip install --upgrade --force pip ```
ManyToMany field not saved when using Django admin
6,200,233
7
2011-06-01T11:12:57Z
6,200,451
9
2011-06-01T11:33:14Z
[ "python", "django", "m2m", "django-orm" ]
I'm experiencing a weird problem which I hope someone in here may be able to shed some light on. I'm overriding the save() method of a model to add some values to a ManyToMany-field after running super(). My problem is that when I'm saving in Django admin the values seems to get added to the relationship but is then e...
So it turns out the above was not the correct way to implement it. The code belonged in StoreAdmin, by overriding model\_save(). This is how I solved it: ``` class StoreAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): if obj.copy_holidays_from: form.cleaned_data['holi...
Decorator to print function call details - parameters names and effective values
6,200,270
10
2011-06-01T11:16:15Z
6,200,396
9
2011-06-01T11:28:36Z
[ "python" ]
I want to make a function that being a decorator to another function will print that function call details - parameters names and effective values. My current implementation is this. ``` def describeFuncCall(func): '''Decorator to print function call details - parameters names and effective values''' def wrapp...
Sorry its a bit messy. I modified some code from <http://wiki.python.org/moin/PythonDecoratorLibrary#Easy_Dump_of_Function_Arguments> ``` def dump_args(func): "This decorator dumps out the arguments passed to a function before calling it" argnames = func.func_code.co_varnames[:func.func_code.co_argcount] f...
numpy and Global Interpreter Lock
6,200,437
18
2011-06-01T11:31:48Z
6,201,158
8
2011-06-01T12:30:06Z
[ "python", "multithreading", "numpy", "gil", "python-multithreading" ]
I am about to write some computationally-intensive Python code that'll almost certainly spend most of its time inside `numpy`'s linear algebra functions. The problem at hand is [embarrassingly parallel](http://en.wikipedia.org/wiki/Embarrassingly_parallel). Long story short, the easiest way for me to take advantage of...
You will probably find answers to all your questions regarding NumPy and parallel programming on [the official wiki](http://scipy-cookbook.readthedocs.org/items/ParallelProgramming.html). Also, have a look at [this recipe page](http://scipy-cookbook.readthedocs.org/items/Multithreading.html) -- it contains example cod...
Relationship between scipy and numpy
6,200,910
173
2011-06-01T12:11:19Z
6,201,035
37
2011-06-01T12:21:06Z
[ "python", "numpy", "scipy" ]
`scipy` appears to provide most (but not all [1]) of `numpy`'s functions in its own namespace. In other words, if there's a function named `numpy.foo`, there's almost certainly a `scipy.foo`. Most of the time, the two appear to be exactly the same, oftentimes even pointing to the same function object. Sometimes, they'...
From the SciPy Reference Guide: > ... all of the Numpy functions have > been subsumed into the `scipy` > namespace so that all of those > functions are available without > additionally importing Numpy. The intention is for users not to have to know the distinction between the `scipy` and `numpy` namespaces, though ap...
Relationship between scipy and numpy
6,200,910
173
2011-06-01T12:11:19Z
6,201,054
95
2011-06-01T12:22:06Z
[ "python", "numpy", "scipy" ]
`scipy` appears to provide most (but not all [1]) of `numpy`'s functions in its own namespace. In other words, if there's a function named `numpy.foo`, there's almost certainly a `scipy.foo`. Most of the time, the two appear to be exactly the same, oftentimes even pointing to the same function object. Sometimes, they'...
Last time I checked it, the scipy `__init__` method executes a ``` from numpy import * ``` so that the whole numpy namespace is included into scipy when the scipy module is imported. The log10 behaviour you are describing is interesting, because *both* versions are coming from numpy. One is a `ufunc`, the other is a...
Relationship between scipy and numpy
6,200,910
173
2011-06-01T12:11:19Z
6,919,628
9
2011-08-02T22:46:51Z
[ "python", "numpy", "scipy" ]
`scipy` appears to provide most (but not all [1]) of `numpy`'s functions in its own namespace. In other words, if there's a function named `numpy.foo`, there's almost certainly a `scipy.foo`. Most of the time, the two appear to be exactly the same, oftentimes even pointing to the same function object. Sometimes, they'...
There is a short comment at the end of the [introduction to SciPy](http://docs.scipy.org/doc/scipy/reference/tutorial/general.html) documentation: > Another useful command is`source`. When given a function written in Python as an argument, it prints out a listing of the source code for that function. This can be helpf...
Relationship between scipy and numpy
6,200,910
173
2011-06-01T12:11:19Z
17,964,045
24
2013-07-31T07:21:40Z
[ "python", "numpy", "scipy" ]
`scipy` appears to provide most (but not all [1]) of `numpy`'s functions in its own namespace. In other words, if there's a function named `numpy.foo`, there's almost certainly a `scipy.foo`. Most of the time, the two appear to be exactly the same, oftentimes even pointing to the same function object. Sometimes, they'...
It seems from the [scipy FAQ](http://www.scipy.org/scipylib/faq.html#id17) that some functions from numpy are here for historical reasons while it should only be in scipy: > ## What is the difference between NumPy and SciPy? > > In an ideal world, NumPy would contain nothing but the array data type and > the most basi...
Trouble splitting a String with Python
6,201,087
3
2011-06-01T12:24:49Z
6,201,119
10
2011-06-01T12:26:59Z
[ "python", "parsing", "split", "text-processing" ]
I'm desperatly trying to split a string using Python but the text file I need to parse is a little bit tricky: * The text file is a comma separated data file I did the following: ``` import fileinput for line in fileinput.input("sample.txt"): data = line.strip().split(',') pass ``` This actually should make the job...
Your data is in a pretty common format -- Comma Separated Values (CSV). Instead of writing yet another parser, consider using the built-in [`csv`](http://docs.python.org/library/csv.html) module.
Why are these two values different when I assign one to the other?
6,202,281
2
2011-06-01T13:53:03Z
6,202,400
7
2011-06-01T13:59:52Z
[ "python" ]
The code below gives different values for c and d when I print them > ``` > import csv > > datafile = open('test1.csv', 'r') > datareader = csv.reader(datafile) > c = [] > for row in datareader: > c.append(row) > > d = [[0]*2]*2 > i=0 > > while i < 2: > > j=0 > > while j < 2: > > d[i][j] = float(c[...
This line: ``` d = [[0]*2]*2 ``` doesn't create copies of the inner lists, it just creates multiple references to the same list. Replace it with an explicit declaration: ``` d = [[0, 0], [0, 0]] ```
Word tokenization using python regular expressions
6,202,549
9
2011-06-01T14:09:45Z
6,203,000
16
2011-06-01T14:41:37Z
[ "python", "regex", "string", "tags" ]
I am trying to split strings into lists of "tags" in python. The splitting should handle strings such as "HappyBirthday" and remove most punctuation but preserve hyphens, and apostrophes. My starting point is: ``` tags = re.findall("([A-Z]{2,}(?=[A-Z]|$)|[A-Z][a-z]*)|\w+-\w+|[\w']+" ``` I would want to turn this samp...
I suggest the following: ``` re.findall("[A-Z]{2,}(?![a-z])|[A-Z][a-z]+(?=[A-Z])|[\'\w\-]+",s) ``` This yields for your example: ``` ["Jeff's", 'dog', 'is', 'un-American', 'Some', 'Times', 'BUT', 'NOT', 'Always'] ``` Explanation: The RegExp is made up of 3 alternatives: 1. `[A-Z]{2,}(?![a-z])` matches words with a...
Writing UTF-8 String to MySQL with Python
6,202,726
21
2011-06-01T14:23:18Z
6,203,001
11
2011-06-01T14:41:39Z
[ "python", "unicode", "utf-8" ]
I am trying to push user account data from an Active Directory to our MySQL-Server. This works flawlessly but somehow the strings end up showing an encoded version of umlauts and other special characters. The Active Directory returns a string using this sample format: `M\xc3\xbcller` This actually is the UTF-8 encodi...
Assuming you are using MySQLdb you need to pass use\_unicode=True and charset="utf8" when creating your connection. UPDATE: If I run the following against a test table I get - ``` >>> db = MySQLdb.connect(host="localhost", user='root', passwd='passwd', db='sandbox', use_unicode=True, charset="utf8") >>> c = db.cursor...
Writing UTF-8 String to MySQL with Python
6,202,726
21
2011-06-01T14:23:18Z
6,203,782
27
2011-06-01T15:32:59Z
[ "python", "unicode", "utf-8" ]
I am trying to push user account data from an Active Directory to our MySQL-Server. This works flawlessly but somehow the strings end up showing an encoded version of umlauts and other special characters. The Active Directory returns a string using this sample format: `M\xc3\xbcller` This actually is the UTF-8 encodi...
As @marr75 suggests, make sure you set `charset='utf8'` on your connections. Setting `use_unicode=True` is not *strictly* necessary as it is implied by setting the charset. Then make sure you are passing *unicode* objects to your db connection as it will encode it using the charset you passed to the cursor. If you are...
Is there a meaningful way to use context managers inside generators?
6,203,300
9
2011-06-01T15:00:48Z
6,203,665
14
2011-06-01T15:25:27Z
[ "python", "generator", "contextmanager" ]
``` from contextlib import contextmanager @contextmanager def context(): print "entering" yield print "exiting" def test(): with context(): for x in range(10): yield x for x in test(): if x == 5: break # or raise ``` output: ``` entering ``` Is there a way to make ...
Well, you could wrap the yield in context() function with a try/finally clause: ``` from contextlib import contextmanager @contextmanager def context(): print "entering" try: yield finally: print "exiting" def test(): with context(): for x in range(10): yield x fo...
How do you execute multiple commands in a single session in Paramiko? (Python)
6,203,653
24
2011-06-01T15:25:03Z
6,203,877
26
2011-06-01T15:41:20Z
[ "python", "paramiko" ]
``` def exec_command(self, command, bufsize=-1): #print "Executing Command: "+command chan = self._transport.open_session() chan.exec_command(command) stdin = chan.makefile('wb', bufsize) stdout = chan.makefile('rb', bufsize) stderr = chan.makefile_stderr('rb', bufsize) return stdin, stdout,...
This is a *non-interactive* example... it sends `cd tmp`, `ls` and then `exit`. ``` import sys sys.stderr = open('/dev/null') # Silence silly warnings from paramiko import paramiko as pm sys.stderr = sys.__stderr__ import os class AllowAllKeys(pm.MissingHostKeyPolicy): def missing_host_key(self, client, hos...
How do you execute multiple commands in a single session in Paramiko? (Python)
6,203,653
24
2011-06-01T15:25:03Z
6,205,996
16
2011-06-01T18:33:07Z
[ "python", "paramiko" ]
``` def exec_command(self, command, bufsize=-1): #print "Executing Command: "+command chan = self._transport.open_session() chan.exec_command(command) stdin = chan.makefile('wb', bufsize) stdout = chan.makefile('rb', bufsize) stderr = chan.makefile_stderr('rb', bufsize) return stdin, stdout,...
Strictly speaking, you can't. According to the ssh spec: > A session is a remote execution of a program. The program may be a > shell, an application, a system command, or some built-in subsystem. This means that, once the command has executed, the session is finished. You cannot execute multiple commands in one sess...
python empty class object
6,203,995
37
2011-06-01T15:50:56Z
6,204,010
13
2011-06-01T15:52:15Z
[ "python", "oop", "empty-class" ]
I'm teaching a python class on Object Oriented Programming and as I'm brushing up on how to explain Classes, I saw an empty class definition: ``` class Employee: pass ``` the example then goes on to define a name and other attributes for an object of this class: ``` john = Employee() john.full_name = "john doe" ...
Try with `lambda`: ``` john.greet = lambda : print( 'hello world!' ) ``` The you'll be able to do: ``` john.greet() ``` --- **EDIT**: Thanks *Thomas K* for the note - this works on `Python 3.2` and not for Python2, where `print` appeared to be `statement`. But this will work for `lambda`s, without *statements* (ri...
python empty class object
6,203,995
37
2011-06-01T15:50:56Z
6,204,100
24
2011-06-01T15:57:29Z
[ "python", "oop", "empty-class" ]
I'm teaching a python class on Object Oriented Programming and as I'm brushing up on how to explain Classes, I saw an empty class definition: ``` class Employee: pass ``` the example then goes on to define a name and other attributes for an object of this class: ``` john = Employee() john.full_name = "john doe" ...
A class is more or less a fancy wrapper for a `dict` of attributes to objects. When you instantiate a class you can assign to its attributes, and those will be stored in `foo.__dict__`; likewise, you can look in `foo.__dict__` for any attributes you have already written. This means you can do some neat dynamic things ...
Extending BaseHTTPRequestHandler - getting the posted data
6,204,029
2
2011-06-01T15:53:05Z
6,204,532
8
2011-06-01T16:27:07Z
[ "python", "http", "networking", "variables" ]
I've seen [this](http://stackoverflow.com/questions/4233218/python-basehttprequesthandler-post-variables) question, but I want to be able to access the data that's POST'd, external from the handler. Is there a way to do this? Following is the code: ``` import BaseHTTPServer HOST_NAME = '' PORT_NUMBER=8088 postVars...
This because the `postVars` is locally affected in the MyHandler instance created by the HTTPServer. If you want to access it, declare `postVars` as a global variable at the start of `do_POST` method. ``` def do_POST(s): global postVars s.send_response(200) s.end_headers() varLen = int(s.headers['Content-Lengt...
How to implement curl -u in Python?
6,205,307
7
2011-06-01T17:30:51Z
8,466,276
7
2011-12-11T18:13:01Z
[ "python", "https", "github-api" ]
I am trying to use <http://developer.github.com/v3/> to retrieve project issues. This works: ``` curl -u "Littlemaple:mypassword" https://api.github.com/repos/MyClient/project/issues ``` It returns all private issues of my client's project. However, I am not able to find out how to implement this in Python. Both ways...
``` r = requests.get('https://api.github.com', auth=('user', 'pass')) ``` Python requests is the way to go here. I've been using requests extensively at work and at home for various web service interactions. It is a joy to use compared to what came before it. Note: the auth keyword arg works on any call that requires ...
python - how to find datetime 10 mins after current time?
6,205,442
21
2011-06-01T17:43:37Z
6,205,529
48
2011-06-01T17:51:16Z
[ "python", "datetime" ]
I want to find out the datetime 10 mins after current time. Let's say we have ``` from datetime import datetime now = datetime.now() new_now = datetime.strptime(now, '%a, %d %b %Y %H:%M:%S %Z') ``` I want to find this `now` and `new_now` 10 minutes later. How can I do that?
This is a duplicate of [this](http://stackoverflow.com/questions/546321/python-date-time-get-date-6-months-from-now) question. You basically just need to add a [timedelta](http://docs.python.org/library/datetime.html#timedelta-objects) of 10 minutes to get the time you want. ``` now = datetime.datetime.now() now_plus_...
Is it a good practice to add names to __all__ using a decorator?
6,206,089
17
2011-06-01T18:41:16Z
6,206,624
17
2011-06-01T19:32:46Z
[ "python", "coding-style" ]
Is this a good practice in Python (from [Active State Recipes -- Public Decorator](http://code.activestate.com/recipes/576993-public-decorator-adds-an-item-to-__all__/))? ``` import sys def public(f): """Use a decorator to avoid retyping function/class names. * Based on an idea by Duncan Booth: http://groups.g...
The more idiomatic way to do this in Python is to mark the private functions as private by starting their name with an underscore: ``` def public(x): ... def _private_helper(y): ... ``` More people will be familiar with this style (which is also supported by the language: `_private_helper` will not be exp...
Python: Importing an "import file"
6,206,204
4
2011-06-01T18:52:26Z
6,206,421
9
2011-06-01T19:11:31Z
[ "python", "python-import" ]
I am importing a lot of different scripts, so at the top of my file it gets cluttered with import statements, i.e.: ``` from somewhere.fileA import ... from somewhere.fileB import ... from somewhere.fileC import ... ... ``` Is there a way to move all of these somewhere else and then all I have to do is import that fi...
I strongly advise against what you want to do. You are doing the [global include file mistake again](http://forthescience.org/blog/2007/08/11/global-includes/). Although only one module is importing all your modules (as opposed to all modules importing the global one), the remaining point is that if there's a valid rea...
SQLAlchemy - subquery in a WHERE clause
6,206,600
24
2011-06-01T19:30:43Z
6,211,630
24
2011-06-02T07:21:28Z
[ "python", "sqlalchemy", "subquery" ]
I've just recently started using SQLAlchemy and am still having trouble wrapping my head around some of the concepts. Boiled down to the essential elements, I have two tables like this (this is through Flask-SQLAlchemy): ``` class User(db.Model): __tablename__ = 'users' user_id = db.Column(db.Integer, primary...
This should work (different SQL, same result): ``` t = Session.query( Posts.user_id, func.max(Posts.post_time).label('max_post_time'), ).group_by(Posts.user_id).subquery('t') query = Session.query(User, Posts).filter(and_( User.user_id == Posts.user_id, User.user_id == t.c.user_id, Posts.post_time...
SQLAlchemy - subquery in a WHERE clause
6,206,600
24
2011-06-01T19:30:43Z
6,325,582
35
2011-06-13T00:09:15Z
[ "python", "sqlalchemy", "subquery" ]
I've just recently started using SQLAlchemy and am still having trouble wrapping my head around some of the concepts. Boiled down to the essential elements, I have two tables like this (this is through Flask-SQLAlchemy): ``` class User(db.Model): __tablename__ = 'users' user_id = db.Column(db.Integer, primary...
the previous answer works, but also the exact sql you asked for is written much as the actual statement: ``` print s.query(Posts).\ outerjoin(Posts.user).\ filter(Posts.post_time==\ s.query( func.max(Posts.post_time) ). filter(Posts.user_id==User.user_id). correlate(...
Regex to replace %variables%
6,206,804
6
2011-06-01T19:49:41Z
6,206,877
8
2011-06-01T19:54:48Z
[ "python", "regex" ]
I've been yanking clumps of hair out for 30 minutes doing this one... I have a dictionary, like so: ``` {'search': 'replace', 'foo': 'bar'} ``` And a string like this: ``` Foo bar %foo% % search %. ``` I'd like to replace each variable with it's equivalent text from the dictionary: ``` Foo bar bar replace. ``...
If you're flexible with your syntax in your string, Python has a built in mechanism for that: ``` >>> print 'Hello, %(your_name)s, my name is %(my_name)s' % {'your_name': 'Blender', 'my_name': 'Ken'} Hello, Blender, my name is Ken ``` Alternatively, if you want that syntax, I'd avoid regular expressions and just do t...
Python: joining 2 lists of the same size
6,208,522
3
2011-06-01T22:34:06Z
6,208,549
9
2011-06-01T22:37:25Z
[ "python", "list", "sum" ]
Let's say I have 2 following lists: list1 = [1,1,1,1] list2 = [3,3,3,3] I want the result of join to be: list3 [4,4,4,4] What's would be the best way to do it?
``` list3 = [x + y for (x, y) in itertools.izip(list1, list2)] ``` or ``` list3 = map(operator.add, list1, list2) ```
Python: joining 2 lists of the same size
6,208,522
3
2011-06-01T22:34:06Z
6,208,573
11
2011-06-01T22:40:40Z
[ "python", "list", "sum" ]
Let's say I have 2 following lists: list1 = [1,1,1,1] list2 = [3,3,3,3] I want the result of join to be: list3 [4,4,4,4] What's would be the best way to do it?
Extremely similar to Ignacio's answer, but for a tiny bit more brevity: ``` list3 = [sum(i) for i in zip(list1, list2)] ``` or ``` list3 = map(sum, zip(list1, list2)) ``` I prefer the map version myself. **Edit:** As JBernardo rightly points out, if using Python 2.x you should replace zip with its iterator counter...
Sorting a list of RGB triplets into a spectrum
6,208,980
15
2011-06-01T23:43:45Z
6,209,065
11
2011-06-01T23:59:35Z
[ "python", "python-imaging-library", "color-space", "spectrum", "hsv" ]
I have a list of RGB triplets, and I'd like to plot them in such a way that they form something like a spectrum. I've converted them to HSV, which people seem to recommend. ``` from PIL import Image, ImageDraw import colorsys def make_rainbow_rgb(colors, width, height): """colors is an array of RGB tuples, with ...
You're trying to convert a three-dimensional space into a one-dimensional space. There's no guarantee that you can make a pleasing rainbow out of it, as Oli says. What you can do is "bucket" the colors into a few different categories based on saturation and value/lightness, and then sort within the categories, to get ...
Checking if float is equivalent to an integer value in python
6,209,008
20
2011-06-01T23:49:16Z
6,209,038
9
2011-06-01T23:55:07Z
[ "python", "floating-point" ]
In Python 3, I am checking whether a given value is triangular, that is, it can be represented as n(n+1)/2 for some positive integer n Can I just write: ``` import math def is_triangular1(x): num=(1/2) * (math.sqrt(8*x+1)-1 ) return int(num)==num ``` Or do I need to do it like this? : ``` epsilon = 0.000000...
You'll want to do the latter. In *Programming in Python 3* the following example is given as the most accurate way to compare ``` def equal_float(a, b): #return abs(a - b) <= sys.float_info.epsilon return abs(a - b) <= chosen_value #see edit below for more info ``` Also, since epsilon is the "smallest differe...
Checking if float is equivalent to an integer value in python
6,209,008
20
2011-06-01T23:49:16Z
6,209,261
9
2011-06-02T00:37:46Z
[ "python", "floating-point" ]
In Python 3, I am checking whether a given value is triangular, that is, it can be represented as n(n+1)/2 for some positive integer n Can I just write: ``` import math def is_triangular1(x): num=(1/2) * (math.sqrt(8*x+1)-1 ) return int(num)==num ``` Or do I need to do it like this? : ``` epsilon = 0.000000...
Both your implementations have problems. It actually *can* happen that you end up with something like `4.999999999999997`, so using `int()` is not an option. I'd go for a completely different approach: First assume that your number is triangular, and compute what `n` would be in that case. In that first step, you can ...
Checking if float is equivalent to an integer value in python
6,209,008
20
2011-06-01T23:49:16Z
22,053,804
11
2014-02-26T21:31:24Z
[ "python", "floating-point" ]
In Python 3, I am checking whether a given value is triangular, that is, it can be represented as n(n+1)/2 for some positive integer n Can I just write: ``` import math def is_triangular1(x): num=(1/2) * (math.sqrt(8*x+1)-1 ) return int(num)==num ``` Or do I need to do it like this? : ``` epsilon = 0.000000...
There is [`is_integer`](http://docs.python.org/2/library/stdtypes.html#float.is_integer) function in python float type: ``` >>> float(1.0).is_integer() True >>> float(1.001).is_integer() False >>> ```
Converting ConfigParser values to python data types
6,209,094
9
2011-06-02T00:04:42Z
6,209,146
10
2011-06-02T00:12:24Z
[ "python", "eval", "configparser" ]
`ConfigParser` requires all sections, keys and values to be strings; no surprise. It has methods to convert the values to datatypes with `getfloat`, `getint`, `getboolean`. If you don't know the datatype, you can wrap the `get()` with an `eval()` to get have the string evaluated such as: ``` >>> from ConfigParser impo...
If you are using Python 2.6 or above you can use [`ast.literal_eval`](http://docs.python.org/library/ast.html#ast.literal_eval): > **ast.literal\_eval(node\_or\_string)** > Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Pyt...
Parse small string for name and email?
6,209,910
5
2011-06-02T02:53:00Z
6,209,946
17
2011-06-02T03:02:10Z
[ "python", "email" ]
I have a string: `John Smith <jsmith@gmail.com>` I would like to get two variables: name (John Smith) and email (jsmith@gmail.com) How might I do that? Thanks for the help!
There are more forms of valid Internet Email address than you probably realize. I would suggest using somebody else's code to parse them, like [email.utils.parseaddr](http://docs.python.org/library/email.util.html). For example, the following is a valid address: ``` "Rocky J. Squirrel" <rocky.squirrel@gmail.com> ``` ...
How to read parameters from GET request in CherryPy?
6,211,381
4
2011-06-02T06:51:56Z
6,211,574
10
2011-06-02T07:14:38Z
[ "python", "cherrypy" ]
How to read parameters from GET request in CherryPy ? I generate request from JQuery like ``` $.get( "http://localhost:8080/temp", "{a:10}", function(data) { alert(data); }, "html" ); ``` and I have class temp with @cherrypy.expose function index(self). How to extract data from GET request ?
``` @cherrypy.expose def index(self, a) ``` where a is your GET param
How to read parameters from GET request in CherryPy?
6,211,381
4
2011-06-02T06:51:56Z
6,211,607
7
2011-06-02T07:18:07Z
[ "python", "cherrypy" ]
How to read parameters from GET request in CherryPy ? I generate request from JQuery like ``` $.get( "http://localhost:8080/temp", "{a:10}", function(data) { alert(data); }, "html" ); ``` and I have class temp with @cherrypy.expose function index(self). How to extract data from GET request ?
As virhilo mentioned, you can take named parameters in with your method. Also, you can read `cherrypy.request.params`.
Is pyramid_who (repoze.who) the preferred way to do authentication for pyramid?
6,211,553
5
2011-06-02T07:12:04Z
6,224,651
10
2011-06-03T08:19:07Z
[ "python", "authentication", "pyramid", "repoze.who" ]
I am just starting to learn [Pyramid Framework](http://docs.pylonsproject.org/docs/pyramid.html). Is pyramid\_who (repoze.who) the preferred way to do authentication? What other options do I have?
pyramid\_who is the best way to utilize repoze.who v2 for doing authentication. Whether this is the best authentication solution for you or not is dependent on your needs. Typically repoze.who is the best solution for doing SSO (single sign-on) solutions where you need to connect to a service like LDAP. If SSO is not...
python read next()
6,213,063
7
2011-06-02T10:05:19Z
6,213,117
22
2011-06-02T10:10:36Z
[ "python" ]
next() in python does not work. what is an alternative to reading next line in python. here is a sample ``` filne = "D:/testtube/testdkanimfilternode.txt" f = open(filne, 'r+') while 1: lines = f.readlines() if not lines: break for line in lines: print line if (line[:5] == "anim ")...
When you do : `f.readlines()` you already read all the file so `f.tell()` will show you that you are in the end of the file, and doing `f.next()` will result in a `StopIteration` error. Alternative of what you want to do is: ``` filne = "D:/testtube/testdkanimfilternode.txt" with open(filne, 'r+') as f: for line...
python read next()
6,213,063
7
2011-06-02T10:05:19Z
6,213,132
9
2011-06-02T10:11:45Z
[ "python" ]
next() in python does not work. what is an alternative to reading next line in python. here is a sample ``` filne = "D:/testtube/testdkanimfilternode.txt" f = open(filne, 'r+') while 1: lines = f.readlines() if not lines: break for line in lines: print line if (line[:5] == "anim ")...
`next()` does not work in your case because you first call `readlines()` which basically sets the file iterator to point to the end of file. Since you are reading in all the lines anyway you can refer to the next line using an index: ``` filne = "in" with open(filne, 'r+') as f: lines = f.readlines() for i in...
python pyusb import usb.core doesn't work
6,213,361
8
2011-06-02T10:32:30Z
9,358,180
10
2012-02-20T08:38:18Z
[ "python", "import", "usb", "pyusb" ]
I am following the tutorial(http://pyusb.sourceforge.net/docs/1.0/tutorial.html) I am on windows xp sp3, my python version is 2.7 and I downloaded and installed the pyusb-1.0.0-a1.zip and libusb-win32-bin-1.2.4.0.zip ``` import usb ``` works fine but ``` import usb.core ``` doesn't working at all it says ``` T...
Your question says you're using 1.0, but I had the same symptoms as you did, so I'll put this here for future search-engine users. If you can `import usb` but not `import usb.core` you may be running python-usb 0.x instead of 1.0. <https://github.com/walac/pyusb>
Finding the calculation that generates a NaN
6,213,869
6
2011-06-02T11:24:16Z
6,213,898
7
2011-06-02T11:26:35Z
[ "python", "debugging", "numpy", "scipy", null ]
I have a moderately large piece (a few thousand lines) of Python/Numpy/Scipy code that is throwing up NaNs with certain inputs. I've looked for, and found, some of the usual suspects (`log(0)` and the like), but none of the obvious ones seem to be the culprits in this case. Is there a relatively painless way (i.e., ap...
I would start with [`numpy.seterr`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.seterr.html). There, an invalid operation is defined as "result is not an expressible number, typically indicates that a NaN was produced". By default, this seems to be set to "ignore".
Python and performance of list comprehensions
6,214,091
5
2011-06-02T11:44:22Z
6,214,159
7
2011-06-02T11:53:08Z
[ "python", "performance", "list-comprehension" ]
Suppose you have got a list comprehension in python, like ``` Values = [ f(x) for x in range( 0, 1000 ) ] ``` with f being just a function without side effects. So all the entries can be computed independently. Is Python able to increase the performance of this list comprehension compared with the "obvious" implemen...
No, Python will not magically parallelize this for you. In fact, it can't, since it cannot prove the independence of the entries; that would require a great deal of program inspection/verification, which is impossible to get right in the general case. If you want quick coarse-grained multicore parallelism, I recommend...
Python and performance of list comprehensions
6,214,091
5
2011-06-02T11:44:22Z
6,215,284
7
2011-06-02T13:37:20Z
[ "python", "performance", "list-comprehension" ]
Suppose you have got a list comprehension in python, like ``` Values = [ f(x) for x in range( 0, 1000 ) ] ``` with f being just a function without side effects. So all the entries can be computed independently. Is Python able to increase the performance of this list comprehension compared with the "obvious" implemen...
In Python 3.2 they added [`concurrent.futures`](http://docs.python.org/dev/library/concurrent.futures.html#processpoolexecutor-example), a nice library for solving problems concurrently. Consider this example: ``` import math, time from concurrent import futures PRIMES = [112272535095293, 112582705942171, 11227253509...
Is Django middleware thread safe?
6,214,509
12
2011-06-02T12:29:26Z
6,214,554
26
2011-06-02T12:33:41Z
[ "python", "django", "thread-safety", "middleware" ]
Are Django middleware thread safe? Can I do something like this, ``` class ThreadsafeTestMiddleware(object): def process_request(self, request): self.thread_safe_variable = some_dynamic_value_from_request def process_response(self, request, response): # will self.thread_safe_variable always e...
Why not bind your variable to the request object, like so: ``` class ThreadsafeTestMiddleware(object): def process_request(self, request): request.thread_safe_variable = some_dynamic_value_from_request def process_response(self, request, response): #... do something with request.thread_safe_v...
Finding empty directories in Python
6,215,334
25
2011-06-02T13:42:04Z
6,215,416
11
2011-06-02T13:48:40Z
[ "python", "rmdir" ]
All, What is the best way to check to see if there is data in a directory before deleting it? I am browsing through a couple pages to find some pics using wget and of course every page does not have an image on it but the directory is still created. ``` dir = 'Files\\%s' % (directory) os.mkdir(dir) cmd = 'wget -r -l1...
Try: ``` if not os.listdir(dir): print "Empty" ``` or ``` if os.listdir(dir) == []: print "Empty" ```
Finding empty directories in Python
6,215,334
25
2011-06-02T13:42:04Z
6,215,421
29
2011-06-02T13:48:57Z
[ "python", "rmdir" ]
All, What is the best way to check to see if there is data in a directory before deleting it? I am browsing through a couple pages to find some pics using wget and of course every page does not have an image on it but the directory is still created. ``` dir = 'Files\\%s' % (directory) os.mkdir(dir) cmd = 'wget -r -l1...
``` import os if not os.listdir(dir): os.rmdir(dir) ``` [LBYL](http://docs.python.org/glossary.html#term-lbyl) style. for [EAFP](http://docs.python.org/glossary.html#term-eafp), see mouad's answer.
Finding empty directories in Python
6,215,334
25
2011-06-02T13:42:04Z
6,215,451
34
2011-06-02T13:51:38Z
[ "python", "rmdir" ]
All, What is the best way to check to see if there is data in a directory before deleting it? I am browsing through a couple pages to find some pics using wget and of course every page does not have an image on it but the directory is still created. ``` dir = 'Files\\%s' % (directory) os.mkdir(dir) cmd = 'wget -r -l1...
I will go with [EAFP](http://docs.python.org/glossary.html#term-eafp) like so: ``` try: os.rmdir(dir) except OSError as ex: if ex.errno == errno.ENOTEMPTY: print "directory not empty" ``` N.B: [os.rmdir](http://docs.python.org/library/os.html#os.rmdir) don't delete directory that are not empty.
Most efficient way in Python to iterate over a large file (10GB+)
6,215,523
11
2011-06-02T13:56:21Z
6,215,755
14
2011-06-02T14:17:18Z
[ "python", "file", "design-patterns", "matching" ]
I'm working on a Python script to go through two files - one containing a list of UUIDs, the other containing a large amount of log entries - each line containing one of the UUIDs from the other file. The purpose of the program is to create a list of the UUIDS from file1, then for each time that UUID is found in the lo...
Think functionally! 1. Write a function which will take a line of the log file and return the uuid. Call it `uuid`, say. 2. Apply this function to every line of the log file. If you are using Python 3 you can use the built-in function map; otherwise, you need to use itertools.imap. 3. Pass this iterator to a collectio...
Python interp1d vs. UnivariateSpline
6,216,881
8
2011-06-02T15:46:42Z
6,236,482
9
2011-06-04T11:30:46Z
[ "python", "matlab", "numpy", "scipy", "interpolation" ]
I'm trying to port some MatLab code over to Scipy, and I've tried two different functions from scipy.interpolate, [interp1d](http://docs.scipy.org/doc/scipy-dev/reference/generated/scipy.interpolate.interp1d.html#scipy.interpolate.interp1d) and [UnivariateSpline](http://docs.scipy.org/doc/scipy-dev/reference/generated/...
The reason why the results are different (but both likely correct) is that the interpolation routines used by `UnivariateSpline` and `interp1d` are different. * `interp1d` constructs a smooth B-spline using the `x`-points you gave to it as knots * `UnivariateSpline` is based on FITPACK, which also constructs a smooth ...
Python interp1d vs. UnivariateSpline
6,216,881
8
2011-06-02T15:46:42Z
17,729,054
12
2013-07-18T16:26:33Z
[ "python", "matlab", "numpy", "scipy", "interpolation" ]
I'm trying to port some MatLab code over to Scipy, and I've tried two different functions from scipy.interpolate, [interp1d](http://docs.scipy.org/doc/scipy-dev/reference/generated/scipy.interpolate.interp1d.html#scipy.interpolate.interp1d) and [UnivariateSpline](http://docs.scipy.org/doc/scipy-dev/reference/generated/...
I just ran into the same issue. # Short answer Use [InterpolatedUnivariateSpline](http://docs.scipy.org/doc/scipy-dev/reference/generated/scipy.interpolate.InterpolatedUnivariateSpline.html#scipy.interpolate.InterpolatedUnivariateSpline) instead: ``` f = InterpolatedUnivariateSpline(row1, row2) return f(interp) ``` ...
Redefining Pythons builtin datatypes
6,217,351
3
2011-06-02T16:29:28Z
6,217,424
7
2011-06-02T16:36:11Z
[ "python", "list", "object", "subclass", "built-in-types" ]
Is it possible to redefine which object the brackets [] use? I can subclass the `list` object, but how to I make the interpreter use my subclass in place of the buildin list object? Is it possible? (I'm pretty sure I'm using the wrong terms for the question- feel free to edit) ``` >>> class mlist(list): ... def ...
The brackets are part of the language. They're used to create lists. It's not possible to redefine that (and not desirable either!).
XPath predicate with sub-paths with lxml?
6,218,126
5
2011-06-02T17:40:44Z
6,231,045
16
2011-06-03T18:17:12Z
[ "python", "xml", "xpath", "lxml" ]
I'm trying to understand and XPath that was sent to me for use with ACORD XML forms (common format in insurance). The XPath they sent me is (truncated for brevity): ``` ./PersApplicationInfo/InsuredOrPrincipal[InsuredOrPrincipalInfo/InsuredOrPrincipalRoleCd="AN"]/GeneralPartyInfo ``` Where I'm running into trouble is...
Change `tree.find` to `tree.xpath`. `find` and `findall` are present in lxml to provide compatibility with other implementations of ElementTree. [These methods do not implement the entire XPath language](http://lxml.de/FAQ.html#what-are-the-findall-and-xpath-methods-on-element-tree). To employ XPath expressions contain...
How to implement followers/following in Django
6,218,175
7
2011-06-02T17:45:12Z
6,218,463
15
2011-06-02T18:09:13Z
[ "python", "django", "django-orm" ]
I want to implement the followers/following feature in my Django application. I've an **UserProfile** class for every **User** (django.contrib.auth.User): ``` class UserProfile(models.Model): user = models.ForeignKey(User, unique = True, related_name = 'user') follows = models.ManyToManyField("self", related_...
Set [symmetrical](https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ManyToManyField.symmetrical) to False in your Many2Many relation: ``` follows = models.ManyToManyField('self', related_name='follows', symmetrical=False) ```
How to implement followers/following in Django
6,218,175
7
2011-06-02T17:45:12Z
6,218,833
10
2011-06-02T18:38:39Z
[ "python", "django", "django-orm" ]
I want to implement the followers/following feature in my Django application. I've an **UserProfile** class for every **User** (django.contrib.auth.User): ``` class UserProfile(models.Model): user = models.ForeignKey(User, unique = True, related_name = 'user') follows = models.ManyToManyField("self", related_...
In addition to mouad's answer, may I suggest choosing a different \*related\_name\*: If Mark **follows** John, then Mark is one of John's **followers**, right?
Pydev Code Completion for everything
6,218,778
22
2011-06-02T18:34:21Z
7,147,934
22
2011-08-22T13:07:52Z
[ "python", "eclipse", "pydev", "code-completion" ]
In many cases (such as function parameters) [Pydev](http://pydev.org/) doesn't statically know the type of a variable. Therefore code completion (after `.` or when using `ctrl+space`) doesn't work. In most cases, you **know** what type will be in run-time as you are designing the software. Is there a way to hint Pydev...
**[Edit]** Since PyDev 2.8.0, it can use docstrings and comments to discover the type of objects. See: <http://pydev.org/manual_adv_type_hints.html> for details on the supported formats. **[Before PyDev 2.8.0]** Previously, it only supported assert isinstance calls (and this still works): ``` assert isinstance(a_l...
Pyramid logging
6,219,073
11
2011-06-02T19:00:42Z
6,224,590
10
2011-06-03T08:12:33Z
[ "python", "logging", "stdout", "stderr", "pyramid" ]
I have a pyramid application and I want the logs to got to stderr and stdout. stdout should be "INFO" level and below. stderr should be "WARN" and higher. How would I change my .ini file to do this? Currently I am logging like this, is this considered the correct way? ``` log = logger.getLogger(__name__) log.info("up...
You can add multiple handlers to the root, comma-delimited. If you want to filter outside of the normal "only accept messages above this logging level" criterion (i.e. only debug messages) then you need to use something like a logging filter to accept/reject records based on their specific levels: <http://docs.python.o...
Searching for a string in a large text file - profiling various methods in python
6,219,141
25
2011-06-02T19:06:12Z
6,219,943
9
2011-06-02T20:24:05Z
[ "python", "performance", "search", "profiling", "large-files" ]
This question has been asked many times. After spending some time reading the answers, I did some quick profiling to try out the various methods mentioned previously... > * I have a **600 MB** file with **6 million** lines of strings (Category paths from DMOZ project). > * The entry on each line is unique. > * I want ...
Variant 1 is great if you need to launch many sequential searches. Since `set` is internally a hash table, it's rather good at search. It takes time to build, though, and only works well if your data fit into RAM. Variant 3 is good for very big files, because you have plenty of address space to map them and OS caches ...
bdist_rpm from Ubuntu to CentOs
6,220,315
4
2011-06-02T20:58:27Z
6,220,687
7
2011-06-02T21:38:09Z
[ "python", "ubuntu", "centos", "rpm" ]
We develop on Ubuntu/Macs and deploy RPMs to CentOS (this is the settings, can't be changed much). The problem is that when installing from the rpm, the packages go to `/usr/local/lib/python2.7/dist-packages` (which is the right location for Ubuntu). However the default python path in CentOS is looking at `/usr/local/...
You can use a `setup.cfg` file to override the Python lib install path: **setup.cfg**: ``` [install] install-lib=/usr/local/lib/python2.7/site-packages ``` Example: ``` % python setup.py bdist_rpm % rpm -qpl dist/foo-0.0.0-1.noarch.rpm | grep foo /usr/local/lib/python2.7/site-packages/foo/__init__.py /usr/local/li...
In Python, how do i check if 2 different links actually point to the same page?
6,220,407
3
2011-06-02T21:07:03Z
6,220,530
10
2011-06-02T21:19:39Z
[ "python", "urllib2" ]
For example, these 2 links point to the same location: > <http://www.independent.co.uk/life-style/gadgets-and-tech/news/chinese-blamed-for-gmail-hacking-2292113.html> > > <http://www.independent.co.uk/life-style/gadgets-and-tech/news/2292113.html> How do i check this in python?
Call `geturl()` on the result of `urllib2.urlopen()`. `geturl()` "returns the URL of the resource retrieved, commonly used to determine if a redirect was followed." For example: ``` #!/usr/bin/env python # coding: utf-8 import urllib2 url1 = 'http://www.independent.co.uk/life-style/gadgets-and-tech/news/chinese-bla...
Get related models in SQLAlchemy
6,221,145
4
2011-06-02T22:32:34Z
6,295,388
8
2011-06-09T15:30:17Z
[ "python", "sqlalchemy" ]
I have various models chained in [SQLAlchemy](http://en.wikipedia.org/wiki/SQLAlchemy) (has many, belongs to, etc.). Is there a way of finding the related models given ones instance? Something like: ``` usersModelInstance.getRelatedTables() // This should provide an array or something with the related tables of users...
I'm not sure quite what you want -- a list of tables or a list of mapped classes? In either case, first build a list of properties for your mapped *object*: ``` # Import sqlalchemy so we can use it import sqlalchemy as sa # Rename the OP's object to `obj` obj = usersModelInstance # Build a list of only relationship...
Django calling save on a QuerySet object - 'QuerySet' object has no attribute 'save'
6,221,510
8
2011-06-02T23:29:28Z
6,221,545
10
2011-06-02T23:35:47Z
[ "python", "django" ]
How would I get the below to work? ``` player = Player.objects.get(pk=player_id) game = Game.objects.get(pk=game_id) game_participant = GameParticipant.objects.filter(player=player, game=game) game_participant.save() ``` I when the object already exists in the datbase then I get: > 'QuerySet' object has no attribute...
**filter** returns a queryset. A queryset isn't a single object, it's a group of objects so it doesn't make sense to call save() on a queryset. Instead you save each individual object **IN** the queryset: ``` game_participants = GameParticipant.objects.filter(player=player, game=game) for object in game_participants: ...
Django calling save on a QuerySet object - 'QuerySet' object has no attribute 'save'
6,221,510
8
2011-06-02T23:29:28Z
6,221,575
10
2011-06-02T23:40:08Z
[ "python", "django" ]
How would I get the below to work? ``` player = Player.objects.get(pk=player_id) game = Game.objects.get(pk=game_id) game_participant = GameParticipant.objects.filter(player=player, game=game) game_participant.save() ``` I when the object already exists in the datbase then I get: > 'QuerySet' object has no attribute...
You'll want to use the `update` method since you're dealing with multiple objects: <https://docs.djangoproject.com/en/dev/topics/db/queries/#updating-multiple-objects-at-once>
The best way to store a python list to a database?
6,222,381
2
2011-06-03T02:22:34Z
6,224,703
7
2011-06-03T08:25:04Z
[ "python", "database", "sqlalchemy", "pyramid" ]
What would be the best way of storing a python list of numbers (such as [4, 7, 10, 39, 91]) to a database? I am using the Pyramid framework with SQLAlchemy to communicate to a database. Thanks!
Well conceptually you can store a list as a bunch of rows in a table using a one-to-many relation, or you can focus on how to store a list in a particular database backend. For example postgres can store an array in a particular cell using the sqlalchemy.dialects.postgres.ARRAY data type which can serialize a python ar...
shortest python quine?
6,223,285
18
2011-06-03T05:23:05Z
6,659,007
13
2011-07-12T02:52:16Z
[ "python", "quine" ]
``` _='_=%r;print _%%_';print _%_ ``` Is this the shortest possible python quine, or can it be done better? This one seems to improve on all the entries on [The Quine Page](http://www.nyx.net/~gthompso/quine.htm). I'm not counting the trivial 'empty' program, and I'm not counting Terry Reedy's submission which is sus...
Technically, the shortest Python quine is the empty file. Apart from this trivial case: Since Python's print automatically appends a newline, the quine is actually `_='_=%r;print _%%_';print _%_\n` (where `\n` represents a single newline character in the file).
shortest python quine?
6,223,285
18
2011-06-03T05:23:05Z
19,674,136
8
2013-10-30T04:52:26Z
[ "python", "quine" ]
``` _='_=%r;print _%%_';print _%_ ``` Is this the shortest possible python quine, or can it be done better? This one seems to improve on all the entries on [The Quine Page](http://www.nyx.net/~gthompso/quine.htm). I'm not counting the trivial 'empty' program, and I'm not counting Terry Reedy's submission which is sus...
Both ``` print open(__file__).read() ``` and anything involving import are not valid quines, because a quine by definition cannot take any input. Reading an external file is considered taking input, and thus a quine cannot read a file -- including itself. For the record, technically speaking, the shortest possible q...
shortest python quine?
6,223,285
18
2011-06-03T05:23:05Z
31,724,322
10
2015-07-30T12:52:21Z
[ "python", "quine" ]
``` _='_=%r;print _%%_';print _%_ ``` Is this the shortest possible python quine, or can it be done better? This one seems to improve on all the entries on [The Quine Page](http://www.nyx.net/~gthompso/quine.htm). I'm not counting the trivial 'empty' program, and I'm not counting Terry Reedy's submission which is sus...
I'm just going to leave this here (save as exceptionQuine.py): ``` File "exceptionQuine.py", line 1 File "exceptionQuine.py", line 1 ^ IndentationError: unexpected indent ```
**kwargs vs 10 arguments in a python function?
6,223,561
5
2011-06-03T06:05:32Z
6,223,663
7
2011-06-03T06:21:41Z
[ "python", "ebay" ]
I am starting out with python and trying to construct an XML request for an [ebay web service](http://developer.ebay.com/DevZone/best-match-item-details/CallRef/findBestMatchItemDetailsAcrossStores.html): Now, my question is: Say, this is my function: ``` def findBestMatchItemDetailsAcrossStores(): request = ""...
A good idea is to put all the parameters with appropriate defaults (or just `None` defaults) in the function signature. Yeah, it will require a little more typing in the function itself, but the interface will be clean, self-documented and simple to use, as you won't have to look up possible parameters in ebay docs or ...
What is the difference between a string and a byte string?
6,224,052
36
2011-06-03T07:06:53Z
6,224,384
44
2011-06-03T07:49:39Z
[ "python", "string", "byte" ]
I am working with a library which returns a byte string and I need to convert this to a string. Although I'm not sure what the difference is - if any.
Assuming Python 3 (in Python 2, this difference is a little less well-defined) - a string is a sequence of characters, ie [unicode codepoints](http://en.wikipedia.org/wiki/Unicode); these are an abstract concept, and can't be directly stored on disk. A byte string is a sequence of, unsurprisingly, bytes - things that *...
What is the difference between a string and a byte string?
6,224,052
36
2011-06-03T07:06:53Z
31,322,359
35
2015-07-09T15:46:40Z
[ "python", "string", "byte" ]
I am working with a library which returns a byte string and I need to convert this to a string. Although I'm not sure what the difference is - if any.
The only thing that a computer can store is bytes. To store anything in a computer, you must first *encode* it, i.e. convert it to bytes. For example: * If you want to store music, you must first *encode* it using `MP3`, `WAV`, etc. * If you want to store a picture, you must first *encode* it using `PNG`, `JPEG`, etc...
How to install Python 2.7 devel if I have Python 2.7 in a different directory
6,224,228
5
2011-06-03T07:29:59Z
6,224,291
7
2011-06-03T07:37:28Z
[ "python", "dependencies", "development-environment" ]
I have python 2.7 installed in `/opt/python2.7`. Now i want to install the devel packages for it but could not find it. How can i install it os that goes in python2.7 not for default python2.4
Installing Python from source installs the development files in the same prefix.
How to write Python code that is able to properly require a minimal python version?
6,224,736
30
2011-06-03T08:29:54Z
6,224,814
28
2011-06-03T08:38:28Z
[ "python" ]
I would like to see if there is any way of requiring a minimal python version. I have several python modules that are requiring Python 2.6 due to the new exception handling (`as` keyword). It looks that even if I check the python version at the beginning of my script, the code will not run because the interpreter wil...
You should not use any Python 2.6 features inside the script itself. Also, you must do your version check before importing any of the modules requiring a new Python version. E.g. start your script like so: ``` #!/usr/bin/env python import sys if sys.version_info[0] != 2 or sys.version_info[1] < 6: print("This sc...
How to write Python code that is able to properly require a minimal python version?
6,224,736
30
2011-06-03T08:29:54Z
6,224,857
10
2011-06-03T08:42:34Z
[ "python" ]
I would like to see if there is any way of requiring a minimal python version. I have several python modules that are requiring Python 2.6 due to the new exception handling (`as` keyword). It looks that even if I check the python version at the beginning of my script, the code will not run because the interpreter wil...
``` import sys if sys.hexversion < 0x02060000: sys.exit("Python 2.6 or newer is required to run this program.") import module_requiring_26 ``` Also the cool part about this is that it can be included inside the `__init__` file or the module.
How to write Python code that is able to properly require a minimal python version?
6,224,736
30
2011-06-03T08:29:54Z
6,224,906
14
2011-06-03T08:48:33Z
[ "python" ]
I would like to see if there is any way of requiring a minimal python version. I have several python modules that are requiring Python 2.6 due to the new exception handling (`as` keyword). It looks that even if I check the python version at the beginning of my script, the code will not run because the interpreter wil...
The simplest way I've found to do this (see this [question](http://stackoverflow.com/questions/3035749/how-to-write-a-python-2-6-script-that-gracefully-fails-with-older-python) also) is just to add a line like: ``` b'You need Python 2.6 or later.' ``` at the start of the file. This exploits the fact that byte literal...
Can't show image display windows in openCV
6,225,508
5
2011-06-03T09:50:46Z
6,228,707
10
2011-06-03T14:53:24Z
[ "python", "opencv", "window" ]
I am using openCV python bindings. I am trying to show the output image using the following listing: ``` cv.NamedWindow('display') cv.MoveWindow('display', 10, 10) cv.ShowImage('display', cvImage) ``` But I do not see any window. My platform is Linux (openSuse 11.4), python-opencv version 2.1 and python 2.7.
You need to call the WaitKey function to process the events. Check out the documentation: <http://opencv.willowgarage.com/documentation/python/highgui_user_interface.html#waitkey> > This function is the only method in HighGUI that can fetch and handle events, so it needs to be called periodically for normal event proc...
Downloading multiple attachments using imaplib
6,225,763
9
2011-06-03T10:15:50Z
27,556,667
8
2014-12-18T22:15:38Z
[ "python", "email", "imap", "attachment" ]
How can I download multiple attachments from a single mail using [imaplib](http://docs.python.org/library/imaplib.html)? Let's say I have an e-mail and that e-mail contains 4 attachments. How can I download all of those attachments? The code below only downloads a single attachment from an e-mail. ``` detach_dir = 'c...
For any future python travellers. Here is a class that downloads any attachment found for an email and saves it to a specific location. ``` import email import imaplib import os class FetchEmail(): connection = None error = None def __init__(self, mail_server, username, password): self.connectio...
Lazy loading of columns in sqlalchemy
6,225,901
12
2011-06-03T10:29:18Z
6,226,444
15
2011-06-03T11:19:45Z
[ "python", "orm", "sqlalchemy", "lazy-loading", "lazy-evaluation" ]
Is it possible in sqlalchemy to lazy load a column? I have large BLOB column that I'm usually using but in some cases I don't want to load this specific column (while I'd like to have ORM object). Is it possible without adding separate table?
``` class Book(Base): __tablename__ = 'books' book_id = Column(Integer, primary_key=True) title = Column(String(200), nullable=False) summary = Column(String(2000)) excerpt = deferred(Column(Text)) photo = deferred(Column(Binary)) ``` [Deferred Column Loading](http://docs.sqlalchemy.org/en/rel...
Detect re (regexp) object in Python
6,226,180
14
2011-06-03T10:55:35Z
6,227,280
15
2011-06-03T12:48:20Z
[ "python", "regex", "types" ]
I wonder what is the proper pythonic backward- and forward-compatible method how check if an object is compiled `re` object. `isinstance` method cannot be easily used, while the resulting object claims to be `_sre.SRE_Pattern` object: ``` >>> import re >>> rex = re.compile('') >>> rex <_sre.SRE_Pattern object at 0x7f...
`re._pattern_type` exists, and appears to do what you want: ``` >>> isinstance(re.compile(''), re._pattern_type) True ``` But this is not a good idea - per Python convention, names starting with \_ are not part of the public API of a module and not part of the backward compatibility guarantees. So, using `type(re.com...
openCV vs GIMP, edge detection fails in openCV
6,226,597
6
2011-06-03T11:35:18Z
6,227,355
9
2011-06-03T12:55:03Z
[ "python", "opencv", "gimp", "edge-detection" ]
I am doing Sobel edge detection in openCV using the with following parameters: ``` cv.Sobel(mat, edgemat, 1, 1) # mat -> source image # edgemat -> taget output image # 1 -> xorder (int) – Order of the derivative x # 1 -> yorder (int) – Order of the derivative y # apertureSize (int) – Size of the extended Sobel ...
Simple answer: You are doing it wrong. See [the documentation](http://opencv.willowgarage.com/documentation/STRAWMAN/cpp/image_filtering.html#cv-sobel) - what you are doing is computing the `d^2/(dx dy)` derivative of the image - that means "how do the horizontal edges change vertically" (or, equivalently, "how do the ...
Python fork(): passing data from child to parent
6,227,039
9
2011-06-03T12:22:09Z
6,227,151
8
2011-06-03T12:35:00Z
[ "python", "numpy", "fork", "shared-memory", "large-data" ]
I have a main Python process, and a bunch or workers created by the main process using [`os.fork()`](http://docs.python.org/library/os.html#os.fork). I need to pass large and fairly involved data structures from the workers back to the main process. What existing libraries would you recommend for that? The data struc...
Use the [`multiprocessing` module](http://docs.python.org/library/multiprocessing.html) to create your worker processes (instead of `fork`), and use [Queues or Pipes](http://docs.python.org/library/multiprocessing.html#exchanging-objects-between-processes) to exchange data. --- Another idea: use [`mmap.mmap(-1, lengt...
How to block the main thread until all the other threads finish executing?
6,227,219
5
2011-06-03T12:43:21Z
6,227,233
7
2011-06-03T12:44:37Z
[ "python" ]
This is a newbie question. I start 10 threads from my main thread. How do I stop the main thread from continuing until all the other threads finish?
[Join](http://docs.python.org/library/threading.html#threading.Thread.join) all threads: ``` for t in threads: t.join() ``` Here `threads` is the list of your threads.
Finding the user's "My Documents" path
6,227,590
16
2011-06-03T13:18:33Z
6,227,623
20
2011-06-03T13:21:26Z
[ "python" ]
I have this small program and it needs to create a small .txt file in their 'My Documents' Folder. Here's the code I have for that: ``` textfile=open('C:\Users\MYNAME\Documents','w') lines=['stuff goes here'] textfile.writelines(lines) textfile.close() ``` The problem is that if other people use it, how do I change t...
Use `os.path.expanduser(path)`, see <http://docs.python.org/library/os.path.html> e.g. `expanduser('~/filename')` This works on both Unix and Windows, according to the docs. Edit: forward slash due to Sven's comment.
How to start mapreduce job from cron on GAE Python
6,228,802
5
2011-06-03T15:01:31Z
6,231,762
10
2011-06-03T19:31:23Z
[ "python", "google-app-engine", "cron", "mapreduce" ]
I have mapreduce job defined in mapreduce.yaml: ``` mapreduce: - name: JobName mapper: input_reader: google.appengine.ext.mapreduce.input_readers.DatastoreInputReader handler: handler_name params: - name: entity_kind default: KindName ``` How to start it from cron? Is there some url that can ...
You can start a mapreduce task from any kind of AppEngine handler using [control.py](http://code.google.com/p/appengine-mapreduce/source/browse/trunk/python/src/mapreduce/control.py) ``` from mapreduce import control mapreduce_id = control.start_map( "My Mapper", "main.my_mapper", "mapreduce.input_readers...
How to make a python dictionary that returns key for keys missing from the dictionary instead of raising KeyError?
6,229,073
26
2011-06-03T15:23:37Z
6,229,111
19
2011-06-03T15:26:34Z
[ "python", "dictionary" ]
I want to create a python dictionary that returns me the key value for the keys are missing from the dictionary. Usage example: ``` dic = smart_dict() dic['a'] = 'one a' print(dic['a']) # >>> one a print(dic['b']) # >>> b ```
Why don't you just use ``` dic.get('b', 'b') ``` Sure, you can subclass `dict` as others point out, but I find it handy to remind myself every once in a while that `get` can have a default value! If you want to have a go at the `defaultdict`, try this: ``` dic = defaultdict() dic.__missing__ = lambda key: key dic['...
How to make a python dictionary that returns key for keys missing from the dictionary instead of raising KeyError?
6,229,073
26
2011-06-03T15:23:37Z
6,229,253
37
2011-06-03T15:36:40Z
[ "python", "dictionary" ]
I want to create a python dictionary that returns me the key value for the keys are missing from the dictionary. Usage example: ``` dic = smart_dict() dic['a'] = 'one a' print(dic['a']) # >>> one a print(dic['b']) # >>> b ```
`dict`s have a [`__missing__`](http://docs.python.org/library/stdtypes.html#dict) hook for this: ``` class smart_dict(dict): def __missing__(self, key): return key ```
How to make a python dictionary that returns key for keys missing from the dictionary instead of raising KeyError?
6,229,073
26
2011-06-03T15:23:37Z
7,811,939
8
2011-10-18T18:27:57Z
[ "python", "dictionary" ]
I want to create a python dictionary that returns me the key value for the keys are missing from the dictionary. Usage example: ``` dic = smart_dict() dic['a'] = 'one a' print(dic['a']) # >>> one a print(dic['b']) # >>> b ```
The first respondent mentioned `defaultdict`, but you can define `__missing__` for any subclass of `dict`: ``` >>> class Dict(dict): def __missing__(self, key): return key >>> d = Dict(a=1, b=2) >>> d['a'] 1 >>> d['z'] 'z' ``` Also, I like the second respondent's approach: ``` >>> d = dict(a=1,...
accessing two or more list in a single for-loop
6,229,299
2
2011-06-03T15:39:18Z
6,229,308
11
2011-06-03T15:40:16Z
[ "python", "python-3.x" ]
provided that I have two lists in same length, list\_a, list\_b. I can print they items in a single for loop as follows: ``` for i in range(0, len(list_a)): print "%s %s" % (list_a[i], list_b[i]) ``` is there any alternative and elegant way to do above mentioned task ? I have tried ``` for a, b in list_a, list...
You need [`zip()`](http://docs.python.org/library/functions.html#zip): ``` for a, b in zip(list_a, list_b): # whatever ``` When the lists are long and you are using Python 2.x, you might prefer [`itertools.izip()`](http://docs.python.org/library/itertools.html#itertools.izip) to save some memory.
Running commands from within python that need root access
6,229,358
5
2011-06-03T15:43:58Z
6,229,576
8
2011-06-03T15:58:07Z
[ "python", "subprocess", "sudo" ]
I have been playing around with subprocess lately. As I do more and more; I find myself needing root access. I was wondering if there is an easy way to enter the root password for a command that needs it with subprocess module. So when I am prompted for the password my script and provide it and run the command. I know ...
It would probably be best to leverage [sudo](http://www.linuxhomenetworking.com/wiki/index.php/Quick_HOWTO_%3a_Ch09_%3a_Linux_Users_and_Sudo) for the user running the Python program. You can specify specific commands and arguments that can be run from sudo without requiring a password. Here is an example: There are ma...
numpy: column-wise dot product
6,229,519
11
2011-06-03T15:54:03Z
6,229,665
15
2011-06-03T16:04:58Z
[ "python", "numpy", "dot-product" ]
Given a 2D `numpy` array, I need to compute the dot product of every column with itself, and store the result in a 1D array. The following works: ``` In [45]: A = np.array([[1,2,3,4],[5,6,7,8]]) In [46]: np.array([np.dot(A[:,i], A[:,i]) for i in xrange(A.shape[1])]) Out[46]: array([26, 40, 58, 80]) ``` Is there a si...
How about: ``` >>> A = np.array([[1,2,3,4],[5,6,7,8]]) >>> (A*A).sum(axis=0) array([26, 40, 58, 80]) ``` --- EDIT: Hmm, okay, you don't want intermediate large objects. Maybe: ``` >>> from numpy.core.umath_tests import inner1d >>> A = np.array([[1,2,3,4],[5,6,7,8]]) >>> inner1d(A.T, A.T) array([26, 40, 58, 80]) ```...
How to use str.format() with a dictionary in python?
6,229,671
11
2011-06-03T16:05:19Z
6,229,705
21
2011-06-03T16:07:08Z
[ "python", "dictionary" ]
What is wrong in this piece of code? ``` dic = { 'fruit': 'apple', 'place':'table' } test = "I have one {fruit} on the {place}.".format(dic) print(test) >>> KeyError: 'fruit' ```
Should be ``` test = "I have one {fruit} on the {place}.".format(**dic) ``` Note the [`**`](http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists). [`format()`](http://docs.python.org/library/string.html#format-examples) does not accept a single dictionary, but rather keyword arguments.
Google App Engine set up a user when using testbed
6,229,773
13
2011-06-03T16:13:26Z
10,852,849
18
2012-06-01T15:09:47Z
[ "python", "google-app-engine", "testbed" ]
I'm using the GAE [testbed](http://code.google.com/appengine/docs/python/tools/localunittesting.html) service and when I run `users.get_current_user()` I get `None` i.e. ``` >>> import sys >>> sys.path.append("/usr/local/google_appengine") # for Mac OS X >>> from google.appengine.api import users >>> from google.appen...
To simulate a sign in of an admin user, you can call anywhere in your test function: ``` self.testbed.setup_env( USER_EMAIL = 'test@example.com', USER_ID = '123', USER_IS_ADMIN = '1', overwrite = True) ``` Note that you need to use the `overwrite=True` parameter!
Python - reduce function and | operator
6,230,117
2
2011-06-03T16:45:53Z
6,230,229
7
2011-06-03T16:59:14Z
[ "python", "web2py", "reduce" ]
I am looking at some Web2py code. The variable `tokens` is some kind of a list of strings. To be more precise, it is defined as `tokens = form.vars.name.split()` where `form.vars.name` is a string. My question deals with the following instruction : ``` query = reduce(lambda a,b:a&b,[User.first_name.contains(k)|User....
1. In Web2Py `&` and `|` **are not bitwise and/or here**, but are used to build a special object that represents a database query! They correspond to `AND` and `OR` in SQL statements 2. [contains](http://web2py.com/book/default/chapter/06#like,-startswith,-contains,-upper,-lower) is part of [Web2Pys DAL](http://web2py....
How to install python developer package?
6,230,444
23
2011-06-03T17:18:57Z
6,233,512
48
2011-06-03T23:11:47Z
[ "python", "linux", "amazon-ec2", "mod-wsgi" ]
I am trying to get `mod_wsgi 3.3` to work. When I run `make` it is telling me that I am missing the Python developer package. How do I get and install the Python developer package? The error I get is as follows: ``` mod_wsgi.c:135:20: error: Python.h: No such file or directory mod_wsgi.c:138:2: error: #error Sorry, P...
`yum install python-devel` will work. If `yum` doesn't work then use `apt-get install python-dev`
100% CPU usage with a regexp depending on input length
6,230,489
8
2011-06-03T17:23:36Z
6,230,559
20
2011-06-03T17:31:43Z
[ "python", "regex", "cpu-usage" ]
I'm trying to come up with a regexp in Python that has to match any character but avoiding three or more consecutive commas or semicolons. In other words, only up to two consecutive commas or semicolons are allowed. So this is what I currently have: ``` ^(,|;){,2}([^,;]+(,|;){,2})*$ ``` And it seems to work as expec...
You're running into [catastrophic backtracking](http://www.regular-expressions.info/catastrophic.html). The reason for this is that you have made the separators optional, and therefore the `[^,;]+` part (which is itself in a repeating group) of your regex will try loads of permutations (of `baaaaaaaz`) before finally ...
100% CPU usage with a regexp depending on input length
6,230,489
8
2011-06-03T17:23:36Z
6,230,587
11
2011-06-03T17:34:16Z
[ "python", "regex", "cpu-usage" ]
I'm trying to come up with a regexp in Python that has to match any character but avoiding three or more consecutive commas or semicolons. In other words, only up to two consecutive commas or semicolons are allowed. So this is what I currently have: ``` ^(,|;){,2}([^,;]+(,|;){,2})*$ ``` And it seems to work as expec...
I think the following should do what you want: ``` ^(?!.*[,;]{3}) ``` This will fail if the string contains three or more `,` or `;` in a row. If you actually want it to match a character add a `.` at the end. This utilizes [negative lookahead](http://www.regular-expressions.info/lookaround.html), which will cause t...
"if var and var2 == getSomeValue()" in python - if the first is false, is the second statement evaluated?'
6,230,701
5
2011-06-03T17:45:31Z
6,230,720
10
2011-06-03T17:47:44Z
[ "python", "short-circuiting" ]
I have some code like this: ``` if var: if var2 == getSomeValue() ``` This could be in a single expression. ``` if var and var2 == getSomeValue(): ``` ...but `getSomeValue()` can only be called if `var` is True. So, when calling `if var and var2 == getSomeValue()`, are both evaluated by the interpreter, or the...
This is called short-circuiting, and Python does it, so you're good. UPDATE: Here's a quick example. ``` >>> def foo(): ... print "Yay!" ... >>> if True and foo() is None: ... print "indeed" ... Yay! indeed >>> if False and foo() is None: ... print "nope" ... ``` UPDATE 2: Putting the [relevant PEP (30...
Extracting page sizes from PDF in Python
6,230,752
3
2011-06-03T17:33:55Z
6,230,955
7
2011-06-03T18:08:29Z
[ "python", "pdf" ]
I want to read a PDF and get some list of it's pages and each page's size. I don't need to manipulate it in any way, just read it. Currently trying out pyPdf and it does everything I need except a way to get page sizes. Understanding that I will probably have to iterate through, as page sizes can vary in a pdf documen...
[pyPdf](http://pybrary.net/pyPdf/) gets the page size in the example on its home page: ``` >>> input1 = PdfFileReader(file('example.pdf')) >>> input1.getPage(0).mediaBox RectangleObject([0, 0, 612, 792]) ```
how to install pycairo for python 3 on Ubuntu 10.04
6,232,529
5
2011-06-03T20:49:55Z
6,722,892
10
2011-07-17T09:15:10Z
[ "python", "python-3.x", "ubuntu-10.04", "cairo", "pycairo" ]
i am trying to install pycairo 1.10.0 for use with my custom-build python 3.1. however, ``` sudo /flower/bin/easy_install-3.1 pycairo ``` fails with ``` XXX@XXXX:/adventures$ sudo /flower/bin/easy_install-3.1 pycairo install_dir /flower/lib/python3.1/site-packages/ Searching for pycairo Reading http://pypi.python.or...
By looking at the python.py file in that subdir I decided to try setting an environment var before executing the waf thru python3: export PYTHON="python3" And then the install mysteriously succeeded...
How to continuously run a Python script on an EC2 server?
6,232,564
11
2011-06-03T20:53:01Z
6,232,612
18
2011-06-03T20:56:54Z
[ "python", "amazon-ec2" ]
I've setup an Amazon EC2 server. I have a Python script that is supposed to download large amounts of data from the web onto the server. I can run the script from the terminal through `ssh`, however very often I loose the `ssh` connection. When I loose the connection, the script stops. Is there a method where I tell t...
You have a few options. * You can add your script to `cron` to be run regularly. * You can run your script manually, and detach+background it using `nohup`. * You can run a tool such as GNU Screen, and detach your terminal and log out, only to continue where you left off later. I use this a lot. + For example: 1...