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
why does b'(and sometimes b' ') show up when I split some HTML source[Python]
8,102,471
2
2011-11-12T04:05:35Z
8,102,479
7
2011-11-12T04:07:28Z
[ "python", "parsing", "python-3.x" ]
I'm fairly new to Python and programming in general. I have done a few tutorials and am about 2/3 through a pretty good book. That being said I've been trying to get more comfortable with Python and proggramming by just trying things in the std lib out. that being said I have recently run into a wierd quirk that I'm s...
The "b" prefix means that the type is *bytes* not *str*. To convert the bytes into text, use the *decode* method and name the appropriate encoding. The encoding is often found in the "Content-Type" header: ``` >>> u = urllib.request.urlopen('http://cnn.com') >>> u.getheader('Content-Type') 'text/html; charset=UTF-8' >...
Intersection complexity
8,102,478
8
2011-11-12T04:07:15Z
8,102,536
13
2011-11-12T04:23:58Z
[ "python", "set", "complexity-theory" ]
In Python you can get the intersection of two sets doing: ``` >>> s1 = {1, 2, 3, 4, 5, 6, 7, 8, 9} >>> s2 = {0, 3, 5, 6, 10} >>> s1 & s2 set([3, 5, 6]) >>> s1.intersection(s2) set([3, 5, 6]) ``` Anybody knows the complexity of this intersection (`&`) algorithm? **EDIT:** In addition, does anyone know what is the dat...
The [intersection algorithm](http://hg.python.org/cpython/file/2.7/Objects/setobject.c#l1240) always runs at O(min(len(s1), len(s2))). In pure Python, it looks like this: ``` def intersection(self, other): if len(self) <= len(other): little, big = self, other else: little, ...
If Python 3 is the newest python, why is python 2 still around?
8,102,987
10
2011-11-12T06:34:14Z
8,102,993
9
2011-11-12T06:36:23Z
[ "python" ]
I used Python a few years ago when 2 was the only version. Now there is 2 and 3. Was there a a reason 2 hasn't continued to upgrade and now there is a split into two different pythons? Like no one uses Python 2.5. They all use 2.7 or whatever it is. Why not just use 3? Obviously there's a reason, but I was unable to ...
> Why not just use 3? A lot of existing Python code is not compatible with Python 3 yet. If you need to use [Django](https://docs.djangoproject.com/en/dev/faq/install/#can-i-use-django-with-python-3) for example you are forced to use Python 2.x. > My second question is, which one should I use? * [Python 3 and PyQt 4...
Difference Between Two Lists with Duplicates in Python
8,106,227
7
2011-11-12T17:32:55Z
8,106,270
15
2011-11-12T17:37:43Z
[ "python" ]
I have two lists that contain many of the same items, including duplicate items. I want to check which items in the first list are not in the second list. For example, I might have one list like this: ``` l1 = ['a', 'b', 'c', 'b', 'c'] ``` and one list like this: ``` l2 = ['a', 'b', 'c', 'b'] ``` Comparing these tw...
You didn't specify if the order matters. If it does not, you can do this in >= Python 2.7: ``` l1 = ['a', 'b', 'c', 'b', 'c'] l2 = ['a', 'b', 'c', 'b'] from collections import Counter c1 = Counter(l1) c2 = Counter(l2) diff = c1-c2 print list(diff.elements()) ```
cc1plus: warning: command line option "-Wstrict-prototypes" is valid for Ada/C/ObjC but not for C++
8,106,258
12
2011-11-12T17:36:06Z
8,106,847
22
2011-11-12T19:08:17Z
[ "c++", "python", "gcc", "swig" ]
I am building a C++ extension for use in Python. I am seeing this warning being generated during the compilation process - when a type: ``` python setup.py build_ext -i ``` What is causing it, and how do I fix it? BTW, here is a copy of my setup file: ``` #!/usr/bin/env python """ setup.py file for SWIG ex...
I can answer part of the question, why you're getting the message. Something in your build process is invoking gcc on a C++ source file with the option `-Wstrict-prototypes`. For C and Objective-C, this causes the compiler to warn about old-style function declarations that don't declare the types of arguments. For C+...
cc1plus: warning: command line option "-Wstrict-prototypes" is valid for Ada/C/ObjC but not for C++
8,106,258
12
2011-11-12T17:36:06Z
9,740,721
9
2012-03-16T16:10:10Z
[ "c++", "python", "gcc", "swig" ]
I am building a C++ extension for use in Python. I am seeing this warning being generated during the compilation process - when a type: ``` python setup.py build_ext -i ``` What is causing it, and how do I fix it? BTW, here is a copy of my setup file: ``` #!/usr/bin/env python """ setup.py file for SWIG ex...
`-Wstrict-prototypes` option is read by distutils from `/usr/lib/pythonX.Y/config/Makefile` as part of OPT variable. It seems hackish, but you can override it by setting `os.environ['OPT']` in your setup.py. Here is a code that seems not too harmful: ``` import os from distutils.sysconfig import get_config_vars (opt...
On a django form, how do I loop through individual options per field?
8,106,311
4
2011-11-12T17:44:13Z
8,106,524
7
2011-11-12T18:18:28Z
[ "python", "django", "forms" ]
I'm building a form wizard. On the first step I have a form with one field. That field is a foreign key. Django's default widget for a foreign key gives me the field's options in a drop down (select) menu and represenets each option as an html option. I changed the default widget to a RadioSelect. So now it gives me th...
you can access the choices queryset, but note that a template is probably not the right place for this kind of logic. NB the `field.field` which isn't a typo ``` {% for field in form %} {% for option in field.field.choices.queryset %} {{ option.image }} {{ option.title }} {{ option.descript...
__new__ and __init__ in Python
8,106,900
30
2011-11-12T19:16:35Z
8,106,977
30
2011-11-12T19:29:09Z
[ "python", "class" ]
I am learning Python and so far I can tell the things below about `__new__` and `__init__`: 1. `__new__` is for object creation 2. `__init__` is for object initialization 3. `__new__` is invoked before `__init__` as `__new__` returns a new instance and `__init__` invoked afterwards to initialize inner state. 4. `__new...
> how I should structure the class using `__init__` and `__new__` as they are different and both accepts arbitrary arguments besides default first argument. Only rarely will you have to worry about `__new__`. Usually, you'll just define `__init__` and let the default `__new__` pass the constructor arguments to it. > ...
Using Amazon S3 with Heroku, Python, and Flask
8,107,198
9
2011-11-12T20:05:54Z
8,524,363
12
2011-12-15T17:43:38Z
[ "python", "file-upload", "heroku", "amazon-s3", "flask" ]
I am trying to get a simple image upload app working on Heroku using Flask. I'm following the tutorial here: <http://flask.pocoo.org/docs/patterns/fileuploads/> However, I want to use S3 to store the file instead of a temporary directory, since Heroku does not let you write to disk. I cannot find any examples of how t...
It seems to me that in the example code that stores the uploaded file to a temporary file, you would just replace `file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))` with code that uploads the file to S3 instead. For example, from the linked page: ``` def upload_file(): if request.method == 'POST': ...
Force Overwrite in Os.Rename
8,107,352
24
2011-11-12T20:30:59Z
8,107,391
18
2011-11-12T20:35:50Z
[ "python" ]
Is it possible to force a rename os.rename to overwrite another file if it already exists? For example in the code below if the file Tests.csv already exists it would be replaced by the Tests.txt file (that was also renamed to Tests.csv). ``` os.rename("C:\Users\Test.txt","C:\Users\Tests.csv"); ```
You could try [`shutil.move()`](http://docs.python.org/library/shutil.html#shutil.move): ``` from shutil import move move('C:\\Users\\Test.txt', 'C:\\Users\\Tests.csv') ``` Or `os.remove` and then `shutil.move`: ``` from os import remove from shutil import move remove('C:\\Users\\Tests.csv') move('C:\\Users\\Test....
Force Overwrite in Os.Rename
8,107,352
24
2011-11-12T20:30:59Z
8,107,434
7
2011-11-12T20:41:54Z
[ "python" ]
Is it possible to force a rename os.rename to overwrite another file if it already exists? For example in the code below if the file Tests.csv already exists it would be replaced by the Tests.txt file (that was also renamed to Tests.csv). ``` os.rename("C:\Users\Test.txt","C:\Users\Tests.csv"); ```
As the [documentation](http://docs.python.org/library/os.html) says it's impossible to guarantee an atomic renaming operation on Windows if the file exists so what Python does is asking to do the double step `os.remove` + `os.rename` yourself, handling potential errors. On unix systems `rename` overwrites the destinat...
Python FAQ: “How fast are exceptions?”
8,107,695
11
2011-11-12T21:30:48Z
8,108,440
13
2011-11-12T23:45:26Z
[ "python", "performance", "exception" ]
I was just looking at the Python FAQ because it was mentioned in another question. Having never really looked at it in detail before, I came across [this question](http://docs.python.org/3/faq/design.html#how-fast-are-exceptions): “How fast are exceptions?”: > A try/except block is extremely efficient. Actually ca...
Catching exceptions *is* expensive, but exceptions should be *exceptional* (read, not happen very often). If exceptions are rare, `try/catch` is faster than LBYL. The following example times a dictionary key lookup using exceptions and LBYL when the key exists and when it doesn't exist: ``` import timeit s = [] s.a...
Using 'argparse.ArgumentError' in Python
8,107,713
21
2011-11-12T21:34:32Z
8,107,776
28
2011-11-12T21:45:15Z
[ "python", "argparse" ]
I'd like to use the `ArgumentError` exception in the `argparse` module in Python, but I can't figure out how to use it. The signature says that it should be called as `ArgumentError(argument, message)`, but I can't figure out what `argument` should be. I think it should be some part of the parser object, but I couldn't...
From [the source documentation](https://hg.python.org/cpython/file/v3.5.2/Lib/argparse.py#l34): > ArgumentError: The exception raised by ArgumentParser objects when there are errors with the parser's actions. Errors raised while parsing the command-line are caught by ArgumentParser and emitted as command-line messages...
Standalone Python web server and/or nginx
8,107,986
2
2011-11-12T22:19:03Z
8,108,094
7
2011-11-12T22:36:34Z
[ "python", "nginx", "webserver", "tornado", "bottle" ]
So I've done some reading about Python web frameworks (or servers?), mostly [Tornado](http://www.tornadoweb.org/) and [Bottle](http://bottlepy.org/) but also [FAPWS3](http://www.fapws.org/), and there are still some grey areas. First, these three web frameworks are all said to be fast, yet they all include a web serve...
First of, Tornado and FAPWS3 are web servers, while Bottle is a web framework. Those belong to completely different categories. Web frameworks are usually run as a [WSGI](http://en.wikipedia.org/wiki/Web_Server_Gateway_Interface) server behind a HTTP ("web") proxy. The HTTP server included in most frameworks is only t...
General approach to developing an image classification algorithm for Dilbert cartoons
8,108,550
28
2011-11-13T00:08:15Z
8,112,714
23
2011-11-13T15:51:32Z
[ "python", "machine-learning", "computer-vision", "classification", "feature-detection" ]
As a self-development exercise, I want to develop a simple classification algorithm that, given a particular cell of a Dilbert cartoon, is able to identify which characters are present in the cartoon (Dilbert, PHB, Ratbert etc.). I assume the best way to do this is to (1) apply some algorithm to the image, which conve...
So i think you are on the right track w/r/t your step 1 (*apply some algorithm to the image, which converts it into a set of features)*. This project is more challenging that most ML problems because here you will actually have to create your training data set from the raw data (the individual frames comprising the ca...
In Python, when should I use a function instead of a method?
8,108,688
58
2011-11-13T00:38:33Z
8,108,821
40
2011-11-13T01:14:08Z
[ "python", "function", "coding-style", "methods" ]
The Zen of Python states that there should only be one way to do things- yet frequently I run into the problem of deciding when to use a function versus when to use a method. Let's take a trivial example- a ChessBoard object. Let's say we need some way to get all the legal King moves available on the board. Do we writ...
My general rule is this - *is the operation performed on the object or by the object?* if it is done by the object, it should be a member operation. If it could apply to other things too, or is done by something else to the object then it should be a function (or perhaps a member of something else). When introducing ...
In Python, when should I use a function instead of a method?
8,108,688
58
2011-11-13T00:38:33Z
8,108,930
14
2011-11-13T01:36:12Z
[ "python", "function", "coding-style", "methods" ]
The Zen of Python states that there should only be one way to do things- yet frequently I run into the problem of deciding when to use a function versus when to use a method. Let's take a trivial example- a ChessBoard object. Let's say we need some way to get all the legal King moves available on the board. Do we writ...
Use a class when you want to: 1) Isolate calling code from implementation details -- taking advantage of [abstraction](http://en.wikipedia.org/wiki/Abstraction_%28computer_science%29) and [encapsulation](http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29). 2) When you want to be substitutabl...
How to sort mongodb with pymongo
8,109,122
77
2011-11-13T02:13:58Z
8,109,158
166
2011-11-13T02:22:38Z
[ "python", "mongodb", "pymongo" ]
I'm trying to use the sort feature when querying my mongoDB, but it is failing. The same query works in the MongoDB console but not here. Code is as follows: ``` import pymongo from pymongo import Connection connection = Connection() db = connection.myDB print db.posts.count() for post in db.posts.find({}, {'entitie...
`.sort()`, in pymongo, takes `key` and `direction` as parameters. So if you want to sort by, let's say, `id` then you should `.sort("_id", 1)`
How to sort mongodb with pymongo
8,109,122
77
2011-11-13T02:13:58Z
25,781,364
10
2014-09-11T07:16:21Z
[ "python", "mongodb", "pymongo" ]
I'm trying to use the sort feature when querying my mongoDB, but it is failing. The same query works in the MongoDB console but not here. Code is as follows: ``` import pymongo from pymongo import Connection connection = Connection() db = connection.myDB print db.posts.count() for post in db.posts.find({}, {'entitie...
You can try this: ``` db.Account.find().sort("UserName") db.Account.find().sort("UserName",pymongo.ASCENDING) db.Account.find().sort("UserName",pymongo.DESCENDING) ```
Understanding gi.repository
8,109,805
11
2011-11-13T05:27:39Z
8,856,900
13
2012-01-13T20:37:14Z
[ "python", "gtk", "matplotlib" ]
I have troubles understanding gi.repository I use this contruction in my code ``` from gi.repository import Gtk ``` But if I want to use some component I get import error I searched and I got it worked for some components, like GtkSource, Vte, GLib, ... So my code is like ``` from gi.repository import Gtk, GtkSou...
It seems that the support for Gtk3 it's been [added recently](https://github.com/matplotlib/matplotlib/pull/590). I guess it will take some time till it's available in the main distributions. The best solution would be to download and install the latest version. As a workaround to avoid installing stuff in my Ubuntu ...
python - regex search and findall
8,110,059
12
2011-11-13T06:33:27Z
8,110,193
12
2011-11-13T07:13:01Z
[ "python", "regex", "search", "string-matching", "findall" ]
I need to find all matches in a string for a given regex. I've been using `findall()` to do that until I came across a case where it wasn't doing what I expected. For example: ``` regex = re.compile('(\d+,?)+') s = 'There are 9,000,000 bicycles in Beijing.' print re.search(regex, s).group(0) > 9,000,000 print re.fin...
Ok, I see what's going on... from the docs: ``` If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. ``` As it turns out, you do have a group, "(\d+,?)"... so, what it's returning is the last occurrence of this group, or 000....
Simple way to query connected USB devices info in Python?
8,110,310
13
2011-11-13T07:43:21Z
8,110,666
18
2011-11-13T09:14:21Z
[ "python", "usb", "libusb" ]
How can we query connected USB devices info in Python? I want to get UID Device Name (ex: SonyEricsson W660), path to device (ex: /dev/ttyACM0) And also what would be the best Parameter out of above info to be used as identifying the device whenever it's connected again? (UID?) I am working on Ubuntu 11.04. ATM I ha...
If you are working on windows, you can use [`pywin32`](http://sourceforge.net/projects/pywin32/). I found an example [here](http://www.velocityreviews.com/forums/t746030-get-usb-id-of-a-serial-port-through-pyserial.html): ``` import win32com.client wmi = win32com.client.GetObject ("winmgmts:") for usb in wmi.Instanc...
Simple way to query connected USB devices info in Python?
8,110,310
13
2011-11-13T07:43:21Z
8,265,634
20
2011-11-25T06:50:51Z
[ "python", "usb", "libusb" ]
How can we query connected USB devices info in Python? I want to get UID Device Name (ex: SonyEricsson W660), path to device (ex: /dev/ttyACM0) And also what would be the best Parameter out of above info to be used as identifying the device whenever it's connected again? (UID?) I am working on Ubuntu 11.04. ATM I ha...
I can think of a quick code like this. Since all USB ports can be accessed via /dev/bus/usb/< bus >/< device > For the ID generated, even if you unplug the device and reattach it [ could be some other port ]. It will be the same. ``` import re import subprocess device_re = re.compile("Bus\s+(?P<bus>\d+)\s+Device\s+(...
Python package without __init__
8,110,951
14
2011-11-13T10:31:43Z
8,128,033
18
2011-11-14T21:00:14Z
[ "python", "built-in" ]
I `pip install`-ed the [flufl.enum](http://pypi.python.org/pypi/flufl.enum) Python package and I noticed that it works despite missing a `flufl/__init__.py` module as regular Python packages. Even stranger is this: ``` >>> import flufl >>> flufl <module 'flufl' (built-in)> ``` I tried to reproduce this creating `foo/...
the magic is done in the flufl.enum-3.2-py2.7-nspkg.pth file, which is put into site-packages by "pip install": ``` import sys,new,os p = os.path.join(sys._getframe(1).f_locals['sitedir'], *('flufl',)) ie = os.path.exists(os.path.join(p,'__init__.py')) m = not ie and sys.modules.setdefault('flufl',new.module('flufl'))...
psycopg2 does not execute PostgreSQL function
8,111,278
5
2011-11-13T11:43:36Z
8,111,323
11
2011-11-13T11:52:38Z
[ "python", "postgresql", "psycopg2" ]
I'm trying to call a function from `psycopg2` like such: ``` conn = psycopg2.connect(host="name.host.ex", user="username", password="secret") cur = conn.cursor() cur.callproc("f_do_action", ["aaa", "bbb"]) cur.close() conn.close() ``` When calling this function from `psql` everything works fine but using `psycopg2` n...
Try committing before closing your connection: ``` cur.close() conn.commit() conn.close() ``` From [psycopg2 documentation](http://initd.org/psycopg/docs/connection.html): > Note that closing a connection without committing the changes first > will cause any pending change to be discarded as if a ROLLBACK was > perf...
Python operator that mimic javascript || operator
8,111,484
2
2011-11-13T12:23:27Z
8,111,499
12
2011-11-13T12:25:38Z
[ "python" ]
I am Python newbie, so maybe don't knew if this is obvious or not. In Javascript `a||b` returns `a` if `a` is evaluated to true, else returns `b`. Is that possible in Python other than lengthy if else statement.
I believe this is correct: ``` x = a or b ``` ## Proof This is how "`||`" works in JavaScript: ``` > 'test' || 'again' "test" > false || 'again' "again" > false || 0 0 > 1 || 0 1 ``` This is how "`or`" works in Python: ``` >>> 'test' or 'again' 'test' >>> False or 'again' 'again' >>> False or 0 0 >>> 1 or 0 1 ```
How to pass flags to a distutils extension?
8,111,754
8
2011-11-13T13:12:13Z
8,114,529
7
2011-11-13T20:34:54Z
[ "python", "setuptools", "distutils" ]
I'm trying to install a Python module that contains C modules. The C code relies on a library being available in the system's global install locations (/usr/include, /usr/lib), but in my case I only have a local installation of this lib available. Therefore, I would like to pass parameters (e.g., --incdir, --libdir) wh...
I found out that prepending ``` CFLAGS="-I<local include dir>" LDFLAGS="-L<local lib dir>" ``` to the command line when calling setup.py did the trick.
can't create django project using Windows command prompt
8,112,630
10
2011-11-13T15:37:11Z
8,112,652
12
2011-11-13T15:40:02Z
[ "python", "django" ]
if i run ``` django-admin.py startproject mysite ``` django-admin.py (which is located in `C:\python27\scripts/django-admin.py`) will open in a file editor (now it opens in python ide, but in the past i had pype so it would open in pype) so the file opens: ``` #!C:\Python27\python.exe from django.core import managem...
I don't think Windows supports the shebang line. Try invoking it with `python django-admin.py ...`
BeautifulSoup innerhtml?
8,112,922
13
2011-11-13T16:26:24Z
18,602,241
15
2013-09-03T22:04:31Z
[ "python", "html", "beautifulsoup", "innerhtml" ]
Let's say I have a page with a `div`. I can easily get that div with `soup.find()`. Now that I have the result, I'd like to print the WHOLE `innerhtml` of that `div`: I mean, I'd need a string with ALL the html tags and text all toegether, exactly like the string I'd get in javascript with `obj.innerHTML`. Is this pos...
There is an undocumented function that does approximate the [DOMs innerHTML method](http://domparsing.spec.whatwg.org/#innerhtml): ``` def innerHTML(element): return element.decode_contents(formatter="html") ``` This has passed all my test cases so far. Perhaps someone should update the docs?
Supressing namespace prefixes in ElementTree 1.2
8,113,296
22
2011-11-13T17:24:08Z
8,116,716
15
2011-11-14T02:40:55Z
[ "python", "xml", "xml-serialization", "elementtree" ]
In python 2.7 (with etree 1.3), I can suppress the XML prefixes on elements like this: ``` 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 Type "help", "copyright", "credits" or "license" for more information. >>> import xml.etree.Element...
After looking at the [source code for ElementTree in python2.6](http://svn.python.org/view/python/tags/r267/Lib/xml/etree/ElementTree.py?revision=88851&view=markup), the `:` is hard coded in the `fixtag` function. As a workaround, here's what I did: ``` from xml.etree import ElementTree as etree if etree.VERSION[0:3]...
Python Itertools.Permutations()
8,113,684
14
2011-11-13T18:27:33Z
8,113,692
27
2011-11-13T18:30:11Z
[ "python", "python-3.x" ]
Why does itertools.permutations() return a list of characters or digits for each permutation, instead of just returning a string? For example: ``` >>> print([x for x in itertools.permutations('1234')]) >>> [('1', '2', '3', '4'), ('1', '2', '4', '3'), ('1', '3', '2', '4') ... ] ``` Why doesn't it return this? ``` >>...
`itertools.permutations()` simply works this way. It takes an arbitrary iterable as an argument, and always returns an iterator yielding tuples. It doesn't (and shouldn't) special-case strings. To get a list of strings, you can always join the tuples yourself: ``` list(map("".join, itertools.permutations('1234'))) ```
Python Itertools.Permutations()
8,113,684
14
2011-11-13T18:27:33Z
8,113,695
12
2011-11-13T18:30:29Z
[ "python", "python-3.x" ]
Why does itertools.permutations() return a list of characters or digits for each permutation, instead of just returning a string? For example: ``` >>> print([x for x in itertools.permutations('1234')]) >>> [('1', '2', '3', '4'), ('1', '2', '4', '3'), ('1', '3', '2', '4') ... ] ``` Why doesn't it return this? ``` >>...
Because it expects an iterable as a parameter and doesn't know, it's a string. The parameter is described in the docs. <http://docs.python.org/library/itertools.html#itertools.permutations>
Split string on whitespace in Python
8,113,782
173
2011-11-13T18:46:11Z
8,113,787
324
2011-11-13T18:46:54Z
[ "python", "regex", "string", "split", "whitespace" ]
I'm looking for the Python equivalent of ``` String str = "many fancy word \nhello \thi"; String whiteSpaceRegex = "\\s"; String[] words = str.split(whiteSpaceRegex); ["many", "fancy", "word", "hello", "hi"] ```
The `str.split()` method without an argument splits on whitespace: ``` >>> "many fancy word \nhello \thi".split() ['many', 'fancy', 'word', 'hello', 'hi'] ```
Split string on whitespace in Python
8,113,782
173
2011-11-13T18:46:11Z
8,113,811
40
2011-11-13T18:49:54Z
[ "python", "regex", "string", "split", "whitespace" ]
I'm looking for the Python equivalent of ``` String str = "many fancy word \nhello \thi"; String whiteSpaceRegex = "\\s"; String[] words = str.split(whiteSpaceRegex); ["many", "fancy", "word", "hello", "hi"] ```
``` import re s = "many fancy word \nhello \thi" re.split('\s+', s) ```
Split string on whitespace in Python
8,113,782
173
2011-11-13T18:46:11Z
30,899,640
7
2015-06-17T18:33:44Z
[ "python", "regex", "string", "split", "whitespace" ]
I'm looking for the Python equivalent of ``` String str = "many fancy word \nhello \thi"; String whiteSpaceRegex = "\\s"; String[] words = str.split(whiteSpaceRegex); ["many", "fancy", "word", "hello", "hi"] ```
Another method through `re` module. ``` >>> import re >>> s = "many fancy word \nhello \thi" >>> re.findall(r'\S+', s) ['many', 'fancy', 'word', 'hello', 'hi'] ``` This would match one or more non-space characters.
Nullable DecimalField returns 'This value must be a decimal number' when blank
8,114,192
2
2011-11-13T19:48:46Z
8,168,598
7
2011-11-17T14:19:13Z
[ "python", "django", "django-models" ]
I have a field in my model that's of type `DecimalField`. Even though I have `blank=True` and `null=True` in the options, when my model goes through form validation and that field is blank, I get an error 'This value must be a decimal number.' Can `DecimalField`s not be null? I could set a default of 0 for this field b...
Your `forms.CharField` will return an empty string, not `None` (Python's `NULL`). Therefore it tries to set the column to `''` (empty string), not `NULL`. You should probably use a `django.forms.DecimalField` in the form. See <https://docs.djangoproject.com/en/dev/ref/forms/fields/#decimalfield>
Is there a way to "compile" Python code onto an Arduino (Uno)?
8,114,916
41
2011-11-13T21:33:33Z
8,130,115
16
2011-11-15T00:31:53Z
[ "python", "arduino", "pyserial" ]
I have a robotics type project with an [Arduino Uno](http://arduino.cc/en/Main/ArduinoBoardUno), and to make a long story short, I am experimenting with some AI algorithms. However, I need to implement some high level matrix algorithms that would be quite simple using [NumPy](http://en.wikipedia.org/wiki/NumPy)/[SciPy]...
There was a talk about using Python with robotics at this years [PyConAU](http://pycon-au.org/2011/about/) called [*Ah! I see you have the machine that goes 'BING'!*](http://www.youtube.com/user/PyConAU#p/u/17/nzCvomTixzU) by Dr. Graeme Cross. The only option he recommended for using Python on a microcontroller board ...
How to remove all the escape sequences from a list of strings?
8,115,261
4
2011-11-13T22:28:35Z
8,115,286
7
2011-11-13T22:32:17Z
[ "python" ]
I want to remove all types of escape sequences from a list of strings. How can I do this? input: ``` ['william', 'short', '\x80', 'twitter', '\xaa', '\xe2', 'video', 'guy', 'ray'] ``` output: ``` ['william', 'short', 'twitter', 'video', 'guy', 'ray'] ``` <http://docs.python.org/reference/lexical_analysis.html#strin...
Something like this? ``` >>> from ast import literal_eval >>> s = r'Hello,\nworld!' >>> print(literal_eval("'%s'" % s)) Hello, world! ``` **Edit**: ok, that's not what you want. What you want can't be done in general, because, as @Sven Marnach explained, strings don't actually contain escape sequences. Those are just...
How to remove all the escape sequences from a list of strings?
8,115,261
4
2011-11-13T22:28:35Z
8,115,378
13
2011-11-13T22:45:45Z
[ "python" ]
I want to remove all types of escape sequences from a list of strings. How can I do this? input: ``` ['william', 'short', '\x80', 'twitter', '\xaa', '\xe2', 'video', 'guy', 'ray'] ``` output: ``` ['william', 'short', 'twitter', 'video', 'guy', 'ray'] ``` <http://docs.python.org/reference/lexical_analysis.html#strin...
If you want to strip out some characters you don't like, you can use the [translate](http://docs.python.org/library/string.html#string.translate) function to strip them out: ``` >>> s="\x01\x02\x10\x13\x20\x21hello world" >>> print(s) !hello world >>> s '\x01\x02\x10\x13 !hello world' >>> delete = "" >>> i=1 >>> esca...
ImportError: No module named bz2 for Python 2.7.2
8,115,280
30
2011-11-13T22:31:29Z
8,115,329
21
2011-11-13T22:38:54Z
[ "python", "ubuntu" ]
I'm using Python 2.7.2 on Ubuntu 11.10. I got this error when importing the bz2 module: `ImportError: No module named bz2` I thought the bz2 module is supposed to come with Python 2.7. How can I fix this problem? EDIT: I think I previously installed Python 2.7.2 by compiling from source. Probably at that point I did...
Okay, this is much easier to understand in answer form, so I'll move what I would write in my comment to this answer. Luckily for you, you didn't overwrite the system version of python, as Ubuntu 11.10 comes with 2.7.2 preinstalled. Your python binaries (`python` and `python2.7`) are located in `/usr/local/bin`, whic...
ImportError: No module named bz2 for Python 2.7.2
8,115,280
30
2011-11-13T22:31:29Z
14,123,902
36
2013-01-02T14:36:50Z
[ "python", "ubuntu" ]
I'm using Python 2.7.2 on Ubuntu 11.10. I got this error when importing the bz2 module: `ImportError: No module named bz2` I thought the bz2 module is supposed to come with Python 2.7. How can I fix this problem? EDIT: I think I previously installed Python 2.7.2 by compiling from source. Probably at that point I did...
I meet the same problem, here's my solution. The reason of import error is while you are building python, system couldn't find the bz2 headers and skipped building bz2 module. Install them on Ubuntu/Debian: ``` sudo apt-get install libbz2-dev ``` Fedora: ``` sudo yum install bzip2-devel ``` and then rebuild pytho...
ImportError: No module named bz2 for Python 2.7.2
8,115,280
30
2011-11-13T22:31:29Z
20,987,218
19
2014-01-08T04:44:41Z
[ "python", "ubuntu" ]
I'm using Python 2.7.2 on Ubuntu 11.10. I got this error when importing the bz2 module: `ImportError: No module named bz2` I thought the bz2 module is supposed to come with Python 2.7. How can I fix this problem? EDIT: I think I previously installed Python 2.7.2 by compiling from source. Probably at that point I did...
In case, you must be used python2.7, you should run: (Centos 6.4) ``` sudo cp /usr/lib64/python2.6/lib-dynload/bz2.so /usr/local/lib/python2.7/ ```
Why wont Web.py let me run a server on port 80?
8,115,330
5
2011-11-13T22:39:20Z
8,115,527
11
2011-11-13T23:10:41Z
[ "python", "web.py" ]
Im trying to create a website with Web.py but its not letting me open a create a socket on port 80 but it works on every other port. I have port forwarded and all that so that's not the problem. ``` python main.py 80 ``` but when I do this I get the error: ``` http://0.0.0.0:80/ Traceback (most recent call last): ...
You possibly have something else working on port 80. Try the command `netstat -ln | grep 80` to check that. Alternatively, you can try `telnet localhost 80`, and if the connection is refused then that port should be clear to use.
Python gives 'Not well-formed xml' error because of presence of '&' characters
8,115,875
5
2011-11-14T00:08:50Z
8,119,387
7
2011-11-14T09:16:17Z
[ "python", "xml", "ampersand" ]
I am reading an xml file using Python. But my xml file contains `&` characters, because of which while running my Python code, it gives the following error: ``` xml.parsers.expat.ExpatError: not well-formed (invalid token): ``` Is there a way to ignore the `&` check by python?
No, you can't ignore the check. Your 'xml file' is not an XML file - to be an XML file, the ampersand would have to be escaped. Therefore, no software that is designed to read XML files will parse it without error. You need to correct the software that generated this file so that it generates proper ("well-formed") XML...
Python Conditional Variable Setting
8,116,127
10
2011-11-14T00:51:59Z
8,116,132
16
2011-11-14T00:53:30Z
[ "python", "variables", "if-statement", "condition" ]
For some reason I can't remember how to do this - I believe there was a way to set a variable in Python, if a condition was true? What I mean is this: ``` value = 'Test' if 1 == 1 ``` Where it would hopefully set *value* to 'Test' if the condition (1 == 1) is true. And with that, I was going to test for multiple con...
This is the closest thing to what you are looking for: ``` value = 'Test' if 1 == 1 else 'NoTest' ``` Otherwise, there isn't much else.
itertools.groupby()
8,116,666
4
2011-11-14T02:29:08Z
8,116,674
11
2011-11-14T02:30:49Z
[ "python", "itertools" ]
I have this data: ``` self.data = list: [(1, 1, 5.0), (1, 2, 3.0), (1, 3, 4.0), (2, 1, 4.0), (2, 2, 2.0), (2, 3, 4.0), (2, 5, 3.0), (3, 2, 2.0), (3, 4, 4.0), ...
[itertools.groupby](http://docs.python.org/library/itertools.html#itertools.groupby) collects together **contiguous** items with the same key. If you want all items with the same key, you have to sort `self.data` first. ``` for mid, group in itertools.groupby( sorted(self.data,key=operator.itemgetter(1)), key=oper...
itertools.groupby()
8,116,666
4
2011-11-14T02:29:08Z
15,250,161
8
2013-03-06T14:37:54Z
[ "python", "itertools" ]
I have this data: ``` self.data = list: [(1, 1, 5.0), (1, 2, 3.0), (1, 3, 4.0), (2, 1, 4.0), (2, 2, 2.0), (2, 3, 4.0), (2, 5, 3.0), (3, 2, 2.0), (3, 4, 4.0), ...
Variant without sorting (via dictionary). Should be better performance-wise. ``` def full_group_by(l, key=lambda x: x): d = defaultdict(list) for item in l: d[key(item)].append(item) return d.items() ```
Relationship between python map reduce and cloud-computing map/reduce?
8,117,515
6
2011-11-14T04:58:18Z
8,117,691
8
2011-11-14T05:30:31Z
[ "python", "cloud", "mapreduce" ]
I'm new to Python, Do someone know what's relationships between Python (and functional languages') functions `map()` / `reduce()` and MapReduce concept related to distributed computations?
The cloud concept of map/reduce is very similar, but changed to work in parallel. First, each data object is passed through a function that `map`s it to a new object (usually, some sort of dictionary). Then, a `reduce` function is called on pairs of the objects returned by `map` until there is only one left. That is th...
Python - Rounding by quarter-intervals
8,118,679
11
2011-11-14T07:50:47Z
8,118,744
16
2011-11-14T07:58:09Z
[ "python", "documentation", "rounding", "intervals" ]
I'm running into the following issue: Given various numbers like: 10.38 11.12 5.24 9.76 does an already 'built-in' function exists to round them up to the closest 0.25 step like e.g.: 10.38 --> 10.50 11.12 --> 11.00 5.24 --> 5.25 9.76 --> 9-75 ? Or can I go ahead and hack together a function that performs th...
``` >>> def my_round(x): ... return round(x*4)/4 ... >>> >>> assert my_round(10.38) == 10.50 >>> assert my_round(11.12) == 11.00 >>> assert my_round(5.24) == 5.25 >>> assert my_round(9.76) == 9.75 >>> ```
Python - Rounding by quarter-intervals
8,118,679
11
2011-11-14T07:50:47Z
8,118,808
22
2011-11-14T08:07:41Z
[ "python", "documentation", "rounding", "intervals" ]
I'm running into the following issue: Given various numbers like: 10.38 11.12 5.24 9.76 does an already 'built-in' function exists to round them up to the closest 0.25 step like e.g.: 10.38 --> 10.50 11.12 --> 11.00 5.24 --> 5.25 9.76 --> 9-75 ? Or can I go ahead and hack together a function that performs th...
This is a general purpose solution which allows rounding to arbitrary resolutions. For your specific case, you just need to provide `0.25` as the resolution but other values are possible, as shown in the test cases. ``` def roundPartial (value, resolution): return round (value / resolution) * resolution print "Ro...
Doctest for nested docstring
8,119,308
5
2011-11-14T09:08:26Z
8,119,837
9
2011-11-14T09:55:20Z
[ "python", "doctest", "docstring" ]
Suppose I have following code: ``` def foo(s): """A dummy function foo. For example: >>> a = '''This is a test string line 1 This is a test string line 2 This is a test string line 3''' >>> foo(a) This is a test string line 1 This is a test string line 2 This is a test string line 3 >>> """ print s if __...
I think you need to put some dots there ``` >>> a = """This is a test string line 1 ... This is a test string line 2 ... This is a test string line 3""" ```
TypeError: 'float' object not iterable
8,120,019
8
2011-11-14T10:10:56Z
8,120,045
16
2011-11-14T10:14:04Z
[ "python", "for-loop", "floating-point", "python-3.x" ]
I'm using python 3.2.2 on windows 7 and I'm trying to create a program which accepts 7 numbers and then tells the user how many are positive, how many are negative and how many are zero. this is what I have got so far: ``` count=7 for i in count: num = float(input("Type a number, any number:")) if num == 0: ...
`for i in count:` means `for i in 7:`, which won't work. The bit after the `in` should be of an iterable type, not a number. Try this: ``` for i in range(count): ```
Python. Doing some work on background with Gtk GUI
8,120,860
5
2011-11-14T11:26:10Z
8,138,098
8
2011-11-15T14:42:10Z
[ "python", "gtk", "python-3.x", "pygobject", "gtk3" ]
* **python 3.2.2** * **gtk3 3.2.2** * **python-gobject 3.0.2** I'm trying to display a GUI and do some work in the background. As I understand it should look something like this: ``` #!/usr/bin/env python3 # -*- coding: utf-8 -*- import time from threading import Thread from gi.repository import Gtk, Gdk class Gui...
Can't claim to be any expert on python threading nor gtk3 but after playing around a little with your example I found something that appears to work the way you want it. Instead of sub classing Thread i use threading.start(target=loop\_sleep), and placed that inside Gui. Glib.threads\_init() also seem to be needed. `...
Circular import in python+django?! how to make it work?
8,121,656
2
2011-11-14T12:33:56Z
8,121,691
7
2011-11-14T12:36:34Z
[ "python", "django" ]
Hello I'm spliting my files because the model is getting bigger. So here we are again with problems: My models; If in my Category model I remove the "ArticleToCategory" and the many-to-many relationship it works well. But I need them! How to fix it? I deleted the model.py in order to load files from the model packag...
You can define foreign keys using strings, to avoid exactly this problem. ``` class Art2C(..): art = m.ForeignKey('Article') from_other_app = m.ForeignKey('other_app.Article') ```
accessing selenium web elements with python
8,121,886
12
2011-11-14T12:53:42Z
8,122,105
16
2011-11-14T13:11:48Z
[ "python", "selenium" ]
I'm sure this has been answered somewhere, because it's a very basic question - I can not, however, for the life of me, find the answer on the web. I feel like a complete idiot, but I have to ask so, here goes: I'm writing a python code that will produce a list of all page addresses on a domain. This is done using sel...
I'm familiar with python's api of selenium but you probably can receive link using GetAttribute(attributename ) method. So it should be something like ``` linkstr = "" for link in Listlinker: linkstr = link.get_attribute("href") if linkstr in Domenesider: pass ...
The copy variable changes the original var in Python
8,122,627
5
2011-11-14T13:56:23Z
8,122,672
15
2011-11-14T14:00:26Z
[ "python", "variables" ]
I have a simple problem in Python that is very very strange. ``` def estExt(matriz,erro): # (1) Determinar o vector X das soluções print ("Matrix after:"); print(matriz); aux=matriz; x=solucoes(aux); # IF aux is a copy of matrix, why the matrix is changed?? print ("Matrix before: "); pr...
The line ``` aux=matriz; ``` Does not make a copy of `matriz`, it merely creates a new reference to `matriz` named `aux`. You probably want ``` aux=matriz[:] ``` Which will make a copy, assuming `matriz` is a simple data structure. If it is more complex, you should probably use [`copy.deepcopy`](http://docs.python....
matching all characters in any order in regex
8,123,131
3
2011-11-14T14:36:33Z
8,123,173
9
2011-11-14T14:39:19Z
[ "python", "regex" ]
I'm a regex newbie, but I understand how to match any characters in a regex query in order (ex. [abc] will match any of a, b or c. Also, I believe "abc" will match abc exactly). However, how do I construct a regex query that will match all the characters abc in any order? So for example, I want it to match "cab" or "b...
In Python, I wouldn't use a regualar expression for this purpose, but rather a set: ``` >>> chars = set("abc") >>> chars.issubset("bracket") True >>> chars.issubset("fish") False >>> chars.issubset("bad") False ``` Regular expressions are useful, but there are situations where different tools are more appropriate.
matching all characters in any order in regex
8,123,131
3
2011-11-14T14:36:33Z
8,123,199
9
2011-11-14T14:40:53Z
[ "python", "regex" ]
I'm a regex newbie, but I understand how to match any characters in a regex query in order (ex. [abc] will match any of a, b or c. Also, I believe "abc" will match abc exactly). However, how do I construct a regex query that will match all the characters abc in any order? So for example, I want it to match "cab" or "b...
This *can* be done with lookahead assertions: ``` ^(?=.*a)(?=.*b)(?=.*c) ``` matches if your string contains at least one occurrence of `a`, `b` and `c`. But as you can see, that's not really what regexes are good at. I would have done: ``` if all(char in mystr for char in "abc"): # do something ``` Checking ...
How to git commit nothing without an error?
8,123,674
37
2011-11-14T15:13:49Z
8,123,700
33
2011-11-14T15:16:13Z
[ "python", "git", "fabric" ]
I'm trying to write a fabric script that does a `git commit`; however, if there is nothing to commit, git exits with a status of `1`. The deploy script takes that as unsuccessful, and quits. I do want to detect *actual* failures-to-commit, so I can't just give fabric a blanket ignore for `git commit` failures. How can ...
From the `git commit` man page: ``` --allow-empty Usually recording a commit that has the exact same tree as its sole parent commit is a mistake, and the command prevents you from making such a commit. This option bypassesthe safety, and is primarily for use by foreign SCM interface scripts. ```
How to git commit nothing without an error?
8,123,674
37
2011-11-14T15:13:49Z
8,123,841
43
2011-11-14T15:27:20Z
[ "python", "git", "fabric" ]
I'm trying to write a fabric script that does a `git commit`; however, if there is nothing to commit, git exits with a status of `1`. The deploy script takes that as unsuccessful, and quits. I do want to detect *actual* failures-to-commit, so I can't just give fabric a blanket ignore for `git commit` failures. How can ...
Catch this condition beforehand by checking the exit code of git diff? For example (in shell): ``` git add -A git diff --quiet --exit-code --cached || git commit -m 'bla' ```
"is" not working in python IDE but working in command line
8,123,872
2
2011-11-14T15:29:12Z
8,123,934
9
2011-11-14T15:33:59Z
[ "python" ]
I couldn't understand why this is happening actually.. Take a look at this python code : ``` word = raw_input("Enter Word") length = len(word) if word[length-1:] is "e" : print word + "d" ``` If I give input "love", its output must be "loved". So, when I wrote this in PyScripter IDE, its neithe...
The `is` keyword will only work if the strings have exactly the same identity, which is not guaranteed even if the strings have the same value. You should use `==` instead of `is` here to compare the values of the strings. Or better still, use [`endswith`](http://docs.python.org/library/stdtypes.html#str.endswith): `...
Does Coldfusion support dynamic arguments?
8,124,249
6
2011-11-14T15:57:36Z
8,125,687
10
2011-11-14T17:39:13Z
[ "python", "coldfusion", "coldfusion-9" ]
In python there is the `*args` convention I am wondering if CF9 supports something similar. Here is the python example ``` >>> def func(*args): for a in args: print a, "is a quality argument" >>> func(1, 2, 3) 1 is a quality argument 2 is a quality argument 3 is a quality argument >>> ```
Yes, CFML has supported dynamic arguments for as long as it has supported user-defined functions. All arguments, whether explicitly defined, or whether passed in without being defined, exist in the Arguments scope. The Arguments scope can be treated as both an array and a structure (key/value). Here is the closest e...
Parsing .rst files with Sphinx-specific directives programmatically
8,125,238
7
2011-11-14T17:05:23Z
8,125,293
7
2011-11-14T17:09:54Z
[ "python", "python-sphinx", "docutils" ]
I would like to be able to parse sphinx based rst in Python for further processing and checking. Something like: ``` import sphinx p = sphinx.parse("/path/to/file.rst") do_something_with(p) ``` It seems that something is possible in docutils using the docutils.core.publish\_file: ``` publish_file(open("/path/to/file...
You can use [Sphinx Extensions](http://sphinx.pocoo.org/extensions.html) to do custom processing before the final write. There is a very good getting started example project in the documentation that discusses various hooks that allow you to customize Sphinx. Depending on what you're trying to do, you may need to supp...
What is the differences between container.__iter__() and iterator.__iter__()?
8,125,930
2
2011-11-14T17:58:29Z
8,126,070
8
2011-11-14T18:10:20Z
[ "python" ]
I am poor in python so don't beat me please. ``` >>> a = ['a', 'b', 'c'] >>> a.__iter__() <listiterator object at 0x03531750> >>> a.__iter__().__iter__() <listiterator object at 0x03531690> ``` I see that both of listiterator objects lives in other places (true that `0x03531750` is like place?). I need to know that b...
An iterator has an `__iter__()` method so that you can call `iter()` on it to get an iterator for it, even though it already is one. Makes it easier to write things that use iterators if you don't have to be constantly checking whether something is already an iterator or not. So you're getting an iterator for the list...
Parsing a YAML file in Python, and accessing the data?
8,127,686
37
2011-11-14T20:32:34Z
8,127,777
80
2011-11-14T20:38:53Z
[ "python", "json", "parsing", "yaml" ]
I am new to YAML and have been searching for ways to parse a YAML file and use/access the data from the parsed YAML. I have come across explanations on how to parse the YAML file, for example, the PyYAML [tutorial](http://pyyaml.org/wiki/PyYAMLDocumentation#Tutorial), "[How can I parse a YAML file](http://stackoverflo...
Since PyYAML's `yaml.load()` function maps YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked: ``` import yaml with open('tree.yaml', 'r') as f: doc = yaml.load(f) ``` To access "branch1 text" you would use: ``` txt = doc["tr...
Twisted web - redirects in request
8,128,045
2
2011-11-14T21:01:33Z
8,137,713
7
2011-11-15T14:17:45Z
[ "python", "twisted.web" ]
I was wondering if it is possible to redirect from within a render method in twisted web. I have tried the various ways of redirecting and have only found it documented when used in the getChild method. Basically I am checking to see if a user is logged in and if it isn't then forward the user onto a different Resour...
Apologies Upon further investigation and by fault of my own I had overlooked the "`redirectTo`" method of twisted.web.util This has worked for me perfectly for me. Just thought I would post this here in case anyone else is looking for the same answer. ``` from twisted.web.util import redirectTo def render_G...
How to populate my WTForm variables?
8,128,238
8
2011-11-14T21:17:24Z
8,372,972
19
2011-12-04T03:13:45Z
[ "python", "google-app-engine", "jinja2", "wtforms" ]
I'm enabling a function that can edit an entity. I want to populate the form with the variables from the datastore. How can I do it? My code doesn't populate the form: ``` if self.request.get('id'): id = int(self.request.get('id')) ad = Ad.get(db.Key.from_path('Ad', id)) im = ad.matched_images editAdForm = AdF...
You need to pass your object via the form's second argument, "obj": ``` editAdForm = AdForm(obj=ad) ``` Outlined in the documentation crash course here: <http://wtforms.simplecodes.com/docs/dev/crash_course.html#editing-existing-objects>
Python simple regex
8,129,648
3
2011-11-14T23:26:55Z
8,129,661
9
2011-11-14T23:28:15Z
[ "python", "regex" ]
So I have a pattern: ``` hourPattern = re.compile('\d{2}:\d{2}') ``` And match against the compiled pattern ``` hourStart = hourPattern.match('Sat Jan 28 01:15:00 GMT 2012') ``` When I print `hourStart` it gives me None. Any help?
Match expects the found value to be at the beginning of the string. You want search. ``` >>> import re >>> >>> s = re.compile('\d+') >>> >>> s2 = 'a123' >>> >>> s.match(s2) >>> s.search(s2) <_sre.SRE_Match object at 0x01E29AD8> ```
Optparser-print Usage Help when no argument is given
8,130,016
11
2011-11-15T00:16:44Z
17,111,371
13
2013-06-14T14:56:04Z
[ "python" ]
What I am doing now is to simply check for args length, if it is 0, tell user to type -h. Is there a better way to do this ? Thanks
You can do it with optparse just fine. You don't need to use argparse. ``` if options.foo is None: # where foo is obviously your required option parser.print_help() sys.exit(1) ```
What's try-else good for in Python?
8,130,355
6
2011-11-15T01:13:26Z
16,207,272
7
2013-04-25T05:49:17Z
[ "python", "try-catch" ]
I'm trying to learn the minor details of Python, and I came upon [the try-else statement](http://docs.python.org/reference/compound_stmts.html#the-try-statement). ``` try1_stmt ::= "try" ":" suite ("except" [expression [("as" | ",") target]] ":" suite)+ ["else" ":" suite] ...
> Usually there's no practical difference between putting code in the > end of the try block or in the else block. > > What is the else clause good for? The else-clause itself is interesting. It runs when there is no exception but before the finally-clause. That is its one use-case for which there isn't a reasonable a...
set matplotlib 3d plot aspect ratio?
8,130,823
16
2011-11-15T02:35:27Z
9,349,255
10
2012-02-19T12:45:57Z
[ "python", "matplotlib" ]
``` import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D ``` Setting the aspect ratio works for 2d plots: ``` ax = plt.axes() ax.plot([0,1],[0,10]) ax.set_aspect('equal','box') ``` But does not for 3d: ``` ax = plt.axes(projection='3d') ax.plot([0,1],[0,1],[0,10]) ax.set_aspect('equal','box') ```...
If you know the bounds, eg. +-3 centered around (0,0,0), you can add invisible points like this: ``` import numpy as np import pylab as pl from mpl_toolkits.mplot3d import Axes3D fig = pl.figure() ax = fig.gca(projection='3d') ax.set_aspect('equal') MAX = 3 for direction in (-1, 1): for point in np.diag(direction ...
set matplotlib 3d plot aspect ratio?
8,130,823
16
2011-11-15T02:35:27Z
19,248,731
11
2013-10-08T13:15:16Z
[ "python", "matplotlib" ]
``` import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D ``` Setting the aspect ratio works for 2d plots: ``` ax = plt.axes() ax.plot([0,1],[0,10]) ax.set_aspect('equal','box') ``` But does not for 3d: ``` ax = plt.axes(projection='3d') ax.plot([0,1],[0,1],[0,10]) ax.set_aspect('equal','box') ```...
I didn't try all of these answers, but this kludge did it for me: ``` def axisEqual3D(ax): extents = np.array([getattr(ax, 'get_{}lim'.format(dim))() for dim in 'xyz']) sz = extents[:,1] - extents[:,0] centers = np.mean(extents, axis=1) maxsize = max(abs(sz)) r = maxsize/2 for ctr, dim in zip(c...
Install Python Module in local install of web2py
8,131,279
6
2011-11-15T03:52:52Z
8,132,009
10
2011-11-15T05:44:48Z
[ "python", "windows", "module", "web2py" ]
I am running web2py on a Windows machine. I'm working on an application, but it keeps erroring because it says the module I'm trying to use isn't installed. It is however installed in my local python install. How can I install modules so that web2py can recognize them?
web2py recognize any module you have in your local Python installation, unless you have a module with the same name under /modules folder of your application. If you are on windows I do not recommend the use of .exe version of web2py (this version is only for studies) and it has a self contained isolated Python interp...
Python : How to pass default argument to instance method with an instance variable?
8,131,942
7
2011-11-15T05:34:30Z
8,131,960
15
2011-11-15T05:37:40Z
[ "python", "class", "object", "instance", "default-arguments" ]
My Code : ``` class c: def __init__(self, format): self.format = format def process(self, formatting=self.format) print formatting ``` `Error` : `name 'self' is not defined` I want : (Desired output) ``` c("abc").process() # prints "abc" c("abc").process("xyz") # prints "xyz" `...
You can't really define this as the default value, since the default value is set before any instances exist. An easy work-around is to do something like this: ``` class C: def __init__(self, format): self.format = format def process(formatting=None): formatting = formatting or self.format ...
How to slice a string in Python using a dictionary containing character positions?
8,132,332
2
2011-11-15T06:27:53Z
8,132,415
10
2011-11-15T06:37:11Z
[ "python" ]
I have a dictionary containing the character positions of different fields in a string. I'd like to use that information to slice the string. I'm not really sure how to best explain this, but the example should make it clear: input: ``` mappings = {'name': (0,4), 'job': (4,11), 'color': (11, 15)} data = "JohnChemistB...
``` >>> dict((f, data[slice(*p)]) for f, p in mappings.iteritems()) {'color': 'Blue', 'job': 'Chemist', 'name': 'John'} ```
"self" in python lambda expression
8,132,619
3
2011-11-15T07:01:48Z
8,132,642
7
2011-11-15T07:04:22Z
[ "python", "lambda" ]
``` def buildTestCase(xmlfile, description, method, evalString): func = lambda self, xmlfile=xmlfile, method=method, evalString=evalString: \ method(self, evalString, feedparser.parse(xmlfile)) func.__doc__ = description return func ``` Above is a code snippet from feedparser, why there is a "self" in f...
`self`simply refers to the first argument of the lambda named `self`. the name `self` is not a reserved keyword, it is merely a convention above pythonistas to name the instance of the object on which the function applies. here, the author uses the name `self` as the first argument to the lambda, because this argument...
What is the difference between django classonlymethod and python classmethod?
8,133,312
14
2011-11-15T08:16:58Z
8,133,425
32
2011-11-15T08:30:00Z
[ "python", "django" ]
Why is there a need for Django to introduce the decorator `classonlymethod` ? Why can't it reuse python `classmethod`?
The best explanation may be the source code itself : ``` class classonlymethod(classmethod): def __get__(self, instance, owner): if instance is not None: raise AttributeError("This method is available only on the view class.") return super(classonlymethod, self).__get__(instance, owner)...
psycopg2: insert multiple rows with one query
8,134,602
57
2011-11-15T10:09:24Z
8,503,467
16
2011-12-14T11:06:51Z
[ "python", "postgresql", "psycopg2" ]
I need to insert multiple rows with one query (number of rows is not constant), so I need to execute query like this one: ``` INSERT INTO t (a, b) VALUES (1, 2), (3, 4), (5, 6); ``` The only way I know is ``` args = [(1,2), (3,4), (5,6)] args_str = ','.join(cursor.mogrify("%s", (x, )) for x in args) cursor.execute("...
A snippet from Psycopg2's tutorial page at [Postgresql.org (see bottom)](http://wiki.postgresql.org/wiki/Psycopg2_Tutorial): > A last item I would like to show you is how to insert multiple rows using a dictionary. If you had the following: ``` namedict = ({"first_name":"Joshua", "last_name":"Drake"}, {"f...
psycopg2: insert multiple rows with one query
8,134,602
57
2011-11-15T10:09:24Z
10,147,451
94
2012-04-13T19:53:55Z
[ "python", "postgresql", "psycopg2" ]
I need to insert multiple rows with one query (number of rows is not constant), so I need to execute query like this one: ``` INSERT INTO t (a, b) VALUES (1, 2), (3, 4), (5, 6); ``` The only way I know is ``` args = [(1,2), (3,4), (5,6)] args_str = ','.join(cursor.mogrify("%s", (x, )) for x in args) cursor.execute("...
I built a program that inserts multiple lines to a server that was located in another city. I found out that using this method was about 10 times faster than `executemany`. In my case `tup` is a tuple containing about 2000 rows. It took about 10 seconds when using this method: ``` args_str = ','.join(cur.mogrify("(%...
psycopg2: insert multiple rows with one query
8,134,602
57
2011-11-15T10:09:24Z
30,721,460
7
2015-06-09T01:06:49Z
[ "python", "postgresql", "psycopg2" ]
I need to insert multiple rows with one query (number of rows is not constant), so I need to execute query like this one: ``` INSERT INTO t (a, b) VALUES (1, 2), (3, 4), (5, 6); ``` The only way I know is ``` args = [(1,2), (3,4), (5,6)] args_str = ','.join(cursor.mogrify("%s", (x, )) for x in args) cursor.execute("...
[cursor.copy\_from](http://initd.org/psycopg/docs/cursor.html#cursor.copy_from "copy_from") is the fastest solution I've found for bulk inserts by far. [Here's a gist](http://gist.github.com/jsheedy/ed81cdf18190183b3b7d) I made containing a class named IteratorFile which allows an iterator yielding strings to be read l...
psycopg2: insert multiple rows with one query
8,134,602
57
2011-11-15T10:09:24Z
30,985,541
34
2015-06-22T16:50:14Z
[ "python", "postgresql", "psycopg2" ]
I need to insert multiple rows with one query (number of rows is not constant), so I need to execute query like this one: ``` INSERT INTO t (a, b) VALUES (1, 2), (3, 4), (5, 6); ``` The only way I know is ``` args = [(1,2), (3,4), (5,6)] args_str = ','.join(cursor.mogrify("%s", (x, )) for x in args) cursor.execute("...
Do not mess with string manipulation. All the answers suggesting that are missing the point. Following is the clean way of doing it. Short answer: ``` args = [(1,2), (3,4), (5,6)] records_list_template = ','.join(['%s'] * len(args)) insert_query = 'insert into t (a, b) values {0}'.format(records_list_template) cur.exe...
How to detect if a process is running using Python on Win and MAC
8,135,899
10
2011-11-15T11:49:56Z
8,136,371
15
2011-11-15T12:30:58Z
[ "python", "process" ]
I am trying to find out a way to detect if a process is running in Windows Task Manager for Windows OS and Macintosh Activity Monitor for MAC OS using Python Can someone please help me out with the code please?
[psutil](https://github.com/giampaolo/psutil) is a cross-platform library that retrieves information about running processes and system utilization. ``` import psutil pythons_psutil = [] for p in psutil.process_iter(): try: if p.name() == 'python.exe': pythons_psutil.append(p) except psuti...
Difference in recursion handling between languages
8,136,559
3
2011-11-15T12:48:18Z
8,136,622
10
2011-11-15T12:54:26Z
[ "javascript", "python", "ruby", "recursion", "lisp" ]
Here are some snippets in different languages. Function `double` in question is taken from SICP, ex. 1.41. Lisp: ``` (define (double f) (lambda (x) (f (f x)))) (define (inc x) (+ x 1)) (((double (double double)) inc) 5) ``` Python: ``` def double(f): def result(x): return f(f(x)) return result def inc(x):...
How you call the functions in the scheme code is different from the others. The equivalent python would be: ``` double(double(double))(inc)(5) ``` In words, the scheme code creates a function that applies another function 16 times, and applies that function to `inc`. The python creates functions that apply `inc` 8 ti...
Decode escaped characters in URL
8,136,788
28
2011-11-15T13:06:25Z
8,136,831
54
2011-11-15T13:09:00Z
[ "python", "escaping" ]
I have a list containing URLs with escaped characters in them. Those characters have been set by `urllib2.urlopen` when it recovers the html page: ``` http://www.sample1webpage.com/index.php?title=%E9%A6%96%E9%A1%B5&action=edit http://www.sample1webpage.com/index.php?title=%E9%A6%96%E9%A1%B5&action=history http://www....
[Oh my.](http://docs.python.org/library/urllib.html#urllib.unquote) > `urllib.unquote(`*string*`)` > > Replace `%xx` escapes by their single-character equivalent. > > Example: `unquote('/%7Econnolly/')` yields `'/~connolly/'`. And then just decode.
Decode escaped characters in URL
8,136,788
28
2011-11-15T13:06:25Z
34,193,681
7
2015-12-10T04:27:02Z
[ "python", "escaping" ]
I have a list containing URLs with escaped characters in them. Those characters have been set by `urllib2.urlopen` when it recovers the html page: ``` http://www.sample1webpage.com/index.php?title=%E9%A6%96%E9%A1%B5&action=edit http://www.sample1webpage.com/index.php?title=%E9%A6%96%E9%A1%B5&action=history http://www....
or `urllib.unquote_plus` ``` >>> import urllib >>> urllib.unquote('erythrocyte+membrane+protein+1%2C+PfEMP1+%28VAR%29') 'erythrocyte+membrane+protein+1,+PfEMP1+(VAR)' >>> urllib.unquote_plus('erythrocyte+membrane+protein+1%2C+PfEMP1+%28VAR%29') 'erythrocyte membrane protein 1, PfEMP1 (VAR)' ```
Using Celery as a control channel for Twisted applications
8,137,277
11
2011-11-15T13:45:00Z
8,139,607
11
2011-11-15T16:24:20Z
[ "python", "twisted", "celery" ]
I am trying to use Celery as the control channel for a Twisted application. My Twisted application is an abstraction layer that provides a standard interface to various locally running processes (via ProcessProtocol). I would like to use Celery to control this remotely - AMQP seems like the ideal method of controlling ...
Celery probably blocks while waiting for new messages from the network. Since you're running it in one single-threaded process along with the Twisted reactor, it blocks the reactor from running. This will disable most of Twisted, which requires the reactor to actually run (you called `reactor.run`, but with Celery bloc...
After executing a command by Python Paramiko how could I save result?
8,138,241
4
2011-11-15T14:53:12Z
8,138,442
10
2011-11-15T15:07:58Z
[ "python", "save", "result", "paramiko" ]
As you see below, is it possible to save the result? Cause, at second and third stdout.read() I couldn't reach the result. ``` import paramiko import os dssh = paramiko.SSHClient() dssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) dssh.connect('192.168.1.250', username='root', password='pass') import os stdin...
Imagine that `stdout` is an ordinary file. What do you expect to get if you call `file.read()` the second time? -- nothing (empty string) unless the file has changed outside. To save the string: ``` output = stdout.read() ``` You might find [Fabric](http://fabfile.org) simpler to use (it uses `paramiko` to execute c...
Notify celery task of worker shutdown
8,138,642
4
2011-11-15T15:20:05Z
8,230,470
8
2011-11-22T16:47:36Z
[ "python", "rabbitmq", "celery", "django-celery" ]
I am using celery 2.4.1 with python 2.6, the rabbitmq backend, and django. I would like my task to be able to clean up properly if the worker shuts down. As far as I am aware you cannot supply a task destructor so I tried hooking into the [worker\_shutdown](http://ask.github.com/celery/userguide/signals.html#worker-shu...
`worker_shutdown` is only sent by the `MainProcess`, not the child pool workers. All `worker_*` signals `except for worker_process_init`, refer to the `MainProcess`. However, the shutdown hook never gets called. Ctrl-C'ing the worker doesn't kill the task and I have to manually kill it from the shell. The worker neve...
How do I extract table data in pairs using BeautifulSoup?
8,139,797
6
2011-11-15T16:37:52Z
8,139,900
16
2011-11-15T16:45:20Z
[ "loops", "beautifulsoup", "python" ]
My data sample : ``` <table id = "history"> <tr class = "printCol"> <td class="name">Google</td><td class="date">07/11/2001</td><td class="state"> <span>CA</span> </td> </tr> <tr class = "printCol"> <td class="name">Apple</td><td class="date">27/08/2001</td> </tr> <tr class = "printCol"> <td class="name">Microsoft</td...
List comprehension will make it easier: ``` table = soup.find("table", id = "history") rows = table.findAll('tr') data = [[td.findChildren(text=True) for td in tr.findAll("td")] for tr in rows] # data now contains: [[u'Google', u'07/11/2001'], [u'Apple', u'27/08/2001'], [u'Microsoft', u'01/11/1991']] # If the data ...
How to load training data in PyBrain?
8,139,822
8
2011-11-15T16:39:15Z
8,143,012
19
2011-11-15T20:54:35Z
[ "python", "neural-network", "pybrain" ]
I am trying to use PyBrain for some simple NN training. What I don't know how to do is to load the training data from a file. It is not explained in their website anywhere. I don't care about the format because I can build it now, but I need to do it in a file instead of adding row by row manually, because I will have ...
Here is how I did it: ``` ds = SupervisedDataSet(6,3) tf = open('mycsvfile.csv','r') for line in tf.readlines(): data = [float(x) for x in line.strip().split(',') if x != ''] indata = tuple(data[:6]) outdata = tuple(data[6:]) ds.addSample(indata,outdata) n = buildNetwork(ds.indim,8,8,ds.outdim,recu...
boost.python confused about similar constructor
8,140,155
5
2011-11-15T17:02:58Z
8,142,943
9
2011-11-15T20:48:35Z
[ "c++", "python", "boost" ]
I have a class that looks like ``` class Foo{ Foo(); Foo(int i); Foo(bool b); Foo(double d); }; ``` and I expose my class to python as usual ``` class_<Foo>("Foo") .def(init<int>()) .def(init<bool>()) .def(init<double>()); ``` when I try to use to in python, the python code always cast the c'tor par...
Well, you can change the order of constructor's definitions, the last one will have higher priority. Here is my results: ``` class_<Foo>("Foo") .def(init<bool>()) .def(init<double>()) .def(init<int>()); Foo() # calls Foo() Foo(True) # calls Foo(int) Foo(1) # calls Foo(int) Foo(4.2) # calls Foo(double) ``` As you see...
Python: How do I redirect output of os.system to python shell?
8,140,750
3
2011-11-15T17:45:55Z
8,141,236
7
2011-11-15T18:29:08Z
[ "python" ]
I want to make a simple batch script using python using os.system. I am able to run the commands just fine, but the output for those commands dont print to the python shell. Is there some way to redirect the output to the python shell?
You can use [`subprocess`](http://docs.python.org/library/subprocess.html#module-subprocess). ``` from subprocess import Popen, PIPE p1 = Popen(['ls'], stdout=PIPE) print p1.communicate()[0] ``` This will print the directory listing for the current directory. The `communicate()` method returns a tuple `(stdoutdata, s...
Difference between python 1 and 2
8,141,025
4
2011-11-15T18:10:05Z
8,141,055
8
2011-11-15T18:13:05Z
[ "python", "python-2.x" ]
Just out of complete curiosity, but did python 2 add anything major to python 1? and if so, what?
Summarised from <http://docs.python.org/whatsnew/2.0.html>: * Unicode objects * List comprehensions * Augmented assigment * Cyclic garbage collection * `*args` and `**kwargs` argument unpacking
Parsing meta tags efficiently with lxml?
8,141,553
7
2011-11-15T18:54:59Z
8,141,593
7
2011-11-15T18:58:26Z
[ "python", "screen-scraping", "css-selectors", "web-scraping", "lxml" ]
I'm parsing HTML pages with lxml. The pages have meta tags as follows: ``` <meta property="og:locality" content="Detroit" /> <meta property="og:country-name" content="USA" /> ``` How can I use lxml to find the value of the `og:locality` meta tag on each page, efficiently? I've currently got the following, which just...
You could use this XPath selector: `//meta[@property='og:locality']/@content`
Why is only one Flask teardown_request function being called when view raises Exception?
8,141,721
7
2011-11-15T19:08:14Z
8,142,344
17
2011-11-15T19:56:30Z
[ "python", "flask", "werkzeug" ]
This simple application, has two `teardown_request` handlers, and I'd expect both of them to be called for every request, no matter what happens in the view implementation, as per the [documentation](http://flask.pocoo.org/docs/api/#flask.Flask.teardown_request) ``` import flask import werkzeug.exceptions app = flask...
Just discovered the answer myself. The `teardown_request` functions are not supposed to take a response and return a response, the way [`after_request`](http://flask.pocoo.org/docs/api/#flask.Flask.after_request) does. They apparently take an argument which is usually `None` unless an `Exception` which does not derive...
How to compare two dates?
8,142,364
107
2011-11-15T19:58:14Z
8,142,411
143
2011-11-15T20:02:10Z
[ "python" ]
How would I compare two dates to see which is later, using Python? For example, I want to check if the current date is past the last date in this list I am creating, of holiday dates, so that it will send an email automatically, telling the admin to update the holiday.txt file.
Use the `datetime` method and the operator `<` and its kin. ``` >>> from datetime import datetime >>> past = datetime.now() >>> present = datetime.now() >>> past < present True >>> datetime(3000, 1, 1) < present False >>> present - datetime(2000, 4, 4) datetime.timedelta(4242, 75703, 762105) ```
How to compare two dates?
8,142,364
107
2011-11-15T19:58:14Z
8,142,436
16
2011-11-15T20:03:46Z
[ "python" ]
How would I compare two dates to see which is later, using Python? For example, I want to check if the current date is past the last date in this list I am creating, of holiday dates, so that it will send an email automatically, telling the admin to update the holiday.txt file.
`datetime.date(2011, 1, 1) < datetime.date(2011, 1, 2)` will return `True`. `datetime.date(2011, 1, 1) - datetime.date(2011, 1, 2)` will return `datetime.timedelta(-1)`. `datetime.date(2011, 1, 1) + datetime.date(2011, 1, 2)` will return `datetime.timedelta(1)`. see the [docs](http://docs.python.org/library/datetime...
How to compare two dates?
8,142,364
107
2011-11-15T19:58:14Z
31,544,886
13
2015-07-21T16:41:02Z
[ "python" ]
How would I compare two dates to see which is later, using Python? For example, I want to check if the current date is past the last date in this list I am creating, of holiday dates, so that it will send an email automatically, telling the admin to update the holiday.txt file.
Use `time` Let's say you have the initial dates as strings like these: `date1 = "31/12/2015"` `date2 = "01/01/2016"` You can do the following: `newdate1 = time.strptime(date1, "%d/%m/%Y")` and `newdate2 = time.strptime(date2, "%d/%m/%Y")` to convert them to python's date format. Then, the comparison is obvious:...
Using Selenium and python to save a table
8,143,023
2
2011-11-15T20:56:03Z
8,143,352
14
2011-11-15T21:26:43Z
[ "python", "selenium" ]
I'm trying to use Selenium with Python to store the contents of a table. My script is as follows: ``` import sys import selenium from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get("http://testsite.com") value = selenium.getTable("table_id_10") prin...
The old Selenium RC API included a `get_table` method: ``` In [14]: sel=selenium.selenium("localhost",4444,"*firefox", "http://www.google.com/webhp") In [19]: sel.get_table? Type: instancemethod Base Class: <type 'instancemethod'> String Form: <bound method selenium.get_table of <selenium.selenium.selenium ob...
using Flask and Tornado together?
8,143,141
42
2011-11-15T21:06:52Z
8,247,457
73
2011-11-23T18:44:42Z
[ "python", "wsgi", "nonblocking", "flask", "tornado" ]
I am a big fan of **Flask** - in part because it is simple and in part because has a lot of [extensions](http://flask.pocoo.org/extensions/). However, Flask is meant to be used in a WSGI environment, and WSGI is not a non-blocking, so (I believe) it doesn't scale as well as **Tornado** for certain kinds of applications...
i think i got 50% of the solution, the cookies are not tested yet, but now i can load Flask application using Tornado, and mixing Tornado + Flask together :) first here is *flasky.py* the file where the flask application is: ``` from flask import Flask app = Flask(__name__) @app.route('/flask') def hello_world(): ...