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 Lambda with Or
2,382,023
3
2010-03-04T19:13:36Z
2,382,033
8
2010-03-04T19:15:06Z
[ "python", "lambda" ]
Reading the documentation it seems this might not be possible, but it seems that a lot of people have been able to beat more complicated functionality into pythons lambda function. I'm leveraging the scapy libraries to do some packet creation. Specially this questions is about the ConditionalField which takes it a fie...
``` lambda pkt:((pkt.chksumpresent == 1) or (pkt.special == 1)) ```
Change Node Display Size in Networkx
2,383,121
9
2010-03-04T22:12:11Z
2,383,859
7
2010-03-05T00:57:21Z
[ "python", "networkx" ]
I am not using GraphViz because I am having problems with making it play nice with Networkx. I know this is weird, but I've tried many suggestions to fix this problem, but I just seem to have some of the worst luck in the world. Therefore the problem that I have must be solved withing Networkx without using GraphViz. ...
Try [`nx.draw(G, node_size=size`)](http://networkx.lanl.gov/reference/generated/networkx.draw.html#networkx.draw), where `size` can be a scalar or an array of length equal to the number of nodes.
How can I make an error verifiy with os.makedirs in Python?
2,383,816
3
2010-03-05T00:46:44Z
2,383,829
12
2010-03-05T00:50:10Z
[ "python" ]
How can I make a verify error for this command? ``` if blablablabla: os.makedirs('C:\\test\\') ``` If the folder already exists, he return me an error... how can I make it ignore this error? and move on ?
``` try: os.makedirs('C:\\test\\') except OSError: pass ``` You also might want to check the specific "already exists" error (since `OSError` could mean other things, like *permission denied*... ``` import errno try: os.makedirs('C:\\test\\') except OSError as e: if e.errno != errno.EEXIST: ra...
Why is ''>0 True in Python?
2,384,078
24
2010-03-05T01:57:02Z
2,384,090
21
2010-03-05T02:00:40Z
[ "python", "operators", "logic" ]
In Python 2.6.4: ``` >> ''>0 True ``` Why is that?
from <http://docs.python.org/tutorial/datastructures.html#id1> Note that comparing objects of different types is legal. The outcome is deterministic but arbitrary: the types are ordered by their name. Thus, a list is always smaller than a string, a string is always smaller than a tuple, etc. [1] Mixed numeric types ar...
Why is ''>0 True in Python?
2,384,078
24
2010-03-05T01:57:02Z
2,384,139
55
2010-03-05T02:16:19Z
[ "python", "operators", "logic" ]
In Python 2.6.4: ``` >> ''>0 True ``` Why is that?
The original design motivation for allowing order-comparisons of arbitrary objects was to allow sorting of heterogenous lists -- usefully, that would put all strings next to each other in alphabetical order, and all numbers next to each other in numerical order, although which of the two blocks came first was not guara...
List of evented / asynchronous languages
2,384,314
9
2010-03-05T03:07:00Z
2,384,368
19
2010-03-05T03:21:22Z
[ "javascript", "python", "ruby", "asynchronous", "lisp" ]
I'm working on a system than has to be pretty scalable from the beginning. I've started looking at / playing around with asynchronous/evented approaches to writing serverside code. I've played around with both ruby's EventMachine and node.js. EventMachine is cool, but doesn't have asynchronous file I/O, which I need. ...
[Erlang](http://ftp.sunet.se/pub/lang/erlang/) may be the language with the highest intrinsic scalability for server-side code (it manages multiprocessing for you, mostly by doing async, cooperative task switching "under the covers") -- if you can stomach its peculiar syntax and (often) peculiar semantics. Python has ...
List of evented / asynchronous languages
2,384,314
9
2010-03-05T03:07:00Z
2,387,765
13
2010-03-05T15:20:18Z
[ "javascript", "python", "ruby", "asynchronous", "lisp" ]
I'm working on a system than has to be pretty scalable from the beginning. I've started looking at / playing around with asynchronous/evented approaches to writing serverside code. I've played around with both ruby's EventMachine and node.js. EventMachine is cool, but doesn't have asynchronous file I/O, which I need. ...
I would recommend that you take another look at [node.js](http://NodeJS.Org/). One of the biggest problems with using libraries to do event-based programming in an object-oriented programming language (rather than using an event-based programming language in the first place), is that usually all the *other* existing li...
How to introspect django model fields?
2,384,436
32
2010-03-05T03:45:00Z
2,384,902
68
2010-03-05T06:10:31Z
[ "python", "django-models", "introspection" ]
I am trying to obtain class information on a field inside a model, when I only know name of the field and name of the model (both plain strings). How is it possible? I can load the model dynamically: ``` from django.db import models model = models.get_model('myapp','mymodel') ``` Now I have field - 'myfield' - how c...
You can use model's `_meta` attribute to get field object and from field you can get relationship and much more e.g. consider a employee table which has a foreign key to a department table ``` In [1]: from django.db import models In [2]: model = models.get_model('timeapp', 'Employee') In [3]: dep_field = model._meta...
Which is best in Python: urllib2, PycURL or mechanize?
2,385,855
70
2010-03-05T10:02:48Z
2,385,955
35
2010-03-05T10:21:12Z
[ "python", "urllib2", "mechanize", "pycurl" ]
Ok so I need to download some web pages using Python and did a quick investigation of my options. Included with Python: [urllib](http://docs.python.org/library/urllib.html) - seems to me that I should use urllib2 instead. urllib has no cookie support, HTTP/FTP/local files only (no SSL) [urllib2](http://docs.python.o...
* `urllib2` is found in every Python install everywhere, so is a good base upon which to start. * `PycURL` is useful for people already used to using libcurl, exposes more of the low-level details of HTTP, plus it gains any fixes or improvements applied to libcurl. * `mechanize` is used to persistently drive a connecti...
Which is best in Python: urllib2, PycURL or mechanize?
2,385,855
70
2010-03-05T10:02:48Z
2,386,102
42
2010-03-05T10:48:30Z
[ "python", "urllib2", "mechanize", "pycurl" ]
Ok so I need to download some web pages using Python and did a quick investigation of my options. Included with Python: [urllib](http://docs.python.org/library/urllib.html) - seems to me that I should use urllib2 instead. urllib has no cookie support, HTTP/FTP/local files only (no SSL) [urllib2](http://docs.python.o...
I think this talk (at pycon 2009), has the answers for what you're looking for (Asheesh Laroia has lots of experience on the matter). And he points out the good and the bad from most of your listing * [Scrape the Web: Strategies for programming websites that don't expect it (Part 1 of 3)](http://pyvideo.org/video/...
Which is best in Python: urllib2, PycURL or mechanize?
2,385,855
70
2010-03-05T10:02:48Z
8,775,397
35
2012-01-08T04:32:34Z
[ "python", "urllib2", "mechanize", "pycurl" ]
Ok so I need to download some web pages using Python and did a quick investigation of my options. Included with Python: [urllib](http://docs.python.org/library/urllib.html) - seems to me that I should use urllib2 instead. urllib has no cookie support, HTTP/FTP/local files only (no SSL) [urllib2](http://docs.python.o...
Python [requests](http://pypi.python.org/pypi/requests) is also a good candidate for HTTP stuff. It has a nicer api IMHO, an example http request from their offcial documentation: ``` >>> r = requests.get('https://api.github.com', auth=('user', 'pass')) >>> r.status_code 204 >>> r.headers['content-type'] 'application/...
Counting Duplicates Integers in Python
2,385,867
6
2010-03-05T10:04:39Z
2,385,877
17
2010-03-05T10:05:58Z
[ "python", "count", "duplicates" ]
How do I find the total number of duplicates in a string? i.e., if it was `j= [1,1,1,2,2,2]` it would find `4` duplicates? I've only been able to find counting which shows how many times each individual number occurred.
``` >>> j= [1,1,1,2,2,2] >>> len(j) - len(set(j)) 4 ``` and btw, `j` is a list and not a string, although for the purpose of this exercise it doesn't really matter.
Counting Duplicates Integers in Python
2,385,867
6
2010-03-05T10:04:39Z
2,386,056
7
2010-03-05T10:41:04Z
[ "python", "count", "duplicates" ]
How do I find the total number of duplicates in a string? i.e., if it was `j= [1,1,1,2,2,2]` it would find `4` duplicates? I've only been able to find counting which shows how many times each individual number occurred.
There seems to be a popular answer already, but if you would like to maintain the individual duplicate counts as well, the new `Counter()` collection object in Python 2.7 is perfect for this. ``` >>> from collections import Counter >>> j = [1,1,1,2,2,2] >>> Counter(j) Counter({1: 3, 2: 3}) >>> sum([i - 1 for i in c...
Creating a custom Django form field that uses two <input>s
2,386,541
5
2010-03-05T12:11:24Z
2,386,650
9
2010-03-05T12:29:16Z
[ "python", "django", "django-forms" ]
How can I make a Django field that renders itself as a pair of input fields? Reasoning: I am trying to write a new custom field. I will use it for a captcha-like service. The service works by requesting a question - then receiving one and a *token*. The validation happens by sending the *answer* along with the *token*...
I think you're looking for the [MultiWidget](http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.MultiWidget), you can simply give it 2 regular widgets and it will render the combination.
Why is "import *" bad?
2,386,714
65
2010-03-05T12:40:41Z
2,386,740
105
2010-03-05T12:43:42Z
[ "python", "python-import" ]
It is recommended to not to use `import *` in Python. Can anyone please share the reason for that, so that I can avoid it doing next time?
* Because it puts a lot of stuff into your namespace (might shadow some other object from previous import and you won't know about it). * Because you don't know exactly what is imported and can't find place from what module certain thing was imported easily (readability). * Because you can't use cool tools like `pyflak...
Why is "import *" bad?
2,386,714
65
2010-03-05T12:40:41Z
2,386,754
9
2010-03-05T12:45:31Z
[ "python", "python-import" ]
It is recommended to not to use `import *` in Python. Can anyone please share the reason for that, so that I can avoid it doing next time?
<http://docs.python.org/tutorial/modules.html> > Note that in general the practice of importing `*` from a module or package is frowned upon, since it often causes **poorly readable code**.
Why is "import *" bad?
2,386,714
65
2010-03-05T12:40:41Z
2,386,759
14
2010-03-05T12:45:55Z
[ "python", "python-import" ]
It is recommended to not to use `import *` in Python. Can anyone please share the reason for that, so that I can avoid it doing next time?
That is because you are polluting the namespace. You will import all the functions and classes in your own namespace, which may clash with the functions you define yourself. Furthermore, I think using a qualified name is more clear for the maintenance task; you see on the code line itself where a function comes from, ...
Why is "import *" bad?
2,386,714
65
2010-03-05T12:40:41Z
2,386,926
8
2010-03-05T13:14:16Z
[ "python", "python-import" ]
It is recommended to not to use `import *` in Python. Can anyone please share the reason for that, so that I can avoid it doing next time?
It is OK to do `from ... import *` in an interactive session.
Why is "import *" bad?
2,386,714
65
2010-03-05T12:40:41Z
2,386,943
30
2010-03-05T13:17:04Z
[ "python", "python-import" ]
It is recommended to not to use `import *` in Python. Can anyone please share the reason for that, so that I can avoid it doing next time?
According to the [Python Zen](http://www.python.org/dev/peps/pep-0020/): > Explicit is better than implicit. ... can't argue with that, surely?
Why is "import *" bad?
2,386,714
65
2010-03-05T12:40:41Z
2,454,460
19
2010-03-16T12:59:33Z
[ "python", "python-import" ]
It is recommended to not to use `import *` in Python. Can anyone please share the reason for that, so that I can avoid it doing next time?
You don't pass `**locals()` to functions, do you? Since Python lacks an "include" statement, *and* the `self` parameter is explicit, *and* scoping rules are quite simple, it's usually very easy to point a finger at a variable and tell where that object comes from -- without reading other modules and without any kind o...
"No source for code" message in Coverage.py
2,386,975
26
2010-03-05T13:21:19Z
2,401,206
25
2010-03-08T12:25:19Z
[ "python", "continuous-integration", "code-coverage", "nosetests" ]
I ran a build last night, successfully. I got up this morning and ran another without changing any configuration or modifying any source code. Now my build is failing with the message **"No source for code"** when running my *nosetests* with *coverage*. ``` NoSource: No source for code: '/home/matthew/.hudson/jobs/myp...
I'm not sure why it thinks that file exists, but you can tell coverage.py to ignore these problems with a `coverage xml -i` switch. If you want to track down the error, drop me a line (ned at ned batchelder com).
"No source for code" message in Coverage.py
2,386,975
26
2010-03-05T13:21:19Z
2,402,780
31
2010-03-08T16:22:26Z
[ "python", "continuous-integration", "code-coverage", "nosetests" ]
I ran a build last night, successfully. I got up this morning and ran another without changing any configuration or modifying any source code. Now my build is failing with the message **"No source for code"** when running my *nosetests* with *coverage*. ``` NoSource: No source for code: '/home/matthew/.hudson/jobs/myp...
Ensure theres no .pyc file there, that may have existed in the past.
"No source for code" message in Coverage.py
2,386,975
26
2010-03-05T13:21:19Z
3,123,157
13
2010-06-26T07:57:05Z
[ "python", "continuous-integration", "code-coverage", "nosetests" ]
I ran a build last night, successfully. I got up this morning and ran another without changing any configuration or modifying any source code. Now my build is failing with the message **"No source for code"** when running my *nosetests* with *coverage*. ``` NoSource: No source for code: '/home/matthew/.hudson/jobs/myp...
**Summary**: Existing .coverage data is kept around when running `nosetests --with-coverage`, so remove it first. **Details**: I too just encountered this via Hudson and nosetests. This error was coming from `coverage/results.py:18` (coverage 3.3.1 - there were 3 places raising this error, but this was the relevant on...
"No source for code" message in Coverage.py
2,386,975
26
2010-03-05T13:21:19Z
12,693,475
8
2012-10-02T15:32:20Z
[ "python", "continuous-integration", "code-coverage", "nosetests" ]
I ran a build last night, successfully. I got up this morning and ran another without changing any configuration or modifying any source code. Now my build is failing with the message **"No source for code"** when running my *nosetests* with *coverage*. ``` NoSource: No source for code: '/home/matthew/.hudson/jobs/myp...
Just use the '--cover-erase' argument. It fixes this error and you don't have to manually delete coverage files ``` nosetests --with-coverage --cover-erase ``` I'd strongly recommend checking out the help to see what other args you're missing too and don't forget those plugins either
Open Source FIX Client Simulator
2,387,173
8
2010-03-05T13:58:35Z
2,421,178
11
2010-03-10T22:35:14Z
[ "c++", "python", "quickfix", "fix" ]
I want test a FIX gateway for our company and was wondering if anything in opensource already exists that I can use or perhaps leverage to complete this task. I am currently looking at QuickFix but I am not sure if it has a client that can be use against any standard FIX gateway. Also links to any learning material t...
**QuickFIXengine code comes with couple of examples, see <http://www.quickfixengine.org/quickfix/doc/html/examples.html>** You probably want `tradeclient` for sending messages. It is a command line tool that will send FIX messages to server. You can use the `ordermatch` example to start up simple FIX server which wil...
Best way to convert csv data to dict
2,387,697
11
2010-03-05T15:11:29Z
2,387,748
11
2010-03-05T15:18:26Z
[ "python", "csv" ]
I have csv file with following data ``` val1,val2,val3 1,2,3 22,23,33 ``` So how can I convert data into dict ``` dict1 = { 'val1': 1, 'val2': 2, 'val3': 3} dict2 = { 'val1': 22, 'val2': 23, 'val3': 33} fp = open('file.csv', 'r') reader = csv.reader(fp) for row in reader: ???? ``` Thanks
Use [csv.DictReader](http://docs.python.org/library/csv.html#csv.DictReader): > Create an object which operates like a regular reader but maps the information read into a dict whose keys are given by the optional *fieldnames* parameter. The *fieldnames* parameter is a [`sequence`](https://docs.python.org/3/library/col...
Best way to convert csv data to dict
2,387,697
11
2010-03-05T15:11:29Z
2,387,754
17
2010-03-05T15:18:59Z
[ "python", "csv" ]
I have csv file with following data ``` val1,val2,val3 1,2,3 22,23,33 ``` So how can I convert data into dict ``` dict1 = { 'val1': 1, 'val2': 2, 'val3': 3} dict2 = { 'val1': 22, 'val2': 23, 'val3': 33} fp = open('file.csv', 'r') reader = csv.reader(fp) for row in reader: ???? ``` Thanks
``` import csv reader = csv.DictReader(open('myfile.csv')) for row in reader: # profit ! ```
Python - Can I access the object who call me?
2,387,756
3
2010-03-05T15:19:27Z
2,387,857
10
2010-03-05T15:32:48Z
[ "python", "oop", "function-calls" ]
If I have this: ``` class A: def callFunction(self, obj): obj.otherFunction() class B: def callFunction(self, obj): obj.otherFunction() class C: def otherFunction(self): # here I wan't to have acces to the instance of A or B who call me. ... # in main or other object (not matter...
If this is for debugging purposes you can use inspect.currentframe(): ``` import inspect class C: def otherFunction(self): print inspect.currentframe().f_back.f_locals ``` Here is the output: ``` >>> A().callFunction(C()) {'self': <__main__.A instance at 0x96b4fec>, 'obj': <__main__.C instance at 0x951e...
Pythonic way to compare two lists and print out the differences
2,387,981
13
2010-03-05T15:50:13Z
2,388,064
18
2010-03-05T16:01:08Z
[ "python", "comparison" ]
I have two lists which are guaranteed to be the same length. I want to compare the corresponding values in the list (except the first item) and print out the ones which dont match. The way I am doing it is like this ``` i = len(list1) if i == 1: print 'Nothing to compare' else: for i in range(i): if no...
``` list1=[1,2,3,4] list2=[1,5,3,4] print [(i,j) for i,j in zip(list1,list2) if i!=j] ``` Output: ``` [(2, 5)] ``` **Edit:** Easily extended to skip *n* first items (same output): ``` list1=[1,2,3,4] list2=[2,5,3,4] print [(i,j) for i,j in zip(list1,list2)[1:] if i!=j] ```
Can you help me solve this SUDS/SOAP issue?
2,388,046
15
2010-03-05T15:58:37Z
2,388,590
32
2010-03-05T17:19:10Z
[ "python", "soap", "wsdl", "suds" ]
So I'm trying to access this api <https://www.clarityaccounting.com/api-docs/> using SUDS. Here is the code that should work: ``` from suds.client import Client client = Client('https://www.clarityaccounting.com/api/v1?wsdl') token = client.service.doLogin('demo', 'demo', 'www.kashoo.com', 'en_US', 300000) ``` But I ...
At first glance looks like the problem you're having is with SSL. You are accessing an https URL, and the Transport handler for suds.client talks http by default. **The problem** If you look at the bottom of the WSDL it is specifying the default location as `http://www.clarityaccounting.com/api/v1`, which is an http...
Python string decoding issue
2,389,410
3
2010-03-05T19:32:03Z
2,389,643
12
2010-03-05T20:08:02Z
[ "python", "string", "unicode", "character-encoding" ]
I am trying to parse a CSV file containing some data, mostly numeral but with some strings - which I do not know their encoding, but I do know they are in Hebrew. Eventually I need to know the encoding so I can unicode the strings, print them, and perhaps throw them into a database later on. I tried using [Chardet](h...
This is what's happening: * sampleString is a byte string (cp1255 encoded) * `sampleString.decode("cp1255")` decodes (decode==bytes -> unicode string) the byte string to a unicode string * `print sampleString.decode("cp1255")` attempts to print the unicode string to stdout. Print has to **encode** the unicode string t...
python: inheriting or composition
2,389,816
13
2010-03-05T20:44:22Z
2,389,871
10
2010-03-05T20:57:40Z
[ "python", "inheritance", "composition", "dictionary" ]
Let's say that I have `class`, that uses some functionality of `dict`. I used to composite a `dict` object inside and provide some access from the outside, but recently thought about simply inheriting `dict` and adding some attributes and methods that I might require. Is it a good way to go, or should I stick to compos...
Inheritance is very often abused. Unless your class is meant to be used as a generic dictionary with extra functionality, I would say composition is the way to go. Saving forwarding calls is usually not a good enough reason for choosing inheritance. From the Design Pattern book: > Favor object composition over class...
Python Decimals format
2,389,846
29
2010-03-05T20:51:59Z
2,389,956
9
2010-03-05T21:11:35Z
[ "python", "decimal" ]
WHat is a good way to format a python decimal like this way? 1.00 --> '1' 1.20 --> '1.2' 1.23 --> '1.23' 1.234 --> '1.23' 1.2345 --> '1.23'
Here's a function that will do the trick: ``` def myformat(x): return ('%.2f' % x).rstrip('0').rstrip('.') ``` And here are your examples: ``` >>> myformat(1.00) '1' >>> myformat(1.20) '1.2' >>> myformat(1.23) '1.23' >>> myformat(1.234) '1.23' >>> myformat(1.2345) '1.23' ``` **Edit:** From looking at other peo...
Python Decimals format
2,389,846
29
2010-03-05T20:51:59Z
2,390,047
62
2010-03-05T21:25:06Z
[ "python", "decimal" ]
WHat is a good way to format a python decimal like this way? 1.00 --> '1' 1.20 --> '1.2' 1.23 --> '1.23' 1.234 --> '1.23' 1.2345 --> '1.23'
If you have Python 2.6 or newer, use [`format`](http://docs.python.org/library/string.html#format-string-syntax): ``` '{0:.3g}'.format(num) ``` For Python 2.5 or older: ``` '%.3g'%(num) ``` Explanation: `{0}`tells `format` to print the first argument -- in this case, `num`. Everything after the colon (:) specifie...
Python Decimals format
2,389,846
29
2010-03-05T20:51:59Z
4,313,951
13
2010-11-30T12:51:36Z
[ "python", "decimal" ]
WHat is a good way to format a python decimal like this way? 1.00 --> '1' 1.20 --> '1.2' 1.23 --> '1.23' 1.234 --> '1.23' 1.2345 --> '1.23'
Only first part of Justin's answer is correct. Using "%.3g" will not work for all cases as .3 is not the precision, but total number of digits. Try it for numbers like 1000.123 and it breaks. So, I would use what Justin is suggesting: ``` >>> ('%.4f' % 12340.123456).rstrip('0').rstrip('.') '12340.1235' >>> ('%.4f' % ...
Most efficent way to create all possible combinations of four lists in Python?
2,390,316
5
2010-03-05T22:15:29Z
2,390,326
10
2010-03-05T22:17:40Z
[ "python", "algorithm" ]
I have four different lists. `headers`, `descriptions`, `short_descriptions` and `misc`. I want to combine these into all the possible ways to print out: ``` header\n description\n short_description\n misc ``` like if i had (i'm skipping short\_description and misc in this example for obvious reasons) ``` headers = ...
Is this what you're looking for? <http://docs.python.org/library/itertools.html#itertools.product>
Is there a way to transparently perform validation on SQLAlchemy objects?
2,390,753
15
2010-03-05T23:58:23Z
4,361,919
7
2010-12-05T23:17:26Z
[ "python", "validation", "model", "dns", "sqlalchemy" ]
Is there a way to perform validation on an object after (or as) the properties are set but before the session is committed? For instance, I have a domain model `Device` that has a `mac` property. I would like to ensure that the `mac` property contains a valid and sanitized mac value before it is added to or updated in...
Yes. This can be done nicely using a MapperExtension. ``` # uses sqlalchemy hooks to data model class specific validators before update and insert class ValidationExtension( sqlalchemy.orm.interfaces.MapperExtension ): def before_update(self, mapper, connection, instance): """not every instance here is act...
Is there a way to transparently perform validation on SQLAlchemy objects?
2,390,753
15
2010-03-05T23:58:23Z
18,222,696
10
2013-08-14T03:23:05Z
[ "python", "validation", "model", "dns", "sqlalchemy" ]
Is there a way to perform validation on an object after (or as) the properties are set but before the session is committed? For instance, I have a domain model `Device` that has a `mac` property. I would like to ensure that the `mac` property contains a valid and sanitized mac value before it is added to or updated in...
You can add data validation inside your SQLAlchemy classes using the `@validates()` decorator. From the docs - [Simple Validators](http://docs.sqlalchemy.org/en/rel_0_8/orm/mapper_config.html#simple-validators): > An attribute validator can raise an exception, halting the process of mutating the attribute’s value, ...
How do I disable and then re-enable a warning?
2,390,766
11
2010-03-06T00:03:18Z
2,391,106
8
2010-03-06T02:14:11Z
[ "python", "warnings" ]
I'm writing some unit tests for a Python library and would like certain warnings to be raised as exceptions, which I can easily do with the [simplefilter](http://docs.python.org/library/warnings.html#warnings.simplefilter) function. However, for one test I'd like to disable the warning, run the test, then re-enable the...
Reading through the docs and few times and poking around the source and shell I think I've figured it out. The docs could probably improve to make clearer what the behavior is. The warnings module keeps a registry at \_\_warningsregistry\_\_ to keep track of which warnings have been shown. If a warning (message) is no...
How to properly subclass dict and override __getitem__ & __setitem__
2,390,827
41
2010-03-06T00:24:33Z
2,390,889
16
2010-03-06T00:42:16Z
[ "python", "dictionary" ]
I am debugging some code and I want to find out when a particular dictionary is accessed. Well, it's actually a class that subclass `dict` and implements a couple extra features. Anyway, what I would like to do is subclass `dict` myself and add override `__getitem__` and `__setitem__` to produce some debugging output. ...
What you're doing should absolutely work. I tested out your class, and aside from a missing opening parenthesis in your log statements, it works just fine. There are only two things I can think of. First, is the output of your log statement set correctly? You might need to put a `logging.basicConfig(level=logging.DEBUG...
How to properly subclass dict and override __getitem__ & __setitem__
2,390,827
41
2010-03-06T00:24:33Z
2,390,997
43
2010-03-06T01:27:09Z
[ "python", "dictionary" ]
I am debugging some code and I want to find out when a particular dictionary is accessed. Well, it's actually a class that subclass `dict` and implements a couple extra features. Anyway, what I would like to do is subclass `dict` myself and add override `__getitem__` and `__setitem__` to produce some debugging output. ...
Another issue when subclassing `dict` is that the built-in `__init__` doesn't call `update`, and the built-in `update` doesn't call `__setitem__`. So, if you want all setitem operations to go through your `__setitem__` function, you should make sure that it gets called yourself: ``` class DictWatch(dict): def __in...
Django serializer for one object
2,391,002
8
2010-03-06T01:31:04Z
2,391,243
15
2010-03-06T03:32:57Z
[ "python", "django", "json" ]
I'm trying to figure out a way to serialize some Django model object to JSON format, something like: ``` j = Job.objects.get(pk=1) ############################################## #a way to get the JSON for that j variable??? ############################################## ``` I don't want: ``` from django.core import ...
How about just massaging what you get back from serializers.serialize? It is not that hard to trim off the square brackets from the front and back of the result. ``` job = Job.objects.get(pk=1) array_result = serializers.serialize('json', [job], ensure_ascii=False) just_object_result = array_result[1:-1] ``` Not a fa...
Python, dynamically invoke script
2,391,099
3
2010-03-06T02:12:23Z
2,391,105
8
2010-03-06T02:13:38Z
[ "python", "command" ]
I want to run a python script from within another. By within I mean any state changes from the child script effect the parent's state. So if a variable is set in the child, it gets changed in the parent. Normally you could do something like ``` import module ``` But the issue is here the child script being run is an...
You can use the [`__import__`](http://docs.python.org/library/functions.html#__import__) function which allows you to import a module dynamically: ``` module = __import__(sys.argv[1]) ``` (You may need to remove the trailing `.py` or not specify it on the command line.) From the Python documentation: > Direct use o...
Starting VirtualBox VM using Python
2,391,511
2
2010-03-06T05:57:38Z
2,392,695
9
2010-03-06T14:03:56Z
[ "python", "virtualbox" ]
How can I start a virtual machine from virtualbox as *headless* using **`pyvb`** modules?
You can use the real python bindings instead (and not a wrapper that call the VBoxManager command line in a subprocess, say pyvb) relatively easily by using the [vboxshell.py](http://www.virtualbox.org/svn/vbox/trunk/src/VBox/Frontends/VBoxShell/vboxshell.py) script from virtual box. Or you can use it for reference do...
SQLite or flat text file?
2,392,017
8
2010-03-06T09:30:49Z
2,392,026
15
2010-03-06T09:35:32Z
[ "python", "sql", "database", "file-format" ]
I process a lot of text/data that I exchange between Python, R, and sometimes Matlab. My go-to is the flat text file, but also use SQLite occasionally to store the data and access from each program (not Matlab yet though). I don't use GROUPBY, AVG, etc. in SQL as much as I do these operations in R, so I don't necessar...
If all the languages support SQLite - use it. The power of SQL might not be useful to you right now, but it probably will be at some point, and it saves you having to rewrite things later when you decide you want to be able to query your data in more complicated ways. SQLite will also probably be substantially faster ...
Calculating very large exponents in python
2,392,235
6
2010-03-06T11:02:52Z
2,392,249
11
2010-03-06T11:08:32Z
[ "python" ]
Currently i am simulating my cryptographic scheme to test it. I have developed the code but i am stuck at one point. I am trying to take: `g**x` where ``` g = 256 bit number x = 256 bit number ``` Python hangs at this point, i have read alot of forums, threads etcc but only come to the conclusion that python hangs, ...
It's not hanging, it's just processing. It *will* eventually give you the answer, provided it doesn't run out of memory first. I haven't heard of the result of such a process being used in cryptography though; usually it's the modulus of said power that matters. If it's the same in your case then you can just use the ...
Calculating very large exponents in python
2,392,235
6
2010-03-06T11:02:52Z
2,392,261
7
2010-03-06T11:12:23Z
[ "python" ]
Currently i am simulating my cryptographic scheme to test it. I have developed the code but i am stuck at one point. I am trying to take: `g**x` where ``` g = 256 bit number x = 256 bit number ``` Python hangs at this point, i have read alot of forums, threads etcc but only come to the conclusion that python hangs, ...
I'm not quite sure you appreciate the sheer magnitude of what you're asking Python to do. Raising something to a power `x` where `x` is 256 bits long, is doing the equivalent of 2\*\*256 multiplications, or 115792089237316195423570985008687907853269984665640564039457584007913129639936 multiplications. As you can imagin...
Calculating very large exponents in python
2,392,235
6
2010-03-06T11:02:52Z
2,392,288
8
2010-03-06T11:20:35Z
[ "python" ]
Currently i am simulating my cryptographic scheme to test it. I have developed the code but i am stuck at one point. I am trying to take: `g**x` where ``` g = 256 bit number x = 256 bit number ``` Python hangs at this point, i have read alot of forums, threads etcc but only come to the conclusion that python hangs, ...
You shouldn't try to calculate x^y directly for huge values of y - as has already been pointed out, this is pretty difficult to do (takes lots of space and processing power). You need to look at algorithms that solve the problem for you with fewer multiplication operations. Take a look at: <http://en.wikipedia.org/wiki...
How do you run a python script from within notepad++?
2,392,629
39
2010-03-06T13:41:20Z
2,392,662
10
2010-03-06T13:55:05Z
[ "python", "notepad++", "nppexec" ]
When I'm using textmate, I simply hit "apple+r" and the program gets interpreted. How can I run a program from within notepad++? I see that F5 is for "Run", but pointing that to Python.exe simply opens up a terminal with python running. It does not run my script.
You need to pass through the FULL\_CURRENT\_PATH environment variable to the program, as described in the [notepad++ wiki](http://npp-wiki.tuxfamily.org/index.php?title=External_Programs): ``` python "$(FULL_CURRENT_PATH)" ```
How do you run a python script from within notepad++?
2,392,629
39
2010-03-06T13:41:20Z
3,071,177
44
2010-06-18T15:56:22Z
[ "python", "notepad++", "nppexec" ]
When I'm using textmate, I simply hit "apple+r" and the program gets interpreted. How can I run a program from within notepad++? I see that F5 is for "Run", but pointing that to Python.exe simply opens up a terminal with python running. It does not run my script.
Plugins **NppExec** Execute (`F6`) is much more powerful than plain Run (`F5`). Install NppExec via Plugins, Plugin Manager. Then in `F6` add/save the following: ``` NPP_SAVE cd "$(FULL_CURRENT_PATH)" C:\Python34\python.exe -u "$(FULL_CURRENT_PATH)" ``` In Plugins NppExec Console output filters (`Shift`+`F6`) add the...
SQLite, python, unicode, and non-utf data
2,392,732
57
2010-03-06T14:15:42Z
2,392,803
31
2010-03-06T14:40:35Z
[ "python", "sqlite", "unicode", "utf-8" ]
I started by trying to store strings in sqlite using python, and got the message: > sqlite3.ProgrammingError: You must > not use 8-bit bytestrings unless you > use a text\_factory that can interpret > 8-bit bytestrings (like text\_factory = > str). It is highly recommended that > you instead just switch your > applica...
> I'm still ignorant of whether there is a way to correctly convert 'ó' from latin-1 to utf-8 and not mangle it repr() and unicodedata.name() are your friends when it comes to debugging such problems: ``` >>> oacute_latin1 = "\xF3" >>> oacute_unicode = oacute_latin1.decode('latin1') >>> oacute_utf8 = oacute_unicode....
SQLite, python, unicode, and non-utf data
2,392,732
57
2010-03-06T14:15:42Z
2,395,414
19
2010-03-07T06:36:56Z
[ "python", "sqlite", "unicode", "utf-8" ]
I started by trying to store strings in sqlite using python, and got the message: > sqlite3.ProgrammingError: You must > not use 8-bit bytestrings unless you > use a text\_factory that can interpret > 8-bit bytestrings (like text\_factory = > str). It is highly recommended that > you instead just switch your > applica...
UTF-8 is the default encoding of SQLite databases. This shows up in situations like "SELECT CAST(x'52C3B373' AS TEXT);". However, the SQLite C library doesn't actually check whether a string inserted into a DB is valid UTF-8. If you insert a Python unicode object (or str object in 3.x), the Python sqlite3 library will...
SQLite, python, unicode, and non-utf data
2,392,732
57
2010-03-06T14:15:42Z
2,589,423
16
2010-04-07T01:17:44Z
[ "python", "sqlite", "unicode", "utf-8" ]
I started by trying to store strings in sqlite using python, and got the message: > sqlite3.ProgrammingError: You must > not use 8-bit bytestrings unless you > use a text\_factory that can interpret > 8-bit bytestrings (like text\_factory = > str). It is highly recommended that > you instead just switch your > applica...
I fixed this pysqlite problem by setting: ``` conn.text_factory = lambda x: unicode(x, 'utf-8', 'ignore') ``` By default text\_factory is set to unicode(), which will use the current default encoding (ascii on my machine)
How to get unique values with respective occurance count from a list in Python?
2,392,929
18
2010-03-06T15:14:45Z
2,392,942
8
2010-03-06T15:18:04Z
[ "python" ]
I have a list which has repeating items and I want a list of the unique items with their frequency. For example, I have ['a', 'a', 'b', 'b', 'b'], and I want [('a', 2), ('b', 3)] Looking for a simple way to do this without looping twice.
If your items are grouped (i.e. similar items come together in a bunch), the most efficient method to use is `itertools.groupby`: ``` >>> [(g[0], len(list(g[1]))) for g in itertools.groupby(['a', 'a', 'b', 'b', 'b'])] [('a', 2), ('b', 3)] ```
How to get unique values with respective occurance count from a list in Python?
2,392,929
18
2010-03-06T15:14:45Z
2,392,948
45
2010-03-06T15:20:11Z
[ "python" ]
I have a list which has repeating items and I want a list of the unique items with their frequency. For example, I have ['a', 'a', 'b', 'b', 'b'], and I want [('a', 2), ('b', 3)] Looking for a simple way to do this without looping twice.
When Python 2.7 comes out you can use its [collections.Counter class](http://docs.python.org/dev/library/collections.html#collections.Counter) otherwise see [counter receipe](http://code.activestate.com/recipes/576611/) Under Python 2.7a3 ``` from collections import Counter input = ['a', 'a', 'b', 'b', 'b'] c = Cou...
How to extend the comments framework (django) by removing unnecesary fields?
2,393,237
13
2010-03-06T16:43:00Z
3,421,386
12
2010-08-06T06:11:22Z
[ "python", "django", "django-comments" ]
I've been reading on the django docs about the comments framework and how to customize it (http://docs.djangoproject.com/en/1.1/ref/contrib/comments/custom/) In that page, it shows how to *add* new fields to a form. But what I want to do is to **remove** unnecesary fields, like URL, email (amongst other minor mods.) O...
I recently implemented the solution that Ofri mentioned, since I only wanted to accept a solitary "comment" field for a comment (like SO does, no "name", no "email" and no "url"). To customize the default comment form and list display, I created a "comments" directory in my root "templates" directory and overrode the ...
How do I disable history in python mechanize module?
2,393,299
10
2010-03-06T17:01:56Z
2,393,395
17
2010-03-06T17:29:05Z
[ "python", "memory", "mechanize" ]
I have a web scraping script that gets new data once every minute, but over the course of a couple of days, the script ends up using 200mb or more of memory, and I found out it's because mechanize is keeping an infinite browser history for the .back() function to use. I have looked in the docstrings, and I found the c...
You can pass an argument `history=whatever` when you instantiate the `Browser`; the default value is `None` which means the browser actually instantiates the `History` class (to allow `back` and `reload`). The simplest approach (will give an attribute error exception if you ever do call back or reload): ``` class NoHi...
Python double iteration
2,393,444
7
2010-03-06T17:42:28Z
2,393,492
11
2010-03-06T17:53:38Z
[ "python" ]
What is the pythonic way of iterating simultaneously over two lists? Suppose I want to compare two files line by line (compare each `i`th line in one file with the `i`th line of the other file), I would want to do something like this: ``` file1 = csv.reader(open(filename1),...) file2 = csv.reader(open(filename2),...)...
In Python 2, you should import [itertools](http://docs.python.org/library/itertools.html?highlight=itertools#module-itertools) and use its [izip](http://docs.python.org/library/itertools.html?highlight=itertools#itertools.izip): ``` with open(file1) as f1: with open(file2) as f2: for line1, line2 in itertools.iz...
Python code to parse and inspect c++
2,393,527
4
2010-03-06T18:07:50Z
2,393,575
7
2010-03-06T18:16:40Z
[ "c++", "python" ]
Is there a library for Python that will allow me to parse c++ code? For example, let's say I want to parse some c++ code and find the names of all classes and their member functions/variables. I can think of a few ways to hack it together using regular expressions, but if there is an existing library it would be more...
In the past I've used for such purposes [gccxml](http://www.gccxml.org/HTML/Index.html) (a C++ parser that emits easily-parseable XML) -- I hacked up my own Python interfaces to it, but now there's a [pygccxml](http://pypi.python.org/pypi/pygccxml/0.6.9) which should package that up nicely for you.
Python: Classname same as file/module name leads to inheritance issue?
2,393,544
8
2010-03-06T18:10:48Z
2,393,571
16
2010-03-06T18:16:04Z
[ "python", "google-app-engine", "class", "import", "module" ]
My code worked fine when it was all in one file. Now, I'm splitting up classes into different modules. The modules have been given the same name as the classes. Perhaps this is a problem, because `MainPage` is failing when it is loaded. Does it think that I'm trying to inherit from a module? Can module/class namespace ...
Yes, module names share the same namespace as everything else, and, yes, Python thinks you are trying to inherit from a module. Change: ``` class MainPage(BaseHandler): ``` to: ``` class MainPage(BaseHandler.BaseHandler): ``` and you should be good to go. That way, you're saying "please inherit from the BaseHandle...
Python: Classname same as file/module name leads to inheritance issue?
2,393,544
8
2010-03-06T18:10:48Z
2,393,574
14
2010-03-06T18:16:31Z
[ "python", "google-app-engine", "class", "import", "module" ]
My code worked fine when it was all in one file. Now, I'm splitting up classes into different modules. The modules have been given the same name as the classes. Perhaps this is a problem, because `MainPage` is failing when it is loaded. Does it think that I'm trying to inherit from a module? Can module/class namespace ...
First of all the filenames should be all lowercase. That's Python convention that helps to avoid confusion such as this, at least most of the time. Next, your import from withing `MainHandler.py` is wrong. You are importing `BaseHandler` (the module) and referencing it as if it were a class. The class is actually `Bas...
Get POSIX/Unix time in seconds and nanoseconds in Python?
2,394,485
16
2010-03-06T23:30:36Z
2,394,534
17
2010-03-06T23:45:36Z
[ "python", "time", "posix" ]
I've been trying to find a way to get the time since 1970-01-01 00:00:00 UTC in seconds and nanoseconds in python and I cannot find anything that will give me the proper precision. I have tried using time module, but that precision is only to microseconds, so the code I tried was: ``` import time print time.time() `...
Your precision is just being lost due to string formatting: ``` >>> import time >>> print "%.20f" % time.time() 1267919090.35663390159606933594 ```
Suppose I have 400 rows of people's names in a database. What's the best way to do a search for their names?
2,394,870
3
2010-03-07T01:54:54Z
2,394,876
10
2010-03-07T01:57:55Z
[ "python", "mysql", "database", "search", "indexing" ]
They will also search part of their name. Not only words with spaces. If they type "Matt", I expect to retrieve "Matthew" too.
You can use: ``` SELECT * FROM mytable WHERE name LIKE '%matt%' ```
Suppose I have 400 rows of people's names in a database. What's the best way to do a search for their names?
2,394,870
3
2010-03-07T01:54:54Z
2,394,937
12
2010-03-07T02:29:25Z
[ "python", "mysql", "database", "search", "indexing" ]
They will also search part of their name. Not only words with spaces. If they type "Matt", I expect to retrieve "Matthew" too.
``` SELECT * FROM mytable WHERE name LIKE 'matt%' OR name LIKE '[ ,-/]matt%' ``` Notes: 1) **Fancy wildcard.** The reason for not using the simpler LIKE '%xyz%' form is that depending on the xyz the database could return many non-relevant records. For example "Jeff Zermatt" in the case of the "Matt" search. The ...
How do you NOT automatically dereference a db.ReferenceProperty in Google App Engine?
2,395,144
2
2010-03-07T04:05:34Z
2,395,230
8
2010-03-07T04:53:04Z
[ "python", "google-app-engine", "gae-datastore" ]
Suppose I have ``` class Foo(db.Model): bar = db.ReferenceProperty(Bar) foo = Foo.all().get() ``` Is there a way for me to do foo.bar without a query being made to Datastore? The docs say that `foo.bar` will be an instance of `Key`, so I would expect to be able to do `foo.bar.id()` and be able to get the `id` of ...
As [the docs](http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#ReferenceProperty) say, > The ReferenceProperty value can be > used as if it were a model instance, > and the datastore entity will be > fetched and the model instance created > when it is first used in this way. > Untouc...
What is the correct syntax for 'else if'?
2,395,160
129
2010-03-07T04:17:47Z
2,395,167
219
2010-03-07T04:20:40Z
[ "python", "python-3.x" ]
I'm a new Python programmer who is making the leap from 2.6.4 to 3.1.1. Everything has gone fine until I tried to use the 'else if' statement. The interpreter gives me a syntax error after the 'if' in 'else if' for a reason I can't seem to figure out. ``` def function(a): if a == '1': print ('1a') else...
In python "else if" is spelled "elif". Also, you need a colon after the `elif` and the `else`. Simple answer to a simple question. I had the same problem, when I first started (in the last couple of weeks). So your code should read: ``` def function(a): if a == '1': print('1a') elif a == '2': ...
What is the correct syntax for 'else if'?
2,395,160
129
2010-03-07T04:17:47Z
2,395,172
9
2010-03-07T04:23:10Z
[ "python", "python-3.x" ]
I'm a new Python programmer who is making the leap from 2.6.4 to 3.1.1. Everything has gone fine until I tried to use the 'else if' statement. The interpreter gives me a syntax error after the 'if' in 'else if' for a reason I can't seem to figure out. ``` def function(a): if a == '1': print ('1a') else...
Do you mean [`elif`](http://docs.python.org/3.1/tutorial/controlflow.html)?
Using Tkinter in python to edit the title bar
2,395,431
26
2010-03-07T06:50:21Z
2,398,906
46
2010-03-08T02:06:21Z
[ "python", "tkinter", "titlebar" ]
I am trying to add a custom title to a window but I am having troubles with it. I know my code isn't right but when I run it, it creates 2 windows instead, one with just the title tk and another bigger window with "Simple Prog". How do I make it so that the tk window has the title "Simple Prog" instead of having a new ...
Tkinter automatically creates a window for you -- the one created when you call Tk(). I'm not sure why you're seeing two windows with the code you posted. Typically that means you're creating a toplevel window at some point in your code. Try this: ``` from Tkinter import Tk root = Tk() root.wm_title("Hello, world") `...
Whoosh index viewer
2,395,675
11
2010-03-07T08:48:38Z
5,296,975
10
2011-03-14T09:46:48Z
[ "python", "django-haystack", "whoosh" ]
I'm using haystack with whoosh as backend for a Django app. Is there any way to view the content (in a easy to read format) of the indexes generated by whoosh? I'd like to see what data was indexed and how so I can better understand how it works.
You can do this pretty easily from python's interactive console: ``` >>> from whoosh.index import open_dir >>> ix = open_dir('whoosh_index') >>> ix.schema <<< <Schema: ['author', 'author_exact', 'content', 'django_ct', 'django_id', 'id', 'lexer', 'lexer_exact', 'published', 'published_exact']> ``` You can perform sea...
Python: startswith any alpha character
2,395,821
8
2010-03-07T09:49:34Z
2,395,875
28
2010-03-07T10:08:43Z
[ "python", "startswith" ]
How can I use the startswith function to match any alpha character [a-zA-Z]. For example I would like to do this: ``` if line.startswith(ALPHA): Do Something ```
If you want to match non-ASCII letters as well, you can do: ``` if line and line[0].isalpha(): ```
how to document a python package
2,396,141
10
2010-03-07T11:54:49Z
2,396,158
13
2010-03-07T12:04:15Z
[ "python", "documentation", "package" ]
I know what's the standard way to document functions, classes and modules, but how do I document packages - do I put a docstring in `__init__.py`, or something else?
Yes, just like for a function or class comment, the first item in the **\_\_init\_\_.py** file should be a comment string: ``` """ This is the xyz package. """ ``` Now if you import the package, and use help(package), you will see your docstring. See more here: <http://www.python.org/dev/peps/pep-0257/>
Using one Scrapy spider for several websites
2,396,529
9
2010-03-07T14:13:38Z
2,397,334
9
2010-03-07T18:19:52Z
[ "python", "web-crawler", "scrapy" ]
I need to create a user configurable web spider/crawler, and I'm thinking about using Scrapy. But, I can't hard-code the domains and allowed URL regex:es -- this will instead be configurable in a GUI. How do I (as simple as possible) create a spider or a set of spiders with Scrapy where the domains and allowed URL reg...
**WARNING: This answer was for Scrapy v0.7, spider manager api changed a lot since then.** Override default SpiderManager class, load your custom rules from a database or somewhere else and instanciate a custom spider with your own rules/regexes and domain\_name in mybot/settings.py: ``` SPIDER_MANAGER_CLASS = 'mybo...
How to encode HTML non-ASCII data to UTF-8 in Python
2,396,925
2
2010-03-07T16:15:16Z
2,396,944
7
2010-03-07T16:22:28Z
[ "python", "unicode", "utf-8" ]
I tried to do that, and I found this errors: ``` >>> import re >>> x = 'Ingl\xeas' >>> x 'Ingl\xeas' >>> print x Ingl�s >>> x.decode('utf8') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.6/encodings/utf_8.py", line 16, in decode retu...
You need to know how the input data is encoded before you decode it. In some of you're attempts, you're trying to decode it from UTF-8, but Python throws an exception because the input isn't valid UTF-8. It looks like it might be latin-1. This works for me: ``` >>> x = 'Ingl\xeas' >>> print x.decode('latin1') Inglês ...
In Django, what is the best way to manage both a mobile and desktop site?
2,396,938
4
2010-03-07T16:18:48Z
2,396,949
9
2010-03-07T16:23:30Z
[ "python", "css", "django", "mobile", "templates" ]
I'd like everything to function correctly, except when it's mobile, the entire site will used a set of specific templates. Also, I'd like to autodetect if it's mobile. If so, then use that set of templates throughout the entire site.
Have two sets of templates, one for mobile, one for desktop. Store the filenames in a pair of dictionaries, and use the `User-agent` header to detect which set should be used. Also allow manual selection of which site to use via a session entry.
How to initialize a two-dimensional array in Python?
2,397,141
140
2010-03-07T17:27:54Z
2,397,146
19
2010-03-07T17:29:40Z
[ "python", "multidimensional-array" ]
I'm beginning python and I'm trying to use a two-dimensional list, that I initially fill up with the same variable in every place. I came up with this: ``` def initialize_twodlist(foo): twod_list = [] new = [] for i in range (0, 10): for j in range (0, 10): new.append(foo) twod_...
``` [[foo for x in xrange(10)] for y in xrange(10)] ```
How to initialize a two-dimensional array in Python?
2,397,141
140
2010-03-07T17:27:54Z
2,397,147
17
2010-03-07T17:29:46Z
[ "python", "multidimensional-array" ]
I'm beginning python and I'm trying to use a two-dimensional list, that I initially fill up with the same variable in every place. I came up with this: ``` def initialize_twodlist(foo): twod_list = [] new = [] for i in range (0, 10): for j in range (0, 10): new.append(foo) twod_...
Usually when you want multidimensional arrays you don't want a list of lists, but rather a numpy array or possibly a dict. For example, with numpy you would do something like ``` import numpy a = numpy.empty((10, 10)) a.fill(foo) ```
How to initialize a two-dimensional array in Python?
2,397,141
140
2010-03-07T17:27:54Z
2,397,150
112
2010-03-07T17:30:38Z
[ "python", "multidimensional-array" ]
I'm beginning python and I'm trying to use a two-dimensional list, that I initially fill up with the same variable in every place. I came up with this: ``` def initialize_twodlist(foo): twod_list = [] new = [] for i in range (0, 10): for j in range (0, 10): new.append(foo) twod_...
You can use a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions): ``` x = [[foo for i in range(10)] for j in range(10)] # x is now a 10x10 array of 'foo' (which can depend on i and j if you want) ```
How to initialize a two-dimensional array in Python?
2,397,141
140
2010-03-07T17:27:54Z
2,397,192
214
2010-03-07T17:43:11Z
[ "python", "multidimensional-array" ]
I'm beginning python and I'm trying to use a two-dimensional list, that I initially fill up with the same variable in every place. I came up with this: ``` def initialize_twodlist(foo): twod_list = [] new = [] for i in range (0, 10): for j in range (0, 10): new.append(foo) twod_...
A pattern that often came up in Python was ``` bar = [] for item in some_iterable: bar.append(SOME EXPRESSION) ``` which helped motivate the introduction of list comprehensions, which convert that snippet to ``` bar = [SOME EXPRESSION for item in some_iterable] ``` which is shorter and sometimes clearer. Usuall...
How to initialize a two-dimensional array in Python?
2,397,141
140
2010-03-07T17:27:54Z
2,398,187
86
2010-03-07T22:10:37Z
[ "python", "multidimensional-array" ]
I'm beginning python and I'm trying to use a two-dimensional list, that I initially fill up with the same variable in every place. I came up with this: ``` def initialize_twodlist(foo): twod_list = [] new = [] for i in range (0, 10): for j in range (0, 10): new.append(foo) twod_...
**This way is faster** than the nested list comprehensions ``` [x[:] for x in [[foo] * 10] * 10] # for immutable foo! ``` Here are some python3 timings, for small and large lists ``` $python3 -m timeit '[x[:] for x in [[1] * 10] * 10]' 1000000 loops, best of 3: 1.55 usec per loop $ python3 -m timeit '[[1 for i i...
How to initialize a two-dimensional array in Python?
2,397,141
140
2010-03-07T17:27:54Z
20,526,889
22
2013-12-11T18:15:29Z
[ "python", "multidimensional-array" ]
I'm beginning python and I'm trying to use a two-dimensional list, that I initially fill up with the same variable in every place. I came up with this: ``` def initialize_twodlist(foo): twod_list = [] new = [] for i in range (0, 10): for j in range (0, 10): new.append(foo) twod_...
To initialize a two-dimensional array in Python: ``` a = [[x for x in range(columns)] for y in range(rows)] ```
How to initialize a two-dimensional array in Python?
2,397,141
140
2010-03-07T17:27:54Z
25,601,284
8
2014-09-01T08:00:26Z
[ "python", "multidimensional-array" ]
I'm beginning python and I'm trying to use a two-dimensional list, that I initially fill up with the same variable in every place. I came up with this: ``` def initialize_twodlist(foo): twod_list = [] new = [] for i in range (0, 10): for j in range (0, 10): new.append(foo) twod_...
You can do just this: ``` [[element] * numcols] * numrows ``` For example: ``` >>> [['a'] *3] * 2 [['a', 'a', 'a'], ['a', 'a', 'a']] ``` But this has a undesired side effect: ``` >>> b = [['a']*3]*3 >>> b [['a', 'a', 'a'], ['a', 'a', 'a'], ['a', 'a', 'a']] >>> b[1][1] 'a' >>> b[1][1] = 'b' >>> b [['a', 'b', 'a'], ...
Web scraping with Python
2,397,295
10
2010-03-07T18:07:24Z
2,398,430
10
2010-03-07T23:23:04Z
[ "python", "firefox", "webkit", "web-scraping" ]
I'm currently trying to scrape a website that has fairly poorly-formatted HTML (often missing closing tags, no use of classes or ids so it's incredibly difficult to go straight to the element you want, etc.). I've been using BeautifulSoup with some success so far but every once and a while (though quite rarely), I run ...
Use [`BeautifulSoup`](http://www.crummy.com/software/BeautifulSoup/) as a tree builder for [`html5lib`](http://code.google.com/p/html5lib/): ``` from html5lib import HTMLParser, treebuilders parser = HTMLParser(tree=treebuilders.getTreeBuilder("beautifulsoup")) text = "a<b>b<b>c" soup = parser.parse(text) print soup...
Web Server frameworks for Python Web Apps
2,397,445
8
2010-03-07T18:46:20Z
2,397,473
13
2010-03-07T18:52:49Z
[ "python", "http", "jython" ]
I'd like to get suggestions on the best way to serve python scripts up as web pages. Typically I'd like a way for me and my colleagues to write simple web pages with minimal effort ie we focus on the business logic eg creating simple forms etc. Possibly with some way to manage sessions but this is a nice-to-have. It do...
The new standard is **[WSGI](http://en.wikipedia.org/wiki/Web_Server_Gateway_Interface)** (Web Server Gateway Interface) and it is supported with [mod\_wsgi](http://code.google.com/p/modwsgi/) for Apache. > The Web Server Gateway Interface > defines a simple and universal > interface between web servers and web > appl...
Web Server frameworks for Python Web Apps
2,397,445
8
2010-03-07T18:46:20Z
2,398,928
7
2010-03-08T02:14:48Z
[ "python", "http", "jython" ]
I'd like to get suggestions on the best way to serve python scripts up as web pages. Typically I'd like a way for me and my colleagues to write simple web pages with minimal effort ie we focus on the business logic eg creating simple forms etc. Possibly with some way to manage sessions but this is a nice-to-have. It do...
These kinds of questions usually result in every python web framework known to man being mentioned once or twice. As Desintegr pointed out, wsgi is the standard interface for python web applications. However, if it is a tad too low level for your tastes, I recommend [pyramid](http://pylonsproject.org/). Here's a simple...
How can I create an array/list of dictionaries in python?
2,397,754
23
2010-03-07T20:07:02Z
2,397,775
22
2010-03-07T20:12:08Z
[ "python", "list", "arrays", "dictionary" ]
I have a dictionary as follows: ``` {'A':0,'C':0,'G':0,'T':0} ``` I want to create an array with many dictionaries in it, as follows: ``` [{'A':0,'C':0,'G':0,'T':0},{'A':0,'C':0,'G':0,'T':0},{'A':0,'C':0,'G':0,'T':0},...] ``` This is my code: ``` weightMatrix = [] for k in range(motifWidth): weightMatrix[k] = ...
``` weightMatrix = [{'A':0,'C':0,'G':0,'T':0} for k in range(motifWidth)] ```
How can I create an array/list of dictionaries in python?
2,397,754
23
2010-03-07T20:07:02Z
13,550,417
20
2012-11-25T11:03:08Z
[ "python", "list", "arrays", "dictionary" ]
I have a dictionary as follows: ``` {'A':0,'C':0,'G':0,'T':0} ``` I want to create an array with many dictionaries in it, as follows: ``` [{'A':0,'C':0,'G':0,'T':0},{'A':0,'C':0,'G':0,'T':0},{'A':0,'C':0,'G':0,'T':0},...] ``` This is my code: ``` weightMatrix = [] for k in range(motifWidth): weightMatrix[k] = ...
This is how I did it and it works: ``` dictlist = [dict() for x in range(n)] ``` It gives you a list of n empty dictionaries.
How can I show figures separately in matplotlib?
2,397,791
28
2010-03-07T20:18:04Z
2,397,838
28
2010-03-07T20:28:54Z
[ "python", "matplotlib" ]
Say that I have two figures in matplotlib, with one plot per figure: ``` import matplotlib.pyplot as plt f1 = plt.figure() plt.plot(range(0,10)) f2 = plt.figure() plt.plot(range(10,20)) ``` Then I show both in one shot ``` plt.show() ``` Is there a way to show them separately, i.e. to show just `f1`? Or better: h...
Sure. Add an `Axes` using `add_subplot`. (Edited `import`.) (Edited `show`.) ``` import matplotlib.pyplot as plt f1 = plt.figure() f2 = plt.figure() ax1 = f1.add_subplot(111) ax1.plot(range(0,10)) ax2 = f2.add_subplot(111) ax2.plot(range(10,20)) plt.show() ``` Alternatively, use `add_axes`. ``` ax1 = f1.add_axes([0....
How can I show figures separately in matplotlib?
2,397,791
28
2010-03-07T20:18:04Z
2,399,978
19
2010-03-08T08:07:34Z
[ "python", "matplotlib" ]
Say that I have two figures in matplotlib, with one plot per figure: ``` import matplotlib.pyplot as plt f1 = plt.figure() plt.plot(range(0,10)) f2 = plt.figure() plt.plot(range(10,20)) ``` Then I show both in one shot ``` plt.show() ``` Is there a way to show them separately, i.e. to show just `f1`? Or better: h...
With Matplotlib prior to version 1.0.1, `show()` [should only be called once per program](http://matplotlib.sourceforge.net/faq/howto_faq.html#use-show), even if it seems to work within certain environments (some backends, on some platforms, etc.). The relevant drawing function is actually `draw()`: ``` import matplo...
saving and loading objects from file using jsonpickle
2,398,078
11
2010-03-07T21:39:11Z
2,405,814
17
2010-03-09T00:27:23Z
[ "python", "json", "serialization", "jsonpickle" ]
I have the following simple methods for writing a python object to a file using jsonpickle: ``` def json_serialize(obj, filename, use_jsonpickle=True): f = open(filename, 'w') if use_jsonpickle: import jsonpickle json_obj = jsonpickle.encode(obj) f.write(json_obj) else: simp...
The correct answer was that I was not inheriting from `object`. Without inheriting from `object`, jsonpickle cannot correctly decode classes that take one or more arguments in the constructor, it seems. I am by no means an expert but making it `Foo(object):` rather than `Foo:` in the class declaration fixed it.
using os.system in python to run program with parameters
2,398,095
2
2010-03-07T21:43:56Z
2,398,125
8
2010-03-07T21:51:48Z
[ "python" ]
How do I get python to run sudo openvpn --cd /etc/openvpn --config client.ovpn I'm trying the following at the minute without success ``` vpnfile2 = '/etc/init.d/openvpn' cfgFile = 'client.ovpn' os.system('sudo \"" + vpnFile2 + "\" --cd \"" + vpnpath + "\" --config \"" + cfgFile + "\"') ```
use the `subprocess` module ``` import subprocess subprocess.call(['sudo', vpnFile2, '--cd', vpnpath, '--config', cfgFile]) ```
Python - BaseHTTPServer.HTTPServer Concurrency & Threading
2,398,144
13
2010-03-07T21:56:54Z
2,398,283
19
2010-03-07T22:36:52Z
[ "python", "multithreading", "httpserver", "basehttpserver", "socketserver" ]
Is there a way to make BaseHTTPServer.HTTPServer be multi-threaded like SocketServer.ThreadingTCPServer?
You can simply use the threading mixin using both of those classes to make it multithread :) It won't help you much in performance though, but it's atleast multithreaded. ``` from SocketServer import ThreadingMixIn from BaseHTTPServer import HTTPServer class MultiThreadedHTTPServer(ThreadingMixIn, HTTPServer): p...
How to check if datetime is older than 20 seconds
2,398,205
15
2010-03-07T22:14:22Z
2,398,242
28
2010-03-07T22:25:24Z
[ "python", "google-app-engine", "datetime", "time" ]
This is my first time here so I hope I post this question at the right place. :) I need to build flood control for my script but I'm not good at all this datetime to time conversions with UTC and stuff. I hope you can help me out. I'm using the Google App Engine with Python. I've got a datetimeproperty at the DataStor...
You can use the datetime.timedelta datatype, like this: ``` import datetime lastplus = q.get() if lastplus.date < datetime.datetime.now()-datetime.timedelta(seconds=20): print "Go" ``` Read more about it here: <http://docs.python.org/library/datetime.html> Cheers, Philip
How to organize Python modules for PyPI to support 2.x and 3.x
2,398,626
14
2010-03-08T00:25:57Z
2,729,050
14
2010-04-28T11:40:05Z
[ "python", "python-3.x", "software-distribution", "python-2.x" ]
I have a Python module that I would like to upload to PyPI. So far, it is working for Python 2.x. It shouldn't be too hard to write a version for 3.x now. But, after following guidelines for making modules in these places: * [Distributing Python Modules](http://docs.python.org/distutils/index.html) * [The Hitchhikerâ...
I found that [`setup.py` for `httplib2`](http://code.google.com/p/httplib2/source/browse/setup.py) seems to have an elegant way to support Python 2.x and 3.x. So I decided to copy that method. The task is to craft a single `setup.py` for the package distribution that works with all the supported Python distributions. ...
Schedule a repeating event in Python 3
2,398,661
17
2010-03-08T00:35:52Z
2,399,145
22
2010-03-08T03:35:34Z
[ "python", "python-3.x", "scheduled-tasks", "timing" ]
I'm trying to schedule a repeating event to run every minute in Python 3. I've seen class `sched.scheduler` but I'm wondering if there's another way to do it. I've heard mentions I could use multiple threads for this, which I wouldn't mind doing. I'm basically requesting some JSON and then parsing it; its value chang...
You could use [`threading.Timer`](http://docs.python.org/3.1/library/threading.html?highlight=timer#timer-objects), but that also schedules a one-off event, similarly to the `.enter` method of scheduler objects. The normal pattern (in any language) to transform a one-off scheduler into a periodic scheduler is to have ...
Schedule a repeating event in Python 3
2,398,661
17
2010-03-08T00:35:52Z
13,151,104
12
2012-10-31T04:03:59Z
[ "python", "python-3.x", "scheduled-tasks", "timing" ]
I'm trying to schedule a repeating event to run every minute in Python 3. I've seen class `sched.scheduler` but I'm wondering if there's another way to do it. I've heard mentions I could use multiple threads for this, which I wouldn't mind doing. I'm basically requesting some JSON and then parsing it; its value chang...
My humble take on the subject: ``` from threading import Timer class RepeatedTimer(object): def __init__(self, interval, function, *args, **kwargs): self._timer = None self.function = function self.interval = interval self.args = args self.kwargs = kwargs ...
Linking a qtDesigner .ui file to python/pyqt?
2,398,800
49
2010-03-08T01:27:56Z
2,399,618
22
2010-03-08T06:19:05Z
[ "python", "user-interface", "qt", "pyqt", "qt-designer" ]
So if I go into QtDesigner and build a UI, it'll be saved as a .ui file. How can I make this as a python file or use this in python?
You need to generate a python file from your ui file with the pyuic tool (site-packages\pyqt4\bin) ``` pyuic form1.ui > form1.py ``` with pyqt4 ``` pyuic4.bat form1.ui > form1.py ``` Then you can import the form1 into your script.
Linking a qtDesigner .ui file to python/pyqt?
2,398,800
49
2010-03-08T01:27:56Z
2,500,905
44
2010-03-23T14:59:33Z
[ "python", "user-interface", "qt", "pyqt", "qt-designer" ]
So if I go into QtDesigner and build a UI, it'll be saved as a .ui file. How can I make this as a python file or use this in python?
Another way to use .ui in your code is: ``` from PyQt4 import QtCore, QtGui, uic class MyWidget(QtGui.QWidget) ... #somewhere in constructor: uic.loadUi('MyWidget.ui', self) ``` both approaches are good. Do not forget, that if you use Qt resource files (extremely useful) for icons and so on, you must comp...
Linking a qtDesigner .ui file to python/pyqt?
2,398,800
49
2010-03-08T01:27:56Z
9,526,625
20
2012-03-02T01:05:25Z
[ "python", "user-interface", "qt", "pyqt", "qt-designer" ]
So if I go into QtDesigner and build a UI, it'll be saved as a .ui file. How can I make this as a python file or use this in python?
I found this article very helpful. <http://talk.maemo.org/archive/index.php/t-43663.html> I'll briefly describe the actions to create and change .ui file to .py file, taken from that article. 1. Start Qt Designer from your start menu. 2. From "New Form" window, create "Main Window" 3. From "Display Widgets" towards ...
Linking a qtDesigner .ui file to python/pyqt?
2,398,800
49
2010-03-08T01:27:56Z
17,133,008
21
2013-06-16T11:51:33Z
[ "python", "user-interface", "qt", "pyqt", "qt-designer" ]
So if I go into QtDesigner and build a UI, it'll be saved as a .ui file. How can I make this as a python file or use this in python?
Combining [Max's answer](http://stackoverflow.com/a/2500905/544059) and [Shriramana Sharma's mailing list post](http://www.riverbankcomputing.com/pipermail/pyqt/2007-April/015902.html), I built a small working example for loading a `mywindow.ui` file containing a `QMainWindow` (so just choose to create a Main Window in...
Python, print delimited list
2,399,112
25
2010-03-08T03:25:03Z
2,399,122
60
2010-03-08T03:27:18Z
[ "python", "string", "printing" ]
Consider this Python code for printing a list of comma separated values ``` for element in list: print element + ",", ``` What is the preferred method for printing such that a comma does not appear if `element` is the final element in the list. ex ``` a = [1, 2, 3] for element in a print str(element) +",", o...
``` >>> ','.join(map(str,a)) '1,2,3' ```