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
difference between datetime vs time modules
7,479,777
56
2011-09-20T03:26:57Z
7,479,986
43
2011-09-20T04:00:50Z
[ "python", "datetime", "time" ]
I know that datetime provides both dates and time. What is the use of the time module? are there any differences? This might seem naive but, I am trying to figure out the differences, and what each should be used for. Examples would be appreciated, differences concerning timezones would especially of interest. Thanks...
the `time` module is principally for working with unix time stamps; expressed as a floating point number taken to be seconds since the unix epoch. the `datetime` module can support many of the same operations, but provides a more object oriented set of types, and also has some limited support for time zones.
python operator precedence of in and comparision
7,479,808
5
2011-09-20T03:33:21Z
7,479,836
9
2011-09-20T03:37:15Z
[ "python" ]
python manual said that the `in` operator has lower precendence than comparsion operators, so: ``` '1' in '11' ==> True ('1' in '11') == True ==> True ``` then why: ``` '1' in '11' == True ==> False >>> '1' in ('11' == True) Traceback (most recent call last): File "<pyshell#20>", line 1, in <module> '1' i...
The Python manual says `in` and `==` are of equal precedence: <http://docs.python.org/reference/expressions.html#summary> Thus, they're evaluated from left to right by default, but there's also chaining to consider. The expression you put above (`'1' in '11' == True`) is *actually* being evaluated as... ``` ('1' in ...
Getting all items of QComboBox - PyQt4 (Python)
7,479,915
15
2011-09-20T03:49:17Z
7,480,072
24
2011-09-20T04:14:29Z
[ "python", "get", "pyqt4", "qcombobox" ]
I have A LOT of `QComboBoxes`, and at a certain point, I need to fetch every item of a particular `QComboBox` to iterate through. Although I could just have a list of items that correspond to the items in the `QComboBox`, I'd rather get them straight from the widget itself (there are a huge amount of `QComboBoxes` wi...
As far as I can tell, you can just reference an item using `.itemText()`: ``` AllItems = [QComboBoxName.itemText(i) for i in range(QComboBoxName.count())] ```
Numeric function for log of sum in Python
7,480,996
4
2011-09-20T06:29:42Z
7,481,325
7
2011-09-20T07:05:15Z
[ "python", "logarithm", "numerical-computing" ]
Given `log(a)` and `log(b)`, I want to compute `log(a+b)` (in a numerically stable way). I wrote a little function for this: ``` def log_add(logA,logB): if logA == log(0): return logB if logA<logB: return log_add(logB,logA) return log( 1 + math.exp(logB-logA) ) + logA ``` I wrote a progra...
Note: Best answer until now is to simply use `numpy.logaddexp(logA,logB)`. Why exactly do you compare with `log(0)`? This is equal to `-numpy.inf`, in this case you come to `log(1 + math.exp(-inf-logB) ) + logB` Which reduces itself to logB. This call always will give an warning message which is extremely slow. I cou...
Precision, why do Matlab and Python numpy give so different outputs?
7,482,205
17
2011-09-20T08:29:17Z
7,482,409
14
2011-09-20T08:46:29Z
[ "python", "matlab", "statistics", "floating-point-precision" ]
I know about basic data types and that float types (float,double) can not hold some numbers exactly. In porting some code from Matlab to Python (Numpy) I however found some significant differences in calculations, and I think it's going back to precision. Take the following code, z-normalizing a 500 dimensional vecto...
To answer your question, **no**, this is not a problem of precision. As [@rocksportrocker](http://stackoverflow.com/questions/7482205/precisison-why-do-matlab-and-python-numpy-give-so-different-outputs/7482413#7482413) points out, there are [two popular estimators for the standard deviation](http://en.wikipedia.org/wik...
Precision, why do Matlab and Python numpy give so different outputs?
7,482,205
17
2011-09-20T08:29:17Z
7,482,413
24
2011-09-20T08:46:44Z
[ "python", "matlab", "statistics", "floating-point-precision" ]
I know about basic data types and that float types (float,double) can not hold some numbers exactly. In porting some code from Matlab to Python (Numpy) I however found some significant differences in calculations, and I think it's going back to precision. Take the following code, z-normalizing a 500 dimensional vecto...
Maybe the difference comes from the `mean` and `std` calls. Compare those first. There are several definitions for `std`, some use the sqaure root of ``` 1 / n * sum((xi - mean(x)) ** 2) ``` others use ``` 1 / (n - 1) * sum((xi - mean(x)) ** 2) ``` instead. From a mathematical point: these formulas are estimators...
Is there a python assert() method which checks between two boundaries?
7,482,824
9
2011-09-20T09:17:38Z
7,482,883
13
2011-09-20T09:23:02Z
[ "python", "unit-testing" ]
In some unit testing I'm currently doing, I need to pass a test when a variable lies between two boundary conditions. Something like - ``` def myTest(self): myInt = 5 self.assertBetween(myInt,3,8) ``` would pass the test. Or if myInt lied outside of the range 3 to 8 it would fail. I've looked down the list ...
You can use [assertTrue()](http://docs.python.org/library/unittest.html#unittest.TestCase.assertTrue) for that purpose: ``` self.assertTrue(myInt >= 3 and myInt <= 8) ``` Or, using Python's comparison chaining idiom: ``` self.assertTrue(3 <= myInt <= 8) ```
Python - the zipfile module doesn't seem to work with passwords
7,483,138
5
2011-09-20T09:43:08Z
7,483,763
8
2011-09-20T10:35:02Z
[ "python" ]
I've been trying to implement a very simple script, extracting zip files that are password protected. I have created a simple zip file (test.zip) with the password "1234" containing 2 text files (1.txt, 2.txt) and i wrote this script: ``` import zipfile PASSWORD = "1234" zip = zipfile.ZipFile("test.zip", "r") zip.se...
As indicated in a comment it could be a problem with your encryption mode. Using 7-zip to create the zip file using AES-256 I get the same error as yours. With ZypCrypto encryption it works OK. ``` PyCrust 0.9.8 - The Flakiest Python Shell Python 2.6.7 (r267:88850, Jun 27 2011, 13:20:48) [MSC v.1500 64 bit (AMD64)] on...
Python MySQLdb returns datetime.date and decimal
7,483,363
7
2011-09-20T09:59:54Z
7,484,893
20
2011-09-20T12:08:22Z
[ "python", "mysql-python" ]
I have a MySQL query like: ``` SELECT mydate, countryCode, qtySold from sales order mydate, countryCode ``` This returns tuples of tuples with values like: ``` ((datetime.date(2011, 1, 3), 'PR', Decimal('1')), (datetime.date(2011, 1, 31), 'MX', Decimal('1'))) ``` When I try printing this using a loop, it prints per...
The default converter, `MySQLdb.converters.conversions` is a dict with entries like this: ``` {0: <class 'decimal.Decimal'>, 1: <type 'int'>, 2: <type 'int'>, 3: <type 'long'>, 4: <type 'float'>, 5: <type 'float'>, 7: <function mysql_timestamp_converter at 0x89e4454>, 8: <type 'long'>, 9: <type 'int'>, 10: <f...
Argparse: ignore multiple positional arguments when optional argument is specified
7,484,044
15
2011-09-20T10:58:20Z
7,485,255
8
2011-09-20T12:36:07Z
[ "python", "argparse" ]
I'm trying to make argparse ignore the fact that two normally required positional arguments shouldn't be evaluated when an optional argument (`-l`) is specified. Basically I'm trying to replicate the behavior of --help: when you specify the -h, all missing required arguments are ignored. Example code: ``` parser = a...
Unfortunately, `argparse` isn't quite flexible enough for this. The best you can do is to make `arg1` and `arg2` optional using `nargs="?"` and check yourself whether they are given if needed. The internal `help` action is implemented by printing the help message and exiting the program as soon as `-h` or `--help` are...
Removing handlers from python's logging loggers
7,484,454
17
2011-09-20T11:37:05Z
7,484,605
45
2011-09-20T11:48:12Z
[ "python", "logging" ]
I am playing with Python's logging system. I have noticed a strange behavior while removing handlers from a Logger object in a loop. Namely, my for loop removes all but one handler. Additional call to `.removeHandler` removes the last handler smoothly. No error messages are issued during the calls. This is the test co...
This isn't logger-specific behaviour. *Never* mutate (insert/remove elements) the list you're currently iterating on. If you need, make a copy. In this case `testLogger.handlers = []` should do the trick.
PyQt4 - Remove Item Widget from QListWidget
7,484,699
4
2011-09-20T11:55:21Z
7,486,225
8
2011-09-20T13:47:08Z
[ "python", "pyqt4", "qlistwidget" ]
I have a QListWidget and I need to remove some items. From what I've researched, this is a generally unpleasant thing to do. I've read a tonne of solutions, but none are applicable to my specific scenario. At the moment, I only have the actual Item Widgets to deal with; not their values or index. This is because I...
[takeItem()](http://doc.qt.nokia.com/stable/qlistwidget.html#takeItem) should work: ``` for SelectedItem in self.ListDialog.ContentList.selectedItems(): self.ListDialog.ContentList.takeItem(self.ListDialog.ContentList.row(SelectedItem)) ```
python reading text file
7,485,458
4
2011-09-20T12:52:04Z
7,485,660
7
2011-09-20T13:09:39Z
[ "python" ]
I have a text file, of which i need each column, preferably into a dictionary or list, the format is : ``` N ID REMAIN VERS 2 2343333 bana twelve 3 3549287 moredp twelve 3 9383737 hinsila twelve 3 8272655 hinsila eight ``` I h...
This works fine for me: ``` >>> crs = open("file.txt", "r") >>> for columns in ( raw.strip().split() for raw in crs ): ... print columns[0] ... N 2 3 3 3 ``` If you want to convert columns to rows, use `zip`. ``` >>> crs = open("file.txt", "r") >>> rows = (row.strip().split() for row in crs) >>> zip(*rows) [(...
Renaming a django model class-name and corresponding foreign keys with south, without loosing the data
7,485,507
5
2011-09-20T12:56:08Z
7,488,229
8
2011-09-20T16:04:54Z
[ "python", "django", "mysql-management", "django-south" ]
Following is my model: ``` class myUser_Group(models.Model): name = models.CharField(max_length=100) class Channel(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=1000) belongs_to_group = models.ManyToManyField(myUser_Group) class Video(models.Model):...
You can do this using just South. For this example I have an app called `usergroups` with the following model: ``` class myUser_Group(models.Model): name = models.CharField(max_length=100) ``` which I assume is already under migration control with South. Make the model name change: ``` class MyUserGroup(models...
Sending messages or datas with bluetooth via python
7,485,750
7
2011-09-20T13:15:15Z
15,922,571
7
2013-04-10T09:54:33Z
[ "python", "bluetooth" ]
How can i send messages over bluetooth via python without key authentification like type numbers ? i used pybluez but i got this error: ``` File "./send", line 12, in <module> connect() File "./send", line 8, in connect sock.connect((bd_addr, port)) File "<string>", line 5, in connect bluetooth.btcommon.B...
As @TJD said, you need to ensure you bind with the correct port for the service you want. ``` >>> from bluetooth import * >>> from pprint import pprint >>> >>> devices = discover_devices() >>> devices ['xx:yy:tt:zz:44:BD', '00:yy:72:zz:bb:aa'] ``` Then as the second step try to find the service on the device you want...
How can I reconnect a socket after a broken pipe?
7,486,561
3
2011-09-20T14:10:46Z
7,486,581
7
2011-09-20T14:12:35Z
[ "python", "sockets" ]
The program connects to a server, and when the connection is closed by the server, if I try to reconnect it says: `socket.error: [Errno 9] Bad file descriptor` If I close the socket in the client and then i try to reconnect, it says: `socket.error: [Errno 106] Transport endpoint is already connected`. --- Is there ...
Assuming this is a connection oriented socket: No. You have to close the old one and create a new socket,
Having both single and double quotation in a python string
7,487,145
6
2011-09-20T14:46:29Z
7,487,171
15
2011-09-20T14:48:11Z
[ "python" ]
Hi I'm trying to have a string that contains both single and double quotation in python -- ('"). The reason I need this expression is to use as an input to some external batch command. However, python always automatically corrects this to (\' "). I wonder if there's a way to put a double quotation and a single quotatio...
Use triple quotes. ``` """Trip'le qu"oted""" ``` or ``` '''Ag'ain qu"oted''' ``` Keep in mind that just because Python `repr`s a string with backslashes, doesn't mean it's actually added any slashes to the string, it may just be showing special characters escaped. Using an example from the Python tutorial: ``` >>...
OSError: Directory not empty raised, how to fix?
7,487,307
4
2011-09-20T14:59:10Z
7,487,520
11
2011-09-20T15:13:19Z
[ "python", "file", "exception", "directory", "rename" ]
I'm just trying to write a little application that takes a value from a file named 'DATA.DAT' and renames the folder which contains that file with that value. The .py script runs in another folder and allows the user to define the path. To give you a better idea, the user defined path must be like (on a mac) '/Users/U...
**Edit:** The right tool is [`shutil.move`](http://docs.python.org/library/shutil.html#shutil.move): ``` shutil.move(path_paths[-1], data_data) ``` assuming `path_paths[-1]` is the absolute directory you want to rename, and `data_data` is the absolute directory name you want to rename it to. The destination director...
Example python script that uses DBPedia?
7,487,789
9
2011-09-20T15:34:23Z
7,489,613
11
2011-09-20T18:00:29Z
[ "python", "mysql", "sparql", "dbpedia", "information-extraction" ]
I am writing a python script to extract "Entity names" from a collection of thousands of news articles from a few countries and languages. I would like to make use of the amazing [DBPedia](http://dbpedia.org) structured knwoledge, say for example to look up the names of "artists in egypt" and names of "companies in Ca...
DBpedia content is in RDF format. The dumps can be download from [here](http://wiki.dbpedia.org/Downloads37) Dbpedia is a large dataset in RDF, for handling that amount of data you need to use [Triple Store](http://en.wikipedia.org/wiki/Triplestore) technology. For Dbpedia you will need one of native triple stores, I ...
What is the fastest way to add data to a list without duplication in python (2.5)
7,489,219
11
2011-09-20T17:29:19Z
7,489,249
10
2011-09-20T17:32:18Z
[ "python", "list" ]
I have about half a million items that need to be placed in a list, I can't have duplications, and if an item is already there I need to get it's index. So far I have ``` if Item in List: ItemNumber=List.index(Item) else: List.append(Item) ItemNumber=List.index(Item) ``` The problem is that as the list gr...
You can use a [set](http://docs.python.org/library/stdtypes.html#set-types-set-frozenset) (in CPython since version 2.4) to efficiently look up duplicate values. If you really need an indexed system as well, you can use both a set and list. Doing your lookups using a set will remove the overhead of `if Item in List`, ...
Why does pip fail when installing local egg repository?
7,489,546
13
2011-09-20T17:55:24Z
7,490,955
25
2011-09-20T19:50:29Z
[ "python", "local", "pip", "egg" ]
I am working on Windows 7.I have created a python egg using distutils. Now I try to install this egg in a virtual environment using pip 1.0.2 using the following command: Then I create a virtual environment *myVirtualEnv* I activate it using activate.bat then execute the following command: `pip install path_to_my_loc...
<http://www.pip-installer.org/en/latest/other-tools.html#pip-compared-to-easy-install> > pip doesn’t do everything that easy\_install does. Specifically: > > It cannot install from eggs. It only installs from source.
Easiest way to add a function to existing class
7,489,732
4
2011-09-20T18:10:32Z
7,489,828
11
2011-09-20T18:17:46Z
[ "python", "wrapper", "shelve" ]
I'm using the python's built-in shelve module to manage some simple dictionaries. The problem I'm having is I want to use `with shelve.open(filename) as f:`, but when I try it claims DbfilenameShelf has no attribute `__exit__`. So, I'm guessing the easiest way to do this is to wrap it in another class and add an `__ex...
Don't subclass it. Python comes with a tool for automatically calling `close()`, [`contextlib.closing`](http://docs.python.org/library/contextlib.html#contextlib.closing): ``` from contextlib import closing with closing(shelve.open(filename)) as f: # your 'with' block here ``` will automatically call the `close()...
netbeans 7.1 and python
7,490,181
11
2011-09-20T18:48:11Z
9,993,301
9
2012-04-03T12:30:54Z
[ "python", "netbeans", "netbeans-7.1" ]
I used to use my Netbeans 6.9 for Python development. As well as Java and PHP. I had a cool debugger in PHP with xDebug, good Python support. Have no complaints whatsoever. I moved to another computer downloaded the latest netbeans(7.1) and now I have no more python plugin. I tried the solution [here](https://techknowh...
Ok, I fixed this. Say you've screwed up your netbeans installation by installing the pythonplugin then this might just work for you, provided you're using a non-windows OS. This is because Windows uses precompiled binaries to start the Netbeans IDE. The problem that I solved is that, by default, a set of classes is no...
Python: repr vs backquote
7,490,261
15
2011-09-20T18:54:32Z
7,490,299
20
2011-09-20T18:57:41Z
[ "python", "python-2.x" ]
In python, is there a difference between `repr` and the backquote `` ` `` (left of 1)? For demonstration: ``` class A(object): def __repr__(self): return 'repr A' def __str__(self): return 'str A' >>> a = A() >>> repr(a) #'repr A' >>> `a` #'repr A' >>> str(a) #'str A' ``` Do the backquot...
They're an alias for `repr`. They have the exact same effect. However, they're deprecated and have been removed in Python 3. Don't use them; use `repr`.
Python: repr vs backquote
7,490,261
15
2011-09-20T18:54:32Z
7,490,311
9
2011-09-20T18:58:50Z
[ "python", "python-2.x" ]
In python, is there a difference between `repr` and the backquote `` ` `` (left of 1)? For demonstration: ``` class A(object): def __repr__(self): return 'repr A' def __str__(self): return 'str A' >>> a = A() >>> repr(a) #'repr A' >>> `a` #'repr A' >>> str(a) #'str A' ``` Do the backquot...
According to [python.org](http://docs.python.org/library/functions.html#repr) covering repr: > This is the same value yielded by conversions (reverse quotes). It should be noted that the backtick method is considered something of an abomination by the language designers at the moment, and [it was removed in python 3]...
Capture embedded google map image with Python without using a browser
7,490,491
5
2011-09-20T19:14:01Z
7,491,390
8
2011-09-20T20:29:57Z
[ "python", "google-maps", "image-stitching" ]
I have noticed that, from Google Maps page, you can get an "embed" link to put inside an iframe and load the map in a browser. (no news here) The image size can be adjusted to be very large, so I am interested in getting som big images as single .PNGs. More specifically, I would like to define a rectangular area from...
Rather than trying to use the embed link, you should go directly to the Google API to get images as static graphics. Here's the link to the [Google Maps static image API](http://code.google.com/apis/maps/documentation/staticmaps/) - it looks like you can just pass in the long/lat parameters in the URL just as you do fo...
Capture embedded google map image with Python without using a browser
7,490,491
5
2011-09-20T19:14:01Z
7,919,917
10
2011-10-27T17:29:37Z
[ "python", "google-maps", "image-stitching" ]
I have noticed that, from Google Maps page, you can get an "embed" link to put inside an iframe and load the map in a browser. (no news here) The image size can be adjusted to be very large, so I am interested in getting som big images as single .PNGs. More specifically, I would like to define a rectangular area from...
I thank for all the answers. I ended up solving the problem another way, using Google Maps Static API and some formulas to convert from Coordinate space to Pixel space, so that I can get precise images which "stich" nicely together. For anyone interested, here is the code. If it helps someone, please comment! =======...
Python Regex Capture Only Certain Text
7,491,604
2
2011-09-20T20:51:13Z
7,491,639
7
2011-09-20T20:54:36Z
[ "python", "regex" ]
I am trying to find functionality in python similar to the Ruby function scan. My goal is to grab all the text in-between two curly braces in a list. If there are multiple pairs of curly braces in the string, I want to have multiple entries in the list. When I run this code: ``` match = re.search(r'\{(.+)\}', reques...
``` re.findall(r'\{(.+?)\}', request.params['upsell']) ``` This will return a list where each entry is the contents of a different group of curly braces. Note that this will not work for nested braces. The `?` after the `.+` will make it a lazy match (as opposed to greedy). This means that the match will stop at the ...
Python builtin "all" with generators
7,491,951
5
2011-09-20T21:21:51Z
7,492,031
7
2011-09-20T21:30:45Z
[ "python", "numpy" ]
I have the following problem with python's "all" and generators: ``` G = (a for a in [0,1]) all(list(G)) # returns False - as I expected ``` But: ``` G = (a for a in [0,1]) all(G) # returns True! ``` Can anybody explain that? UPDATE: I swear I get this! Check this out: ``` In [1]: G = (a for a in [0,1])...
No, it doesn't. The following snippet returns False ``` G = (a for a in [0,1]) all(G) # returns False ``` Are you perhaps doing the following ``` G = (a for a in [0,1]) all(list(G)) # returns False all(G) # returns True! ``` In that case, you are exhausting the generator `G` when you construct the...
Python builtin "all" with generators
7,491,951
5
2011-09-20T21:21:51Z
7,493,265
11
2011-09-21T00:16:07Z
[ "python", "numpy" ]
I have the following problem with python's "all" and generators: ``` G = (a for a in [0,1]) all(list(G)) # returns False - as I expected ``` But: ``` G = (a for a in [0,1]) all(G) # returns True! ``` Can anybody explain that? UPDATE: I swear I get this! Check this out: ``` In [1]: G = (a for a in [0,1])...
Aha! Does Python(x,y) happen to import numpy? [It looks like it.] ``` Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> >>> >>> G = (a for a in [0,1]) >>> all(G) False >>> from n...
Python class decorator arguments
7,492,068
8
2011-09-20T21:34:06Z
7,492,124
9
2011-09-20T21:41:01Z
[ "python", "arguments", "decorator" ]
I'm trying to pass optional arguments to my class decorator in python. Below the code I currently have: ``` class Cache(object): def __init__(self, function, max_hits=10, timeout=5): self.function = function self.max_hits = max_hits self.timeout = timeout self.cache = {} def __...
`@Cache(max_hits=100, timeout=50)` calls `__init__(max_hits=100, timeout=50)`, so you aren't satisfying the `function` argument. You could implement your decorator via a wrapper method that detected whether a function was present. If it finds a function, it can return the Cache object. Otherwise, it can return a wrapp...
Python class decorator arguments
7,492,068
8
2011-09-20T21:34:06Z
7,492,150
10
2011-09-20T21:42:29Z
[ "python", "arguments", "decorator" ]
I'm trying to pass optional arguments to my class decorator in python. Below the code I currently have: ``` class Cache(object): def __init__(self, function, max_hits=10, timeout=5): self.function = function self.max_hits = max_hits self.timeout = timeout self.cache = {} def __...
``` @Cache def double(...): ... ``` is equivalent to ``` def double(...): ... double=Cache(double) ``` While ``` @Cache(max_hits=100, timeout=50) def double(...): ... ``` is equivalent to ``` def double(...): ... double = Cache(max_hits=100, timeout=50)(double) ``` `Cache(max_hits=100, timeout=50)(...
MongoEngine User authentication (django)
7,492,775
8
2011-09-20T22:57:27Z
7,494,578
9
2011-09-21T04:22:28Z
[ "python", "django", "authentication", "mongoengine" ]
I am trying to use MongoEngine in a django project I am writing. I am having difficulty getting (or understanding how) the authentication backend works. The user object as far as I can tell is not stored in the request. I have it working but I am not sure if I am doing it in the right/safe way. If someone could look ...
Not sure if you are seeing any issues because you make no mention of any but I use mongoengine for my auth backend and this is how I would handle it: ``` from django.contrib.auth import login, User from mongoengine.queryset import DoesNotExist def login_view(request): try: user = User.objects.get(username...
try/except in list comprehension
7,493,220
2
2011-09-21T00:06:59Z
7,493,249
9
2011-09-21T00:11:48Z
[ "python", "django" ]
Is it possible to convert the following into a list comprehension? ``` cleaned_list = [] for item in dirtry_list: try: item.video except Video.DoesNotExist: pass else: cleaned_list.append(item) ```
You cannot put a `try:`statement in a list comprehension. [Generators](http://docs.python.org/tutorial/classes.html#generators) exist for more complex list processing: ``` def clean(lst): for item in lst: try: item.video except Video.DoesNotExist: pass else: ...
try/except in list comprehension
7,493,220
2
2011-09-21T00:06:59Z
7,493,269
9
2011-09-21T00:16:42Z
[ "python", "django" ]
Is it possible to convert the following into a list comprehension? ``` cleaned_list = [] for item in dirtry_list: try: item.video except Video.DoesNotExist: pass else: cleaned_list.append(item) ```
Since, based on your other questions, you're using Django, just check the [actual field](https://docs.djangoproject.com/en/dev/ref/models/fields/#database-representation). ``` cleaned_list = [item for item in dirty_list if item.video_id is not None] ```
How to iterate over Unicode characters in Python 3?
7,494,064
12
2011-09-21T02:53:38Z
7,495,204
7
2011-09-21T05:58:35Z
[ "python", "unicode", "python-3.x" ]
I need to step through a Python string one character at a time, but a simple "for" loop gives me UTF-16 code units instead: ``` str = "abc\u20ac\U00010302\U0010fffd" for ch in str: code = ord(ch) print("U+{:04X}".format(code)) ``` That prints: ``` U+0061 U+0062 U+0063 U+20AC U+D800 U+DF02 U+DBFF U+DFFD ``` ...
On Python 3.2.1 with narrow Unicode build: ``` PythonWin 3.2.1 (default, Jul 10 2011, 21:51:15) [MSC v.1500 32 bit (Intel)] on win32. Portions Copyright 1994-2008 Mark Hammond - see 'Help/About PythonWin' for further copyright information. >>> import sys >>> sys.maxunicode 65535 ``` What you've discovered (UTF-16 enc...
Python (CherryPy) web app deployed locally, but not visible over intranet
7,494,171
13
2011-09-21T03:11:48Z
7,494,745
17
2011-09-21T04:48:57Z
[ "python", "cherrypy", "intranet" ]
I've created a Python web app using CherryPy, and have deployed in on my local machine. When I try to view it from another computer in the house, nothing comes back. However, if I create a simple html file, and deploy it with: ``` $ python -m SimpleHTTPServer ``` It is visible over the intranet. I'm stumped as to ...
The default settings likely bind to localhost, which is not publicly available. If you want CherryPy to run on a public interface, you'll have to direct it to do that. From [this discussion](http://groups.google.com/group/cherrypy-users/browse_thread/thread/66c2a3e0baef9a48) I found: ``` cherrypy.config.update( {'...
Gettext : How to update po and pot files after the source is modified
7,496,156
8
2011-09-21T07:34:23Z
7,497,395
10
2011-09-21T09:17:54Z
[ "python", "gettext", "xgettext" ]
I've got a python project with internationalized strings. I've modified the source codes and the lines of the strings are changed, i.e. in pot and po files lines of he strings are not pointing to correct lines. So how to update the po and pot files to new string locations in files.
You could have a look to [this script](http://www.lxg.de/code/playing-with-xgettext) to update your po files with new code. It use [xgettext](http://www.gnu.org/software/hello/manual/gettext/xgettext-Invocation.html) and [msgmerge](http://www.gnu.org/software/hello/manual/gettext/msgmerge-Invocation.html). ``` echo ''...
Does Python SciPy need BLAS?
7,496,547
161
2011-09-21T08:11:54Z
8,470,124
41
2011-12-12T04:58:49Z
[ "python", "scipy" ]
``` numpy.distutils.system_info.BlasNotFoundError: Blas (http://www.netlib.org/blas/) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [blas]) or by setting the BLAS environment variable. ``` Which tar do I need to download off...
I guess you are talking about installation in Ubuntu. Just use: ``` apt-get install python-numpy python-scipy ``` That should take care of the BLAS libraries compiling as well. Else, compiling the BLAS libraries is very difficult.
Does Python SciPy need BLAS?
7,496,547
161
2011-09-21T08:11:54Z
9,173,550
132
2012-02-07T09:08:31Z
[ "python", "scipy" ]
``` numpy.distutils.system_info.BlasNotFoundError: Blas (http://www.netlib.org/blas/) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [blas]) or by setting the BLAS environment variable. ``` Which tar do I need to download off...
The [SciPy webpage](http://www.scipy.org/Installing_SciPy/BuildingGeneral) used to provide build and installation instructions, but the instructions there now rely on OS binary distributions. To build SciPy (and NumPy) on operating systems without precompiled packages of the required libraries, you must build and then ...
Does Python SciPy need BLAS?
7,496,547
161
2011-09-21T08:11:54Z
14,541,175
304
2013-01-26T20:18:02Z
[ "python", "scipy" ]
``` numpy.distutils.system_info.BlasNotFoundError: Blas (http://www.netlib.org/blas/) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [blas]) or by setting the BLAS environment variable. ``` Which tar do I need to download off...
If you need to use the latest versions of SciPy rather than the packaged version, without going through the hassle of building BLAS and LAPACK, you can follow the below procedure. Install linear algebra libraries from repository (for Ubuntu), ``` sudo apt-get install gfortran libopenblas-dev liblapack-dev ``` Then i...
Does Python SciPy need BLAS?
7,496,547
161
2011-09-21T08:11:54Z
15,286,438
64
2013-03-08T03:56:59Z
[ "python", "scipy" ]
``` numpy.distutils.system_info.BlasNotFoundError: Blas (http://www.netlib.org/blas/) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [blas]) or by setting the BLAS environment variable. ``` Which tar do I need to download off...
On Fedora, this works: ``` yum install lapack lapack-devel blas blas-devel pip install numpy pip install scipy ``` Remember to install '**lapack-devel**' and '**blas-devel**' in addition to 'blas' and 'lapack' otherwise you'll get the error you mentioned or the "numpy.distutils.system\_info.**LapackNotFoundError**...
Does Python SciPy need BLAS?
7,496,547
161
2011-09-21T08:11:54Z
24,700,640
10
2014-07-11T14:53:46Z
[ "python", "scipy" ]
``` numpy.distutils.system_info.BlasNotFoundError: Blas (http://www.netlib.org/blas/) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [blas]) or by setting the BLAS environment variable. ``` Which tar do I need to download off...
For Windows users there is a nice binary package by Chris (warning: it's a pretty large download, 191 MB): * <http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy-stack>
How to find all groups in a list in python?
7,498,335
4
2011-09-21T10:36:09Z
7,498,355
8
2011-09-21T10:37:34Z
[ "python", "list", "group" ]
I have a list like this [0,0,1,1,1,0,0,0,1,1,0,0,1,1,1,1] and I want to group them and then find the length of each group.So the result will be like that :[[2,0],[3,1].....[4,1]].Any help is appreciated.Thanks.
Use [`itertools.groupby`](http://docs.python.org/library/itertools.html#itertools.groupby): ``` >>> import itertools >>> l = [0,0,1,1,1,0,0,0,1,1,0,0,1,1,1,1] >>> [(len(list(g)), k) for k,g in itertools.groupby(l)] [(2, 0), (3, 1), (3, 0), (2, 1), (2, 0), (4, 1)] ```
Python argparse - Add argument to multiple subparsers
7,498,595
28
2011-09-21T10:59:45Z
7,498,853
34
2011-09-21T11:19:20Z
[ "python", "argparse" ]
My script defines one main parser and multiple subparsers. I want to apply the `-p` argument to some subparsers. So far the code looks like this: ``` parser = argparse.ArgumentParser(prog="myProg") subparsers = parser.add_subparsers(title="actions") parser.add_argument("-v", "--verbose", action="s...
This can be achieved by defining a [parent parser](http://docs.python.org/library/argparse.html#parents) containing the common option(s): ``` [...] parent_parser = argparse.ArgumentParser(add_help=False) parent_parser.add_argument("-p", type=int, required=True, help="set db parameter") parse...
Thrift : TypeError: getaddrinfo() argument 1 must be string or None
7,500,409
7
2011-09-21T13:17:47Z
7,500,838
16
2011-09-21T13:46:42Z
[ "python", "thrift" ]
Hi I am trying to write a simple thrift server in python (named PythonServer.py) with a single method that returns a string for learning purposes. The server code is below. I am having the following errors in the Thrift's python libraries when I run the server. Has anyone experienced this problem and suggest a workarou...
Your problem seems to be related to this [tutorial error report](http://www.apacheserver.net/an-error-in-tutorial-py-PythonServer-py-at1279173.htm) From that report alone, my guess is your problem is the line: ``` transport = TSocket.TServerSocket(port) ``` When calling `TSocket.TServerSocket` which a single argumen...
Python array of datetime objects from numpy ndarray
7,500,864
2
2011-09-21T13:48:49Z
7,501,549
7
2011-09-21T14:29:14Z
[ "python", "datetime", "numpy" ]
I have numpy ndarray which contains two columns: one is date, e.g. 2011-08-04, another one is time, e.g. 19:00:00:081. How can I combine them into one array of datetime objects? Currently, they're strings in numpy array.
If the date and time string in the [example.txt](http://pastebin.com/CTwwPPKA) data file were given as one column with no separating whitespace, then `genfromtxt` could convert it into a datetime object like this: ``` import numpy as np import datetime as dt def mkdate(text): return dt.datetime.strptime(text, '%Y-...
MongoDB not that faster than MySQL?
7,501,100
7
2011-09-21T14:00:53Z
7,501,739
27
2011-09-21T14:41:50Z
[ "python", "mysql", "mongodb" ]
I discovered mongodb some months ago,and after reading this [post](http://www.vedana.it/it/component/content/article/9-linux/62-testing-mongodb-vs-mysql-with-python-scripting-under-linux), I thought mongodb was really faster than mysql, so I decided to build my own bench, the problem is that I do not have the same resu...
Sigh. These kind of benchmarks, and I use the term loosely in this case, usually break down from the very start. MySQL isn't a "slower" database than MongoDB. One is a relational database, the other a NoSQL document store. They will/should be faster in the functional areas that they were designed to cover. In the case ...
cPickle - different results pickling the same object
7,501,577
8
2011-09-21T14:30:57Z
7,501,980
8
2011-09-21T14:57:37Z
[ "python", "serialization", "pickle" ]
Is anyone able to explain the comment under `testLookups()` in this **[code snippet](https://github.com/shrubberysoft/django-picklefield/blob/master/src/picklefield/tests.py)**? I've run the code and indeed what the comment sais is true. However I'd like to understand why it's true, i.e. why is cPickle outputting diff...
There is no guarantee that seemingly identical objects will produce identical pickle strings. The pickle protocol is a virtual machine, and a pickle string is a program for that virtual machine. For a given object there exist multiple pickle strings (=programs) that will reconstruct that object exactly. To take one o...
Python re.split() vs split()
7,501,609
7
2011-09-21T14:33:32Z
7,501,659
12
2011-09-21T14:36:03Z
[ "python", "regex" ]
In my quests of optimization, I discovered that that built-in split() method is about 40% faster that the re.split() equivalent. A dummy benchmark (easily copy-pasteable): ``` import re, time, random def random_string(_len): letters = "ABC" return "".join([letters[random.randint(0,len(letters)-1)] for i in ...
`re.split` is **expected** to be slower, as the usage of regular expressions incurs some overhead. Of course if you are splitting on a constant string, there is no point in using `re.split()`.
Python: How do I pass variables between class instances or get the caller?
7,501,706
5
2011-09-21T14:39:17Z
10,818,515
11
2012-05-30T14:38:10Z
[ "python", "variables", "instance" ]
``` class foo(): def __init__(self) self.var1 = 1 class bar(): def __init__(self): print "foo var1" f = foo() b = bar() ``` In foo, I am doing something that produces "var1" being set to 1 In bar, I would like to access the contents of var1 How can I access var1 in the class instance f of foo from withi...
As a general way for different pages in wxPython to access and edit the same information consider creating an instance of info class in your MainFrame (or whatever you've called it) class and then passing that instance onto any other pages it creates. For example: ``` class info(): def __init__(self): self...
Understanding Pickling in Python
7,501,947
10
2011-09-21T14:55:14Z
7,502,003
7
2011-09-21T14:58:52Z
[ "python", "pickle", "python-2.7" ]
I have recently got an assignment where I need to put a dictionary (where each key refers to a list) in pickled form. The only problem is I have no idea what pickled form is. Could anyone point me in the right direction of some good resources to help me learn this concept? Thanks!
Pickling is just serialization: putting data into a form that can be stored in a file and retrieved later. Here are the docs on the `pickle` module: <http://docs.python.org/release/2.7/library/pickle.html>
Understanding Pickling in Python
7,501,947
10
2011-09-21T14:55:14Z
7,502,013
24
2011-09-21T14:59:14Z
[ "python", "pickle", "python-2.7" ]
I have recently got an assignment where I need to put a dictionary (where each key refers to a list) in pickled form. The only problem is I have no idea what pickled form is. Could anyone point me in the right direction of some good resources to help me learn this concept? Thanks!
The pickle module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure. **Pickling -** is the process whereby a Python object hierarchy is converted into a byte stream, and **Unpickling -** is the inverse operation, whereby a byte stream is converted back into a...
Understanding Pickling in Python
7,501,947
10
2011-09-21T14:55:14Z
7,502,056
7
2011-09-21T15:02:37Z
[ "python", "pickle", "python-2.7" ]
I have recently got an assignment where I need to put a dictionary (where each key refers to a list) in pickled form. The only problem is I have no idea what pickled form is. Could anyone point me in the right direction of some good resources to help me learn this concept? Thanks!
While others have pointed to the Python documentation on the pickle module, which is a great resource, you can also check out [Chapter 13: Serializing Python Objects](http://www.diveinto.org/python3/serializing.html) of *Dive Into Python 3* by Mark Pilgrim.
django models selecting single field
7,503,241
28
2011-09-21T16:26:20Z
7,503,368
49
2011-09-21T16:35:38Z
[ "python", "django", "django-models" ]
I have a table/models called `Employees` and I would like to get all rows of a single field as a queryset. I know I can do it like this (hope I'm doing this right even): ``` emp_list = Employees.objects.get(all) emp_names = emp_list.eng_name ``` Would query the database for all fields and using only one? Is there a ...
``` Employees.objects.values_list('eng_name', flat=True) ``` That creates a flat list of all `eng_name`s. If you want more than one field per row, you can't do a flat list: this will create a list of lists: ``` Employees.objects.values_list('eng_name', 'rank') ```
Save .dta files in python
7,503,487
10
2011-09-21T16:42:56Z
9,056,030
7
2012-01-29T19:24:57Z
[ "python", "numpy", "stata" ]
I'm wondering if anyone knows a Python package that allows you to save numpy arrays/recarrays in the `.dta` format of the statistical data analysis software Stata. This would really speed up a few steps in a system I have.
The [scikits.statsmodels](http://statsmodels.sourceforge.net/) package includes a reader for Stata data files, which relies in part on PyDTA as pointed out by @Sven. In particular, `genfromdta()` will return an `ndarray`, e.g. from Python 2.7/statsmodels 0.3.1: ``` >>> import scikits.statsmodels.api as sm >>> arr = sm...
Python, how i can get gif frames
7,503,567
5
2011-09-21T16:49:41Z
7,504,131
9
2011-09-21T17:37:44Z
[ "python", "frame" ]
I am looking some kind method to get gif frames number. i am looking on google, stackoverflow and any outher sites and i find only rubbish!! Someone know how to do it? i need only simple number of gif frames.
Which method are you using to load/manipulate the frame? Are you using PIL? If not, I suggest checking it out: [Python Imaging Library](http://www.pythonware.com/products/pil/) and specifically [the PIL gif page](http://www.pythonware.com/library/pil/handbook/format-gif.htm). Now, assuming you are using PIL to read in...
Python, how i can get gif frames
7,503,567
5
2011-09-21T16:49:41Z
7,506,880
11
2011-09-21T21:27:13Z
[ "python", "frame" ]
I am looking some kind method to get gif frames number. i am looking on google, stackoverflow and any outher sites and i find only rubbish!! Someone know how to do it? i need only simple number of gif frames.
Just parse the file, gifs are pretty simple: ``` class GIFError(Exception): pass def get_gif_num_frames(filename): frames = 0 with open(filename, 'rb') as f: if f.read(6) not in ('GIF87a', 'GIF89a'): raise GIFError('not a valid GIF file') f.seek(4, 1) def skip_color_table(f...
Submodule importing primary module
7,503,748
5
2011-09-21T17:05:31Z
7,504,209
7
2011-09-21T17:44:14Z
[ "python", "import", "module" ]
First of all, my apologies if this question has already be asked elsewhere. I really searched for it, but didn't find anything. The situation is the following: In a folder `mod`, I have the files `__init__.py` and `sub.py`. They contain the following data: `__init__.py`: ``` print "mod" ``` `sub.py`: ``` import __i...
You can actually inspect what is going on by using the dictionary `sys.modules`. Python decides to reload a module depending on the keys in that dictionary. When you run `import mod`, it creates one entry, `mod` in `sys.modules`. When you run `import mod.sub`, after the call to `import __init__`, Python checks whethe...
python salesforce library to get salesforce data?
7,504,057
7
2011-09-21T17:32:16Z
7,504,244
12
2011-09-21T17:46:29Z
[ "python", "salesforce" ]
Is there a library or package which we can use with python to connect to salesforce and get data?
I use [beatbox](http://code.google.com/p/salesforce-beatbox/) Example to query for a lead by email address ``` import beatbox sf_username = "Username" sf_password = "password" sf_api_token = "api token" def get_lead_records_by_email(email) sf_client = beatbox.PythonClient() password = str("%s%s" % (sf_pa...
Query Python dictionary to get value from tuple
7,504,081
5
2011-09-21T17:33:47Z
7,504,123
7
2011-09-21T17:37:05Z
[ "python", "dictionary", "tuples" ]
Let's say that I have a Python dictionary, but the values are a tuple: E.g. ``` dict = {"Key1": (ValX1, ValY1, ValZ1), "Key2": (ValX2, ValY2, ValZ2),...,"Key99": (ValX99, ValY99, ValY99)} ``` and I want to retrieve only the third value from the tuple, eg. ValZ1, ValZ2, or ValZ99 from the example above. I could do s...
Just keep indexing: ``` >>> D = {"Key1": (1,2,3), "Key2": (4,5,6)} >>> D["Key2"][2] 6 ```
Why does SciPy return negative p-values for extremely small p-values with the Fisher-exact test?
7,504,198
8
2011-09-21T17:43:18Z
7,504,381
10
2011-09-21T17:56:45Z
[ "python", "statistics", "scipy" ]
I've noticed that the Fisher-exact test in SciPy returns a negative p-value if the p-value is extrememly small: ``` >>> import scipy as sp >>> import scipy.stats >>> x = [[48,60],[3088,17134]] >>> sp.stats.fisher_exact(x) (4.4388601036269426, -1.5673906617053035e-11) ``` In R, using the same 2x2 contingency table: `...
Fisher's exact test uses the hypergeometric distribution. The version of scipy you are using uses an implementation of the hypergeometric distribution that is not very precise. This is a [known problem](https://github.com/scipy/scipy/issues/1926) and has been fixed in the scipy repository.
catch wrong-arguments exception, in the general case
7,504,569
4
2011-09-21T18:11:46Z
7,504,697
7
2011-09-21T18:22:34Z
[ "python", "exception", "try-catch", "decorator" ]
I want to catch an exception, but only if it comes from the very next level of logic. The intent is to handle errors caused by the act of calling the function with the wrong number of arguments, without masking errors generated by the function implementation. How can I implement the `wrong_arguments` function below? ...
You can do: ``` try: myfunc() except IndexError: trace = sys.exc_info()[2] if trace.tb_next.tb_next is None: pass else: raise ``` Although it is kinda ugly and would seem to violate encapsulation. Stylistically, wanting to catch having passed too many a...
Relations on composite keys using sqlalchemy
7,504,753
26
2011-09-21T18:27:28Z
7,506,168
44
2011-09-21T20:24:51Z
[ "python", "sqlalchemy", "key", "composite", "database-relations" ]
I have this simple model of Author - Books and can't find a way to make firstName and lastName a composite key and use it in relation. Any ideas? ``` from sqlalchemy import create_engine, ForeignKey, Column, String, Integer from sqlalchemy.orm import relationship, sessionmaker from sqlalchemy.ext.declarative import de...
The problem is that you have defined each of the dependent columns as foreign keys separately, when that's not really what you intend, you of course want a composite foreign key. Sqlalchemy is responding to this by saying (in a not very clear way), that it cannot guess which foreign key to use (`firstName` or `lastName...
Celery-Django: Unable to execute tasks asynchronously
7,505,846
4
2011-09-21T19:54:55Z
7,861,609
8
2011-10-22T18:12:27Z
[ "python", "django", "celery" ]
I'm trying to run some tasks in the background while users browse my site, but whenever I call a function using Celery it seems to be executed synchronously instead of asynchronously. e.g., when I call function.delay() the entire site hangs until function.delay() returns. Other methods of calling functions in a simila...
Try removing ``` CELERY_ALWAYS_EAGER = True ``` You are explicitly asking celery to execute tasks synchronously. It'll always wait for the result. This setting is useful for writing unit tests etc. Read <http://ask.github.com/celery/configuration.html>
Importing from a relative path in Python
7,505,988
30
2011-09-21T20:09:36Z
7,506,029
42
2011-09-21T20:13:20Z
[ "python", "import", "python-3.x", "relative-path" ]
I have a folder for my client code, a folder for my server code, and a folder for code that is shared between them ``` Proj/ Client/ Client.py Server/ Server.py Common/ __init__.py Common.py ``` How do I import Common.py from Server.py and Client.py?
# EDIT Nov 2014 (3 years later): Python 2.6 and 3.x supports proper relative imports, where you can avoid doing anything hacky. With this method, you know you are getting a *relative* import rather than an *absolute* import. The '..' means, go to the directory above me: ``` from ..Common import Common ``` As a cavea...
Checking for unique output in Python
7,506,264
3
2011-09-21T20:33:08Z
7,506,336
8
2011-09-21T20:40:02Z
[ "python", "puzzle" ]
I came across a fun math problem yesterday and have it solved, but with the code I wrote, I had to do a keyboard interrupt or it would run forever, lol. So I changed it to have an end condition, **but now it only prints 1 solution and stops.** The problem goes like this: "You have the numbers 123456789, in that order....
Don't use random, enumerate all possible operator combinations (well, you can cut the search space a bit, if the first couple of numbers the result is larger than 2002, there is no way the result is going to be smaller). `itertools` is your friend. If you do that, your program will finish in no time. If you know that...
Add a method to a list instance in python
7,507,350
8
2011-09-21T22:15:11Z
7,507,385
10
2011-09-21T22:18:30Z
[ "python" ]
I want to add a method to a single instance of the 'list' class. Example: ``` a = [1,2] a.first = lambda self: return self[0] ``` I know this don't work, but I want something like that works like that. I know its not a good practice, and I know I should do a whole new class, but I think this is possible in Python and...
Nothing will work with a native list, since you cannot add methods to a type defined in C. You will need to derive from `list` and add your method to that class.
Is "backporting" Python 3's `range` to Python 2 a bad idea?
7,507,492
10
2011-09-21T22:29:53Z
7,507,528
7
2011-09-21T22:33:41Z
[ "python", "python-3.x", "python-2.x" ]
One of my classes requires assignments to be completed in Python, and as an exercise, I've been making sure my programs work in both Python 2 and Python 3, using a script like this: ``` #!/bin/bash # Run some PyUnit tests python2 test.py python3 test.py ``` One thing I've been doing is making `range` work the same in...
What you probably *should* be doing is making sure it works cleanly under 2.x, and then passing it through [`2to3`](http://docs.python.org/library/2to3.html) and verifying that the result works cleanly in 3.x. That way you won't have to go through hoops such as redefining `range` as you have already done.
Is "backporting" Python 3's `range` to Python 2 a bad idea?
7,507,492
10
2011-09-21T22:29:53Z
7,508,589
8
2011-09-22T01:34:28Z
[ "python", "python-3.x", "python-2.x" ]
One of my classes requires assignments to be completed in Python, and as an exercise, I've been making sure my programs work in both Python 2 and Python 3, using a script like this: ``` #!/bin/bash # Run some PyUnit tests python2 test.py python3 test.py ``` One thing I've been doing is making `range` work the same in...
You can use the [six](http://pypi.python.org/pypi/six/) package which provides a Python 2 and 3 compatibility library and written by one of the Python core developers. Among its features is a set of standard definitions for renamed modules and functions, including `xrange` -> `range`. The use of `six` is one of many re...
python: complete example of dict for logging.config.dictConfig?
7,507,825
38
2011-09-21T23:11:37Z
7,507,842
72
2011-09-21T23:15:23Z
[ "python", "logging" ]
I'd like to use [dictConfig](http://docs.python.org/library/logging.config.html#logging.config.dictConfig), but the documentation is a little bit abstract. Where can I find a concrete, copy+paste-able example of the dictionary used with `dictConfig`?
How about here! ``` { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s' }, }, 'handlers': { 'default': { 'level': 'INFO', 'formatter': 'standar...
Utility To Count Number Of Lines Of Code In Python Or Bash
7,507,846
11
2011-09-21T23:16:02Z
7,507,940
32
2011-09-21T23:34:26Z
[ "python", "bash", "lines-of-code" ]
Is there a quick and dirty way in either python or bash script, that can recursively descend a directory and count the total number of lines of code? We would like to be able to exclude certain directories though. For example: ``` start at: /apps/projects/reallycoolapp exclude: lib/, frameworks/ ``` The excluded dir...
Found an awesome utility CLOC. <https://github.com/AlDanial/cloc> Here is the command we ran: ``` perl cloc.pl /apps/projects/reallycoolapp --exclude-dir=lib,frameworks ``` And here is the output ``` -------------------------------------------------------------------------------- Language files...
Utility To Count Number Of Lines Of Code In Python Or Bash
7,507,846
11
2011-09-21T23:16:02Z
7,509,900
9
2011-09-22T05:25:35Z
[ "python", "bash", "lines-of-code" ]
Is there a quick and dirty way in either python or bash script, that can recursively descend a directory and count the total number of lines of code? We would like to be able to exclude certain directories though. For example: ``` start at: /apps/projects/reallycoolapp exclude: lib/, frameworks/ ``` The excluded dir...
The `find` and `wc` arguments alone can solve your problem. With `find` you can specify very complex logic like this: ``` find /apps/projects/reallycoolapp -type f -iname '*.py' ! -path '*/lib/*' ! -path '*/frameworks/*' | xargs wc -l ``` Here the `!` invert the condition so this command will count the lines for eac...
Could not call install_name_tool
7,508,109
3
2011-09-22T00:04:22Z
9,729,140
10
2012-03-15T22:29:19Z
[ "python", "xcode", "virtualenv" ]
Trying to use virutalenv version 1.6.4 (the latest at writing this post) on 10.7, Lion with yes Xcode 4 installed from mac app store, yet i'm getting the below error message: ``` New python executable in SUPENV/bin/python Error [Errno 2] No such file or directory while executing command install_name_tool -change /Syst...
You need to both install XCode, run it, and select the optional "command line tools" package and then install those. In more detail: * Download XCode from the App Store * Run the downloaded XCode binary from Applications or Launchpad * Select XCode->Preferences, then choose the "Downloads" tab * Click on the "Command ...
How to multiply a scalar throughout a specific column within a NumPy array?
7,508,638
8
2011-09-22T01:43:51Z
7,508,703
9
2011-09-22T01:53:57Z
[ "python", "arrays", "numpy", "multidimensional-array" ]
I need to do some analysis on a large dataset from a hydrolgeology field work. I am using NumPy. I want to know how I can: 1. multiply e.g. the 2nd column of my array by a number (e.g. 5.2). And then 2. calculate the cumulative sum of the numbers in that column. As I mentioned I only want to work on a specific column...
``` you can do this in two simple steps using NumPy: >>> # multiply column 2 of the 2D array, A, by 5.2 >>> A[:,1] *= 5.2 >>> # assuming by 'cumulative sum' you meant the 'reduced' sum: >>> A[:,1].sum() >>> # if in fact you want the cumulative sum (ie, returns a new column) >>> # then do this for the second step in...
How do I import function from .pyx file in python?
7,508,803
4
2011-09-22T02:07:57Z
7,508,826
9
2011-09-22T02:11:10Z
[ "python", "cython" ]
I'm trying to run Hadoopy, which has a file \_main.pyx, and `import _main` is failing with module not found in \_\_init\_\_.py. I'm trying to run this on OS X w/ standard python 2.7.
Add this code before you try to import `_main`: ``` import pyximport pyximport.install() ``` Note that `pyximport` is part of [Cython](http://www.cython.org/), so you'll have to install that if it isn't already.
How to break out of the loop only if a certain case is met, but then continue the iteration?
7,509,211
4
2011-09-22T03:23:52Z
7,509,233
7
2011-09-22T03:26:30Z
[ "python" ]
I realize that the title may be somewhat confusing, so I apologize. Basically, this is my code: ``` while i < 5: do stuff if i == 3: print "i is 3" break ``` Now all that sounds pretty simple, right? Except I don't really want to BREAK from the loop as much as I'd want it to start over again. So in...
``` while i < 5: do stuff if i == 3: print "i is 3" continue ```
How do I change the django-registration e-mail template "site" name?
7,509,962
3
2011-09-22T05:33:44Z
7,510,206
11
2011-09-22T06:02:28Z
[ "python", "django" ]
The current setup ends up substituting example.com into the below code from the template. I want it to point to localhost:8000 Without hard coding this, where and how can I change the template so that the site is linked to my localhost? Thank you for registering an account at {{ site.domain }}. To activate your regis...
The `site` object in the template comes from the Django Site model. When you do a `syncdb`, it defaults automatically to `example.com` If you login to Django's admin interface, you will find "Sites". Inside it, you will be able to change `example.com` to whatever you like. ![enter image description here](http://i.sta...
Python how to check if variable exist and its length, in one if statement?
7,510,038
5
2011-09-22T05:44:11Z
7,510,056
10
2011-09-22T05:46:27Z
[ "python", "if-statement" ]
Here's my situation: ``` if var: if len(var) == 5: do something... else: do the same thing... ``` To avoid repeating the same piece of code, I would like to combine those 2 if conditions, in one. But if var is None, I can't check its length... Any idea? I would like something like this: ``` if var an...
Did you try that? It works: ``` if var and len(var) == 5: .... ``` The `and` operator doesn't evaluate the RHS if the LHS is false. Try this: ``` >>> False and 1/0 False >>> True and 1/0 ZeroDivisionError: division by zero ```
Transparent PNG in PIL turns out not to be transparent
7,510,313
15
2011-09-22T06:12:31Z
7,512,489
26
2011-09-22T09:25:32Z
[ "python", "png", "python-imaging-library", "transparent" ]
I have been hitting my head against the wall for a while with this, so maybe someone out there can help. I'm using PIL to open a PNG with transparent background and some random black scribbles, and trying to put it on top of another PNG (with no transparency), then save it to a third file. It comes out all black at t...
I think what you want to use is the paste mask argument. see the [docs](http://effbot.org/imagingbook/image.htm), (scroll down to `paste`) ``` from PIL import Image img = Image.open(basefile) layer = Image.open(layerfile) # this file is the transparent one print layer.mode # RGBA img.paste(layer, (xoff, yoff), mask=la...
django how to display users full name in FilteredSelectMultiple
7,510,849
4
2011-09-22T07:05:43Z
13,213,007
10
2012-11-03T20:05:57Z
[ "python", "django" ]
i am trying to use FilteredSelectMultiple widget to display list of users. currently it is displaying only username. I have tried to override the label\_from\_instance as seen below but it does not seem to work. how can it get to display users full name. ``` class UserMultipleChoiceField(FilteredSelectMultiple): "...
The simplest solution is to put the following in a **models.py** where `django.contrib.auth.models.User` is imported: ``` def user_unicode_patch(self): return '%s %s' % (self.first_name, self.last_name) User.__unicode__ = user_unicode_patch ``` This will overwrite the `User` model's `__unicode__()` method with a...
How to get key value in django template?
7,511,405
9
2011-09-22T07:53:50Z
7,511,510
23
2011-09-22T08:02:44Z
[ "python", "django" ]
Django template system - how to get python dictionary value from key? I have two dictionaries which represent different data but both have same key so that I am able to access different data from the same key. First dict is: ``` {**'Papa, Joey C'**: {'Office Visit Est Pt Level 3 (99213)': 32, 'LAP VENTABD HERNIA RE...
``` mydict = {'Papa, Joey C': {'10140': 1, '10061': 1, '99214': 1, '99215': 1, '12011': 1, '97606': 1, '49080': 1, '10120': 1, '49440': 1, '49570': 1}, 'Bull, Sherman M': {'99211': 1, '99214': 1, '99215': 1, '99231': 1, '99236': 1, '12051': 1, '15004':1, '47100': 1, '15430': 1, '15431': 1}} {% for mykey,myvalue in myd...
Weighted logistic regression in Python
7,513,067
14
2011-09-22T10:08:33Z
14,854,419
15
2013-02-13T13:12:46Z
[ "python", "regression" ]
I'm looking for a good implementation for logistic regression (not regularized) in Python. I'm looking for a package that can also get weights for each vector. Can anyone suggest a good implementation / package? Thanks!
I notice that this question is quite old now but hopefully this can help someone. With sklearn, you can use the SGDClassifier class to create a logistic regression model by simply passing in 'log' as the loss: ``` sklearn.linear_model.SGDClassifier(loss='log', ...). ``` This class implements weighted samples in the `...
matplotlib large set of colors for plots
7,513,262
16
2011-09-22T10:23:43Z
7,513,401
21
2011-09-22T10:35:45Z
[ "python", "plot", "matplotlib" ]
I have a lot of graphs I want to plot in one plot. I've just started with matplotlib and can't find a good way to generate a lot of distinguishable colors :( Maybe cycling over HSV with SV at maximum? I'm thinking of something like ``` args=[] for i,(x,y) in enumerate(data): args.extend([x,y,hsv(i)]) plot(*args) ...
I think you have the right idea, except that the colors will be more distinguishable if you pass the colormap `hsv` numbers which are spread out over the range (0,1): ``` hsv = plt.get_cmap('hsv') hsv(float(i)/(len(data)-1)) ``` or, using NumPy: ``` colors = hsv(np.linspace(0, 1.0, len(kinds))) ``` For example: ``...
lambda function don't closure the parameter in Python?
7,514,093
6
2011-09-22T11:35:38Z
7,514,158
9
2011-09-22T11:41:08Z
[ "python", "lambda" ]
Code talks more: ``` from pprint import pprint li = [] for i in range(5): li.append(lambda : pprint(i)) for k in li: k() ``` yield: ``` 4 4 4 4 4 ``` why not ``` 0 1 2 3 4 ``` ?? Thanks. P.S. If I write the complete decorator, it works as expected: ``` from pprint import pprint li = [] #fo...
you need to do: ``` lambda i=i: pprint(i) ``` instead to capture the current value of `i`
Generate audio bell in terminal using Python
7,514,925
7
2011-09-22T12:46:09Z
7,514,983
14
2011-09-22T12:50:27Z
[ "python", "xterm" ]
How can I generate audio bell in `xterm` type terminal?
Simple, print the [bell character](http://en.wikipedia.org/wiki/Bell_character). In Python: ``` print('\a') ``` From [bash shell](http://www.gnu.org/s/bash/manual/bash.html#ANSI_002dC-Quoting): ``` echo $'\a' ``` Note that on some terminals, the bell can be disabled. In others, the bell can be replaced with a visua...
Django - how to create a file and save it to a model's FileField?
7,514,964
45
2011-09-22T12:49:24Z
7,515,224
55
2011-09-22T13:07:40Z
[ "python", "django", "django-models" ]
Here's my model. What I want to do is generate a new file and overwrite the existing one whenever a model instance is saved: ``` class Kitten(models.Model): claw_size = ... license_file = models.FileField(blank=True, upload_to='license') def save(self, *args, **kwargs): #Generate a new license fil...
You want to have a look at [FileField and FieldFile](https://docs.djangoproject.com/en/1.9/ref/models/fields/#filefield-and-fieldfile) in the Django docs, and especially [FieldFile.save()](https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.fields.files.FieldFile.save). Basically, a field declare...
Django - how to create a file and save it to a model's FileField?
7,514,964
45
2011-09-22T12:49:24Z
14,885,116
12
2013-02-14T22:18:33Z
[ "python", "django", "django-models" ]
Here's my model. What I want to do is generate a new file and overwrite the existing one whenever a model instance is saved: ``` class Kitten(models.Model): claw_size = ... license_file = models.FileField(blank=True, upload_to='license') def save(self, *args, **kwargs): #Generate a new license fil...
Accepted answer is certainly a good solution, but here is the way I went about generating a CSV and serving it from a view. ``` #Model class MonthEnd(models.Model): report = models.FileField(db_index=True, upload_to='not_used') import csv from os.path import join #build and store the file def write_csv(): pa...
Python - single vs multiline REGEX
7,517,227
5
2011-09-22T15:19:14Z
7,517,397
8
2011-09-22T15:31:24Z
[ "python", "regex", "pattern-matching", "multiline" ]
Considering the following text pattern, #goals: the process report timestamp, eg. **2011-09-21 15:45:00** and the first two stats in succ. statistics line, eg: **1438 1439** ``` input_text = ''' # Process_Name ( 23387) Report at 2011-09-21 15:45:00.001 Type: Periodic #\n some line 1\n some line 2\n some ot...
Use `re.DOTALL` so `.` will match any character, including newlines: ``` import re data = ''' # Process_Name ( 23387) Report at 2011-09-21 15:45:00.001 Type: Periodic #\n some line 1\n some line 2\n some other lines\n succ. statistics | 1438 1439 99 | 3782245 3797376 99 |\n some lines\n repe...
Iterating through prefixes with Python
7,517,789
3
2011-09-22T15:56:51Z
7,517,956
7
2011-09-22T16:07:19Z
[ "python", "iterator" ]
I have a hierarchical descriptor string that looks like `foo:bar:baz` where elements in the hierarchy are delimited by `:`, and I would like to iterate through the hierarchy levels. Is there an easy way to do this, something easier than this: ``` def hierarchy(s): segments = s.split(':') for i in range(len(segment...
How about: ``` In [9]: [s[:m.start()] for m in re.finditer(':|$', s)] Out[9]: ['foo', 'foo:bar', 'foo:bar:baz'] ```
Python. IOError: [Errno 13] Permission denied: when i'm copying file
7,518,067
11
2011-09-22T16:16:00Z
7,518,128
27
2011-09-22T16:20:25Z
[ "python", "windows", "windows-7" ]
I have two folders: In, Out - it is not system folder on disk D: - Windows 7. Out contain "myfile.txt" I run the following command in python: ``` >>> shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" ) Traceback (most recent call last): File "<pyshell#39>", line 1, in <module> shutil.copyfile( r"d:\Out\myfile.txt...
Read the [docs](http://docs.python.org/library/shutil.html#shutil.copyfile): > `shutil.copyfile(src, dst)` > > Copy the contents (no metadata) of the file named *src* to a file > named *dst*. *dst* must be the **complete target file name**; look at `copy()` > for a copy that accepts a target directory path.
Creating a screenshot of a gtk.Window
7,518,376
6
2011-09-22T16:40:46Z
7,519,885
10
2011-09-22T18:53:24Z
[ "python", "gtk", "pygtk", "screenshot" ]
For testing and documentation purposes I would like to create a screenshot of a gtk.Window object. I'm following a basic pygtk sample at the moment. The example with my modifications looks like the following: ``` import gtk def main(): button = gtk.Button("Hello") scroll_win = gtk.ScrolledWindow() scroll_...
The key difference to understand is that `gtk.gdk.Window` isn't a "window" in the sense that most people think of. It's not a GUI element, it's just a section of the screen that acts as a logical display area, as [explained in the documentation](http://www.pygtk.org/docs/pygtk/class-gdkwindow.html). In that way, it is ...
Help me understanding python's logging module and its handlers
7,519,351
6
2011-09-22T18:03:51Z
7,520,157
7
2011-09-22T19:14:50Z
[ "python", "logging" ]
I really miss something basic about python's logging module. In the following code, I create a logger object (`log`) and add to it two handlers. One with 'INFO' level and one with 'WARNING' level. Both of them are supposed to print to stdout. I expect that calling to `log.info(msg)` will result in one copy of `msg` in...
There are two things you need to know: 1. **The root logger is initialized with a level of `WARNING`.** Any log message that reaches a logger is discarded if its level is below the logger's level. If a logger's level is not set, it will take its "effective level" from its parent logger. So if the root logger has a...
Line plot with arrows in matplotlib
7,519,467
14
2011-09-22T18:13:29Z
7,543,518
21
2011-09-25T03:48:38Z
[ "python", "plot", "matplotlib" ]
I have a line graph that I want to plot using arrows instead of lines. That is, the line between successive pairs of points should be an arrow going from the first point to the second point. I know of the `arrow` function, but that only seems to do individual arrows. Before I work out a way to try and use this to do a...
You can do this with [quiver](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.quiver), but it's a little tricky to get the keyword arguments right. ``` import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 2*np.pi, 10) y = np.sin(x) plt.figure() plt.quiver(x[:-1], y[:-1], x[1:...
Python regex gotcha
7,519,493
2
2011-09-22T18:15:27Z
7,519,514
7
2011-09-22T18:18:08Z
[ "python", "regex" ]
Could you explain me why the first regex doesn't match? ``` Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05) [GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin >>> import re >>> re.match(r'\d','.0') >>> re.match(r'.\d','.0') <_sre.SRE_Match object at 0x109adbd30> ```
[`re.match()`](http://docs.python.org/library/re.html#re.match) tries to match from the beginning of the string. Use [`re.search()`](http://docs.python.org/library/re.html#re.search) instead if you want to locate a match anywhere in the string. PS: You might want to escape the `.`, because it's a metacharacter that m...
syntax error with KeyError in python 3.2
7,520,690
6
2011-09-22T19:57:33Z
7,520,724
12
2011-09-22T19:59:27Z
[ "python", "syntax", "python-3.x" ]
I'm a beginner using python 3.2 and i have a book whos code is all in python 2.6. i wrote part of a program and keep getting: Syntax Error: invalid syntax Then python's IDLE highlights the comma after KeyError in my code: ``` from tank import Tank tanks = { "a":Tank("Alice"), "b":Tank("Bob"), "c":Tank("Carol")} alive...
Instead of ``` except KeyError, name: ``` try ``` except KeyError as name: ``` Its a difference between Python 2.x and Python 3.x. The first form is no longer supported.
How to pass a Bash variable to Python?
7,521,061
6
2011-09-22T20:28:30Z
7,522,223
12
2011-09-22T22:30:56Z
[ "python", "bash", "variables" ]
Eventually I understand this and it works. bash script: ``` #!/bin/bash #$ -V #$ -cwd #$ -o $HOME/sge_jobs_output/$JOB_ID.out -j y #$ -S /bin/bash #$ -l mem_free=4G c=$SGE_TASK_ID cd /home/xxx/scratch/test/ FILENAME=`head -$c testlist|tail -1` python testpython.py $FILENAME ``` python script: ``` #!/bin/python im...
Bash variables are actually environment variables. You get at them through the os.environ object with a dictionary-like interface. Note that there are two types of variables in Bash: those local to the current process, and those that are inherited by child processes. Your Python script is a child process, so you need t...
Printing named tuples
7,521,887
4
2011-09-22T21:45:45Z
7,521,941
7
2011-09-22T21:51:16Z
[ "python", "namedtuple" ]
In Python 2.7.1 I can create a named tuple: ``` from collections import namedtuple Test = namedtuple('Test', ['this', 'that']) ``` I can populate it: ``` my_test = Test(this=1, that=2) ``` And I can print it like this: ``` print(my_test) ``` > > Test(this=1, that=2) but why can't I print it like this? ``` print...
Since `my_test` is a tuple, it will look for a `%` format for each item in the tuple. To get around this wrap it in another tuple where the only element is `my_test`: ``` print("my_test = %r" % (my_test,)) ``` Don't forget the comma.
How to include package data with setuptools/distribute?
7,522,250
58
2011-09-22T22:35:23Z
13,783,919
18
2012-12-09T01:50:37Z
[ "python", "setuptools", "distribute" ]
When using setuptools/distribute, I can not get the installer to pull in any [`package_data`](https://pythonhosted.org/setuptools/setuptools.html#including-data-files) files. Everything I've read says that the following is the correct way to do it. Can someone please advise? ``` setup( name='myapp', packages=fin...
I just had this same issue. The solution, was simply to remove `include_package_data=True`. After [reading here](http://svn.python.org/projects/sandbox/trunk/setuptools/setuptools.txt), I realized that `include_package_data` aims to include files from **version control**, as opposed to merely "include package data" as...
How to include package data with setuptools/distribute?
7,522,250
58
2011-09-22T22:35:23Z
14,159,430
119
2013-01-04T14:53:55Z
[ "python", "setuptools", "distribute" ]
When using setuptools/distribute, I can not get the installer to pull in any [`package_data`](https://pythonhosted.org/setuptools/setuptools.html#including-data-files) files. Everything I've read says that the following is the correct way to do it. Can someone please advise? ``` setup( name='myapp', packages=fin...
I realize that this is an old question...but for people finding there way here via Google: `package_data` is a low-down, [dirty lie](http://blog.codekills.net/2011/07/15/lies,-more-lies-and-python-packaging-documentation-on--package_data-/). It is only used when building *binary* packages (`python setup.py bdist ...`) ...