title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
How do I save data from a ModelForm to database in django?
2,837,229
9
2010-05-14T20:03:03Z
2,838,181
10
2010-05-14T23:06:53Z
[ "python", "django" ]
I have a model: ``` class Cost(models.Model): project = models.ForeignKey(Project) cost = models.FloatField() date = models.DateField() ``` For the model I created a `ModelForm` class: ``` class CostForm(ModelForm): class Meta: model = Cost fields = ['date', 'cost'] ``` view.py: ```...
I found the solution. Rewrote code only in view.py as follows: ``` def cost(request, offset): if request.method == 'POST': project = Project.objects.get(title=offset) date = request.POST.get('date', '') cost = request.POST.get('cost', '') cost_obj = Cost(project=project, date=date, ...
Is there a better way of replacing duplicates in a list (Python)
2,837,409
2
2010-05-14T20:30:06Z
2,837,551
15
2010-05-14T20:53:20Z
[ "python", "list", "duplicates" ]
Given a list: * l1: `['a', 'b', 'c', 'a', 'a', 'b']` * output: `['a', 'b', 'c', 'a_1', 'a_2', 'b_1' ]` I created the following code to get the output. It's messyyy.. ``` for index in range(len(l1)): counter = 1 list_of_duplicates_for_item = [dup_index for dup_index, item in enumerate(l1) if item == l1[index]...
In Python, generating a new list is usually much easier than changing an existing list. We have generators to do this efficiently. A dict can keep count of occurrences. ``` l = ['a', 'b', 'c', 'a', 'a', 'b'] def rename_duplicates( old ): seen = {} for x in old: if x in seen: seen[x] += 1 ...
In Python, how to make sure database connection will always close before leaving a code block?
2,837,822
12
2010-05-14T21:44:46Z
2,837,877
13
2010-05-14T21:55:50Z
[ "python", "nested", "database-connection" ]
I want to prevent database connection being open as much as possible, because this code will run on an intensive used server and people here already told me database connections should always be closed as soon as possible. ``` def do_something_that_needs_database (): dbConnection = MySQLdb.connect(host=args['datab...
The traditional approach is the `try`/`finally` statement: ``` def do_something_that_needs_database (): dbConnection = MySQLdb.connect(host=args['database_host'], user=args['database_user'], passwd=args['database_pass'], db=args['database_tabl'], cursorclass=MySQLdb.cursors.DictCursor) try: # as much wo...
Dimension Reduction in Categorical Data with missing values
2,837,850
16
2010-05-14T21:50:21Z
2,840,198
16
2010-05-15T13:06:45Z
[ "python", "statistics" ]
I have a regression model in which the dependent variable is continuous but ninety percent of the independent variables are categorical(both ordered and unordered) and around thirty percent of the records have missing values(to make matters worse they are missing randomly without any pattern, that is, more that forty f...
Regarding imputation of categorical data, I would suggest to check the [mice](http://web.inter.nl.net/users/S.van.Buuren/mi/hmtl/mice.htm) package. Also take a look at this [presentation](http://web.inter.nl.net/users/S.van.Buuren/mi/docs/Multiple%20imputation%20of%20categorical%20data/sld001.htm) which explains how it...
pysqlite2: ProgrammingError - You must not use 8-bit bytestrings
2,838,100
13
2010-05-14T22:44:44Z
2,838,110
14
2010-05-14T22:47:09Z
[ "python", "sqlite", "pysqlite" ]
I'm currently persisting filenames in a sqlite database for my own purposes. Whenever I try to insert a file that has a special character (like é etc.), it throws the following error: ``` pysqlite2.dbapi2.ProgrammingError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytes...
You need to specify the encoding of `filename` for conversion to Unicode, for example: `filename.decode('utf-8')`. Just using `unicode(...)` picks the console encoding, which is often unreliable (and often `ascii`).
get open TCP port in Python
2,838,244
14
2010-05-14T23:27:33Z
2,838,309
26
2010-05-14T23:48:12Z
[ "python", "tcp", "tcp-port" ]
I want to get any random open TCP port on localhost in Python. What is the easiest way?
My current solution: ``` def get_open_port(): import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("",0)) s.listen(1) port = s.getsockname()[1] s.close() return port ``` Not very nice and also not 100% correct but it works for now.
Efficient update of SQLite table with many records
2,838,790
4
2010-05-15T03:18:11Z
2,838,795
12
2010-05-15T03:20:15Z
[ "c++", "python", "sql", "database", "sqlite" ]
I am trying to use sqlite (sqlite3) for a project to store hundreds of thousands of records (would like sqlite so users of the program don't have to run a [my]sql server). I have to update hundreds of thousands of records sometimes to enter left right values (they are hierarchical), but have found the standard ``` up...
Create an index on `table.id` ``` create index table_id_index on table(id) ```
How can this verbose, unpythonic routine be improved?
2,838,889
4
2010-05-15T04:08:24Z
2,838,929
11
2010-05-15T04:30:56Z
[ "refactoring", "code-review", "python" ]
Is there a more pythonic way of doing this? I am trying to find the eight neighbours of an integer coordinate lying within an extent. I am interested in reducing its verbosity without sacrificing execution speed. ``` def fringe8((px, py), (x1, y1, x2, y2)): f = [(px - 1, py - 1), (px - 1, py), (p...
Here's my take on the code cleanup: Edit: I've taken David's code into my answer to make it even more compact (and faster execution time). ``` >>> from itertools import product >>> >>> def fringe8((px, py), (x1, y1, x2, y2)): ... f = [(px+dx, py+dy) for (dx, dy) in product((-1,0,1),(-1,0,1)) if (dx, dy) != (0, 0)...
How can this verbose, unpythonic routine be improved?
2,838,889
4
2010-05-15T04:08:24Z
2,839,022
8
2010-05-15T05:24:19Z
[ "refactoring", "code-review", "python" ]
Is there a more pythonic way of doing this? I am trying to find the eight neighbours of an integer coordinate lying within an extent. I am interested in reducing its verbosity without sacrificing execution speed. ``` def fringe8((px, py), (x1, y1, x2, y2)): f = [(px - 1, py - 1), (px - 1, py), (p...
This is a reworking of Xavier Ho's answer. I think that it's made a little more clear by using intermediate steps. ``` from itertools import product def fringe8((px, py), (x1, y1, x2, y2)): nonzero = (pair for pair in product((-1,0,1),(-1,0,1)) if pair != (0, 0)) f = ((px+dx, py+dy) for (dx,dy) in nonzero) ...
I don't like Python functions that take two or more iterables. Is it a good idea?
2,838,965
3
2010-05-15T04:55:55Z
2,839,007
7
2010-05-15T05:17:50Z
[ "python", "function", "iterable", "code-design" ]
This question came from looking at [this question](http://stackoverflow.com/questions/2838889/how-can-this-verbose-unpythonic-routine-be-improved/): ``` def fringe8((px, py), (x1, y1, x2, y2)): ``` Personally, it's been one of my pet peeves to see a function that takes *two arguments with fixed-number iterables* (lik...
The `def` syntax with unpacking, like ``` def fringe8((px, py), (x1, y1, x2, y2)): ``` is gone in Python 3 -- which means Guido considered it a design error, or at least an unwarranted complication. Named tuples might be even better than special-purpose classes for the clarifying purpose you suggest. However, having...
pysvn client.log() returning empty dictionary
2,839,386
4
2010-05-15T08:08:33Z
3,664,514
7
2010-09-08T03:48:24Z
[ "python", "pysvn" ]
i have the following script that i am using to get the log messages from svn ``` import pysvn class svncheck(): def __init__(self, svn_root="http://10.11.25.3/svn/Moodle/modules", svn_user=None, svn_password=None): self.user = svn_user self.password = svn_password self.root = svn_root ...
pysvn.Client.log method returns a list of log entries; each log entry is a dictionary. (see [pysvn Programmer's reference](http://pysvn.tigris.org/docs/pysvn_prog_ref.html)) you can print log messages in your code like this: ``` for info in log: print info.revision.number, print info.author, print time.ct...
Converting a bash script to python (small script)
2,839,810
7
2010-05-15T10:47:53Z
2,840,338
28
2010-05-15T13:49:14Z
[ "python", "bash" ]
I’ve a bash script I’ve been using for a Linux environment but now I have to use it on a Windows platform and want to convert the bash script to a python script which I can run. The bash script is rather simple (I think) and I’ve tried to convert it by google by way around but can’t convert it successfully. T...
## Answer Let's break it down into pieces. Especially the pieces you got wrong. :) --- ### Assignment > ``` > outfile=ReadsAgain.txt > ``` It should come to little surprise that you need to put quotes around strings. On the other hand, you have the luxury of putting spaces around the `=` for readability. ``` outf...
Problems using User model in django unit tests
2,840,467
16
2010-05-15T14:32:54Z
2,840,474
23
2010-05-15T14:35:57Z
[ "python", "django", "unit-testing", "django-testing" ]
I have the following django test case that is giving me errors: ``` class MyTesting(unittest.TestCase): def setUp(self): self.u1 = User.objects.create(username='user1') self.up1 = UserProfile.objects.create(user=self.u1) def testA(self): ... def testB(self): ... ``` When ...
[`setUp`](http://docs.python.org/dev/library/unittest.html#unittest.TestCase.setUp) and [`tearDown`](http://docs.python.org/dev/library/unittest.html#unittest.TestCase.tearDown) methods on Unittests are called before and after each test case. Define [`tearDown`](http://docs.python.org/dev/library/unittest.html#unittest...
setting url in yaml file for google app engin (page not found) problem
2,840,483
4
2010-05-15T14:38:33Z
2,840,508
7
2010-05-15T14:48:03Z
[ "python", "google-app-engine", "http-status-code-404", "yaml" ]
I am new to python and I am super excited to learn. I am building my first app on app engin and I am not totally understanding why my yaml file is not resolving to the url that I set up. here is the code ``` handlers: - url: .* script: main.py - url: /letmein/.* script: letmein.py ``` so if I go to <http://loca...
Your handlers are in the wrong order as they must always be less general first. Change to: ``` handlers: - url: /letmein/.* script: letmein.py - url: .* script: main.py ``` and it works.
Nested WHILE loops in Python
2,841,489
5
2010-05-15T19:38:12Z
2,841,498
7
2010-05-15T19:40:13Z
[ "python", "for-loop", "while-loop", "nested-loops" ]
I am a beginner with Python and trying few programs. I have something like the following WHILE loop construct in Python (not exact). ``` IDLE 2.6.4 >>> a=0 >>> b=0 >>> while a < 4: a=a+1 while b < 4: b=b+1 print a, b 1 1 1 2 1 3 1 4 ``` I am expecting the outer loop to loop throu...
You're not resetting `b` to 0 right inside your outer loop, so `b` stays at the value it had after the first leg of the outer loop -- 4 -- and the inner loop never executes again. The `for` loops work fine because they *do* reset their loop control variables correctly; with the less-structured `while` loops, such rese...
something like a python's triple-quote in F# (or C#)?
2,841,804
7
2010-05-15T21:21:30Z
2,841,853
7
2010-05-15T21:36:18Z
[ "c#", "python", "string", "f#" ]
I want to assign a xml code into a string variable. I can do this without escaping single or double-quotes by using triple-quote in python. Is there a similar way to do this in F# or C#?
As far as I know, there is no syntax corresponding to this in C# / F#. If you use `@"str"` then you have to replace quote with two quotes and if you just use `"str"` then you need to add backslash. In any case, there is some encoding of `"`: ``` var str = @"allows multiline, but still need to encode "" as two chars...
something like a python's triple-quote in F# (or C#)?
2,841,804
7
2010-05-15T21:21:30Z
13,308,083
11
2012-11-09T12:28:01Z
[ "c#", "python", "string", "f#" ]
I want to assign a xml code into a string variable. I can do this without escaping single or double-quotes by using triple-quote in python. Is there a similar way to do this in F# or C#?
F# 3.0 supports triple quoted strings. See [Visual Studio F# Team Blog Post on 3.0 features.](http://blogs.msdn.com/b/fsharpteam/archive/2012/07/19/more-about-fsharp-3.0-language-features.aspx) The [F# 3.0 Spec](http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/spec.html) **Strings and Characters...
Mako templates inline if statement
2,841,867
13
2010-05-15T21:41:16Z
2,841,908
27
2010-05-15T22:00:36Z
[ "python", "templates", "mako" ]
I have a template variable, c.is\_friend, that I would like to use to determine whether or not a class is applied. For example: ``` if c.is_friend is True <a href="#" class="friend">link</a> if c.is_friend is False <a href="#">link</a> ``` Is there some way to do this inline, like: ``` <a href="#" ${if c.is_friend ...
Python's normal inline if works: ``` <a href="#" ${'class="friend"' if c.is_friend else ''}>link</a> ```
making errorbars not clipped in matplotlib with Python
2,842,123
4
2010-05-15T23:49:04Z
2,854,601
8
2010-05-18T04:39:36Z
[ "python", "matplotlib", "scipy", "plot" ]
I am using matplotlib in Python to plot a line with errorbars as follows: ``` plt.errorbar(xvalues, up_densities, yerr=ctl_sds, fmt='-^', lw=1.2, markersize=markersize, markeredgecolor=up_color, color=up_color, label="My label", clip_on=False) plt.xticks(xvalues) ``` I set the ticks on the x-axis using "xtic...
In matplotlib, most of the detailed control needs to be done through the Artists. I think this should do what you want: ``` import matplotlib.pyplot as plt from random import uniform as r x = range(10) e = plt.errorbar(x, [r(2,10) for i in x], [r(.1,1) for i in x], capsize=8, color='r') for b in e[1]: b.set_clip...
RDF/XML format to JSON
2,842,214
2
2010-05-16T00:39:05Z
2,842,245
8
2010-05-16T00:57:23Z
[ "python", "json", "rdf", "xml-parsing" ]
I am trying to convert the RDF/XML format to JSON format. Is there any python (library) example that i can look into for this to do ?
You can use [rdflib](http://www.rdflib.net/) to parse many RDF variants (including RDF/XML), or maybe the simpler [rdfparser](http://infomesh.net/2003/rdfparser/) if it suits your needs. You can then use the standard library Python `json` module (or equivalently third-party `simplejson` if you're using some Python vers...
Python: undefined reference to `_imp __Py_InitModule4'
2,842,469
9
2010-05-16T03:15:12Z
9,673,051
16
2012-03-12T18:52:58Z
[ "python" ]
I'm trying to do a debug build of the Rabbyt library using mingw's gcc to run with my MSVC built python26\_d.. I got a lot of undefined references which caused me to create libpython26\_d.a, however one of the undefined references remains. Googling gives me: <http://www.techlists.org/archives/programming/pythonlist/20...
If anyone comes across this same error message, but in a different situation: try to add `-D MS_WIN64` to your command line, it worked for me!
Python: undefined reference to `_imp __Py_InitModule4'
2,842,469
9
2010-05-16T03:15:12Z
19,867,426
9
2013-11-08T19:50:35Z
[ "python" ]
I'm trying to do a debug build of the Rabbyt library using mingw's gcc to run with my MSVC built python26\_d.. I got a lot of undefined references which caused me to create libpython26\_d.a, however one of the undefined references remains. Googling gives me: <http://www.techlists.org/archives/programming/pythonlist/20...
In the file `C:\Python27\Lib\distutils\cygwinccompiler.py`, which contains the MinGW compiler settings, find the `Mingw32CCompiler` class: ``` self.set_executables(compiler='gcc -O -Wall', compiler_so='gcc -mdll -O -Wall', compiler_cxx='g++ -O -Wall', linker_exe='gcc ', linker_so='%s %s %s' % (...
How Can I Find a List of All Exceptions That a Given Library Function Throws in Python?
2,843,112
11
2010-05-16T08:56:39Z
2,843,649
11
2010-05-16T12:07:14Z
[ "python", "documentation", "exception" ]
Sorry for the long title, but it seems most descriptive for my question. Basically, I'm having a difficult time finding exception information in the official python documentation. For example, in one program I'm currently writing, I'm using the shutil libary's move function: ``` from shutil import move move('somefile...
To amplify Messa, catch what you expect are failure modes that you know how to recover from. Ian Bicking wrote [an article](http://blog.ianbicking.org/2007/09/12/re-raising-exceptions/) that addresses some of the overarching principles as does Eli Bendersky's [note](http://eli.thegreenplace.net/2008/08/21/robust-except...
Python: how to inherite and override
2,843,165
10
2010-05-16T09:17:02Z
2,844,520
7
2010-05-16T16:32:44Z
[ "python", "inheritance", "override" ]
Consider this situation: I get an object of type `A` which has the function `f`. I.e: ``` class A: def f(self): print 'in f' def h(self): print 'in h' ``` and I get an instance of this class but I want to override the `f` function but save the rest of the functionality of `A`. So what I was thinkin...
How you construct an object of subclass `B` "based on" one of class `A` depends exclusively on how the latter keeps *state*, if any, and how do you best get to that state and copy it over. In your example, instances of `A` are stateless, therefore there is absolutely no work you need to do in `B`'s `'__init__'`. In a m...
keep open windows console after a python syntax error
2,843,545
2
2010-05-16T11:32:50Z
2,843,556
9
2010-05-16T11:37:21Z
[ "python", "windows", "console" ]
File associations on my machine (winxp home) are such that a python script is directly opened with the python interpreter. If I double click on a python script a console window runs and every thing is fine - as long as there is no syntax error in the script. In that case the console window opens up for a moment but it...
Make a batch file: ``` C:\Python26\python.exe %1 IF %ERRORLEVEL% NEQ 0 PAUSE ``` Use that as your file association instead of python.exe directly. This will only cause the PAUSE statement to execute if python.exe returns an error
Python Error-Checking Standard Practice
2,843,702
10
2010-05-16T12:25:01Z
2,843,781
13
2010-05-16T12:47:53Z
[ "python", "error-handling", "assert" ]
I have a question regarding error checking in Python. Let's say I have a function that takes a file path as an input: ``` def myFunction(filepath): infile = open(filepath) #etc etc... ``` One possible precondition would be that the file should exist. There are a few possible ways to check for this preconditi...
If all you want to do is raise an exception, use option `iii`: ``` def myFunction(filepath): with open(filepath) as infile: pass ``` To handle exceptions in a special way, use a `try...except` block: ``` def myFunction(filepath): try: with open(filepath) as infile: pass except...
How to filter a dictionary according to an arbitrary condition function?
2,844,516
74
2010-05-16T16:30:34Z
2,844,533
7
2010-05-16T16:35:19Z
[ "python", "dictionary", "filter" ]
I have a dictionary of points, say: ``` >>> points={'a':(3,4), 'b':(1,2), 'c':(5,5), 'd':(3,3)} ``` I want to create a new dictionary with all the points whose x and y value is smaller than 5, i.e. points 'a', 'b' and 'd'. According to the [the book](http://docs.python.org/library/stdtypes.html#mapping-types-dict), ...
``` dict((k, v) for (k, v) in points.iteritems() if v[0] < 5 and v[1] < 5) ```
How to filter a dictionary according to an arbitrary condition function?
2,844,516
74
2010-05-16T16:30:34Z
2,844,536
10
2010-05-16T16:35:56Z
[ "python", "dictionary", "filter" ]
I have a dictionary of points, say: ``` >>> points={'a':(3,4), 'b':(1,2), 'c':(5,5), 'd':(3,3)} ``` I want to create a new dictionary with all the points whose x and y value is smaller than 5, i.e. points 'a', 'b' and 'd'. According to the [the book](http://docs.python.org/library/stdtypes.html#mapping-types-dict), ...
``` points_small = dict(filter(lambda (a,(b,c)): b<5 and c < 5, points.items())) ```
How to filter a dictionary according to an arbitrary condition function?
2,844,516
74
2010-05-16T16:30:34Z
2,844,544
96
2010-05-16T16:37:47Z
[ "python", "dictionary", "filter" ]
I have a dictionary of points, say: ``` >>> points={'a':(3,4), 'b':(1,2), 'c':(5,5), 'd':(3,3)} ``` I want to create a new dictionary with all the points whose x and y value is smaller than 5, i.e. points 'a', 'b' and 'd'. According to the [the book](http://docs.python.org/library/stdtypes.html#mapping-types-dict), ...
``` dict((k, v) for k, v in points.items() if all(x < 5 for x in v)) ``` You could choose to call `.iteritems()` instead of `.items()` if you're in Python 2 and `points` may have a **lot** of entries. `all(x < 5 for x in v)` may be overkill if you know for sure each point will always be 2D only (in that case you migh...
How to filter a dictionary according to an arbitrary condition function?
2,844,516
74
2010-05-16T16:30:34Z
16,589,453
148
2013-05-16T13:57:42Z
[ "python", "dictionary", "filter" ]
I have a dictionary of points, say: ``` >>> points={'a':(3,4), 'b':(1,2), 'c':(5,5), 'd':(3,3)} ``` I want to create a new dictionary with all the points whose x and y value is smaller than 5, i.e. points 'a', 'b' and 'd'. According to the [the book](http://docs.python.org/library/stdtypes.html#mapping-types-dict), ...
Nowadays, in Python 2.7 and up, you can use a dict comprehension: ``` {k: v for k, v in points.iteritems() if v[0] < 5 and v[1] < 5} ``` And in Python 3: ``` {k: v for k, v in points.items() if v[0] < 5 and v[1] < 5} ```
Where does GoogleAppEngineLauncher keep the local log files?
2,844,635
9
2010-05-16T17:06:16Z
2,845,038
8
2010-05-16T18:57:22Z
[ "python", "google-app-engine", "logging" ]
GoogleAppEngineLauncher can display the local log file of my app while it is running on my Mac during development. However, I can't change the font size there so I would like to use the `tail` command to watch the log file myself. It's a shame but I can't find the log files. They are not under `/var/log/`, `~/Library/...
As you surmise, and can confirm by studying the source file `/usr/local/google_appengine/google/appengine/tools/dev_appserver.py`, the logs are not being written to disk (a `cStringIO.StringIO` instance is used to keep them in memory, as the rest of the code *is* oriented to writing them "to a file-like object"). What...
How to fix this python error? RuntimeError: dictionary changed size during iteration
2,844,837
4
2010-05-16T18:02:17Z
2,844,937
12
2010-05-16T18:28:24Z
[ "python" ]
it gives me this error: ``` Exception in thread Thread-163: Traceback (most recent call last): File "C:\Python26\lib\threading.py", line 532, in __bootstrap_inner self.run() File "C:\Python26\lib\threading.py", line 736, in run self.function(*self.args, **self.kwargs) File "C:\Users\Public\SoundLog\Code\...
The normal advice, as per the other answers, would be to avoid using `iteritems` (use `items` instead). That of course is **not** an option in your case, since the `iteritems` call is being done on your behalf deep in the bowels of a system call. Therefore, what I would suggest, assuming `Auxiliar.DataCollection.getIn...
How do I fix this Django error "Exception Type: OperationalError Exception Value: no such table?"
2,845,080
3
2010-05-16T19:07:18Z
2,845,114
9
2010-05-16T19:17:34Z
[ "python", "django", "sqlite3", "pinax" ]
I've finally installed all the requirements (so i think!) of a Django project, and I'm trying to get a local install running on my Mac (OSX 10.4). I'm getting the following error: > Blockquote > OperationalError at / > no such table: django\_content\_type > Request Method: GET > Request URL: <http://127.0.0.1:8...
* Did you run `./manage.py syncdb` to create all your tables? * Do you have `django.contrib.contenttypes` in your INSTALLED\_APPS in `settings.py`? As an unlikely third option: * Does your project/app use the Django app "South"? If so, you would also need to run `./manage.py migrate` to make sure all tables get creat...
Screen scraping: getting around "HTTP Error 403: request disallowed by robots.txt"
2,846,105
34
2010-05-17T00:35:43Z
2,846,116
15
2010-05-17T00:40:27Z
[ "python", "screen-scraping", "beautifulsoup", "mechanize", "http-status-code-403" ]
Is there a way to get around the following? ``` httperror_seek_wrapper: HTTP Error 403: request disallowed by robots.txt ``` Is the only way around this to contact the site-owner (barnesandnoble.com).. i'm building a site that would bring them more sales, not sure why they would deny access at a certain depth. I'm u...
You can try lying about your user agent (e.g., by trying to make believe you're a human being and not a robot) if you want to get in possible legal trouble with Barnes & Noble. Why not instead get in touch with their business development department and convince them to authorize you specifically? They're no doubt just ...
Screen scraping: getting around "HTTP Error 403: request disallowed by robots.txt"
2,846,105
34
2010-05-17T00:35:43Z
3,849,843
155
2010-10-03T13:02:38Z
[ "python", "screen-scraping", "beautifulsoup", "mechanize", "http-status-code-403" ]
Is there a way to get around the following? ``` httperror_seek_wrapper: HTTP Error 403: request disallowed by robots.txt ``` Is the only way around this to contact the site-owner (barnesandnoble.com).. i'm building a site that would bring them more sales, not sure why they would deny access at a certain depth. I'm u...
oh you need to ignore the robots.txt ``` br = mechanize.Browser() br.set_handle_robots(False) ```
Python: Repeat elements in a list comprehension?
2,846,536
3
2010-05-17T03:43:20Z
2,846,599
7
2010-05-17T04:06:49Z
[ "python", "list-comprehension" ]
I have the following list comprehension which returns a list of coordinate objects for each location. ``` coordinate_list = [Coordinates(location.latitude, location.longitude) for location in locations] ``` This works. Now suppose the location object has a number\_of\_times member. I want a list c...
``` coordinate_list = [x for location in locations for x in [Coordinates(location.latitude, location.longitude) ] * location.number_of_times] ``` **Edit**: the OP suggests a loop may be clearer, which, given the length of the ident...
How to use threading in Python?
2,846,653
532
2010-05-17T04:24:00Z
2,846,695
171
2010-05-17T04:35:11Z
[ "python", "multithreading" ]
I am trying to understand threading in Python. I've looked at the documentation and examples, but quite frankly, many examples are overly sophisticated and I'm having trouble understanding them. How do you clearly show tasks being divided for multi-threading?
**NOTE**: For actual parallelization in Python, you should use the [multiprocessing](https://docs.python.org/2/library/multiprocessing.html) module to fork multiple processes that execute in parallel (due to the global interpreter lock, Python threads provide interleaving but are in fact executed serially, not in paral...
How to use threading in Python?
2,846,653
532
2010-05-17T04:24:00Z
2,846,697
519
2010-05-17T04:36:05Z
[ "python", "multithreading" ]
I am trying to understand threading in Python. I've looked at the documentation and examples, but quite frankly, many examples are overly sophisticated and I'm having trouble understanding them. How do you clearly show tasks being divided for multi-threading?
Here's a simple example: you need to try a few alternative URLs and return the contents of the first one to respond. ``` import Queue import threading import urllib2 # called by each thread def get_url(q, url): q.put(urllib2.urlopen(url).read()) theurls = ["http://google.com", "http://yahoo.com"] q = Queue.Queu...
How to use threading in Python?
2,846,653
532
2010-05-17T04:24:00Z
9,625,995
61
2012-03-08T22:22:17Z
[ "python", "multithreading" ]
I am trying to understand threading in Python. I've looked at the documentation and examples, but quite frankly, many examples are overly sophisticated and I'm having trouble understanding them. How do you clearly show tasks being divided for multi-threading?
Like others mentioned, CPython can use threads only for I\O waits due to GIL. If you want to benefit from multiple cores for CPU-bound tasks, use [multiprocessing](http://docs.python.org/library/multiprocessing.html): ``` from multiprocessing import Process def f(name): print 'hello', name if __name__ == '__main...
How to use threading in Python?
2,846,653
532
2010-05-17T04:24:00Z
15,995,749
12
2013-04-14T04:18:42Z
[ "python", "multithreading" ]
I am trying to understand threading in Python. I've looked at the documentation and examples, but quite frankly, many examples are overly sophisticated and I'm having trouble understanding them. How do you clearly show tasks being divided for multi-threading?
For me, the perfect example for Threading is monitoring Asynchronous events. Look at this code. ``` # thread_test.py import threading import time class Monitor(threading.Thread): def __init__(self, mon): threading.Thread.__init__(self) self.mon = mon def run(self): while True: ...
How to use threading in Python?
2,846,653
532
2010-05-17T04:24:00Z
18,963,931
59
2013-09-23T16:07:36Z
[ "python", "multithreading" ]
I am trying to understand threading in Python. I've looked at the documentation and examples, but quite frankly, many examples are overly sophisticated and I'm having trouble understanding them. How do you clearly show tasks being divided for multi-threading?
Just a note, Queue is not required for threading. This is the simplest example I could imagine that shows 10 processes running concurrently. ``` import threading from random import randint from time import sleep def print_number(number): # Sleeps a random 1 to 10 seconds rand_int_var = randint(1, 10) sl...
How to use threading in Python?
2,846,653
532
2010-05-17T04:24:00Z
19,120,647
27
2013-10-01T15:50:44Z
[ "python", "multithreading" ]
I am trying to understand threading in Python. I've looked at the documentation and examples, but quite frankly, many examples are overly sophisticated and I'm having trouble understanding them. How do you clearly show tasks being divided for multi-threading?
The answer from Alex Martelli helped me, however here is modified version that I thought was more useful (at least to me). ``` import Queue import threading import urllib2 worker_data = ['http://google.com', 'http://yahoo.com', 'http://bing.com'] #load up a queue with your data, this will handle locking q = Queue.Qu...
How to use threading in Python?
2,846,653
532
2010-05-17T04:24:00Z
24,092,195
10
2014-06-06T23:51:06Z
[ "python", "multithreading" ]
I am trying to understand threading in Python. I've looked at the documentation and examples, but quite frankly, many examples are overly sophisticated and I'm having trouble understanding them. How do you clearly show tasks being divided for multi-threading?
I found this very useful: create as many threads as cores and let them execute a (large) number of tasks (in this case, calling a shell program): ``` import Queue import threading import multiprocessing import subprocess q = Queue.Queue() for i in range(30): #put 30 tasks in the queue q.put(i) def worker(): ...
How to use threading in Python?
2,846,653
532
2010-05-17T04:24:00Z
28,463,266
328
2015-02-11T19:53:42Z
[ "python", "multithreading" ]
I am trying to understand threading in Python. I've looked at the documentation and examples, but quite frankly, many examples are overly sophisticated and I'm having trouble understanding them. How do you clearly show tasks being divided for multi-threading?
Since this question was asked in 2010, there has been real simplification in how to do simple multithreading with python with **[map](https://docs.python.org/2/library/functions.html#map)** and **[pool](https://docs.python.org/2/library/multiprocessing.html)**. The code below comes from an article/blog post that you s...
Get screenshot on Windows with Python?
2,846,947
20
2010-05-17T06:04:16Z
2,846,967
14
2010-05-17T06:10:23Z
[ "python", "windows", "screenshot" ]
I am creating a Beta Testers reporting module so they can send in thier comments on my software, but I would like to have the option to include a screenshot with the report. How do I take a screenshot of the screen with Python on Windows? I have found several examples on Linux, but haven't had much luck on Windows.
Here is an example on windows that google found with "python screenshot windows" <http://www.blendedtechnologies.com/quick-screenshots-script-python-pil/38> It uses this [ImageGrab](http://effbot.org/imagingbook/imagegrab.htm) module
Get screenshot on Windows with Python?
2,846,947
20
2010-05-17T06:04:16Z
10,089,645
17
2012-04-10T13:23:23Z
[ "python", "windows", "screenshot" ]
I am creating a Beta Testers reporting module so they can send in thier comments on my software, but I would like to have the option to include a screenshot with the report. How do I take a screenshot of the screen with Python on Windows? I have found several examples on Linux, but haven't had much luck on Windows.
Worth noting that ImageGrab only works on MSWindows. For cross platform compatibility, a person may be best off with using the wxPython library. <http://wiki.wxpython.org/WorkingWithImages#A_Flexible_Screen_Capture_App> ``` import wx wx.App() # Need to create an App instance before doing anything screen = wx.ScreenD...
Python string formatting when string contains "%s" without escaping
2,847,272
16
2010-05-17T07:27:52Z
2,847,311
20
2010-05-17T07:36:39Z
[ "python", "string-formatting" ]
When formatting a string, my string may contain a modulo `"%"` that I do not wish to have converted. I can escape the string and change each `"%"` to `"%%"` as a workaround. e.g., ``` 'Day old bread, 50%% sale %s' % 'today!' ``` output: ``` 'Day old bread, 50% sale today' ``` But are there any alternatives to esca...
You could (and should) use the [new string `.format()` method](http://docs.python.org/tutorial/inputoutput.html#fancier-output-formatting) (if you have Python 2.6 or higher) instead: ``` "Day old bread, 50% sale {0}".format("today") ``` [The manual can be found here](http://docs.python.org/library/string.html#formats...
Python String and Integer concatenation
2,847,386
172
2010-05-17T07:52:05Z
2,847,394
200
2010-05-17T07:53:13Z
[ "python", "string", "integer", "concatenation" ]
I want to create string using integer appended to it, in a for loop. Like this: ``` for i in range [1,10]: string="string"+i ``` But it returns an error: ``` TypeError: unsupported operand type(s) for +: 'int' and 'str' ``` What's the best way to concatenate the String and Integer?
``` for i in range (1,10): string="string"+str(i) ``` To get `string0, string1 ..... string10`, you could do like ``` >>> ["string"+str(i) for i in range(11)] ['string0', 'string1', 'string2', 'string3', 'string4', 'string5', 'string6', 'string7', 'string8', 'string9', 'string10'] ```
Python String and Integer concatenation
2,847,386
172
2010-05-17T07:52:05Z
2,847,396
25
2010-05-17T07:53:20Z
[ "python", "string", "integer", "concatenation" ]
I want to create string using integer appended to it, in a for loop. Like this: ``` for i in range [1,10]: string="string"+i ``` But it returns an error: ``` TypeError: unsupported operand type(s) for +: 'int' and 'str' ``` What's the best way to concatenate the String and Integer?
``` for i in range[1,10]: string = "string" + str(i) ``` The `str(i)` function converts the integer into a string.
Python String and Integer concatenation
2,847,386
172
2010-05-17T07:52:05Z
2,847,397
28
2010-05-17T07:53:23Z
[ "python", "string", "integer", "concatenation" ]
I want to create string using integer appended to it, in a for loop. Like this: ``` for i in range [1,10]: string="string"+i ``` But it returns an error: ``` TypeError: unsupported operand type(s) for +: 'int' and 'str' ``` What's the best way to concatenate the String and Integer?
``` string = 'string%d' % (i,) ```
Python String and Integer concatenation
2,847,386
172
2010-05-17T07:52:05Z
2,847,512
15
2010-05-17T08:17:14Z
[ "python", "string", "integer", "concatenation" ]
I want to create string using integer appended to it, in a for loop. Like this: ``` for i in range [1,10]: string="string"+i ``` But it returns an error: ``` TypeError: unsupported operand type(s) for +: 'int' and 'str' ``` What's the best way to concatenate the String and Integer?
``` for i in range(11): string = "string{0}".format(i) ``` What you did (`range[1,10]`) is * a TypeError since brackets denote an index (`a[3]`) or a slice (`a[3:5]`) of a list, * a SyntaxError since `[1,10]` is invalid, and * a double off-by-one error since `range(1,10)` is `[1, 2, 3, 4, 5, 6, 7, 8, 9]`, and you...
Python String and Integer concatenation
2,847,386
172
2010-05-17T07:52:05Z
18,364,263
71
2013-08-21T17:45:22Z
[ "python", "string", "integer", "concatenation" ]
I want to create string using integer appended to it, in a for loop. Like this: ``` for i in range [1,10]: string="string"+i ``` But it returns an error: ``` TypeError: unsupported operand type(s) for +: 'int' and 'str' ``` What's the best way to concatenate the String and Integer?
## NOTE: The method used in this answer (backticks) is deprecated in later versions of Python 2, and removed in Python 3. Use the [`str()`](https://docs.python.org/3/library/stdtypes.html#str) function instead. --- You can use : ``` string = 'string' for i in range(11): string +=`i` print string ``` It will pr...
How do you extend python with C++?
2,847,617
14
2010-05-17T08:36:37Z
2,847,724
12
2010-05-17T08:57:31Z
[ "c++", "python" ]
I've successfully extended python with C, thanks to [this handy skeleton module](http://www.nevada.edu/~cwebster/Python/MPWHOWTO/xxmodule.c). But I can't find one for C++, and I have circular dependency trouble when trying to fix the errors that C++ gives when I compile this skeleton module. How do you extend Python w...
First of all, even though you don't want to introduce an additional dependency, I suggest you to have a look at [PyCXX](http://cxx.sourceforge.net/). Quoting its webpage: > CXX/Objects is a set of C++ facilities to make it easier to write Python extensions. The chief way in which PyCXX makes it easier to write Python ...
"With" statement in Python with multiple files to handle
2,847,939
7
2010-05-17T09:35:39Z
2,847,983
15
2010-05-17T09:43:03Z
[ "python" ]
How do i use the [with](http://docs.python.org/reference/compound_stmts.html#the-with-statement) statement in this case? ``` f_spam = open(spam,'r') f_bar = open(eggs,'r') ... do something with these files ... f_spam.close() f_bar.close() ``` Files number could be greater than two.
You can also do: ``` from contextlib import nested with nested(open(spam), open(eggs)) as (f_spam, f_eggs): # do something ``` In Python 2.7 and 3.1+ you don't need the `nested` function because `with` supports the following syntax: ``` with open(spam) as f_spam, open(eggs) as f_eggs: # do something ```
Why the need to commit explicitly when doing an UPDATE?
2,847,999
3
2010-05-17T09:45:53Z
2,848,047
7
2010-05-17T09:54:03Z
[ "python", "cx-oracle" ]
Here's my code: ``` import cx_Oracle conn = cx_Oracle.connect(usr, pwd, url) cursor = conn.cursor() cursor.execute("UPDATE SO SET STATUS='PE' WHERE ID='100'") conn.commit() ``` If I remove the `conn.commit()`, the table isn't updated. But for select statements, I don't need that `conn.commit()`. I'm curious why?
The [DB-API](http://www.python.org/dev/peps/pep-0249/) spec requires that connecting to the database begins a new transaction, by default. You must `commit` to confirm any changes you make, or `rollback` to discard them. > Note that if the database supports an auto-commit feature, this must be initially off. Pure `SE...
In Python 2.x, using backticks to get decimal string from int object is Horrible?
2,848,090
2
2010-05-17T09:59:48Z
2,848,113
7
2010-05-17T10:03:12Z
[ "python", "python-2.x", "backticks" ]
In Python 2.x, using backticks to get decimal string from int object is **Horrible**? Because backticks are `repr()`, not `str()`? I have noticed that when I answering [this](http://stackoverflow.com/questions/2847386/pythonstring-and-integer-concatenation/2847394#2847394) question. In Python source, they have same fu...
Well, I wouldn't say it's "horrible", but I feel it isn't right for at least four reasons: 1. `str(my_number)` states your intent more clearly than surrounding `my_number` by backticks. (See "Readability counts" in [the Zen of Python](http://www.python.org/dev/peps/pep-0020/)). 2. The implementation of Python in C is ...
Saving and loading a Numpy Matrix in python
2,848,099
7
2010-05-17T10:00:52Z
2,848,238
13
2010-05-17T10:25:05Z
[ "python", "file", "numpy" ]
Can someone gives me an example of how to save a 2-d matrix in a file and reloading it for further use?
``` >>> import numpy >>> mat = numpy.matrix("1 2 3; 4 5 6; 7 8 9") >>> mat.dump("my_matrix.dat") >>> mat2 = numpy.load("my_matrix.dat") ```
PostgreSQL: Running Python stored procedures as a normal user
2,848,704
5
2010-05-17T11:46:36Z
10,639,594
7
2012-05-17T16:23:28Z
[ "python", "postgresql" ]
I've installed PL/Python on my postgresql server under `postgres` privilleges: ``` netherlands=# CREATE PROCEDURAL LANGUAGE plpythonu; CREATE LANGUAGE ``` Now I need to grant permissions so I can use it as a normal user: ``` netherlands=# GRANT ALL ON LANGUAGE plpythonu TO adam; ERROR: language "plpythonu" is not t...
``` UPDATE pg_language SET lanpltrusted = true WHERE lanname = 'plpythonu'; ```
How to check the type of a many-to-many-field in django?
2,849,108
3
2010-05-17T12:47:44Z
2,849,308
9
2010-05-17T13:18:04Z
[ "python", "django", "django-models", "manytomanyfield", "manyrelatedmanager" ]
How can you check the type of a many-to-many-field in django? I wanted to do it this way: ``` import django field.__class__ == django.db.models.fields.related.ManyRelatedManager ``` This doesn't work, because the class `ManyRelatedManager` can't be found. But if i do `field.__class__` the output is `django.db.mode...
You should be able to check it as a string. ``` field.__class__.__name__ == 'ManyRelatedManager' ```
Python, Matplotlib, subplot: How to set the axis range?
2,849,286
157
2010-05-17T13:12:57Z
2,849,400
187
2010-05-17T13:31:18Z
[ "python", "range", "axis", "matplotlib" ]
How can I set the y axis range of the second subplot to e.g. [0,1000] ? The FFT plot of my data (a column in a text file) results in a (inf.?) spike so that the actual data is not visible. ``` pylab.ylim([0,1000]) ``` has no effect, unfortunately. This is the whole script: ``` # based on http://www.swharden.com/blog...
As found in <http://www.mofeel.net/582-comp-soft-sys-matlab/54166.aspx> ``` pylab.ylim([0,1000]) ``` Note: The command has to be executed after the plot!
Python, Matplotlib, subplot: How to set the axis range?
2,849,286
157
2010-05-17T13:12:57Z
6,851,519
23
2011-07-27T21:34:22Z
[ "python", "range", "axis", "matplotlib" ]
How can I set the y axis range of the second subplot to e.g. [0,1000] ? The FFT plot of my data (a column in a text file) results in a (inf.?) spike so that the actual data is not visible. ``` pylab.ylim([0,1000]) ``` has no effect, unfortunately. This is the whole script: ``` # based on http://www.swharden.com/blog...
Sometimes you really want to set the axes limits *before* you plot the data. In that case, you can set the "autoscaling" feature of the `Axes` or `AxesSubplot` object. The functions of interest are `set_autoscale_on`, `set_autoscalex_on`, and `set_autoscaley_on`. In your case, you want to freeze the y axis' limits, bu...
Python, Matplotlib, subplot: How to set the axis range?
2,849,286
157
2010-05-17T13:12:57Z
12,120,412
70
2012-08-25T08:26:52Z
[ "python", "range", "axis", "matplotlib" ]
How can I set the y axis range of the second subplot to e.g. [0,1000] ? The FFT plot of my data (a column in a text file) results in a (inf.?) spike so that the actual data is not visible. ``` pylab.ylim([0,1000]) ``` has no effect, unfortunately. This is the whole script: ``` # based on http://www.swharden.com/blog...
Using [axes objects](http://matplotlib.sourceforge.net/api/axes_api.html) is a great approach for this. It helps if you want to interact with multiple figures and sub-plots. To add and manipulate the axes objects directly: ``` fig = pylab.figure(figsize=(12,9)) signal_axes = fig.add_subplot(211) signal_axes.plot(xs,r...
In Python, is it better to use list comprehensions or for-each loops?
2,849,645
27
2010-05-17T14:03:18Z
2,849,685
10
2010-05-17T14:08:29Z
[ "python", "coding-style", "foreach", "list-comprehension" ]
Which of the following is better to use and why? Method 1: ``` for k, v in os.environ.items(): print "%s=%s" % (k, v) ``` Method 2: ``` print "\n".join(["%s=%s" % (k, v) for k,v in os.environ.items()]) ``` I tend to lead towards the first as more understandable, but that might just be because I'm new to...
I find the first example better - less verbose, clearer and more readable. In my opinion, go with what best gets your intention across, after all: > Programs should be written for people > to read, and only incidentally for > machines to execute. -- from "Structure and Interpretation of Computer Programs" by Abelson...
In Python, is it better to use list comprehensions or for-each loops?
2,849,645
27
2010-05-17T14:03:18Z
2,849,691
24
2010-05-17T14:09:32Z
[ "python", "coding-style", "foreach", "list-comprehension" ]
Which of the following is better to use and why? Method 1: ``` for k, v in os.environ.items(): print "%s=%s" % (k, v) ``` Method 2: ``` print "\n".join(["%s=%s" % (k, v) for k,v in os.environ.items()]) ``` I tend to lead towards the first as more understandable, but that might just be because I'm new to...
The particular code examples you have chosen do not demonstrate any advantage of the list comprehension, because it is being (mis-)used for the trivial task of printing. In this simple case I would choose the simple `for` loop. In many other cases, you will want to supply an actual list to another function or method, ...
In Python, is it better to use list comprehensions or for-each loops?
2,849,645
27
2010-05-17T14:03:18Z
2,850,192
24
2010-05-17T15:07:47Z
[ "python", "coding-style", "foreach", "list-comprehension" ]
Which of the following is better to use and why? Method 1: ``` for k, v in os.environ.items(): print "%s=%s" % (k, v) ``` Method 2: ``` print "\n".join(["%s=%s" % (k, v) for k,v in os.environ.items()]) ``` I tend to lead towards the first as more understandable, but that might just be because I'm new to...
If the iteration is being done for its side effect ( as it is in your "print" example ), then a loop is clearer. If the iteration is executed in order to build a composite value, then list comprehensions are usually more readable.
In Python, is it better to use list comprehensions or for-each loops?
2,849,645
27
2010-05-17T14:03:18Z
2,851,044
11
2010-05-17T16:56:07Z
[ "python", "coding-style", "foreach", "list-comprehension" ]
Which of the following is better to use and why? Method 1: ``` for k, v in os.environ.items(): print "%s=%s" % (k, v) ``` Method 2: ``` print "\n".join(["%s=%s" % (k, v) for k,v in os.environ.items()]) ``` I tend to lead towards the first as more understandable, but that might just be because I'm new to...
List comprehension is more than twice as fast as explicit loop. Base on Ben James' variation, but replace the x\*\*2 with a more trivial x+2 function, the two alternatives are: ``` def foo(n): L = [] for x in xrange(n): L.append(x+2) return L def bar(n): return [x+2 for x in xrange(n)] ``` Timing result...
OOWrite is to LaTeX as OODraw is to?
2,850,000
6
2010-05-17T14:46:10Z
2,850,021
12
2010-05-17T14:48:56Z
[ "python", "pdf", "latex" ]
I'm looking for a tool to nicely generate single-page PDFs. My needs are: * Able to put a PDF/EPS/... as a background * Absolute positioning * Able to define tables, lists * Able to rotate blocks * Reasonably easy syntax (will be used to automatically generate many similar looking documents) * Easily usable from Pytho...
Definitely **[PGF/Ti*k*Z](http://www.texample.net/tikz/examples/)**. Selling point: ![](http://media.texample.net/tikz/examples/PNG/rooty-helix.png) Created by this code: ``` % Rooty helix % Author: Felix Lindemann \documentclass{minimal} \usepackage{tikz} \usetikzlibrary{calc} \begin{document} \pagestyle{empty} \...
NumPy: how to quickly normalize many vectors?
2,850,743
17
2010-05-17T16:13:45Z
2,850,778
12
2010-05-17T16:17:32Z
[ "python", "vector", "numpy", "normalization" ]
How can a list of vectors be elegantly normalized, in NumPy? Here is an example that does *not* work: ``` from numpy import * vectors = array([arange(10), arange(10)]) # All x's, then all y's norms = apply_along_axis(linalg.norm, 0, vectors) # Now, what I was expecting would work: print vectors.T / norms # vector...
Alright: NumPy's array shape broadcast adds dimensions to the *left* of the array shape, not to its right. NumPy can however be instructed to add a dimension to the right of the `norms` array: ``` print vectors.T / norms[:, newaxis] ``` does work!
NumPy: how to quickly normalize many vectors?
2,850,743
17
2010-05-17T16:13:45Z
2,850,800
12
2010-05-17T16:21:09Z
[ "python", "vector", "numpy", "normalization" ]
How can a list of vectors be elegantly normalized, in NumPy? Here is an example that does *not* work: ``` from numpy import * vectors = array([arange(10), arange(10)]) # All x's, then all y's norms = apply_along_axis(linalg.norm, 0, vectors) # Now, what I was expecting would work: print vectors.T / norms # vector...
Well, unless I missed something, this does work: ``` vectors / norms ``` The problem in your suggestion is the broadcasting rules. ``` vectors # shape 2, 10 norms # shape 10 ``` The shape do not have the same length! So the rule is to first extend the small shape by one on the **left**: ``` norms # shape 1,10 `...
NumPy: how to quickly normalize many vectors?
2,850,743
17
2010-05-17T16:13:45Z
12,712,725
20
2012-10-03T16:24:11Z
[ "python", "vector", "numpy", "normalization" ]
How can a list of vectors be elegantly normalized, in NumPy? Here is an example that does *not* work: ``` from numpy import * vectors = array([arange(10), arange(10)]) # All x's, then all y's norms = apply_along_axis(linalg.norm, 0, vectors) # Now, what I was expecting would work: print vectors.T / norms # vector...
# Computing the magnitude I came across this question and became curious about your method for normalizing. I use a different method to compute the magnitudes. *Note: I also typically compute norms across the last index (rows in this case, not columns).* ``` magnitudes = np.sqrt((vectors ** 2).sum(-1))[..., np.newaxi...
NumPy: how to quickly normalize many vectors?
2,850,743
17
2010-05-17T16:13:45Z
20,262,847
8
2013-11-28T09:56:54Z
[ "python", "vector", "numpy", "normalization" ]
How can a list of vectors be elegantly normalized, in NumPy? Here is an example that does *not* work: ``` from numpy import * vectors = array([arange(10), arange(10)]) # All x's, then all y's norms = apply_along_axis(linalg.norm, 0, vectors) # Now, what I was expecting would work: print vectors.T / norms # vector...
there is already a function in scikit learn: ``` import sklearn.preprocessing as preprocessing norm =preprocessing.normalize(m, norm='l2')* ``` More info at: <http://scikit-learn.org/stable/modules/preprocessing.html>
Multiple XML Namespaces in tag with LXML
2,850,823
11
2010-05-17T16:24:47Z
2,850,877
10
2010-05-17T16:32:17Z
[ "python", "xml", "lxml", "gpx" ]
I am trying to use Pythons LXML library to great a GPX file that can be read by Garmin's Mapsource Product. The header on their GPX files looks like this ``` <?xml version="1.0" encoding="UTF-8" standalone="no" ?> <gpx xmlns="http://www.topografix.com/GPX/1/1" creator="MapSource 6.15.5" version="1.1" xmlns...
The problem is with your attribute name. ``` attrib={"{xsi}schemaLocation" : schemaLocation}, ``` puts schemaLocation in the xsi namespace. I think you meant ``` attrib={"{" + xsi + "}schemaLocation" : schemaLocation} ``` to use the URL for xsi. This matches your uses of namespace variables in the element name. It...
Reading binary data from stdin
2,850,893
14
2010-05-17T16:34:21Z
2,851,966
12
2010-05-17T19:06:33Z
[ "python" ]
Is it possible to read stdin as binary data in Python 2.6? If so, how? I see in the [Python 3.1 documentation](http://docs.python.org/py3k/library/sys.html) that this is fairly simple, but the facilities for doing this in 2.6 don't seem to be there. If the methods described in 3.1 aren't available, is there a way to ...
Use the [`-u` command line switch](http://docs.python.org/2/using/cmdline.html#cmdoption-u) to force Python 2 to treat stdin, stdout and stderr as binary unbuffered streams. ``` C:> type mydoc.txt | python.exe -u myscript.py ```
Reading binary data from stdin
2,850,893
14
2010-05-17T16:34:21Z
4,160,894
8
2010-11-12T01:31:46Z
[ "python" ]
Is it possible to read stdin as binary data in Python 2.6? If so, how? I see in the [Python 3.1 documentation](http://docs.python.org/py3k/library/sys.html) that this is fairly simple, but the facilities for doing this in 2.6 don't seem to be there. If the methods described in 3.1 aren't available, is there a way to ...
If you still need this... This simple test i've used to read binary file that contains 0x1A character in between ``` import os, sys, msvcrt msvcrt.setmode (sys.stdin.fileno(), os.O_BINARY) s = sys.stdin.read() print len (s) ``` My test file data was: ``` 0x23, 0x1A, 0x45 ``` Without setting stdin to binary mode th...
Reading binary data from stdin
2,850,893
14
2010-05-17T16:34:21Z
4,849,792
14
2011-01-31T10:26:47Z
[ "python" ]
Is it possible to read stdin as binary data in Python 2.6? If so, how? I see in the [Python 3.1 documentation](http://docs.python.org/py3k/library/sys.html) that this is fairly simple, but the facilities for doing this in 2.6 don't seem to be there. If the methods described in 3.1 aren't available, is there a way to ...
From the docs (see [here](http://docs.python.org/py3k/library/sys.html#sys.stdin)): > The standard streams are in text mode > by default. To write or read binary > data to these, use the underlying > binary buffer. For example, to write > bytes to stdout, use > `sys.stdout.buffer.write(b'abc')`. But, as in the accept...
Directly call distutils' or setuptools' setup() function with command name/options, without parsing the command line?
2,850,971
6
2010-05-17T16:45:48Z
2,851,036
7
2010-05-17T16:55:31Z
[ "python", "setuptools", "distutils" ]
I'd like to call Python's distutils' or setuptools' setup() function in a slightly unconventional way, but I'm not sure whether distutils is meant for this kind of usage. As an example, let's say I currently have a 'setup.py' file, which looks like this (lifted verbatim from the distutils docs--the setuptools usage is...
Never tried this, but I did happen to look in distutils/core.py, where I notice this near the start of `setup()`: ``` if 'script_name' not in attrs: attrs['script_name'] = os.path.basename(sys.argv[0]) if 'script_args' not in attrs: attrs['script_args'] = sys.argv[1:] ``` So, it looks as if you can "fake-out"...
How can I retrieve the signal strength of nearby wireless LAN networks on Windows using Python?
2,851,233
4
2010-05-17T17:24:26Z
3,191,659
10
2010-07-07T03:18:10Z
[ "python", "windows", "signals", "wireless", "wlan" ]
How can I retrieve the signal strength of nearby wireless LAN networks on Windows using Python? I would like to either show or graph the values.
If you are on **Windows**, you probably want to **use the WLAN API**, which provides the 'WlanGetAvailableNetworkList()' function (see the [API docs](http://msdn.microsoft.com/en-us/library/ms706749%28VS.85%29.aspx) for usage). I am not aware of any python wrappers for `WLANAPI.DLL` so you may have to wrap it yourself ...
Can I turn off implicit Python unicode conversions to find my mixed-strings bugs?
2,851,481
7
2010-05-17T18:00:04Z
2,851,573
10
2010-05-17T18:13:18Z
[ "python", "debugging", "unicode", "decoding" ]
When profiling our code I was surprised to find millions of calls to C:\Python26\lib\encodings\utf\_8.py:15(decode) I started debugging and found that across our code base there are many small bugs, usually comparing a string to a unicode or adding a sting and a unicode. Python graciously decodes the strings and per...
The following should work: ``` >>> import sys >>> reload(sys) <module 'sys' (built-in)> >>> sys.setdefaultencoding('undefined') >>> u"abc" + u"xyz" u'abcxyz' >>> u"abc" + "xyz" Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/...
python: naming a module that has a two-word name
2,852,283
29
2010-05-17T19:56:57Z
2,852,305
35
2010-05-17T20:00:00Z
[ "python", "naming-conventions" ]
I'm trying to put together a really simple module with one .py source file in it, and have already run into a roadblock. I was going to call it `scons-config` but `import scons-config` doesn't work in Python. I found [this SO question](http://stackoverflow.com/questions/711884/python-naming-conventions-for-modules) and...
If you have to, always use underscores `_`. Using a dot `.` would not even work, otherwise ``` from scons.config import whatever ``` would break. But I think PEP 8 clearly describes it here: > Package and Module Names > > Modules should have **short, all-lowercase names**. *Underscores* **can be used** > in the mo...
python: naming a module that has a two-word name
2,852,283
29
2010-05-17T19:56:57Z
2,852,362
10
2010-05-17T20:08:00Z
[ "python", "naming-conventions" ]
I'm trying to put together a really simple module with one .py source file in it, and have already run into a roadblock. I was going to call it `scons-config` but `import scons-config` doesn't work in Python. I found [this SO question](http://stackoverflow.com/questions/711884/python-naming-conventions-for-modules) and...
First, the module name is the same as the name of the single .py file. In Python-speak, a collection of several .py files is a package. PEP-8 discourages breaking up package names with underscores. A quick peak at my site-packages directory shows that multiword names are commonly just run together (e.g., setuptools, s...
Extracting words between delimiters [] in python
2,852,484
5
2010-05-17T20:23:45Z
2,852,501
16
2010-05-17T20:26:32Z
[ "python" ]
From the below string, I want to extract the words between delimters `[ ]` like `'Service Current','Service','9991','1.22'`: ``` str='mysrv events Generating Event Name [Service Current], Category [Service] Test [9991] Value [1.22]' ``` How can I extract the same in python? Thanks in advance Kris
First, avoid using `str` as a variable name. `str` already has a meaning in Python and by defining it to be something else you will confuse people. Having said that you can use the following regular expression: ``` >>> import re >>> print re.findall(r'\[([^]]*)\]', s) ['Service Current', 'Service', '9991', '1.22'] ``...
Django Deserialization
2,852,583
2
2010-05-17T20:35:34Z
2,852,651
8
2010-05-17T20:43:30Z
[ "python", "django", "serialization" ]
I am getting the following error: > Traceback (most recent call last): > File "../tests.py", line 92, in test\_single\_search > > for return\_obj in serializers.deserialize("json",response, ensure\_ascii=False): > File "/Library/Python/2.6/site-packages/django/core/serializers/json.py", > line 38, in Deserializer ...
You need to use `response.content` rather than just `response` in your call to `deserialize`. The response object is an instance of HttpResponse, but has an attribute of `content` which contains the actual JSON in this case.
Python required variable style
2,852,623
3
2010-05-17T20:40:32Z
2,852,646
7
2010-05-17T20:43:00Z
[ "python" ]
What is the best style for a Python method that requires the keyword argument 'required\_arg': ``` def test_method(required_arg, *args, **kwargs): def test_method(*args, **kwargs): required_arg = kwargs.pop('required_arg') if kwargs: raise ValueError('Unexpected keyword arguments: %s' % kwargs) ``` ...
The first method by far. Why duplicate something the language already provides for you? Optional arguments in most cases should be known (only use \*args and \*\*kwargs when there is no possible way of knowing the arguments). Denote optional arguments by giving them their default value (`def bar(foo = 0)` or `def bar(...
What is the equivalent in PHP for Python's pass statement?
2,852,784
14
2010-05-17T21:01:06Z
2,852,795
29
2010-05-17T21:02:26Z
[ "php", "python", "language-comparisons" ]
Do you know any PHP statement that works like Python's `pass` statement?
Just leave the bracket's empty... Python has the pass word because they don't use brackets to define the body part of classes, function, and other statement. PHP doesn't have this dilemma , and therefore doesn't need something to say that a body statement is empty.
What is the equivalent in PHP for Python's pass statement?
2,852,784
14
2010-05-17T21:01:06Z
2,852,801
15
2010-05-17T21:03:29Z
[ "php", "python", "language-comparisons" ]
Do you know any PHP statement that works like Python's `pass` statement?
It isn't needed in PHP. The Python code: ``` if x == y: pass ``` Can be written in PHP by just leaving the brackets empty ``` if ( x == y ){ } ``` The same applies to other PHP constructs requiring brackets such as classes or functions.
Setuptools not passing arguments for entry_points
2,853,088
5
2010-05-17T21:46:54Z
2,853,939
9
2010-05-18T00:42:39Z
[ "python", "setuptools", "distutils" ]
I'm using setuptools for a Python script I wrote After installing, I do: ``` $ megazord -i input -d database -v xx-xx -w yy-yy ``` Like I would if I was running it ./like\_this However, I get: ``` Traceback (most recent call last): File "/usr/local/bin/megazord", line 9, in <module> load_entry_point('megazor...
The setuptools console\_scripts entry point wants a function of no arguments. Happily, [optparse](http://docs.python.org/library/optparse.html) (Parser for command line options) doesn't need to be passed any arguments, it will read in sys.argv[1:] and use that as it's input.
All possible permutations of a set of lists in Python
2,853,212
23
2010-05-17T22:05:15Z
2,853,239
41
2010-05-17T22:10:23Z
[ "python", "list", "permutation" ]
In Python I have a list of n lists, each with a variable number of elements. How can I create a single list containing all the possible permutations: For example ``` [ [ a, b, c], [d], [e, f] ] ``` I want ``` [ [a, d, e] , [a, d, f], [b, d, e], [b, d, f], [c, d, e], [c, d, f] ] ``` Note I don't know n in advance. ...
You don't need to know `n` in advance to use `itertools.product` ``` >>> import itertools >>> s=[ [ 'a', 'b', 'c'], ['d'], ['e', 'f'] ] >>> list(itertools.product(*s)) [('a', 'd', 'e'), ('a', 'd', 'f'), ('b', 'd', 'e'), ('b', 'd', 'f'), ('c', 'd', 'e'), ('c', 'd', 'f')] ```
remove from a list of tuples according to the second part of the tuple in python
2,853,483
3
2010-05-17T22:57:01Z
2,853,499
9
2010-05-17T23:00:13Z
[ "python" ]
`contacts.remove((name,ip))` I have the ip and it's unique. I want to remove this tuple from contacts according to the ip and no need to name. I just tried this `contacts.remove((pass,ip))`, but I encountered an error.
``` contacts = [(name, ip) for name, ip in contacts if ip != removable_ip] ``` or ``` for x in xrange(len(contacts) - 1, -1, -1): if contacts[x][1] == removable_ip: del contacts[x] break # removable_ip is allegedly unique ``` The first method rebinds `contacts` to a newly-created list that exclud...
How do you PEP 8-name a class whose name is an acronym?
2,853,531
25
2010-05-17T23:05:42Z
2,853,562
7
2010-05-17T23:10:18Z
[ "python", "coding-style" ]
I try to adhere to the style guide for Python code (also known as [PEP 8](http://www.python.org/dev/peps/pep-0008/)). Accordingly, the preferred way to name a class is using CamelCase: > Almost without exception, class names > use the CapWords convention. Classes for internal use have a leading underscore in addition....
`#1` in this particular case looks fine to me (if it's *really* an acronym). Out of curiosity, what does it stand for (and what exactly is the class instance, maybe a `module` would be the more appropriate divisor)? ``` class NASAJPL: ``` **EDIT**: when you're combining two acronyms chances are you want to divide fun...
How do you PEP 8-name a class whose name is an acronym?
2,853,531
25
2010-05-17T23:05:42Z
2,853,571
7
2010-05-17T23:11:49Z
[ "python", "coding-style" ]
I try to adhere to the style guide for Python code (also known as [PEP 8](http://www.python.org/dev/peps/pep-0008/)). Accordingly, the preferred way to name a class is using CamelCase: > Almost without exception, class names > use the CapWords convention. Classes for internal use have a leading underscore in addition....
I also work in an acronym-heavy environment. I tend to prefer form #3 because even though it lower-cases parts of an acronym, it clearly delineates parts of the name. It also avoids confusion when part of the name is an acronym and part is a word.
How do you PEP 8-name a class whose name is an acronym?
2,853,531
25
2010-05-17T23:05:42Z
2,853,609
37
2010-05-17T23:19:53Z
[ "python", "coding-style" ]
I try to adhere to the style guide for Python code (also known as [PEP 8](http://www.python.org/dev/peps/pep-0008/)). Accordingly, the preferred way to name a class is using CamelCase: > Almost without exception, class names > use the CapWords convention. Classes for internal use have a leading underscore in addition....
[PEP-8](http://www.python.org/dev/peps/pep-0008/) does cover this (at least partially): > Note: When using abbreviations in CapWords, capitalize all the letters of the abbreviation. Thus `HTTPServerError` is better than `HttpServerError`. Which I would read to mean that `NASAJPL()` is the recommended name according t...
How do you PEP 8-name a class whose name is an acronym?
2,853,531
25
2010-05-17T23:05:42Z
2,853,689
8
2010-05-17T23:37:52Z
[ "python", "coding-style" ]
I try to adhere to the style guide for Python code (also known as [PEP 8](http://www.python.org/dev/peps/pep-0008/)). Accordingly, the preferred way to name a class is using CamelCase: > Almost without exception, class names > use the CapWords convention. Classes for internal use have a leading underscore in addition....
As others have noted, NASAJPL is probably the PEP-8 approved form. Just to be contrary, however, I would probably use NasaJPL. Because if you are reading it, you pronounce "NASA" as a single word, whereas "JPL" you spell out. You can make an argument that this is consistent with PEP-8, since "NASA" is an acronym, but...
What is the preferred syntax for initializing a dict: curly brace literals {} or the dict() function?
2,853,683
84
2010-05-17T23:37:08Z
2,853,710
52
2010-05-17T23:42:21Z
[ "python", "dictionary" ]
I'm putting in some effort to learn Python, and I am paying close attention to common coding standards. This may seem like a pointlessly nit-picky question, but I am trying to focus on best-practices as I learn, so I don't have to unlearn any 'bad' habits. I see two common methods for initializing a dict: ``` a = { ...
The first, curly braces. Otherwise, you run into consistency issues with keys that have odd characters in them, like `=`. ``` # Works fine. a = { 'a': 'value', 'b=c': 'value', } # Eeep! Breaks if trying to be consistent. b = dict( a='value', b=c='value', ) ```
What is the preferred syntax for initializing a dict: curly brace literals {} or the dict() function?
2,853,683
84
2010-05-17T23:37:08Z
2,853,738
38
2010-05-17T23:48:48Z
[ "python", "dictionary" ]
I'm putting in some effort to learn Python, and I am paying close attention to common coding standards. This may seem like a pointlessly nit-picky question, but I am trying to focus on best-practices as I learn, so I don't have to unlearn any 'bad' habits. I see two common methods for initializing a dict: ``` a = { ...
The first version is preferable: * It works for all kinds of keys, so you can, for example, say `{1: 'one', 2: 'two'}`. The second variant only works for (some) string keys. Using different kinds of syntax depending on the type of the keys would be an unnecessary inconsistency. * It is faster: ``` $ python -m tim...
What is the preferred syntax for initializing a dict: curly brace literals {} or the dict() function?
2,853,683
84
2010-05-17T23:37:08Z
2,853,739
100
2010-05-17T23:48:52Z
[ "python", "dictionary" ]
I'm putting in some effort to learn Python, and I am paying close attention to common coding standards. This may seem like a pointlessly nit-picky question, but I am trying to focus on best-practices as I learn, so I don't have to unlearn any 'bad' habits. I see two common methods for initializing a dict: ``` a = { ...
Curly braces. Passing keyword arguments into `dict()`, though it works beautifully in a lot of scenarios, can only initialize a map if the keys are valid Python identifiers. In other words it cannot do: ``` a = {'import': 'trade', 1: 7.8} ```
Whats the python way for recursively setting file permissions?
2,853,723
28
2010-05-17T23:45:17Z
2,853,934
29
2010-05-18T00:41:11Z
[ "python", "recursion", "chown" ]
What's the "python way" to recursively set the owner and group to files in a directory? I could just pass a 'chown -R' command to shell, but I feel like I'm missing something obvious. I'm mucking about with this: ``` import os path = "/tmp/foo" for root, dirs, files in os.walk(path): for momo in dirs: o...
The `dirs` and `files` lists are all always relative to `root` - i.e., they are the `basename()` of the files/folders, i.e. they don't have a `/` in them (or `\` on windows). You need to join the dirs/files to `root` to get their whole path if you want your code to work to infinite levels of recursion: ``` import os ...
Get a list of field values from Python's sqlite3, not tuples representing rows
2,854,011
20
2010-05-18T01:11:18Z
2,854,018
10
2010-05-18T01:13:09Z
[ "python", "sqlite", "sqlite3" ]
It's annoying how Python's [`sqlite3`](https://docs.python.org/2/library/sqlite3.html) module always returns a list of tuples! When I am querying a single column, I would prefer to get a plain list. e.g. when I execute ``` SELECT somecol FROM sometable ``` and call ``` cursor.fetchall() ``` it returns ``` [(u'one...
``` data=cursor.fetchall() COLUMN = 0 column=[elt[COLUMN] for elt in data] ``` (My previous suggestion, `column=zip(*data)[COLUMN]`, raises an `IndexError` if `data` is an empty tuple. In contrast, the list comprehension above just creates an empty list. Depending on your situation, raising an `IndexError` may be pref...
Get a list of field values from Python's sqlite3, not tuples representing rows
2,854,011
20
2010-05-18T01:11:18Z
23,115,247
20
2014-04-16T16:37:30Z
[ "python", "sqlite", "sqlite3" ]
It's annoying how Python's [`sqlite3`](https://docs.python.org/2/library/sqlite3.html) module always returns a list of tuples! When I am querying a single column, I would prefer to get a plain list. e.g. when I execute ``` SELECT somecol FROM sometable ``` and call ``` cursor.fetchall() ``` it returns ``` [(u'one...
`sqlite3.Connection` has a [`row_factory`](https://docs.python.org/2/library/sqlite3.html#sqlite3.Connection.row_factory) attribute. The documentation states that: > You can change this attribute to a callable that accepts the cursor and the original row as a tuple and will return the real result row. This way, you c...
For Django models, is there a shortcut for seeing if a record exists?
2,854,080
22
2010-05-18T01:33:43Z
2,854,132
37
2010-05-18T01:51:46Z
[ "python", "django", "django-models" ]
Say I have a table `People`, is there a way to just quickly check if a `People` object exists with a name of `'Fred'`? I know I can query ``` People.objects.filter(Name='Fred') ``` and then check the length of the returned result, but is there a way to do it in a more elegant way?
An [exists()](https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.exists) method in the QuerySet API is available [since Django 1.2](http://code.djangoproject.com/ticket/11402).
For Django models, is there a shortcut for seeing if a record exists?
2,854,080
22
2010-05-18T01:33:43Z
2,854,134
24
2010-05-18T01:52:02Z
[ "python", "django", "django-models" ]
Say I have a table `People`, is there a way to just quickly check if a `People` object exists with a name of `'Fred'`? I know I can query ``` People.objects.filter(Name='Fred') ``` and then check the length of the returned result, but is there a way to do it in a more elegant way?
**Update**: As mentioned in more recent answers, since Django 1.2 you can use the `exists()` method instead ([link](https://docs.djangoproject.com/en/1.8/ref/models/querysets/#django.db.models.query.QuerySet.exists)). --- **Original Answer:** Dont' use len() on the result, you should use `People.objects.filter(Name...