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
python: read and split files in to list of dictionaries
8,067,389
6
2011-11-09T15:36:19Z
8,067,470
8
2011-11-09T15:40:40Z
[ "python", "file", "list", "dictionary", "split" ]
I'm having troubles with converting file content into list of dictionaries, could you advise? ``` File content: host1.example.com#192.168.0.1#web server host2.example.com#192.168.0.5#dns server host3.example.com#192.168.0.7#web server host4.example.com#192.168.0.9#application server host5.example.com#192.168.0.10#d...
First, you want to split each line on `#`. Then, you can use `zip` to zip them together with the labels, then convert it to a dictionary. ``` out = [] labels = ['dns', 'ip', 'description'] for line in data: out.append(dict(zip(labels, line.split('#')))) ``` That one append line is a bit complex, so to break it do...
ConfigParser vs. import config
8,067,651
22
2011-11-09T15:53:09Z
8,067,754
7
2011-11-09T15:58:49Z
[ "python", "configuration", "configparser", "import-module" ]
[ConfigParser](http://docs.python.org/library/configparser.html) is the [much debated](http://wiki.python.org/moin/ConfigParserShootout) vanilla configuration parser for Python. However you can simply `import config` where `config.py` has python code which sets configuration parameters. What are the pros\cons of the...
This completley depends on your needs and goals for the script. One way really isnt "better", just different. For a very detailed discussion on most of pythons config parsers (including `ConfigParser` and `config` modules), see: [Python Wiki - ConfigParserShootout](http://wiki.python.org/moin/ConfigParserShootout)
ConfigParser vs. import config
8,067,651
22
2011-11-09T15:53:09Z
8,067,855
15
2011-11-09T16:06:34Z
[ "python", "configuration", "configparser", "import-module" ]
[ConfigParser](http://docs.python.org/library/configparser.html) is the [much debated](http://wiki.python.org/moin/ConfigParserShootout) vanilla configuration parser for Python. However you can simply `import config` where `config.py` has python code which sets configuration parameters. What are the pros\cons of the...
The biggest issue I see with `import config` is that you don't know *what* will happen when you import it. Yes, you will get a set of symbols that are naturally referenced using a `.` style interface. But the code in the configuration file can also do who-knows-what. Now, if you completely trust your users, then allowi...
Context manager for Python's MySQLdb
8,067,690
11
2011-11-09T15:54:52Z
8,074,341
14
2011-11-10T02:34:49Z
[ "python", "mysql", "with-statement", "contextmanager" ]
I am used to (spoiled by?) python's [SQLite](http://docs.python.org/library/sqlite3.html) interface to deal with SQL databases. One nice feature in python's SQLite's API the "context manager," i.e., python's `with` statement. I usually execute queries in the following way: ``` import as sqlite with sqlite.connect(db_...
Note that MySQLdb connections are now context managers already. See [user2966041's answer](http://stackoverflow.com/a/22840557/190597). --- You could use something like this: ``` import config import MySQLdb import MySQLdb.cursors as mc import _mysql_exceptions DictCursor = mc.DictCursor SSCursor = mc.SSCursor SSDic...
Context manager for Python's MySQLdb
8,067,690
11
2011-11-09T15:54:52Z
22,840,557
10
2014-04-03T14:20:09Z
[ "python", "mysql", "with-statement", "contextmanager" ]
I am used to (spoiled by?) python's [SQLite](http://docs.python.org/library/sqlite3.html) interface to deal with SQL databases. One nice feature in python's SQLite's API the "context manager," i.e., python's `with` statement. I usually execute queries in the following way: ``` import as sqlite with sqlite.connect(db_...
Think things have changed since this question was originally asked. Somewhat confusingly (from my point of view at least), for recent versions of `MySQLdb`, if you use a connection in a context you get a cursor (as per the `oursql` example), not something that closes automatically (as you would if you opened a file for...
Python: why are * and ** faster than / and sqrt()?
8,068,019
77
2011-11-09T16:20:18Z
8,068,248
110
2011-11-09T16:35:45Z
[ "python", "c", "performance", "python-2.7", "python-internals" ]
While optimising my code I realised the following: ``` >>> from timeit import Timer as T >>> T(lambda : 1234567890 / 4.0).repeat() [0.22256922721862793, 0.20560789108276367, 0.20530295372009277] >>> from __future__ import division >>> T(lambda : 1234567890 / 4).repeat() [0.14969301223754883, 0.14155197143554688, 0.141...
The (somewhat unexpected) reason for your results is that Python seems to fold constant expressions involving floating-point multiplication and exponentiation, but not division. `math.sqrt()` is a different beast altogether since there's no bytecode for it and it involves a function call. On Python 2.6.5, the followin...
Why is python list comprehension sometimes frowned upon?
8,068,251
6
2011-11-09T16:36:01Z
8,068,348
19
2011-11-09T16:41:20Z
[ "python", "list-comprehension" ]
Many developers I have met suggest it's best practice to go with simple loops and if conditions instead of one line list comprehension statements. I have always found them very powerful as I can fit a lot of code in a single line and it saves a lot of variables from being created. Why is it still considered a bad prac...
List comprehensions are used for *creating* lists, for example: ``` squares = [item ** 2 for item in some_list] ``` For loops are better for *doing something* with the elements of a list (or other objects): ``` for item in some_list: print(item) ``` Using a comprehension for its side effects, or a for-loop for ...
How to find out if object has attributes?
8,068,478
3
2011-11-09T16:51:06Z
8,068,499
8
2011-11-09T16:52:29Z
[ "python" ]
``` if groupName.group == "None": ``` error: ``` AttributeError: 'NoneType' object has no attribute 'group' ``` How to check if object has an attribute?
You want [`getattr()`](http://docs.python.org/library/functions.html#getattr), which you can pass a default value, or [`hasattr()`](http://docs.python.org/library/functions.html#hasattr).
How do I solve an import error on 'self' not being globally defined in Python?
8,069,017
3
2011-11-09T17:29:21Z
8,069,122
11
2011-11-09T17:36:57Z
[ "python", "syntax", "ironpython", "self" ]
So I keep getting this error that when I Google for it, the most common fix for it is to be sure that all the methods of a class have 'self' as the first argument. Here is the error: `File "C:\Users\me\Documents\Project\code\model\TrainEvent.py", line 9, in NameError: global name 'self' is not definedPress any key to ...
The problem is in your `__tagGrab` function: ``` def __tagGrab(self, tagName, parent=self._element): ``` You cannot have `self` in the header -- rather have `None` and then correct in the body: ``` def __tagGrab(self, tagName, parent=None): if parent is None: parent = self._element ... ``` The reaso...
try-except inside a loop
8,069,057
3
2011-11-09T17:32:44Z
8,069,109
8
2011-11-09T17:36:00Z
[ "python" ]
I need to invoke method `f`. If it raises an `IOError`, I need to invoke it again (retry), and do it at most three times. I need to log any other exceptions, and I need to log all retries. the code below does this, but it looks ugly. please help me make it elegant and pythonic. I am using Python 2.7. thanks! ``` cou...
Use `try .. except .. else`: ``` for i in range(3, 0, -1): try: f() except IOError: if i == 1: raise print('retry') else: break ``` You should not generically catch all errors. Just let them bubble up to the appropriate handler.
Dynamically add URL rules to Flask app
8,069,846
6
2011-11-09T18:39:48Z
8,070,044
10
2011-11-09T18:55:01Z
[ "python", "flask" ]
I am writing an app in which users will be able to store information that they can specify a REST interface for. IE, store a list of products at `/<username>/rest/products`. Since the URLs are obviously not known before hand, I was trying to think of the best way to implement dynamic URL creation in Flask. The first wa...
Every time you execute `add_url_rule()` the internal routing remaps the URL map. This is neither threadsafe nor fast. I right now don't understand why you need user specific URL rules to be honest. It kinda sounds like you actually want user specific applications mounted? Maybe this is helpful: <http://flask.pocoo.org...
Split string on commas but ignore commas within double-quotes?
8,069,975
16
2011-11-09T18:48:42Z
8,070,008
25
2011-11-09T18:52:08Z
[ "python", "regex", "csv", "split", "double-quotes" ]
I have some input that looks like the following: ``` A,B,C,"D12121",E,F,G,H,"I9,I8",J,K ``` The comma-separated values can be in any order. I'd like to split the string on commas; however, in the case where something is inside double quotation marks, I need it to both ignore commas and strip out the quotation marks (...
Lasse is right; it's a comma separated value file, so you should use the [`csv` module](http://docs.python.org/library/csv.html). A brief example: ``` from csv import reader # test infile = ['A,B,C,"D12121",E,F,G,H,"I9,I8",J,K'] # real is probably like # infile = open('filename', 'r') # or use 'with open(...) as infi...
Boto EC2: Create an instance with tags
8,070,186
19
2011-11-09T19:06:11Z
10,730,428
20
2012-05-24T02:39:35Z
[ "python", "amazon-ec2", "amazon-web-services", "boto" ]
Is there a way with the boto python API to specify tags when creating an instance? I'm trying to avoid having to create an instance, fetch it and then add tags. It would be much easier to have the instance either pre-configured to have certain tags or to specify tags when I execute the following command: ``` ec2server...
Tags cannot be made until the instance has been created. Even though the function is called create\_instance, what it's really doing is reserving and instance. Then that instance may or may not be launched. (Usually it is, but sometimes...) So, you cannot add a tag until it's been launched. And there's no way to tell ...
How to use Python closing context manager
8,070,259
7
2011-11-09T19:13:17Z
8,070,410
13
2011-11-09T19:24:18Z
[ "python", "file-io", "with-statement" ]
The standard library `open` function works both as a function: ``` f = open('file.txt') print(type(f)) <type 'file'> ``` or as a context manager: ``` with open('file.txt') as f: print(type(f)) <type 'file'> ``` I am trying to mimic this behaviour using `contextlib.closing`, where `File` is my custom file I/O cl...
The easiest thing is probably to implement the `__enter__` and `__exit__` methods yourself. Something like this should do it: ``` class File(object): # ... all the methods you already have ... # context management def __enter__(self): return self def __exit__(self, *exc_info): self.close() `...
Using Numpy stride_tricks to get non-overlapping array blocks
8,070,349
9
2011-11-09T19:20:32Z
8,070,716
11
2011-11-09T19:49:27Z
[ "python", "numpy" ]
I'm trying to using numpy.lib.stride\_tricks.as\_strided to iterate over non-overlapping blocks of an array, but I'm having trouble finding documentation of the parameters, so I've only been able to get overlapping blocks. For example, I have a 4x5 array which I'd like to get 4 2x2 blocks from. I'm fine with the extra...
``` import numpy as np n=4 m=5 a = np.arange(1,n*m+1).reshape(n,m) print(a) # [[ 1 2 3 4 5] # [ 6 7 8 9 10] # [11 12 13 14 15] # [16 17 18 19 20]] sz = a.itemsize h,w = a.shape bh,bw = 2,2 shape = (h/bh, w/bw, bh, bw) print(shape) # (2, 2, 2, 2) strides = sz*np.array([w*bh,bw,w,1]) print(strides) # [40 8 20...
Python+matplotlib: custom linestyles
8,070,492
5
2011-11-09T19:30:21Z
8,070,810
7
2011-11-09T19:58:13Z
[ "python", "matplotlib" ]
I'm not satisfied with default set of linestyles, namely the size of line segments and the gap between them. I'd also want to have something like '-..', '-...', etc line patterns. Does anybody know how to customize it? Best witches.
Use [`set_dashes`](http://matplotlib.sourceforge.net/examples/pylab_examples/dash_control.html).
My Python-Java Interface, good design? And how to wrap JNI Functions?
8,071,362
6
2011-11-09T20:40:24Z
8,127,756
11
2011-11-14T20:37:26Z
[ "java", "c++", "python", "jni", "variableargumentlists" ]
I'm going to write my own Python-Java interface. It is compiled as a DLL and wrapped using ctypes. Yet, it is possible to find Java-classes and allocate Java-objects. But what would be an interface to another language without using those objects methods? My aim is to make this as natural as possible. Unfortunately, it...
**1. What do I think of this design?** * it's not clear what actual problem you're trying to solve. * what about edge cases; error-handling; forward-/backward-compatibility; bugs in Python/Java? Not fun, but essential for robust software. * mixing two languages is hard enough, mixing three is sure to be much much wors...
Unable to use a tuple as a dictionary key?
8,072,515
4
2011-11-09T22:14:57Z
8,072,542
9
2011-11-09T22:17:31Z
[ "python", "typeerror", "hashable" ]
The code is a little complex, sorry. Please focus on the `parallel_p` function. Although `sign` is a tuple, Python complains: `if sign in hashtable` and gives a `TypeError`. Why is `sign` a `numpy.ndarray` rather than a tuple? I created it as a tuple. ``` p_dist = dict() def parallel_prog(hashtable): def wrapper...
Not every tuple is hashable. A tuple containing non-hashable items is not hashable: ``` >>> x = ([], []) >>> hash(x) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list' ``` Your tuple obviously contains a NumPy array, which is as far from being hashable as a typ...
Install "scientific python" environment: OS X 10.7 + Numpy + Scipy + Matplotlib
8,072,664
14
2011-11-09T22:28:28Z
8,072,710
13
2011-11-09T22:33:35Z
[ "python", "numpy", "matplotlib", "scipy" ]
What could I have done instead in order to get these items working together? Should I just move everything to windows 7 (I'd prefer not, but if it's the only reliable way.) Okay, so here's what's happened: I wanted to install numpy/scipy onto my mac, which runs 10.7. Unfortunately numpy ver1.6 only supports up python ...
If you are ready to follow a longer term approach, I would advise that you go through the [MacPorts](http://www.macports.org/) **package manager**: they have all this software packaged, and it just works. I followed this approach successfully with Mac OS X Lion. You basically first install the MacPorts package manager...
Install "scientific python" environment: OS X 10.7 + Numpy + Scipy + Matplotlib
8,072,664
14
2011-11-09T22:28:28Z
8,072,935
11
2011-11-09T22:59:13Z
[ "python", "numpy", "matplotlib", "scipy" ]
What could I have done instead in order to get these items working together? Should I just move everything to windows 7 (I'd prefer not, but if it's the only reliable way.) Okay, so here's what's happened: I wanted to install numpy/scipy onto my mac, which runs 10.7. Unfortunately numpy ver1.6 only supports up python ...
Another option would be [EPD](http://enthought.com/products/epd.php) or [EPD Free](http://enthought.com/products/epd_free.php). Either will install NumPy, SciPy, matplotlib, IPython, Traits, and Chaco on Window, OSX, or Linux. EPD is the kitchen-sink-included version with 90+ libraries for science and analysis, and is ...
Number of seconds since the beginning of the day UTC timezone
8,072,740
10
2011-11-09T22:37:04Z
8,072,788
8
2011-11-09T22:41:57Z
[ "python", "utc", "seconds" ]
How do I find "number of seconds since the beginning of the day UTC timezone" in Python? I looked at the docs and didn't understand how to get this using `datetime.timedelta`.
Here's one way to do it. ``` from datetime import datetime, time utcnow = datetime.utcnow() midnight_utc = datetime.combine(utcnow.date(), time(0)) delta = utcnow - midnight_utc print delta.seconds # <-- careful ``` **EDIT** As suggested, if you want microsecond precision, or potentially crossing a 24-hour period (i...
Saving a model in Django gives me "Warning: Field 'id' doesn't have a default value"
8,073,734
6
2011-11-10T00:46:38Z
10,273,221
13
2012-04-22T23:54:41Z
[ "python", "mysql", "django" ]
I have a very basic model in Django: ``` class Case(models.Model): name = models.CharField(max_length=255) created_at = models.DateTimeField(default=datetime.now) updated_at = models.DateTimeField(default=datetime.now) def save(self): if self.created_at == None: self.created_at = ...
I'd like to expand on this question as I've ran into it this week. I was getting this same exact error and taking a look at the model definition and SQL definition showed that: 1. The models affected either had no PK explicitly defined or had a PK explicitly defined (both had problems). This alone seemed unrelated. 2....
cannot import name patterns
8,074,955
16
2011-11-10T04:18:43Z
8,075,082
14
2011-11-10T04:43:14Z
[ "python", "django" ]
Before I wrote in `urls.py`, my code... everything worked perfectly. Now I have problems - can't go to my site. "cannot import name patterns" My `urls.py` is: ``` from django.conf.urls import patterns, include, url ``` They said what error is somewhere here.
You don't need those imports. The only thing you need in your urls.py (to start) is: ``` from django.conf.urls.defaults import * # This two if you want to enable the Django Admin: (recommended) from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^admin/', include(admin.site.url...
cannot import name patterns
8,074,955
16
2011-11-10T04:18:43Z
13,009,708
16
2012-10-22T10:41:41Z
[ "python", "django" ]
Before I wrote in `urls.py`, my code... everything worked perfectly. Now I have problems - can't go to my site. "cannot import name patterns" My `urls.py` is: ``` from django.conf.urls import patterns, include, url ``` They said what error is somewhere here.
Yes: ``` from django.conf.urls.defaults import ... # is for django 1.3 from django.conf.urls import ... # is for django 1.4 ``` I met this problem too.
cannot import name patterns
8,074,955
16
2011-11-10T04:18:43Z
38,799,716
28
2016-08-06T01:25:24Z
[ "python", "django" ]
Before I wrote in `urls.py`, my code... everything worked perfectly. Now I have problems - can't go to my site. "cannot import name patterns" My `urls.py` is: ``` from django.conf.urls import patterns, include, url ``` They said what error is somewhere here.
As of Django 1.10, the `patterns` module has been removed (it had been deprecated since 1.8). Luckily, it should be a simple edit to remove the offending code, since the `urlpatterns` [should now be stored in a plain-old list](https://docs.djangoproject.com/en/1.9/topics/http/urls/#example): ``` urlpatterns = [ u...
If clause in regular Python for-loop
8,075,077
3
2011-11-10T04:42:19Z
8,075,108
11
2011-11-10T04:46:29Z
[ "python" ]
Is it possible to basically do the following in Python: ``` for elem in my_list if elem: #Do something with elem... ``` Note that I want to specifically avoid using map, lambdas, or filter to create a second list that gives the Boolean condition, and I don't want to do the following: ``` for elem in [item for it...
You can use a [generator expression](http://docs.python.org/reference/expressions.html#grammar-token-generator_expression) instead of a list comprehension. ``` for elem in (item for item in my_list if not (item=='')): #Do something... ```
How to maximize a browser window using the Python bindings for Selenium 2-WebDriver?
8,075,297
2
2011-11-10T05:17:19Z
18,481,265
10
2013-08-28T06:58:00Z
[ "python", "webdriver", "selenium-webdriver" ]
I wanted to know how to maximize a browser window using the Python bindings for Selenium 2-WebDriver.
You can use `browser.maximize_window()` for that
Converting String to Int using try/except in Python
8,075,877
14
2011-11-10T06:47:41Z
8,075,959
24
2011-11-10T07:00:59Z
[ "python", "python-3.x" ]
So I'm pretty stumped on how to convert a string into an int using the try/except function. Does anyone know a simple function on how to do this? I feel like I'm still a little hazy on string and ints. I'm pretty confident that ints are related to numbers. Strings...not so much.
It is important to be specific about what exception you're trying to catch when using a try/except block. ``` string = "abcd" try: i = int(string) print i except ValueError: #Handle the exception print 'Please enter an integer' ``` Try/Excepts are powerful because if something can fail in a number of ...
Subclassing and overriding a generator function in python
8,076,312
14
2011-11-10T07:46:24Z
8,078,678
9
2011-11-10T11:17:51Z
[ "python", "python-3.x" ]
I need to override a method of a parent class, which is a generator, and am wondering the correct way to do this. Is there anything wrong with the following, or a more efficient way? ``` class A: def gen(self): yield 1 yield 2 class B(A): def gen(self): yield 3 for n in super()...
What you have looks fine, but is not the only approach. What's important about a generator function is that it returns an iterable object. Your subclass could thus instead directly create an iterable, for example: ``` import itertools class B(A): def gen(self): return itertools.chain([3], super().gen()) `...
Short guide how to use gnuplot with python?
8,077,099
12
2011-11-10T09:05:06Z
8,077,314
12
2011-11-10T09:23:33Z
[ "python", "python-3.x", "gnuplot" ]
I'm trying to draw a graph in Python, using Gnuplot. I have a hard time finding any guide/tutorials how to start. What I'm wondering: what files/programs are necessary?(I'm using Ubuntu), Where do I begin? If anyone could recommend a good tutorial, that would be very appreciated! Thank you!
You could try [gnuplot.py](http://gnuplot-py.sourceforge.net/). It is an interface to gnuplot I used in the past. In the website you have some indications and there are some example scripts in the distribution. In fact it is very easy to run directly gnuplot from python. The gnuplot.py source code will give you valuab...
Purpose of star operator when used on List
8,077,268
7
2011-11-10T09:19:43Z
8,077,327
16
2011-11-10T09:24:47Z
[ "python" ]
What is the star operator doing to the input argument list in this example? ``` def main(name, data_dir='.'): print 'name', type(name) if __name__ == '__main__': main(*sys.argv) ``` Concretely, if I run the program with the star operator it prints: ``` name <type 'str'> ``` if run without the star `main(sy...
The `*` operator [unpacks an argument list](http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists). It allows you to call a function with the list items as individual arguments. For instance, if `sys.argv` is `["./foo", "bar", "quux"]`, `main(*sys.argv)` is equivalent to `main("./foo", "bar", "quux...
Python: subprocess.Popen and subprocess.call hang
8,077,868
11
2011-11-10T10:11:51Z
8,078,815
10
2011-11-10T11:29:38Z
[ "python" ]
I have a problem using the subprocess.Popen or subprocess.call when I use them to execute a command lines that generates a lot of output, the python scripts hangs, but what is weird that after waiting for a while, while the script is in its hanging state, I find that the job commanded by the cmd line has been done, and...
According to the python documentation, `subprocess.call` runs the command and waits for it to complete, so it's equivalent to `subprocess.Popen` followed by `Popen.wait`. However, the `Popen.wait` method documentation explicitly warns about the problem of buffer overflow and recommends to use `Popen.communicate` inste...
How to install pywin32 in virtualenv with python 2.7 64 bit?
8,078,216
10
2011-11-10T10:38:33Z
28,772,951
9
2015-02-27T19:36:41Z
[ "python", "pywin32", "easy-install" ]
I wonder right way to install on virtualenv with 64 bit python 2.7 pywin32 module (Operating system is Windows 7 64 bit). I've found exe installer on [Sourceforge](http://sourceforge.net/projects/pywin32/files/pywin32/Build216/pywin32-216.win-amd64-py2.7.exe). When i run easy\_installer on command line first everyt...
I figured this out, but the process isn't pleasant. There are 3 problems with the PyWin32 installer: 1. It reads your python install location out of the registry. 2. Is assumes that your lib directory is a child of the directory containing python.exe 3. It dumps 3 dlls to %WINDIR%\system32 So if you're running 64 bi...
csv writing within loop
8,078,330
4
2011-11-10T10:49:10Z
8,078,386
8
2011-11-10T10:53:16Z
[ "python", "csv" ]
``` import csv a=[] with open('large.csv','w') as f1: writer=csv.writer(f1, delimiter='\t',lineterminator='\n',) for i in range(1000000): for j in range(i+1): a.append(i+j*0.2) #print i,j,a #want to write into same csv file??? '''like 0...
Do you want to do something like this? ``` import csv with open('large.csv','w') as f1: writer=csv.writer(f1, delimiter='\t',lineterminator='\n',) for i in range(1000000): row = [i + j*0.2 for j in range(i+1)] writer.writerow(row) ``` or also with the row/column headers: ``` import csv with o...
Function application over numpy's matrix row/column
8,079,061
26
2011-11-10T11:51:16Z
8,079,151
30
2011-11-10T11:58:04Z
[ "python", "numpy", "map-function" ]
I am using Numpy to store data into matrices. Coming from R background, there has been an extremely simple way to apply a function over row/columns or both of a matrix. Is there something similar for python/numpy combination? It's not a problem to write my own little implementation but it seems to me that most of the ...
Almost all numpy functions operate on whole arrays, and/or can be told to operate on a particular axis (row or column). As long as you can define your function in terms of numpy functions acting on numpy arrays or array slices, your function will automatically operate on whole arrays, rows or columns. It may be more ...
Function application over numpy's matrix row/column
8,079,061
26
2011-11-10T11:51:16Z
8,079,837
12
2011-11-10T12:57:55Z
[ "python", "numpy", "map-function" ]
I am using Numpy to store data into matrices. Coming from R background, there has been an extremely simple way to apply a function over row/columns or both of a matrix. Is there something similar for python/numpy combination? It's not a problem to write my own little implementation but it seems to me that most of the ...
Selecting elements from a NumPy array based on one or more conditions is straightforward using NumPy's beautifully dense syntax: ``` >>> import numpy as NP >>> # generate a matrix to demo the code >>> A = NP.random.randint(0, 10, 40).reshape(8, 5) >>> A array([[6, 7, 6, 4, 8], [7, 3, 7, 9, 9], [4, ...
Python: do r = random_stuff() while not meets_condition(r)
8,080,072
2
2011-11-10T13:17:17Z
8,080,102
8
2011-11-10T13:19:22Z
[ "python", "design-patterns", "do-while" ]
I often have to randomly generate stuff with certain constraints. In many cases, it's quicker to ignore the constraints in generation, check if they are met afterwards and redo the process otherwise. Lacking a `do` keyword, I usually write ``` r = random_stuff() while not meets_condition(r): r = random_stuff() ```...
``` while True: r = random_stuff() if meets_condition(r): break ``` or ``` condition = True while condition: r = random_stuff() condition = not meets_condition(r) ```
initialize dict with keys,values from two list
8,080,890
6
2011-11-10T14:18:12Z
8,080,903
28
2011-11-10T14:19:07Z
[ "python", "list", "dictionary", "key" ]
I have read [this](http://stackoverflow.com/questions/2241891/how-to-initialize-a-dict-with-keys-from-a-list-and-empty-value-in-python) link But how do I initialize the dictionary as well ? say two list ``` keys = ['a','b','c','d'] values = [1,2,3,4] dict = {} ``` I want initialize `dict` with `keys` & `values...
``` d = dict(zip(keys, values)) ``` (Please don't call your `dict` `dict`, that's a built-in name.)
convert list of tuples to multiple lists in Python
8,081,545
32
2011-11-10T15:02:25Z
8,081,580
51
2011-11-10T15:03:31Z
[ "python", "list", "tuples" ]
Suppose I have a list of tuples and I want to convert to multiple lists. For example, the list of tuples is ``` [(1,2),(3,4),(5,6),] ``` Is there any built-in function in Python that convert it to: ``` [1,3,5],[2,4,6] ``` This can be a simple program. But I am just curious about the existence of such built-in func...
The built-in function `zip()` will almost do what you want: ``` >>> zip(*[(1, 2), (3, 4), (5, 6)]) [(1, 3, 5), (2, 4, 6)] ``` The only difference is that you get tuples instead of lists. You can convert them to lists using ``` map(list, zip(*[(1, 2), (3, 4), (5, 6)])) ```
convert list of tuples to multiple lists in Python
8,081,545
32
2011-11-10T15:02:25Z
8,081,590
21
2011-11-10T15:04:00Z
[ "python", "list", "tuples" ]
Suppose I have a list of tuples and I want to convert to multiple lists. For example, the list of tuples is ``` [(1,2),(3,4),(5,6),] ``` Is there any built-in function in Python that convert it to: ``` [1,3,5],[2,4,6] ``` This can be a simple program. But I am just curious about the existence of such built-in func...
From the [python docs](http://docs.python.org/library/functions.html): > zip() in conjunction with the \* operator can be used to unzip a list: Specific example: ``` >>> zip((1,3,5),(2,4,6)) [(1, 2), (3, 4), (5, 6)] >>> zip(*[(1, 2), (3, 4), (5, 6)]) [(1, 3, 5), (2, 4, 6)] ``` Or, if you really want lists: ``` >>>...
Python split string with multiple-character delimiter
8,081,569
10
2011-11-10T15:02:59Z
8,081,611
28
2011-11-10T15:05:51Z
[ "python", "string", "split" ]
say I have the following string: ``` "Hello there. My name is Fred. I am 25.5 years old." ``` I want to split this into sentences, so that I have the following list: ``` ["Hello there", "My name is Fred", "I am 25.5 years old"] ``` As you can see, I want to split the string on all occurrences of the string `". "`, ...
Works for me ``` >>> "Hello there. My name is Fr.ed. I am 25.5 years old.".split(". ") ['Hello there', 'My name is Fr.ed', 'I am 25.5 years old.'] ```
How to download a youtube video using the youtube's API?
8,081,676
10
2011-11-10T15:10:07Z
8,081,778
19
2011-11-10T15:16:34Z
[ "python", "api", "youtube" ]
I looked at the python's API overview: [Developer's Guide: Python](http://code.google.com/intl/iw-IL/apis/youtube/1.0/developers_guide_python.html) But there is no reference to how to download a video. Does anyone know where can I get information regarding downloading?
Downloading Youtube videos is against their [Terms of Service](https://developers.google.com/youtube/terms), so their API's will not support that. Page linked above refers to [Youtube ToS](https://www.youtube.com/t/terms) that states: > You shall not download any Content unless you see a “download” or similar lin...
How to download a youtube video using the youtube's API?
8,081,676
10
2011-11-10T15:10:07Z
12,200,200
13
2012-08-30T15:17:54Z
[ "python", "api", "youtube" ]
I looked at the python's API overview: [Developer's Guide: Python](http://code.google.com/intl/iw-IL/apis/youtube/1.0/developers_guide_python.html) But there is no reference to how to download a video. Does anyone know where can I get information regarding downloading?
There is obviously no api-side option, but you can simply use [youtube-dl](http://rg3.github.com/youtube-dl/) and call it via subprocess inside your python script, which is way easier/stable than using on standalone youtube-downloaders.
How to download a youtube video using the youtube's API?
8,081,676
10
2011-11-10T15:10:07Z
16,748,883
17
2013-05-25T11:03:43Z
[ "python", "api", "youtube" ]
I looked at the python's API overview: [Developer's Guide: Python](http://code.google.com/intl/iw-IL/apis/youtube/1.0/developers_guide_python.html) But there is no reference to how to download a video. Does anyone know where can I get information regarding downloading?
Check out Python API for YouTube, it downloads videos or can just gets the direct URL to the video: <http://np1.github.io/pafy/>
PyQt4 names showing as undefined in eclipse, but it runs fine
8,082,230
9
2011-11-10T15:48:06Z
8,088,374
16
2011-11-11T00:42:24Z
[ "python", "eclipse", "pyqt4", "pydev", "python-2.7" ]
I am using Eclipse 3.7.1 with the latest PyDev add-in for Python coding. I am using PyQt4. At the top of my file I have: ``` from PyQt4.QtCore import * from PyQt4.QtGui import * ``` In addition, I have the PyQt4 tree included in the Project Explorer listing. However, eclipse still thinks the names like QMainWindow ar...
PyQt is actually a wrapping of C++ Qt libraries. So they are not `.py` files and PyDev can't analyze them to get what is in them. You need to add `PyQt4` in the [Forced Builtins](http://pydev.org/manual_101_interpreter.html#id1) tab, so that PyDev can use a Python shell to "look into" those libraries and know what is i...
Tkinter <Return> event on key release
8,082,277
3
2011-11-10T15:51:34Z
8,089,241
8
2011-11-11T03:12:10Z
[ "python", "tkinter", "tk" ]
Is there a way to make the `<Return>` event call on the key release, instead of press? If you use `<KeyRelease>`, then `event.char` is blank for any special key, not just return.
You can explicitly set a binding on the release of the return key by binding to `<KeyRelease-Return>`. For example: ``` import Tkinter as tk class SampleApp(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.text = tk.Text(self) self.text.pack() ...
django user_passes_test decorator
8,082,670
23
2011-11-10T16:17:44Z
8,083,525
31
2011-11-10T17:13:00Z
[ "python", "django" ]
How do I implement the `@user_passes_test(lambda u: u.is_superuser)` decorator for class based views? I have used this before for function based views, and I have a work around but it feels unnaturally.. Shouldn't this be covered by the dispatch method?
You use `@method_decorator` on the `dispatch` method of the class: ``` from django.views.generic import View from django.utils.decorators import method_decorator from django.contrib.auth.decorators import user_passes_test class MyView(View): @method_decorator(user_passes_test(lambda u: u.is_superuser)) def di...
django user_passes_test decorator
8,082,670
23
2011-11-10T16:17:44Z
17,546,105
21
2013-07-09T10:39:16Z
[ "python", "django" ]
How do I implement the `@user_passes_test(lambda u: u.is_superuser)` decorator for class based views? I have used this before for function based views, and I have a work around but it feels unnaturally.. Shouldn't this be covered by the dispatch method?
Building on @Chris Pratt's answer, you'll probably want to do this in multiple view classes so it makes sense to turn it into a mixin. ``` class SuperuserRequiredMixin(object): @method_decorator(user_passes_test(lambda u: u.is_superuser)) def dispatch(self, *args, **kwargs): return super(SuperuserRequi...
Python: printing a file to stdout
8,084,260
31
2011-11-10T18:12:53Z
8,084,296
10
2011-11-10T18:16:10Z
[ "python" ]
I've searched and I can only find questions about the other way around: writing stdin to a file :) Is there a quick and easy way to dump the contents of a file to stdout?
``` f = open('file.txt', 'r') print f.read() f.close() ``` From <http://docs.python.org/tutorial/inputoutput.html> > To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string. size is an optional numeric argument. When size is omitted or negative, the entire contents...
Python: printing a file to stdout
8,084,260
31
2011-11-10T18:12:53Z
8,084,311
48
2011-11-10T18:16:55Z
[ "python" ]
I've searched and I can only find questions about the other way around: writing stdin to a file :) Is there a quick and easy way to dump the contents of a file to stdout?
Sure. Assuming you have a string with the file's name called `fname`, the following does the trick. ``` with open(fname, 'r') as fin: print fin.read() ```
Python: printing a file to stdout
8,084,260
31
2011-11-10T18:12:53Z
8,084,371
25
2011-11-10T18:21:59Z
[ "python" ]
I've searched and I can only find questions about the other way around: writing stdin to a file :) Is there a quick and easy way to dump the contents of a file to stdout?
If it's a large file and you don't want to consume a ton of memory as might happen with Ben's solution, the extra code in ``` >>> import shutil >>> import sys >>> with open("test.txt", "r") as f: ... shutil.copyfileobj(f, sys.stdout) ``` also works.
Bash: Variable in single quote
8,084,389
4
2011-11-10T18:23:31Z
8,084,448
13
2011-11-10T18:28:06Z
[ "python", "linux", "bash", "command-line", "googlecl" ]
First take a look at this question: [Bash or GoogleCL: new line in a string parameter](http://stackoverflow.com/questions/4918067/bash-or-googlecl-new-line-in-a-string-parameter) I want to add a variable ${date} into the "summary" now: ``` google youtube post ~/videos/cat-falls-down-stairs.avi Comedy \ --tags 'cu...
Rather than attempting to expand a variable inside a single quoted string, the typical solution is to concatenate single and double quoted strings. In other words: ``` 'Today is'"${date}"'. Poor' ... ```
Generating pdf-latex with python script
8,085,520
21
2011-11-10T19:58:22Z
8,086,042
42
2011-11-10T20:44:25Z
[ "python", "latex", "pdflatex" ]
I'm a college guy, and in my college, to present any kind of homework, it has to have a standard coverpage (with the college logo, course name, professor's name, my name and bla bla bla). So, I have a .tex document, which generate my standard coverpages pdfs. It goes something like: ``` ... \begin{document} %% Colleg...
You can start by defining the template tex file as a string: ``` content = r'''\documentclass{article} \begin{document} ... \textbf{\huge %(school)s \\} \vspace{1cm} \textbf{\Large %(title)s \\} ... \end{document} ''' ``` Next, use `argparse` to accept values for the course, title, name and school: ``` parser = argp...
Is there a way to deploy new code with Tornado/Python without restarting the server?
8,086,885
6
2011-11-10T21:54:29Z
8,098,669
9
2011-11-11T19:03:01Z
[ "python", "tornado" ]
I've recently started to experiment with Python and Tornado web server/framework for web development. Previously, I have used PHP with my own framework on a LAMP stack. With PHP, deploying updated code/new code is as easy as uploading it to the server because of the way mod\_php and Apache interact. When I add new cod...
It appears the best method is to use Nginx with multiple Tornado instances as I alluded to in my original question and as Cole mentions. Nginx can reload its configuration file on the fly . So the process looks like this: 1. Update Python/Tornado web application code 2. Start a new instance of the application on a dif...
Problems installing python3 on RHEL
8,087,184
52
2011-11-10T22:21:44Z
8,112,006
89
2011-11-13T13:53:48Z
[ "python", "python-3.x", "rhel" ]
I'm trying to install python3 on RHEL using the following steps: ``` yum search python3 ``` Which returned `No matches found for: python3` Followed by: ``` yum search python ``` None of the search results contained python3. What should I try next?
It is easy to install it manually: 1. Download (there may be newer releases on [Python.org](http://www.python.org/download/)): ``` $ wget https://www.python.org/ftp/python/3.4.3/Python-3.4.3.tar.xz ``` 2. Unzip ``` $ tar xf Python-3.* $ cd Python-3.* ``` 3. Prepare compilation ``` $ ./co...
Problems installing python3 on RHEL
8,087,184
52
2011-11-10T22:21:44Z
11,708,777
24
2012-07-29T11:15:45Z
[ "python", "python-3.x", "rhel" ]
I'm trying to install python3 on RHEL using the following steps: ``` yum search python3 ``` Which returned `No matches found for: python3` Followed by: ``` yum search python ``` None of the search results contained python3. What should I try next?
In addition to gecco's answer I would change step 3 from: ``` ./configure ``` to: ``` ./configure --prefix=/opt/python3 ``` Then after installation you could also: ``` # ln -s /opt/python3/bin/python3 /usr/bin/python3 ``` It is to ensure that installation will not conflict with python installed with yum. See exp...
Problems installing python3 on RHEL
8,087,184
52
2011-11-10T22:21:44Z
14,670,884
9
2013-02-03T08:53:29Z
[ "python", "python-3.x", "rhel" ]
I'm trying to install python3 on RHEL using the following steps: ``` yum search python3 ``` Which returned `No matches found for: python3` Followed by: ``` yum search python ``` None of the search results contained python3. What should I try next?
You can download a source RPMs and binary RPMs for RHEL6 / CentOS6 from [here](http://jur-linux.org/download/el-updates/6/) This is a backport from the newest Fedora development source rpm to RHEL6 / CentOS6
Problems installing python3 on RHEL
8,087,184
52
2011-11-10T22:21:44Z
21,450,656
9
2014-01-30T07:52:42Z
[ "python", "python-3.x", "rhel" ]
I'm trying to install python3 on RHEL using the following steps: ``` yum search python3 ``` Which returned `No matches found for: python3` Followed by: ``` yum search python ``` None of the search results contained python3. What should I try next?
Use the SCL repos. ``` sudo sh -c 'wget -qO- http://people.redhat.com/bkabrda/scl_python33.repo >> /etc/yum.repos.d/scl.repo' sudo yum install python33 scl enable python27 ``` (This last command will have to be run each time you want to use python27 rather than the system default.)
Problems installing python3 on RHEL
8,087,184
52
2011-11-10T22:21:44Z
23,317,640
101
2014-04-26T23:30:28Z
[ "python", "python-3.x", "rhel" ]
I'm trying to install python3 on RHEL using the following steps: ``` yum search python3 ``` Which returned `No matches found for: python3` Followed by: ``` yum search python ``` None of the search results contained python3. What should I try next?
Installing from RPM is generally better, because: * you can install and **uninstall** (properly) python3. * the **installation time is way faster**. If you work in a cloud environment and multiple VMs, compiling python3 on each VMs is not acceptable. The IUS Community provides some **up-to-date packages for RHEL & Ce...
Problems installing python3 on RHEL
8,087,184
52
2011-11-10T22:21:44Z
31,448,480
7
2015-07-16T07:58:23Z
[ "python", "python-3.x", "rhel" ]
I'm trying to install python3 on RHEL using the following steps: ``` yum search python3 ``` Which returned `No matches found for: python3` Followed by: ``` yum search python ``` None of the search results contained python3. What should I try next?
Python3 was recently added to EPEL7 as Python34. There is ongoing (currently) effort to make packaging guidelines about how to package things for Python3 in EPEL7. See <https://bugzilla.redhat.com/show_bug.cgi?id=1219411> and <https://lists.fedoraproject.org/pipermail/python-devel/2015-July/000721.html>
How to randomly delete a number of lines from a big file?
8,087,313
11
2011-11-10T22:33:11Z
8,087,365
9
2011-11-10T22:39:09Z
[ "python", "bash", "random", "sed", "awk" ]
I have a big text file of 13 GB with 158,609,739 lines and I want to randomly select 155,000,000 lines. I have tried to scramble the file and then cut the 155000000 first lines, but it's seem that my ram memory (16GB) isn't enough big to do this. The pipelines i have tried are: ``` shuf file | head -n 155000000 sort ...
You could always pre-generate which line numbers (a list of 3,609,739 random numbers selected without replacement) you plan on deleting, then just iterate through the file and copy to another, skipping lines as necessary. As long as you have space for a new file this would work. You could select the random numbers wit...
How to randomly delete a number of lines from a big file?
8,087,313
11
2011-11-10T22:33:11Z
8,087,377
13
2011-11-10T22:40:55Z
[ "python", "bash", "random", "sed", "awk" ]
I have a big text file of 13 GB with 158,609,739 lines and I want to randomly select 155,000,000 lines. I have tried to scramble the file and then cut the 155000000 first lines, but it's seem that my ram memory (16GB) isn't enough big to do this. The pipelines i have tried are: ``` shuf file | head -n 155000000 sort ...
As you copy each line of the file to the output, assess its probability that it should be deleted. The first line should have a 3,609,739/158,609,739 chance of being deleted. If you generate a random number between 0 and 1 and that number is less than that ratio, don't copy it to the output. Now the odds for the second...
Approximately converting unicode string to ascii string in python
8,087,381
10
2011-11-10T22:41:19Z
8,087,475
14
2011-11-10T22:49:24Z
[ "python", "string", "unicode", "ascii" ]
don't know wether this is trivial or not, but I'd need to convert an unicode string to ascii string, and I wouldn't like to have all those escape chars around. I mean, is it possible to have an "approximate" conversion to some quite similar ascii character? For example: Gavin O’Connor gets converted to Gavin O\x92Co...
Use the [Unidecode](http://pypi.python.org/pypi/Unidecode) package to transliterate the string. ``` >>> import unidecode >>> unidecode.unidecode(u'Gavin O’Connor') "Gavin O'Connor" ```
Why is creating a set from a filter so much faster than creating a list or a tuple?
8,087,761
5
2011-11-10T23:16:36Z
8,087,795
11
2011-11-10T23:20:08Z
[ "python", "python-3.x", "python-internals" ]
I’m running `filter` on an interable and want to store the result in a sequence (I need a sequence so that I can use `random.choice` on it). I noticed that creating a *set* from a *filter* object is a lot faster than creating a *list* or a *tuple*. Why is that? I first though that the filter type is a subtype of set,...
`filter()` returns an iterator in Python 3, and this iterator will be consumed on the first run of the inner for-loop. After that, you are only measuring the speed of the contructor -- that's why you have to repeat it so often to make it consume at least a bit of time. So it seems that the constructor of `set()` is th...
How to display index during list iteration with Django?
8,088,069
3
2011-11-10T23:57:58Z
8,088,095
15
2011-11-11T00:01:51Z
[ "python", "django" ]
I am passing a list to a view. My array looks like this: `[football, basketball, soccer]`. In my view, I would like to display something like this: ``` 1. football 2. basketball 3. soccer ``` This means that I would have to iterate through the list that is passed to the array, do a for loop on the elements. How would...
You want the [forloop.counter](https://docs.djangoproject.com/en/1.3/ref/templates/builtins/#for) template variable. > The for loop sets a number of variables available within the loop: > > **forloop.counter** The current iteration of the loop (1-indexed) So your code would look like: ``` {% for sport in sports %} ...
If len(list) is not divisible by 3, then exclude last item in a function . Python 2.7.1
8,088,340
2
2011-11-11T00:37:13Z
8,088,351
9
2011-11-11T00:38:22Z
[ "python", "string", "function", "division", "string-length" ]
if you have a string ``` string='abcdefg' ``` and you wanted to check if the length of the string is divisible by 3 ``` len(string) ``` what command would you use?
You can use the modulo (division remainder) operator `%`: ``` if len(s) % 3 == 0: ... ``` If you want to strip the string to a length divisible by 3, use ``` s[:len(s) // 3 * 3] ``` or ``` s[:-(len(s) % 3)] ```
How do I convert a single character into it's hex ascii value in python
8,088,375
19
2011-11-11T00:42:24Z
8,088,383
36
2011-11-11T00:43:11Z
[ "python", "hex", "ascii" ]
I am interested in taking in a single character, ``` c = 'c' # for example hex_val_string = char_to_hex_string(c) print hex_val_string ``` output: ``` 63 ``` What is the simplest way of going about this? Any predefined string library stuff?
``` >>> hex(ord("c")) '0x63' >>> format(ord("c"), "x") '63' >>> "c".encode("hex") '63' ```
How do I add multiple "NOT LIKE '%?%' in the WHERE clause of sqlite3 in python code?
8,089,096
14
2011-11-11T02:48:03Z
8,089,111
21
2011-11-11T02:50:20Z
[ "python", "sql", "sqlite" ]
I have a sqlite3 query that is executed inside python code. An example would be ``` SELECT word FROM table WHERE word NOT LIKE '%a%'; ``` This would select all of the words where 'a' does not occur in the word. This I can get to work perfectly. The problem is if I want to further restrict the results to not include '...
``` SELECT word FROM table WHERE word NOT LIKE '%a%' AND word NOT LIKE '%b%' AND word NOT LIKE '%c%'; ```
How do I add multiple "NOT LIKE '%?%' in the WHERE clause of sqlite3 in python code?
8,089,096
14
2011-11-11T02:48:03Z
8,089,198
8
2011-11-11T03:06:44Z
[ "python", "sql", "sqlite" ]
I have a sqlite3 query that is executed inside python code. An example would be ``` SELECT word FROM table WHERE word NOT LIKE '%a%'; ``` This would select all of the words where 'a' does not occur in the word. This I can get to work perfectly. The problem is if I want to further restrict the results to not include '...
If you use Sqlite's REGEXP support ( see the answer at [Problem with regexp python and sqlite](http://stackoverflow.com/questions/5365451/problem-with-regexp-python-and-sqlite) for how to do that ) , then you can do it easily in one clause: ``` SELECT word FROM table WHERE word NOT REGEXP '[abc]'; ```
CSRF Token missing or incorrect
8,089,224
13
2011-11-11T03:10:20Z
8,089,453
19
2011-11-11T03:49:42Z
[ "python", "django", "django-forms", "csrf" ]
Beginner at Django here, I've been trying to fix this for a long time now. I do have 'django.middleware.csrf.CsrfViewMiddleware' in my middleware classes and I do have the token in my post form. Heres my code, what am I doing wrong? ``` from django.contrib.auth.forms import UserCreationForm from django.shortcuts impo...
My guess is that you have the tag in the template but it's not rendering anything (or did you mean you confirmed in the actual HTML that a CSRF token is being generated?) Either use `RequestContext` instead of a dictionary ``` render_to_response("foo.html", RequestContext(request, {})) ``` Or make sure you have `dja...
Applying string operations to numpy arrays?
8,089,940
6
2011-11-11T05:08:26Z
8,096,904
12
2011-11-11T16:22:15Z
[ "python", "numpy" ]
Are there better ways to apply string operations to `ndarray`s rather than iterating over them? I would like to use a "vectorized" operation, but I can only think of using `map` (example shown) or list comprehensions. ``` Arr = numpy.rec.fromrecords(zip(range(5),'as far as i know'.split()), ...
**Update:** See [Larsman's answer](http://stackoverflow.com/a/17994373/325565) to this question: Numpy recently added a `numpy.char` module for basic string operations. **Short answer:** Numpy doesn't provide vectorized string operations. The idiomatic way is to do something like (where `Arr` is your numpy array): ``...
Applying string operations to numpy arrays?
8,089,940
6
2011-11-11T05:08:26Z
17,994,373
11
2013-08-01T12:41:29Z
[ "python", "numpy" ]
Are there better ways to apply string operations to `ndarray`s rather than iterating over them? I would like to use a "vectorized" operation, but I can only think of using `map` (example shown) or list comprehensions. ``` Arr = numpy.rec.fromrecords(zip(range(5),'as far as i know'.split()), ...
Yes, recent NumPy has vectorized string operations, in the [`numpy.char`](http://docs.scipy.org/doc/numpy/reference/routines.char.html) module. E.g., when you want to find all strings starting with a B in an array of strings, that's ``` >>> y = np.asarray("B-PER O O B-LOC I-LOC O B-ORG".split()) >>> y array(['B-PER', ...
resize with averaging or rebin a numpy 2d array
8,090,229
13
2011-11-11T05:58:38Z
8,090,605
21
2011-11-11T06:53:37Z
[ "python", "numpy", "slice", "binning" ]
I am trying to reimplement in python an IDL function: <http://star.pst.qub.ac.uk/idl/REBIN.html> which downsizes by an integer factor a 2d array by averaging. For example: ``` >>> a=np.arange(24).reshape((4,6)) >>> a array([[ 0, 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17], ...
Here's an example based on [the answer you've linked](http://stackoverflow.com/questions/4624112/grouping-2d-numpy-array-in-average/4624923#4624923) (for clarity): ``` >>> import numpy as np >>> a = np.arange(24).reshape((4,6)) >>> a array([[ 0, 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10, 11], [12, 13, 14,...
form object has no attribute 'cleaned_data'
8,090,891
9
2011-11-11T07:26:47Z
8,095,915
23
2011-11-11T15:09:39Z
[ "python", "django-forms", "django-templates", "django-views" ]
I am trying to generate a form using django documentation. I am continously getting the error: ``` 'TestForm' object has no attribute 'cleaned_data' ``` even though `form.is_valid` is `True` (it prints the 'form is valid' line of my code). Following are the relevant portions of my code. *urls.py* ``` url(r'^test/',...
You are not triggering the cleaning and validation of the form, this is made by calling the `is_valid()` method (note the parentheses **`()`** ), that's why you have no cleaned data. Correction: ``` if request.method == 'POST': form = TestForm(request.POST) if form.is_valid(): print 'form is valid' ...
style, formatting the slice operator
8,092,513
8
2011-11-11T10:14:53Z
8,092,813
7
2011-11-11T10:43:25Z
[ "python", "coding-style" ]
[PEP 8](http://www.python.org/dev/peps/pep-0008/) doesn't mention the slice operator. From my understanding, unlike other operators, it should not be surrounded with whitespace ``` spam[3:5] # OK spam[3 : 5] # NOT OK ``` Does this hold when using complex expressions, that is, which one is considered better style `...
As you already mentioned, PEP8 doesn't explicitly mention the slice operator in that format, but `spam[3:5]` is definitely more common and IMHO more readable. If [pep8 checker](http://pypi.python.org/pypi/pep8) is anything to go by, the space before `:` will be flagged up ``` [me@home]$ pep8 <(echo "spam[3:44]") #...
404 on requests without trailing slash to i18n urls
8,092,695
10
2011-11-11T10:32:48Z
8,092,710
18
2011-11-11T10:34:10Z
[ "python", "django" ]
Because of the `APPEND_SLASH = True` setting all requests with "/whatever/path" will be redirected to "/whatever/path/". BUT urls definded within a `i18n_patterns()` don't redirect for some reason even the test works: ``` ./runtests.py --settings=test_sqlite i18n.URLRedirectWithoutTrailingSlashTests ```
it doesn't work properly if the middleware's aren't in order. see: <https://docs.djangoproject.com/en/1.5/topics/i18n/translation/#how-django-discovers-language-preference> that's how it should look like: ``` MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.loca...
Split a list of tuples into sub-lists of the same tuple field
8,092,877
14
2011-11-11T10:49:45Z
8,092,908
18
2011-11-11T10:52:21Z
[ "python" ]
I have a huge list of tuples in this format. The second field of the each tuple is the category field. ``` [(1, 'A', 'foo'), (2, 'A', 'bar'), (100, 'A', 'foo-bar'), ('xx', 'B', 'foobar'), ('yy', 'B', 'foo'), (1000, 'C', 'py'), (200, 'C', 'foo'), ..] ``` What is the most efficient way...
Use [itertools.groupby](http://docs.python.org/library/itertools.html#itertools.groupby): ``` import itertools import operator data=[(1, 'A', 'foo'), (2, 'A', 'bar'), (100, 'A', 'foo-bar'), ('xx', 'B', 'foobar'), ('yy', 'B', 'foo'), (1000, 'C', 'py'), (200, 'C', 'foo'), ] for key,group ...
sort eigenvalues and associated eigenvectors after using numpy.linalg.eig in python
8,092,920
37
2011-11-11T10:53:35Z
8,093,043
54
2011-11-11T11:04:17Z
[ "python", "sorting", "numpy" ]
I'm using numpy.linalg.eig to obtain a list of eigenvalues and eigenvectors: ``` A = someMatrixArray from numpy.linalg import eig as eigenValuesAndVectors solution = eigenValuesAndVectors(A) eigenValues = solution[0] eigenVectors = solution[1] ``` I would like to sort my eigenvalues (e.g. from lowest to highest), i...
Use [numpy.argsort](http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html#numpy.argsort). It returns the indices one would use to sort the array. ``` import numpy as np import numpy.linalg as linalg A = np.random.random((3,3)) eigenValues,eigenVectors = linalg.eig(A) idx = eigenValues.argsort()[::-1...
Python - matplotlib: find intersection of lineplots
8,094,374
12
2011-11-11T13:03:55Z
8,095,198
18
2011-11-11T14:16:12Z
[ "python", "matplotlib", "intersection" ]
I have a probably simple question, that keeps me going already for quiet a while. Is there a simple way to return the intersection of two plotted (non-analytical) datasets in python matplotlib ? For elaboration, I have something like this: ``` x=[1.4,2.1,3,5.9,8,9,23] y=[2.3,3.1,1,3.9,8,9,11] x1=[1,2,3,4,6,8,9] y1=[4...
We could use `scipy.interpolate.PiecewisePolynomial` to create functions which are defined by your piecewise-linear data. ``` p1=interpolate.PiecewisePolynomial(x1,y1[:,np.newaxis]) p2=interpolate.PiecewisePolynomial(x2,y2[:,np.newaxis]) ``` We could then take the difference of these two functions, ``` def pdiff(x):...
is unicode( codecs.BOM_UTF8, "utf8" ) necessary in Python 2.7/3?
8,096,078
6
2011-11-11T15:20:52Z
8,097,903
7
2011-11-11T17:45:55Z
[ "python", "unicode", "utf-8", "byte-order-mark" ]
In a code review I came across the following code: ``` # Python bug that renders the unicode identifier (0xEF 0xBB 0xBF) # as a character. # If untreated, it can prevent the page from validating or rendering # properly. bom = unicode( codecs.BOM_UTF8, "utf8" ) r = r.replace(bom, '') ``` This is in a function that p...
The [Unicode standard states](http://www.unicode.org/unicode/faq/utf_bom.html#BOM) that the character `\ufeff` has two distinct meanings. At the *start* of a data stream, it should be used as a byte-order and/or encoding signature, but elsewhere it should be interpreted as a *zero-width non-breaking space*. So the cod...
Python Twisted WebSocket client
8,096,237
8
2011-11-11T15:31:56Z
8,099,316
8
2011-11-11T20:06:07Z
[ "python", "websocket", "twisted" ]
Having worked with Twisted in the past I'd like to know if there is a way to get WebSocket client support to work. Looking around the documentation I can only find server implementations.
[Tavendo Autobahn](http://www.tavendo.de/autobahn/) is a very featureful websockets implementation. One of those features is [a Python WebSockets client with Twisted support](http://www.tavendo.de/autobahn/python_features.html).
Split large files using python
8,096,614
5
2011-11-11T15:58:50Z
8,096,748
7
2011-11-11T16:08:23Z
[ "python", "split" ]
I have some trouble trying to split large files (say, around 10GB). The basic idea is simply read the lines, and group every, say 40000 lines into one file. But there are two ways of "reading" files. 1) The first one is to read the WHOLE file at once, and make it into a LIST. But this will require loading the WHOLE fi...
``` i = 1 fout = open("output0.txt","wb") for line in fileinput.FileInput(filename): fout.write(line) i+=1 if i%40000 == 0: fout.close() fout = open("output%d.txt"%(i/40000),"wb") fout.close() ```
How would I build python myself from source code on Ubuntu?
8,097,161
16
2011-11-11T16:43:17Z
8,097,241
16
2011-11-11T16:48:50Z
[ "python", "linux", "ubuntu" ]
Ubuntu comes with Python 2.7.2+ pre-installed. (I also downloaded the python dev packages.) Because of another issue I'm having (Explained in extreme depth in [How do I replace/update the version of the expat library used by Apache?](http://stackoverflow.com/questions/8072209/how-do-i-replace-update-the-version-of-the-...
At a shell prompt (in a terminal), run `sudo apt-get install build-essential`. This will fetch all the common packages you need to build anything (e.g. the compiler etc.). Then run `sudo apt-get build-dep python2.7` which will fetch all the libraries you need to build python. Then download the source code for python, d...
Why Python is so slow for a simple for loop?
8,097,408
21
2011-11-11T17:03:56Z
8,097,594
10
2011-11-11T17:17:41Z
[ "python", "performance", "jit" ]
We are making some `kNN` and `SVD` implementations in Python. Others picked Java. Our execution times are very different. I used cProfile to see where I make mistakes but everything is quite [fine](http://wiki.python.org/moin/PythonSpeed/PerformanceTips) actually. Yes, I use `numpy` also. But I would like to ask simple...
Because you mention scientific code, have a look at `numpy`. What you're doing has probably already been done (or rather, it uses LAPACK for things like SVD). When you hear about python being used for scientific code, people probably aren't referring to using it in the way you do in your example. As a quick example: ...
Why Python is so slow for a simple for loop?
8,097,408
21
2011-11-11T17:03:56Z
8,097,669
21
2011-11-11T17:25:30Z
[ "python", "performance", "jit" ]
We are making some `kNN` and `SVD` implementations in Python. Others picked Java. Our execution times are very different. I used cProfile to see where I make mistakes but everything is quite [fine](http://wiki.python.org/moin/PythonSpeed/PerformanceTips) actually. Yes, I use `numpy` also. But I would like to ask simple...
> I think I am making mistakes because I know Python is used by lots of scientific projects. They're heavily using SciPy (NumPy being the most prominent component, but I've heard the ecosystem that developed around NumPy's API is even more important) which *vastly* speeds up all kinds operations these projects need. T...
Multiple Inheritance with same Base Classes in Python
8,097,877
3
2011-11-11T17:43:40Z
8,097,913
13
2011-11-11T17:46:51Z
[ "python", "multiple-inheritance" ]
I'm trying to wrap my head around multiple inheritance in python. Suppose I have the following base class: ``` class Structure(object): def build(self, *args): print "I am building a structure!" self.components = args ``` And let's say I have two classes that inherit from it: ``` class House(Str...
Your `super()` call in `SchoolHouse` is wrong. It is: ``` super(School, self).build(*args) ``` It should be: ``` super(SchoolHouse, self).build(*args) ```
Mongoengine creation_time attribute in Document
8,098,122
21
2011-11-11T18:07:51Z
8,143,443
38
2011-11-15T21:34:54Z
[ "python", "django", "orm", "mongodb", "mongoengine" ]
I am trying to add a `creation_time` attribute to my documents. The following would be an example: ``` import datetime class MyModel(mongoengine.Document): creation_date = mongo.DateTimeField() modified_date = mongo.DateTimeField(default=datetime.datetime.now) ``` Django models have built in parameter for th...
You could override the save method. ``` class MyModel(mongoengine.Document): creation_date = mongo.DateTimeField() modified_date = mongo.DateTimeField(default=datetime.datetime.now) def save(self, *args, **kwargs): if not self.creation_date: self.creation_date = datetime.datetime.now()...
Mongoengine creation_time attribute in Document
8,098,122
21
2011-11-11T18:07:51Z
11,517,262
18
2012-07-17T06:43:30Z
[ "python", "django", "orm", "mongodb", "mongoengine" ]
I am trying to add a `creation_time` attribute to my documents. The following would be an example: ``` import datetime class MyModel(mongoengine.Document): creation_date = mongo.DateTimeField() modified_date = mongo.DateTimeField(default=datetime.datetime.now) ``` Django models have built in parameter for th...
As an aside, the creation time is stamped into the `_id` attribute - if you do: ``` YourObject.id.generation_time ``` Will give you a datetime stamp.
Why is Pydev giving a syntax error for built-in keywords?
8,099,380
12
2011-11-11T20:11:36Z
8,101,987
12
2011-11-12T02:02:00Z
[ "python", "eclipse", "syntax-error", "pydev" ]
Why is Pydev giving me syntax errors for built-in python functions like str()? > Undefined variable: str > > Undefined variable: False > > Undefined variable: float
Remove and re-add the python interpreter in the PyDev configuration. Make sure that the project is using the newly added interpreter.
should I reuse the cursor in the python MySQLdb module
8,099,902
10
2011-11-11T20:59:36Z
8,100,331
11
2011-11-11T21:41:07Z
[ "python", "mysql", "cgi" ]
I'm writing a python CGI script that will query a MySQL database. I'm using the MySQLdb module. Since the database will be queryed repeatedly, I wrote this function.... ``` def getDatabaseResult(sqlQuery,connectioninfohere): # connect to the database vDatabase = MySQLdb.connect(connectioninfohere) # create...
The MySQLdb developer recommends building an application specific API that does the DB access stuff for you so that you don't have to worry about the mysql query strings in the application code. It'll make the code a bit more extendable ([link](http://mysql-python.sourceforge.net/MySQLdb.html#using-and-extending)). As...
Inheriting methods' docstrings in Python
8,100,166
42
2011-11-11T21:26:07Z
8,101,118
20
2011-11-11T23:17:19Z
[ "python", "oop", "inheritance", "docstring", "template-method-pattern" ]
I have an OO hierarchy with docstrings that take as much maintenance as the code itself. E.g., ``` class Swallow(object): def airspeed(self): """Returns the airspeed (unladen)""" raise NotImplementedError class AfricanSwallow(Swallow): def airspeed(self): # whatever ``` Now, the probl...
This is a variation on [Paul McGuire's DocStringInheritor metaclass](http://groups.google.com/group/comp.lang.python/msg/26f7b4fcb4d66c95). 1. It inherits a parent member's docstring if the child member's docstring is empty. 2. It inherits a parent class docstring if the child class docstring is empty. 3. It can...
Inheriting methods' docstrings in Python
8,100,166
42
2011-11-11T21:26:07Z
8,101,598
17
2011-11-12T00:44:31Z
[ "python", "oop", "inheritance", "docstring", "template-method-pattern" ]
I have an OO hierarchy with docstrings that take as much maintenance as the code itself. E.g., ``` class Swallow(object): def airspeed(self): """Returns the airspeed (unladen)""" raise NotImplementedError class AfricanSwallow(Swallow): def airspeed(self): # whatever ``` Now, the probl...
Write a function in a class-decorator style to do the copying for you. In Python2.5, you can apply it directly after the class is created. In later versions, you can apply with the [@decorator](https://docs.python.org/2.7/glossary.html#term-decorator) notation. Here's a first cut at how to do it: ``` import types de...
Duplicate a list of lists in python?
8,100,187
2
2011-11-11T21:28:40Z
8,100,202
8
2011-11-11T21:30:14Z
[ "python", "list", "duplicates" ]
I need to be able to duplicate a list of lists in python. so for example right now I have a function that returns a list. this is always lists within a list. for example: ``` myList = [[1,2,3],[4,5,6],[7,8,9]] ``` now I need to create two copies of this list (myList1, and myList2), each of which is separately mut...
Everything you have tried so far only creates a shallow copy of the outer list. To create a deep copy, use either ``` copied_list = [x[:] for x in my_list] ``` using a list comprehension or ``` copied_list = copy.deepcopy(my_list) ``` using the [`copy.deepcopy()`](http://docs.python.org/library/copy.html#copy.deepc...
Bug with re.split function and re.DOTALL flag in re module of Python 2.7.1
8,100,767
4
2011-11-11T22:31:15Z
8,100,941
10
2011-11-11T22:53:15Z
[ "python", "regex", "python-2.7" ]
I have a Mac running Lion and Python 2.7.1. I am noticing something very strange from the re module. If I run the following line: ``` print re.split(r'\s*,\s*', 'a, b,\nc, d, e, f, g, h, i, j, k,\nl, m, n, o, p, q, r') ``` I get this result: ``` ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', ...
``` >>> s = 'a, b,\nc, d, e, f, g, h, i, j, k,\nl, m, n, o, p, q, r' >>> re.split(r'\s*,\s*', s) ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r'] >>> re.split(r'\s*,\s*', s, maxsplit=16) ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q, r'] >>...
Why does Django create Postgres timestamp columns with time zones?
8,101,506
4
2011-11-12T00:27:43Z
8,101,969
14
2011-11-12T01:59:28Z
[ "python", "django", "postgresql", "datetime", "timezone" ]
I thought that Django created datetime columns that were time zone agnostic, but when I looked at my Postgres table I saw that the values recorded there have time zone information. Going further I found that the Postgres backend directs Django to create columns that use time zones. From django/db/backends/postgresql/...
The bad news is that the root of the problem is in Python's datetime implementation. The good news is that Django has [an open ticket](https://code.djangoproject.com/ticket/2626) on this problem. The bad news is that the ticket was opened in 2006. The good news is that a [recent proposal](http://groups.google.com/gr...
Algorithm (Python): find the smallest number greater than k
8,101,592
5
2011-11-12T00:43:34Z
8,101,599
12
2011-11-12T00:44:53Z
[ "python", "algorithm" ]
I have a question from algorithm point of view. I have a list of numbers (floats) ``` 1.22,3.2, 4.9,12.3.....and so on ``` And I want to find the smallest number greater than (lets say) 4.. So the answer is 4.9 But besides the obvious solution.. (iterating thru list and keeping a track of smallest number greater than...
``` min(x for x in my_list if x > 4) ```
Python dictionary : removing u' chars
8,101,649
27
2011-11-12T00:56:10Z
8,101,675
12
2011-11-12T01:00:47Z
[ "python", "mongodb" ]
How do I remove **u** chars from the following dictionary? ``` {u'name': u'A', u'primary_key': 1} ``` This data is coming from `Mongo Database` **find()** query so that it looks like ``` {'name': 'A', 'primary_key': 1} ```
The `u` characters that you are seeing simply mean that they are unicode strings. If you do not want them to be unicode, you can encode them as something else, such as ASCII. ``` >>> s = u'hi!' >>> s u'hi' >>> s2 = s.encode('ascii') >>> s2 'hi' ```
Python dictionary : removing u' chars
8,101,649
27
2011-11-12T00:56:10Z
8,102,155
36
2011-11-12T02:43:11Z
[ "python", "mongodb" ]
How do I remove **u** chars from the following dictionary? ``` {u'name': u'A', u'primary_key': 1} ``` This data is coming from `Mongo Database` **find()** query so that it looks like ``` {'name': 'A', 'primary_key': 1} ```
Some databases such as Sqlite3 let you define [converter](http://docs.python.org/library/sqlite3.html#sqlite3.register_converter) and [adapter](http://docs.python.org/library/sqlite3.html#sqlite3.register_adapter) functions so you can retrieve text as *str* rather than *unicode*. Unfortunately, MongoDB doesn't provide ...
SWIG C++ to Python: Warning(362): operator= ignored
8,102,244
8
2011-11-12T03:05:32Z
8,102,271
7
2011-11-12T03:09:51Z
[ "c++", "python", "swig" ]
I am exporting a C++ class to Python and I noticed that during compilation, SWIG issued the following warning: ``` Warning(362): operator= ignored ``` I am not sure why the operator is being overloaded, because it says in the [SWIG documentation](http://www.swig.org/Doc1.3/Python.html#Python_nn24), that SWIG is capab...
There is no assignment in python (other than in primitive types), only assignment of pointers. If you want to create a copy, you need a special copy function.
problems installing pycrypto on osx
8,102,292
10
2011-11-12T03:16:01Z
8,102,792
8
2011-11-12T05:41:56Z
[ "python", "django" ]
I'm trying to install a Django project onto my OSX machine, which requires PyCrypto. I'm getting the following error: ``` running install running build running build_py running build_ext running build_configure checking for gcc... no checking for cc... no checking for cl.exe... no configure: error: in `/Users/home/Doc...
``` configure: error: no acceptable C compiler found in $PATH ``` This error is self-explanatory. Get a C compiler. XCode should work.