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
Pythonic way to insert every 2 elements in a string
3,258,573
11
2010-07-15T18:15:33Z
3,258,596
25
2010-07-15T18:19:07Z
[ "python", "string" ]
Is there a pythonic way to insert an element into every 2nd element in a string? I have a string: 'aabbccdd' and I want the end result to be 'aa-bb-cc-dd'. I am not sure how I would go about doing that.
Assume the string's length is always an even number, ``` >>> s = '12345678' >>> t = iter(s) >>> '-'.join(a+b for a,b in zip(t, t)) '12-34-56-78' ``` The `t` can also be eliminated with ``` >>> '-'.join(a+b for a,b in zip(s[::2], s[1::2])) '12-34-56-78' ``` --- The algorithm is to group the string into pairs, then ...
Pythonic way to insert every 2 elements in a string
3,258,573
11
2010-07-15T18:15:33Z
3,258,612
17
2010-07-15T18:21:08Z
[ "python", "string" ]
Is there a pythonic way to insert an element into every 2nd element in a string? I have a string: 'aabbccdd' and I want the end result to be 'aa-bb-cc-dd'. I am not sure how I would go about doing that.
``` >>> s = 'aabbccdd' >>> '-'.join(s[i:i+2] for i in range(0, len(s), 2)) 'aa-bb-cc-dd' ```
Creating Python function with partial parameters
3,258,756
3
2010-07-15T18:39:24Z
3,258,791
13
2010-07-15T18:41:57Z
[ "python", "lambda" ]
I want to pass a Python function to another function with some of its parameters "filled out" ahead of time. This is simplification what I am doing: ``` def add(x, y): return x + y def increment_factory(i): # create a function that increments by i return (lambda y: add(i, y)) inc2 = increment_factory(2) p...
This is called currying, or partial application. You can use the built-in [functools.partial()](http://docs.python.org/library/functools.html#functools.partial). Something like the following would do what you want. ``` import functools def add(x,y): return x + y inc2 = functools.partial(add, 2) print inc2(3) ```
Writing bindings and wrappers
3,259,033
6
2010-07-15T19:07:05Z
3,259,111
7
2010-07-15T19:14:24Z
[ "python", "binding" ]
I keep seeing people writing wrappers for, say a module written in X language to use it in Y language. I wanted to know the basics of writing such wrappers. Where does one start from? My question here is more specific for [libgnokii](http://www.gnokii.org/), how do I begin to write python bindings for it.
You can start with reading this: [extending python with c or c++](http://docs.python.org/extending/extending.html) And then when you decide that it's too much hassle, you can check out [swig](http://www.swig.org/) or possibly [Boost.Python](http://www.boost.org/doc/libs/1_43_0/libs/python/doc/index.html). [ctypes](http...
Django templates: False vs. None
3,259,279
13
2010-07-15T19:36:17Z
3,259,592
10
2010-07-15T20:10:29Z
[ "python", "django", "templates", "if-statement" ]
How can I distinguish between `None` and `False` in django templates? ``` {% if x %} True {% else %} None and False - how can I split this case? {% endif %} ```
Every Django template context [contains `True`, `False` and `None`](https://docs.djangoproject.com/en/1.9/ref/templates/api/#builtin-variables]). For Django 1.10 and later, you can do the following: ``` {% if x %} True {% elif x is None %} None {% else %} False (or empty string, empty list etc) {% endif %} ``` Djang...
Why use lambda functions?
3,259,322
40
2010-07-15T19:41:54Z
3,259,388
22
2010-07-15T19:48:44Z
[ "python", "lambda" ]
I can find lots of stuff showing me what a lambda function is, and how the syntax works and what not. But other than the "coolness factor" (I can make a function in middle a call to another function, neat!) I haven't seen something that's overwelmingly compelling to say why I really need/want to use them. It seems to ...
Here's a good example: ``` def key(x): return x[1] a = [(1, 2), (3, 1), (5, 10), (11, -3)] a.sort(key=key) ``` versus ``` a = [(1, 2), (3, 1), (5, 10), (11, -3)] a.sort(key=lambda x: x[1]) ``` From another angle: Lambda expressions are also known as "anonymous functions", and are very useful in certain program...
Why use lambda functions?
3,259,322
40
2010-07-15T19:41:54Z
3,259,410
11
2010-07-15T19:50:56Z
[ "python", "lambda" ]
I can find lots of stuff showing me what a lambda function is, and how the syntax works and what not. But other than the "coolness factor" (I can make a function in middle a call to another function, neat!) I haven't seen something that's overwelmingly compelling to say why I really need/want to use them. It seems to ...
The syntax is more concise in certain situations, mostly when dealing with `map` et al. ``` map(lambda x: x * 2, [1,2,3,4]) ``` seems better to me than: ``` def double(x): return x * 2 map(double, [1,2,3,4]) ``` I think the lambda is a better choice in this situation because the `def double` seems almost disco...
Run a C# application from python script
3,260,015
3
2010-07-15T20:58:23Z
3,260,110
7
2010-07-15T21:08:22Z
[ "python", "filesystems", "subprocess", "simulation" ]
I've just about finished coding a decently sized disease transmission model in C#. However, I'm fairly new to .NET and am unsure how to proceed. Currently I just double-click on the .exe file and the model imports config setting from text files, does its thing, and outputs the results into a text file. What I would li...
As of Python 2.6+ you should be using the `subprocess` module: ([Docs](http://docs.python.org/library/subprocess.html#module-subprocess)) ``` import subprocess for v in range(1000): cmdLine = r"c:\path\to\my\app.exe" subprocess.Popen(subprocess) subprocess.Popen(r"move output.txt ./acc/output-%d.txt" % (v...
how to check variable against 2 possible values python
3,260,057
14
2010-07-15T21:01:56Z
3,260,070
27
2010-07-15T21:03:19Z
[ "python" ]
I have a variable s which contains a one letter string ``` s = 'a' ``` Depending on the value of that variable, I want to return different things. So far I am doing something along the lines of this: ``` if s == 'a' or s == 'b': return 1 elif s == 'c' or s == 'd': return 2 else: return 3 ``` Is there a be...
``` if s in ('a', 'b'): return 1 elif s in ('c', 'd'): return 2 else: return 3 ```
how to check variable against 2 possible values python
3,260,057
14
2010-07-15T21:01:56Z
3,260,119
12
2010-07-15T21:10:13Z
[ "python" ]
I have a variable s which contains a one letter string ``` s = 'a' ``` Depending on the value of that variable, I want to return different things. So far I am doing something along the lines of this: ``` if s == 'a' or s == 'b': return 1 elif s == 'c' or s == 'd': return 2 else: return 3 ``` Is there a be...
``` d = {'a':1, 'b':1, 'c':2, 'd':2} return d.get(s, 3) ```
Sort list by given order of indices -Python
3,260,427
4
2010-07-15T21:58:23Z
3,260,459
7
2010-07-15T22:04:02Z
[ "python", "sorting", "list" ]
I have a list of lines read from a file. I need to sort the list by time stamp (in UTC), however the time stamp is not always at the beginning of the string. I have parsed out the time stamp using regular expressions and place them into a separate list. The indices of the two lists will match. Once I sort the list of t...
``` [listofLines[i] for i in sortedIndex] ```
How do to multiple imports in Python?
3,260,599
10
2010-07-15T22:28:10Z
3,260,633
9
2010-07-15T22:35:44Z
[ "python", "import", "iterator", "require" ]
In Ruby, instead of repeating the "require" (the "import" in Python) word lots of times, I do ``` %w{lib1 lib2 lib3 lib4 lib5}.each { |x| require x } ``` So it iterates over the set of "libs" and "require" (import) each one of them. Now I'm writing a Python script and I would like to do something like that. Is there ...
Try this: ``` import lib1, lib2, lib3, lib4, lib5 ``` You can also change the name they are imported under in this way, like so: ``` import lib1 as l1, lib2 as l2, lib3, lib4 as l4, lib5 ```
How do to multiple imports in Python?
3,260,599
10
2010-07-15T22:28:10Z
3,260,643
16
2010-07-15T22:39:02Z
[ "python", "import", "iterator", "require" ]
In Ruby, instead of repeating the "require" (the "import" in Python) word lots of times, I do ``` %w{lib1 lib2 lib3 lib4 lib5}.each { |x| require x } ``` So it iterates over the set of "libs" and "require" (import) each one of them. Now I'm writing a Python script and I would like to do something like that. Is there ...
For known module, just seperate them by commas: ``` import lib1, lib2, lib3, lib4, lib5 ``` If you really need to programatically import based on dynamic variables, a literal translation of your ruby would be: ``` modnames = "lib1 lib2 lib3 lib4 lib5".split() for lib in modnames: globals()[lib] = __import__(...
Any way to keep track of the last 5 data points in python
3,261,090
7
2010-07-16T00:28:13Z
3,261,111
11
2010-07-16T00:33:12Z
[ "python" ]
So I have an array that holds several numbers. As my script runs, more and more numbers are appended to this array. However, I am not interested in all the numbers but just want to keep track of the last 5 numbers. Currently, I just store all the numbers in the array. However, this array gets really big and it's full ...
Try using a deque: <http://docs.python.org/library/collections.html#deque-objects> "If maxlen is not specified or is None, deques may grow to an arbitrary length. Otherwise, the deque is bounded to the specified maximum length. Once a bounded length deque is full, when new items are added, a corresponding number of it...
Does anyone have example code for a sqlite pipeline in Scrapy?
3,261,858
5
2010-07-16T04:08:46Z
8,733,888
9
2012-01-04T20:56:42Z
[ "python", "sqlite", "export", "scrapy" ]
I am looking for some example code of a SQLite pipeline in Scrapy. I know there is no built in support for it, but I'm sure it has been done. Only actual code can help me, as I only know enough Python and Scrapy to complete my very limited task, and need the code as a starting point.
I did something like this: ``` # # Author: Jay Vaughan # # Pipelines for processing items returned from a scrape. # Dont forget to add pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/topics/item-pipeline.html # from scrapy import log from pysqlite2 import dbapi2 as sqlite # This pipeline takes the...
Pausing a thread using threading class
3,262,346
10
2010-07-16T06:13:04Z
14,804,328
7
2013-02-11T00:33:27Z
[ "python", "multithreading", "wxpython" ]
I have a long process that i've scheduled to run in a thread, because otherwise it will freeze the ui in my wxpython application. I'm using ``` threading.Thread(target = myLongProcess).start() ``` to start the thread and it works, but I don't know how to pause and resume the thread. I looked in the python docs for t...
I was having the same issue myself, until I found the answer. I did some speed tests as well, the time to set the flag and for action to be taken is pleasantly fast 0.00002 secs on a slow 2 processor Linux box. ## Example thread pause test using set() & clear() events *By Rich O'Regan* ``` import threading import t...
Check Pending AJAX requests or HTTP GET/POST request
3,262,473
7
2010-07-16T06:38:03Z
3,263,539
9
2010-07-16T09:29:57Z
[ "javascript", "python", "html" ]
How do i check if the page has pending AJAX or HTTP GET/POST requests? I use javascript and/or python for this checking. what i wanted to do is execute a script if a page has finished all requests. onload doesn't work for me, if you used firebugs net panel, you would know. onload fires when the page is loaded but ther...
figured it out. thanks for the effort guys. just plain and simple javascript. ``` interValRef = 0; interValRef = setInterval("checkState();",100) function checkState(){ if(document.readyState == 'complete'){ clearInterval(interValRef); myFunc(); } } ```
Validating a yaml document in python
3,262,569
22
2010-07-16T06:55:49Z
3,262,684
7
2010-07-16T07:13:39Z
[ "python", "yaml", "validation" ]
One of the benefits of XML is being able to validate a document against an XSD. YAML doesn't have this feature, so how can I validate that the YAML document I open is in the format expected by my application?
Try [Rx](http://rx.codesimply.com/), it has a Python implementation. It works on JSON and YAML. From the Rx site: > "When adding an API to your web service, you have to choose how to encode the data you send across the line. XML is one common choice for this, but it can grow arcane and cumbersome pretty quickly. Lots ...
Django Abstract Models vs simple Python mixins vs Python ABCs
3,263,417
7
2010-07-16T09:11:21Z
3,265,376
9
2010-07-16T13:38:00Z
[ "python", "django" ]
This is a question prompted by [another question](http://stackoverflow.com/questions/3254436/django-model-mixins-inherit-from-models-model-or-from-object) from me. Django provides [Abstract base classes](http://docs.djangoproject.com/en/dev/topics/db/models/#id6) functionality (which are not to same as ABC classes in ...
I'll try to be reasonably brief, since this can easily turn into a lengthy diatribe: ABCs are out because they were only introduced in Python 2.6, and the Django developers have a set roadmap for Python version support (2.3 support was only dropped in 1.2). As for object-inheriting mixins, they would be less Pythonic...
Python - The difference between sys.stdout.write and print
3,263,672
169
2010-07-16T09:53:23Z
3,263,733
64
2010-07-16T10:03:21Z
[ "python", "printing", "stdout" ]
Are there situations in which `sys.stdout.write()` is preferable to `print`? (**Examples:** better performance; code that makes more sense)
"print" first converts the object to a string (if it is not already a string). It will also put a space before the object if it is not the start of a line and a newline character at the end. When using stdout, you need to convert the object to a string yourself (by calling "str", for example) and there is no newline c...
Python - The difference between sys.stdout.write and print
3,263,672
169
2010-07-16T09:53:23Z
3,263,763
142
2010-07-16T10:06:41Z
[ "python", "printing", "stdout" ]
Are there situations in which `sys.stdout.write()` is preferable to `print`? (**Examples:** better performance; code that makes more sense)
`print` is just a thin wrapper that formats the inputs (space between args and newline at the end) and calls the write function of a given object. By default this object is `sys.stdout`, but you can pass a file for example: ``` print >> open('file.txt', 'w'), 'Hello', 'World', 2+3 ``` In Python 3.x, `print` becomes a...
Python - The difference between sys.stdout.write and print
3,263,672
169
2010-07-16T09:53:23Z
3,264,118
21
2010-07-16T10:59:15Z
[ "python", "printing", "stdout" ]
Are there situations in which `sys.stdout.write()` is preferable to `print`? (**Examples:** better performance; code that makes more sense)
> My question is whether or not there > are situations in which > `sys.stdout.write()` is preferable to > `print` After finishing developing a script the other day, I uploaded it to a unix server. All my debug messages used `print` statements, and these **do not** appear on a server log. This is a case where you may ...
Python - The difference between sys.stdout.write and print
3,263,672
169
2010-07-16T09:53:23Z
12,182,693
16
2012-08-29T16:43:09Z
[ "python", "printing", "stdout" ]
Are there situations in which `sys.stdout.write()` is preferable to `print`? (**Examples:** better performance; code that makes more sense)
Here's some sample code based on the book *Learning Python* by Mark Lutz that addresses your question: ``` import sys temp = sys.stdout # store original stdout object for later sys.stdout = open('log.txt', 'w') # redirect all prints to this log file print("testing123") # nothing appears a...
does python multiplicative expression evaluates faster if finds a zero?
3,264,345
8
2010-07-16T11:31:08Z
3,264,538
7
2010-07-16T11:54:13Z
[ "python", "optimization", "math", "evaluation" ]
suppose i a have a multiplicative expression with lots of multiplicands (small expressions) ``` expression = a*b*c*d*....*w ``` where for example c is (x-1), d is (y\*\*2-16), k is (x\*y-60)..... x,y are numbers and i know that c,d,k,j maybe zero Does the order i write the expression matters for faster evaluation...
Python v2.6.5 does not check for zero values. ``` def foo(): a = 1 b = 2 c = 0 return a * b * c >>> import dis >>> dis.dis(foo) 2 0 LOAD_CONST 1 (1) 3 STORE_FAST 0 (a) 3 6 LOAD_CONST 2 (2) 9 STORE_FAST ...
What is the "sys.stdout.write()" equivalent in Ruby?
3,265,129
18
2010-07-16T13:11:19Z
3,265,187
35
2010-07-16T13:17:17Z
[ "python", "ruby", "stdout" ]
As seen in Python, what is the `sys.stdout.write()` equivalent in Ruby?
In Ruby, you can access standard out with `$stdout` or `STDOUT`. So you can use the [write](http://ruby-doc.org/core-2.2.0/IO.html#method-i-write) method like this: ``` $stdout.write 'Hello, World!' ``` or equivalently: ``` STDOUT.write 'Hello, World!' ``` `$stdout` is a actually a global variable whose default val...
Compiled vs. Interpreted Languages
3,265,357
154
2010-07-16T13:35:33Z
3,265,505
12
2010-07-16T13:52:02Z
[ "java", "python", "compiler-construction", "programming-languages", "interpreter" ]
I'm trying to get a better understanding of the difference. I've found a lot of explanations online, but they tend towards the abstract differences rather than the practical implications. Most of my programming experiences has been with CPython (dynamic, interpreted), and Java (static, compiled). However, I understand...
The extreme and simple cases: * A compiler will produce a binary executable in the target machine's native executable format. This binary file contains all required resources except for system libraries; it's ready to run with no further preparation and processing and it runs like lightning because the code is the nat...
Compiled vs. Interpreted Languages
3,265,357
154
2010-07-16T13:35:33Z
3,265,602
285
2010-07-16T14:00:52Z
[ "java", "python", "compiler-construction", "programming-languages", "interpreter" ]
I'm trying to get a better understanding of the difference. I've found a lot of explanations online, but they tend towards the abstract differences rather than the practical implications. Most of my programming experiences has been with CPython (dynamic, interpreted), and Java (static, compiled). However, I understand...
A compiled language is one where the program, once compiled, is expressed in the instructions of the target machine. For example, an addition "+" operation in your source code could be translated directly to the "ADD" instruction in machine code. An interpreted language is one where the instructions are not directly e...
Compiled vs. Interpreted Languages
3,265,357
154
2010-07-16T13:35:33Z
3,265,680
57
2010-07-16T14:07:38Z
[ "java", "python", "compiler-construction", "programming-languages", "interpreter" ]
I'm trying to get a better understanding of the difference. I've found a lot of explanations online, but they tend towards the abstract differences rather than the practical implications. Most of my programming experiences has been with CPython (dynamic, interpreted), and Java (static, compiled). However, I understand...
A language itself is neither compiled nor interpreted, only a specific implementation of a language is. Java is a perfect example. There is a bytecode-based platform (the JVM), a native compiler (gcj) and an interpeter for a superset of Java (bsh). So what is Java now? Bytecode-compiled, native-compiled or interpreted?...
Compiled vs. Interpreted Languages
3,265,357
154
2010-07-16T13:35:33Z
3,266,025
22
2010-07-16T14:43:33Z
[ "java", "python", "compiler-construction", "programming-languages", "interpreter" ]
I'm trying to get a better understanding of the difference. I've found a lot of explanations online, but they tend towards the abstract differences rather than the practical implications. Most of my programming experiences has been with CPython (dynamic, interpreted), and Java (static, compiled). However, I understand...
Start thinking in terms of a: **blast from the past** Once upon a time, long long ago, there lived in the land of computing interpreters and compilers. All kinds of fuss ensued over the merits of one over the other. The general opinion *at that time* was something along the lines of: * Interpreter: Fast to develop (e...
Compiled vs. Interpreted Languages
3,265,357
154
2010-07-16T13:35:33Z
23,750,310
7
2014-05-20T02:56:30Z
[ "java", "python", "compiler-construction", "programming-languages", "interpreter" ]
I'm trying to get a better understanding of the difference. I've found a lot of explanations online, but they tend towards the abstract differences rather than the practical implications. Most of my programming experiences has been with CPython (dynamic, interpreted), and Java (static, compiled). However, I understand...
The biggest advantage of interpreted source code over compiled source code is **PORTABILITY**. If your source code is compiled, you need to compile a different executable for each type of processor and/or platform that you want your program to run on (e.g. one for Windows x86, one for Windows x64, one for Linux x64, a...
Compiled vs. Interpreted Languages
3,265,357
154
2010-07-16T13:35:33Z
28,067,958
8
2015-01-21T13:04:34Z
[ "java", "python", "compiler-construction", "programming-languages", "interpreter" ]
I'm trying to get a better understanding of the difference. I've found a lot of explanations online, but they tend towards the abstract differences rather than the practical implications. Most of my programming experiences has been with CPython (dynamic, interpreted), and Java (static, compiled). However, I understand...
From <http://www.quora.com/What-is-the-difference-between-compiled-and-interpreted-programming-languages> > There is no difference, because “compiled programming language” and > “interpreted programming language” aren’t meaningful concepts. Any > programming language, and I really mean any, can be interprete...
Can iterators be reset in Python?
3,266,180
76
2010-07-16T15:00:47Z
3,266,353
13
2010-07-16T15:18:52Z
[ "python", "iterator", "generator" ]
Can I reset an iterator / generator in Python? I am using DictReader and would like to reset it (from the csv module) to the beginning of the file.
No. Python's iterator protocol is very simple, and only provides one single method (`.next()` or `__next__()`), and no method to reset an iterator in general. The common pattern is to instead create a new iterator using the same procedure again. If you want to "save off" an iterator so that you can go back to its beg...
Can iterators be reset in Python?
3,266,180
76
2010-07-16T15:00:47Z
3,266,399
21
2010-07-16T15:24:06Z
[ "python", "iterator", "generator" ]
Can I reset an iterator / generator in Python? I am using DictReader and would like to reset it (from the csv module) to the beginning of the file.
If you have a csv file named 'blah.csv' That looks like ``` a,b,c,d 1,2,3,4 2,3,4,5 3,4,5,6 ``` you know that you can open the file for reading, and create a DictReader with ``` blah = open('blah.csv', 'r') reader= csv.DictReader(blah) ``` Then, you will be able to get the next line with `reader.next()`, which shou...
Can iterators be reset in Python?
3,266,180
76
2010-07-16T15:00:47Z
3,267,069
51
2010-07-16T16:39:23Z
[ "python", "iterator", "generator" ]
Can I reset an iterator / generator in Python? I am using DictReader and would like to reset it (from the csv module) to the beginning of the file.
I see many answers suggesting [itertools.tee](http://docs.python.org/library/itertools.html?highlight=itertools.tee#itertools.tee), but that's ignoring one crucial warning in the docs for it: > This itertool may require significant > auxiliary storage (depending on how > much temporary data needs to be > stored). In g...
Can iterators be reset in Python?
3,266,180
76
2010-07-16T15:00:47Z
3,267,604
10
2010-07-16T17:56:51Z
[ "python", "iterator", "generator" ]
Can I reset an iterator / generator in Python? I am using DictReader and would like to reset it (from the csv module) to the beginning of the file.
There's a bug in using .seek(0) as advocated by Alex Martelli and Wilduck above, namely that the next call to .next() will give you a dictionary of your header row in the form of {key1:key1, key2:key2, ...}. The work around is to follow file.seek(0) with a call to reader.next() to get rid of the header row. So your co...
List of Python regular expressions for a newbie?
3,266,870
2
2010-07-16T16:14:10Z
3,272,002
12
2010-07-17T15:00:09Z
[ "python", "regex" ]
I recently learned a little Python and I couldnt find a good list of the RegEx's (don't know if that is the correct plural tense...) with complete explanations even a rookie will understand :) Anybody know a such list?
Vide: ![regEx](http://i26.tinypic.com/24mxgt4.png)
Converting a Mercurial (hg) repository to Git on Windows (7)
3,267,232
22
2010-07-16T17:02:07Z
3,269,811
19
2010-07-17T01:20:05Z
[ "python", "windows", "git", "mercurial" ]
I'm really quite frustrated at this point. I have an existing hg repository that has months of coding history in it, and I want to get this into a private Github repository so I can work on it from there. Unfortunately I use Windows and I can't seem to find *any* way to convert the repository that I can actually get to...
1. Install [Cygwin](http://www.cygwin.com/) (with python, hg, git) 2. Install [git-hg](http://github.com/offbytwo/git-hg) 3. run `git-hg clone ...url...` Or tell me what the url is for this hg repo of yours, and I can convert it for you.
I cannot search sent emails in Gmail with Python
3,267,234
7
2010-07-16T17:02:20Z
12,576,837
19
2012-09-25T05:44:41Z
[ "python", "gmail", "imaplib" ]
I am trying to search for messages in the Sent (actually i care for both) but I only get incoming messages. For the time being i have ``` imap_conn.select() str_after = after.strftime('%d-%b-%Y') typ, msg_ids = imap_conn.search('UTF-8','SINCE',str_after) ``` Which gives equivalent results with this ``` imap_conn.sel...
Man, the error message is so misleading. What it's really saying is that you have tried to select an invalid folder name hence the search operation fails. To verify/check the current valid folders/labels do something like: ``` print imap_conn.list() ``` After I could see what folder names it was expecting, all was w...
How to write a check in python to see if file is valid UTF-8?
3,269,293
10
2010-07-16T22:33:51Z
3,269,387
15
2010-07-16T22:53:51Z
[ "python", "utf-8" ]
As stated in title, I would like to check in given file object (opened as binary stream) is valid UTF-8 file. Anyone? Thanks
``` def try_utf8(data): "Returns a Unicode object on success, or None on failure" try: return data.decode('utf-8') except UnicodeDecodeError: return None data = f.read() udata = try_utf8(data) if udata is None: # Not UTF-8. Do something else else: # Handle unicode data ```
Disabling Django CSRF for views that do not always have a response
3,269,617
15
2010-07-17T00:12:23Z
3,269,637
7
2010-07-17T00:17:56Z
[ "python", "django", "csrf", "decorator", "django-csrf" ]
I have a Django view that receives POSTs which do not need to have the CSRF token. Therefore I used the `@csrf_exempt` decorator on the view. The problem is that sometimes I do not issue a response from the view (it's a Twitter bot, it receives an HTTP POST for every tweet and I do not want to respond to every tweet). ...
Django really expects view functions to return responses. Maybe you could return an empty response instead of None? Or return an HTTP error code?
Disabling Django CSRF for views that do not always have a response
3,269,617
15
2010-07-17T00:12:23Z
4,429,345
9
2010-12-13T13:39:50Z
[ "python", "django", "csrf", "decorator", "django-csrf" ]
I have a Django view that receives POSTs which do not need to have the CSRF token. Therefore I used the `@csrf_exempt` decorator on the view. The problem is that sometimes I do not issue a response from the view (it's a Twitter bot, it receives an HTTP POST for every tweet and I do not want to respond to every tweet). ...
I know you already got your answer, and indeed Ned's right; but in addition to that: not only Django really expects views to return a response, your client also! It's an HTTP error and likely a resource waste not to return something (and thus close the connection straight away)! I would think that a 204 No Content or ...
= Try Except Pattern?
3,269,887
3
2010-07-17T01:45:37Z
3,269,898
10
2010-07-17T01:49:25Z
[ "python", "design-patterns" ]
I find this design pattern comes up a lot: ``` try: year = int(request.GET['year']) except: year = 0 ``` The `try` block can either fail because the key doesn't exist, or because it's not an `int`, but I don't really care. I just need a sane value in the end. Shouldn't there be a nicer way to do this? Or at least a ...
You're probably better off to use `get()` ``` year = int(request.GET.get("year", 0)) ``` This will set year to what ever request.GET['year'] is, or if the key doesn't exist, it will return 0. This gets rid of your KeyError, but you could still have a ValueError from request.GET['year'], if it is not convert'able to a...
Python circular references
3,270,045
2
2010-07-17T02:56:33Z
3,270,066
10
2010-07-17T03:05:15Z
[ "python", "circular-dependency" ]
trying to have two class that reference each others, in the same file. What would be the best way to have this working: ``` class Foo(object): other = Bar class Bar(object): other = Foo if __name__ == '__main__': print 'all ok' ``` ? The problem seems to be that since the property is on the class, sinc...
This would do what you want: ``` class Foo(object): pass class Bar(object): pass Foo.other = Bar Bar.other = Foo ``` I would prefer to avoid such design completely, though.
How do I make Tkinter support PNG transparency?
3,270,209
12
2010-07-17T04:05:23Z
3,442,396
14
2010-08-09T17:08:00Z
[ "python", "png", "transparency", "tkinter" ]
I put in a partially transparent PNG image in Tkinter and all I get is this ![alt text](http://i26.tinypic.com/aelh82.jpg) How do I make the dark triangle on the right clear? (like it's supposed to be) This is python 2.6 on Windows 7, btw.
Here's an example (the PNG file example.png has lots of transparency in different places): ``` from Tkinter import Tk, Frame, Canvas import ImageTk t = Tk() t.title("Transparency") frame = Frame(t) frame.pack() canvas = Canvas(frame, bg="black", width=500, height=500) canvas.pack() photoimage = ImageTk.PhotoImage(...
How does Python compare string and int?
3,270,680
122
2010-07-17T07:48:56Z
3,270,684
17
2010-07-17T07:51:39Z
[ "python", "types", "comparison", "python-2.x" ]
The following snippet is annotated with the output ([as seen on ideone.com](http://ideone.com/1z1r0)): ``` print "100" < "2" # True print "5" > "9" # False print "100" < 2 # False print 100 < "2" # True print 5 > "9" # False print "5" > 9 # True ``` Can someone explain wh...
Strings *are* compared lexicographically, and dissimilar types are compared by the name of their type (`"int"` < `"string"`). 3.x fixes the second point by making them non-comparable.
How does Python compare string and int?
3,270,680
122
2010-07-17T07:48:56Z
3,270,689
150
2010-07-17T07:54:11Z
[ "python", "types", "comparison", "python-2.x" ]
The following snippet is annotated with the output ([as seen on ideone.com](http://ideone.com/1z1r0)): ``` print "100" < "2" # True print "5" > "9" # False print "100" < 2 # False print 100 < "2" # True print 5 > "9" # False print "5" > 9 # True ``` Can someone explain wh...
From the [manual](http://docs.python.org/library/stdtypes.html#comparisons): > CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address. When you order two strings or two nume...
Python 3 with Emacs
3,270,729
21
2010-07-17T08:10:24Z
4,908,638
9
2011-02-05T18:11:44Z
[ "python", "emacs", "python-3.x", "ropemacs", "pymacs" ]
Is there anything that should be done to make GNU Emacs 23.2 work well with Python 3? **How would [an](http://09-f9-11-02-9d-74-e3-5b-d8-41-56-c5-63-56-88-c0.com/2008/05/09/emacs-as-a-powerful-python-ide/) ideal [environment](http://www.emacswiki.org/emacs/PythonProgrammingInEmacs) for development with Python 3 in Ema...
From [Loveshack python.el](http://www.loveshack.ukfsn.org/emacs/python.el): > There is support for editing both Python 2 and Python 3 languages, > and using interpreters for either version to run the emacs.py > module in inferior processes. From [README file for Pymacs (notes for 0.24 beta 2)](http://pymacs.progiciel...
Populating a SQLite3 database from a .txt file with Python
3,270,952
10
2010-07-17T09:38:39Z
3,271,125
14
2010-07-17T10:39:26Z
[ "python", "django", "sqlite3" ]
I am trying to setup a website in django which allows the user to send queries to a database containing information about their representatives in the European Parliament. I have the data in a comma seperated .txt file with the following format: > Parliament, Name, Country, Party\_Group, National\_Party, Position > > ...
So assuming your `models.py` looks something like this: ``` class Representative(models.Model): parliament = models.CharField(max_length=128) name = models.CharField(max_length=128) country = models.CharField(max_length=128) party_group = models.CharField(max_length=128) national_party = models.Cha...
Check list of words in another string
3,271,478
49
2010-07-17T12:33:26Z
3,271,485
103
2010-07-17T12:35:21Z
[ "python", "list" ]
I can do such thing in python: ``` list = ['one', 'two', 'three'] if 'some word' in list: ... ``` This will check if 'some word' exists in the list. But can I do reverse thing? ``` list = ['one', 'two', 'three'] if list in 'some one long two phrase three': ... ``` I have to check whether some words from arra...
``` if any(word in 'some one long two phrase three' for word in list_): ```
Check list of words in another string
3,271,478
49
2010-07-17T12:33:26Z
3,271,672
10
2010-07-17T13:32:51Z
[ "python", "list" ]
I can do such thing in python: ``` list = ['one', 'two', 'three'] if 'some word' in list: ... ``` This will check if 'some word' exists in the list. But can I do reverse thing? ``` list = ['one', 'two', 'three'] if list in 'some one long two phrase three': ... ``` I have to check whether some words from arra...
If your list of words is of substantial length, and you need to do this test many times, it may be worth converting the list to a set and using set intersection to test (with the added benefit that you wil get the actual words that are in both lists): ``` >>> long_word_list = 'some one long two phrase three about abov...
Re-factoring To MVC pattern -Doubts on separation of view from controller
3,271,553
6
2010-07-17T12:56:22Z
3,272,139
9
2010-07-17T15:36:57Z
[ "python", "user-interface", "model-view-controller", "wxpython" ]
Im trying to refactor my application (with 1000+ lines of GUI code) to an MVC style pattern. The logic code is already seperate from the GUI so that is not a problem. My concern is seperation of the view from the controller. I understand the basic principal of MVC and [this tutorial](http://wiki.wxpython.org/ModelViewC...
> If I were to convert that part to MVC > I would have to bind the button events > for each instance of the FilterPanel > in my controller(instead of in the > filterPanel class) Not necessarily! MVC's philosophy and practice do not imply that "views" are elementary widgets; your `FilterPanel` could well be thought of ...
Can I install Python windows packages into virtualenvs?
3,271,590
119
2010-07-17T13:10:51Z
3,273,193
39
2010-07-17T20:41:43Z
[ "python", "windows", "virtualenv" ]
Virtualenv is great: it lets me keep a number of distinct Python installations so that different projects' dependencies aren't all thrown together into a common pile. But if I want to install a package on Windows that's packaged as a .exe installer, how can I direct it to install into the virtualenv? For example, I ha...
I ended up adapting a script (http://effbot.org/zone/python-register.htm) to register a Python installation in the registry. I can pick the Python to be *the* Python in the registry, run the Windows installer, then set the registry back: ``` # -*- encoding: utf-8 -*- # # script to register Python 2.0 or later for use ...
Can I install Python windows packages into virtualenvs?
3,271,590
119
2010-07-17T13:10:51Z
3,274,878
7
2010-07-18T08:52:40Z
[ "python", "windows", "virtualenv" ]
Virtualenv is great: it lets me keep a number of distinct Python installations so that different projects' dependencies aren't all thrown together into a common pile. But if I want to install a package on Windows that's packaged as a .exe installer, how can I direct it to install into the virtualenv? For example, I ha...
easy\_install is able to install .exe packages as long as they were built using distutils' bdist\_wininst target, which covers many popular packages. However, there are many others that aren't (wxPython is one that I've struggled with)
Can I install Python windows packages into virtualenvs?
3,271,590
119
2010-07-17T13:10:51Z
5,442,340
194
2011-03-26T12:33:10Z
[ "python", "windows", "virtualenv" ]
Virtualenv is great: it lets me keep a number of distinct Python installations so that different projects' dependencies aren't all thrown together into a common pile. But if I want to install a package on Windows that's packaged as a .exe installer, how can I direct it to install into the virtualenv? For example, I ha...
Yes, you can. All you need is > easy\_install > binary\_installer\_built\_with\_distutils.exe Surprised? It looks like binary installers for Windows made with distutils combine .exe with .zip into one .exe file. Change extension to .zip to see it's a valid zip file. I discovered this after reading answers to my quest...
Can I install Python windows packages into virtualenvs?
3,271,590
119
2010-07-17T13:10:51Z
20,324,555
67
2013-12-02T09:13:02Z
[ "python", "windows", "virtualenv" ]
Virtualenv is great: it lets me keep a number of distinct Python installations so that different projects' dependencies aren't all thrown together into a common pile. But if I want to install a package on Windows that's packaged as a .exe installer, how can I direct it to install into the virtualenv? For example, I ha...
I know this is quite an old question, and predates the tools I am about to talk about, but for the sake of Google, I think it is a good idea to mention it. easy\_install is the black sheep of python packaging. No one wants to admit using it with the new hotness of pip around. Also, while playing registry tricks will wo...
API of a package in python. In __init__.py?
3,271,794
7
2010-07-17T14:09:08Z
3,271,823
7
2010-07-17T14:16:13Z
[ "python", "design" ]
I have written a python package which consists of several `.py` files which contain classes and so on. I want to expose it to client using "Facade" pattern. So I don't want clients to learn all internal classes but only methods exposed by this API interface. Question is: where do I put this api ? Do I define a file `a...
The `__init__.py` file is an acceptable place to put the public API or a package, with the other modules within it providing the implementation.
API of a package in python. In __init__.py?
3,271,794
7
2010-07-17T14:09:08Z
3,272,161
7
2010-07-17T15:42:11Z
[ "python", "design" ]
I have written a python package which consists of several `.py` files which contain classes and so on. I want to expose it to client using "Facade" pattern. So I don't want clients to learn all internal classes but only methods exposed by this API interface. Question is: where do I put this api ? Do I define a file `a...
The most common choice is to use `__init__.py` -- it's worth hiving off to a module of its own (or more) only if it's complex enough to warrant it (then it wouldn't be much of a Facade;-) or, more importantly, if you provide alternative APIs (a simplified one with reduced functionality but greater ease of use, and a ri...
In python, why is reading from an array slower than reading from list?
3,271,813
7
2010-07-17T14:13:29Z
3,271,829
7
2010-07-17T14:17:52Z
[ "python" ]
I'm learning python recently, and is doing many practice with the language. One thing I found interesting is that, when I read from an array, it's almost half of the time slower than list. Does somebody know why? here's my code: ``` from timeit import Timer import array t = 10000 l = range(t) a = array.array('i', l...
It takes time to wrap a raw integer into a Python `int`.
In python, why is reading from an array slower than reading from list?
3,271,813
7
2010-07-17T14:13:29Z
3,272,181
7
2010-07-17T15:48:46Z
[ "python" ]
I'm learning python recently, and is doing many practice with the language. One thing I found interesting is that, when I read from an array, it's almost half of the time slower than list. Does somebody know why? here's my code: ``` from timeit import Timer import array t = 10000 l = range(t) a = array.array('i', l...
`list`s are "dynamically growing vectors" (very much like C++'s `std::vector`, say) but that in no way slows down random access to them (they're not *linked* lists!-). Lists' entries are references to Python objects (the items): accessing one just requires (in CPython) an increment of the item's reference count (in oth...
Set products in Python
3,271,931
7
2010-07-17T14:43:11Z
3,272,005
9
2010-07-17T15:00:56Z
[ "python", "math" ]
A product of n copies of a set S is denoted Sn. For example, {0, 1}3 is the set of all 3­-bit sequences: {0,1}3 = {(0,0,0),(0,0,1),(0,1,0),(0,1,1),(1,0,0),(1,0,1),(1,1,0),(1,1,1)} What's the simplest way to replicate this idea in Python?
In Python 2.6 or newer you can use [itertools.product](http://docs.python.org/library/itertools.html#itertools.product) with the optional argument `repeat`: ``` >>> from itertools import product >>> s1 = set((0, 1)) >>> set(product(s1, repeat = 3)) ``` For older versions of Python you can implement `product` using th...
How to use logical OR in SPARQL regex()?
3,272,070
6
2010-07-17T15:18:59Z
3,273,233
12
2010-07-17T20:54:02Z
[ "python", "regex", "filter", "sparql" ]
I'm using this line in a SPARQL query in my python program: ``` FILTER regex(?name, "%s", "i" ) ``` (where `%s` is the search text entered by the user) I want this to match if either `?name` or `?featurename` contains `%s`, but I can't seem to find any documentation or tutorial for using regex(). I tried a couple th...
What about this? ``` SELECT ?thing WHERE { { ?thing x:name ?name . FILTER regex(?name, "%s", "i" ) } UNION { ?thing x:featurename ?name . FILTER regex(?featurename, "%s", "i" ) } } ```
Printing a list of objects
3,272,097
5
2010-07-17T15:29:17Z
3,272,116
7
2010-07-17T15:31:33Z
[ "python" ]
I am a Python newbie. I have this small problem. I want to print a list of objects but all it prints is some weird internal representation of object. I have even defined `__str__` method but still I am getting this weird output. What am I missing here? ``` class person(object): def __init__(self, name, age): sel...
Unless you're explicitly converting to a `str`, it's the [`__repr__` method](http://docs.python.org/reference/datamodel.html#object.__repr__) that's used to render your objects. See [Difference between `__str__` and `__repr__` in Python](http://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-pyt...
Forcing a python script to take input from STDIN
3,273,049
7
2010-07-17T19:58:22Z
3,273,071
11
2010-07-17T20:04:57Z
[ "python", "bash" ]
A python script I need to run takes input only from a file passed as a command line argument, like so: ``` $ markdown.py input_file ``` Is there any way to get it to accept input from STDIN instead? I want to be able to do this through Bash, without significantly modifying the python script: ``` $ echo "Some text he...
I'm not sure how portable it is, but on Unix-y systems you can name `/dev/stdin` as your file: ``` $ echo -n hi there | wc /dev/stdin 0 2 8 /dev/stdin ```
What is happening in this Python program?
3,273,092
3
2010-07-17T20:13:27Z
3,273,097
7
2010-07-17T20:14:50Z
[ "python", "iterator", "variable-assignment" ]
I'd like to know what is getting assigned to what in line 8. ``` # Iterators class Fibs: def __init__(self): self.a = 0 self.b = 1 def next(self): self.a, self.b = self.b, self.a+self.b # <--- here return self.a def __iter__(self): return self fibs = Fibs() for f ...
It's a pair assignment, a shorthand of ``` t = self.a self.a = self.b self.b = t+self.b ``` just to use an one-liner instead that two assignments.. to be precise i think that the left operand of the assignment is considered a tuple of two elements, so you are like assigning to tuple `(self.a, self,b)` the value `(sel...
What is happening in this Python program?
3,273,092
3
2010-07-17T20:13:27Z
3,273,104
8
2010-07-17T20:16:55Z
[ "python", "iterator", "variable-assignment" ]
I'd like to know what is getting assigned to what in line 8. ``` # Iterators class Fibs: def __init__(self): self.a = 0 self.b = 1 def next(self): self.a, self.b = self.b, self.a+self.b # <--- here return self.a def __iter__(self): return self fibs = Fibs() for f ...
It's a multiple assignment roughly equivalent to this: ``` tmp = self.a self.a = self.b self.b = tmp + self.b ``` Or this pseudo-code: ``` a' = b b' = a + b ``` As you can see the multiple assignment is much more concise than separate assignments and more closely resembles the pseudo-code example. Almost that exam...
Understanding factorize function
3,273,379
4
2010-07-17T21:37:17Z
3,273,405
12
2010-07-17T21:45:14Z
[ "python", "math" ]
Note that this question contains some spoilers. A [solution for problem #12](http://pyeuler.wikidot.com/problems-11-20) states that > "Number of divisors (including 1 and the number itself) can be calculated taking one element from prime (and power) divisors." The (python) code that it has doing this is `num_factors...
The basic idea is that if you have a number factorized into the following form which is the standard form actually: ``` let p be a prime and e be the exponent of the prime: N = p1^e1 * p2^e2 *....* pk^ek ``` Now, to know how many divisors N has we have to take into consideration every combination of prime factors. S...
Python: defining a union of regular expressions
3,274,027
4
2010-07-18T01:54:39Z
3,274,069
8
2010-07-18T02:18:14Z
[ "python", "regex" ]
I have a list of patterns like ``` list_patterns = [': error:', ': warning:', 'cc1plus:', 'undefine reference to'] ``` what I want to do is to produce a union of all of them yielding a regular expression that matches every element in `list_patterns` [but presumably does not match any re not in list\_patterns -- msw] ...
There are a couple of ways of doing this. The simplest is: ``` list_patterns = [': error:', ': warning:', 'cc1plus:', 'undefine reference to'] string = 'there is an : error: and a cc1plus: in this string' print re.findall('|'.join(list_patterns), string) ``` Output: ``` [': error:', 'cc1plus:'] ``` which is fine as...
append tuples to a list
3,274,095
8
2010-07-18T02:30:43Z
3,274,100
19
2010-07-18T02:33:13Z
[ "python" ]
How can I append the content of each of the following tuples (ie, elements within the list) to another list which already has 'something' in it? So, I want to append the following to a list (eg: result[]) which isn't empty: ``` l = [('AAAA', 1.11), ('BBB', 2.22), ('CCCC', 3.33)] ``` Obviously, the following doesn't d...
``` result.extend(item) ```
How do I force matplotlib to write out the full form of the x-axis label, avoiding scientific notation?
3,274,200
7
2010-07-18T03:26:48Z
3,274,222
8
2010-07-18T03:40:10Z
[ "python", "matplotlib" ]
I've created a simple hexbin plot with matplotlib.pyplot. I haven't changed any default settings. My x-axis information ranges from 2003 to 2009, while the y values range from 15 to 35. Rather than writing out 2003, 2004, etc., matplotlib collapses it into 0, 1, 2, ... + 2.003e+03. Is there a simple way to force matplo...
I think you can use the [`xticks` function](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.xticks) to set string labels: ``` nums = arange(2003, 2010) xticks(nums, (str(n) for n in nums)) ``` **EDIT:** This is a better way: ``` gca().xaxis.set_major_formatter(FormatStrFormatter('%d')) ``` o...
How can I "watch" a file for modification / change?
3,274,334
8
2010-07-18T04:39:46Z
3,274,371
7
2010-07-18T04:51:39Z
[ "python", "linux" ]
I would like to invoke my `chrome` or `firefox` browser when a file that I specify is modified. How could I "watch" that file to do something when it gets modified? Programmatically it seems the steps are.. basically set a never ending interval every second or so and cache the initial modification date, then compare t...
The Linux Kernel has a file monitoring API called inotify. A python binding is [pyinotify](http://pyinotify.sourceforge.net/). With it, you can build what you want.
How can I "watch" a file for modification / change?
3,274,334
8
2010-07-18T04:39:46Z
3,274,376
20
2010-07-18T04:54:26Z
[ "python", "linux" ]
I would like to invoke my `chrome` or `firefox` browser when a file that I specify is modified. How could I "watch" that file to do something when it gets modified? Programmatically it seems the steps are.. basically set a never ending interval every second or so and cache the initial modification date, then compare t...
As noted, you can use [pyinotify](https://github.com/seb-m/pyinotify/wiki/Tutorial): E.g.: ``` import webbrowser import pyinotify class ModHandler(pyinotify.ProcessEvent): # evt has useful properties, including pathname def process_IN_CLOSE_WRITE(self, evt): webbrowser.open(URL) handler = ModHan...
How to make a class field [list] read-only in python?
3,274,350
3
2010-07-18T04:46:07Z
3,274,360
7
2010-07-18T04:49:54Z
[ "python", "oop" ]
i have self.some\_field = [] in my class Im enquiring is there a way to make this list read-only like a property?
You need to make it, indeed, a property...: e.g., in `__init__` ``` self._some_field = [] ``` and then later in the class's body: ``` @property def some_field(self): return self._some_field ``` Note that this does **not** make the list itself immutable: what will fail is an *assignment* like, say, ``` self.som...
how to combine exponents? (x**a)**b => x**(a*b)?
3,274,487
4
2010-07-18T05:50:07Z
3,274,555
7
2010-07-18T06:24:06Z
[ "python", "simplify", "sympy", "exponents" ]
how to simplify exponents in equations in sympy ``` from sympy import symbols a,b,c,d,e,f=symbols('abcdef') j=(a**b**5)**(b**10) print j (a**(b**5))**(b**10) #ans even after using expand simplify # desired output a**(b**15) ``` and if it is not possible with sympy which module should i import in python? **edit**...
(xm)n = xmn is true [only if m, n are real](http://en.wikipedia.org/wiki/Exponent#Failure_of_power_and_logarithm_identities). ``` >>> import math >>> x = math.e >>> m = 2j*math.pi >>> (x**m)**m # (e^(2πi))^(2πi) = 1^(2πi) = 1 (1.0000000000000016+0j) >>> x**(m*m) # e^(2πi×2πi) = e^(-4π²) ≠ 1 (7.157...
How would I determine zodiac / astrological star sign from a birthday in Python?
3,274,597
9
2010-07-18T06:46:06Z
3,274,632
7
2010-07-18T06:58:19Z
[ "python", "django", "date-of-birth" ]
I am building a dating site in Django / Python. I have birthday dates and need to show what the person's Zodiac sign is based on their birthday. Anybody done this before? What would be the most efficient way of accomplishing this?
You could give them some more information about [position of the planets](http://rhodesmill.org/pyephem/index.html) and the stars. ``` import ephem >>> u = ephem.Uranus() >>> u.compute('1871/3/13') >>> print u.ra, u.dec, u.mag 7:38:06.27 22:04:47.4 5.46 >>> print ephem.constellation(u) ('Gem', 'Gemini') ```
How would I determine zodiac / astrological star sign from a birthday in Python?
3,274,597
9
2010-07-18T06:46:06Z
3,274,654
14
2010-07-18T07:07:48Z
[ "python", "django", "date-of-birth" ]
I am building a dating site in Django / Python. I have birthday dates and need to show what the person's Zodiac sign is based on their birthday. Anybody done this before? What would be the most efficient way of accomplishing this?
I've done this before. The simplest solution that I ended up with was an array of the following key/values: ``` 120:Cap, 218:Aqu, 320:Pis, 420:Ari, 521:Tau, 621:Gem, 722:Can, 823:Leo, 923:Vir, 1023:Lib 1122:Sco, 1222:Sag, 1231: Cap ``` Then you write the birth date in the `mdd` format, ie, month number (starting with...
How would I determine zodiac / astrological star sign from a birthday in Python?
3,274,597
9
2010-07-18T06:46:06Z
3,275,886
7
2010-07-18T14:28:41Z
[ "python", "django", "date-of-birth" ]
I am building a dating site in Django / Python. I have birthday dates and need to show what the person's Zodiac sign is based on their birthday. Anybody done this before? What would be the most efficient way of accomplishing this?
Using bisect is more efficient than iterating until you find a match, but a lookup table for each day of the year is faster still and really not that big. ``` from bisect import bisect signs = [(1,20,"Cap"), (2,18,"Aqu"), (3,20,"Pis"), (4,20,"Ari"), (5,21,"Tau"), (6,21,"Gem"), (7,22,"Can"), (8,23,"Leo"), ...
How to write a twisted server that is also a client?
3,275,004
6
2010-07-18T09:33:09Z
3,275,944
12
2010-07-18T14:43:30Z
[ "python", "twisted" ]
How do I create a twisted server that's also a client? I want the reactor to listen while at the same time it can also be use to connect to the same server instance which can also connect and listen.
Call `reactor.listenTCP` and `reactor.connectTCP`. You can have as many different kinds of connections - servers or clients - as you want. For example: ``` from twisted.internet import protocol, reactor from twisted.protocols import basic class SomeServerProtocol(basic.LineReceiver): def lineReceived(self, line)...
Reason for "all" and "any" result on empty lists
3,275,058
16
2010-07-18T09:59:32Z
3,275,077
29
2010-07-18T10:05:16Z
[ "python", "logic" ]
In Python, the built-in functions [`all`](http://docs.python.org/library/functions.html#all) and [`any`](http://docs.python.org/library/functions.html#any) return `True` and `False` respectively for empty iterables. I realise that if it were the other way around, this question could still be asked. But I'd like to know...
How about some analogies... You have a sock drawer, but it is currently empty. Does it contain any black sock? No - you don't have any socks at all so you certainly don't have a black one. Clearly `any([])` must return false - if it returned true this would be counter-intuitive. The case for `all([])` is slightly mor...
Reason for "all" and "any" result on empty lists
3,275,058
16
2010-07-18T09:59:32Z
3,275,099
16
2010-07-18T10:12:45Z
[ "python", "logic" ]
In Python, the built-in functions [`all`](http://docs.python.org/library/functions.html#all) and [`any`](http://docs.python.org/library/functions.html#any) return `True` and `False` respectively for empty iterables. I realise that if it were the other way around, this question could still be asked. But I'd like to know...
One property of `any` is its recursive definition ``` any([x,y,z,...]) == (x or any([y,z,...])) ``` That means ``` x == any([x]) == (x or any([])) ``` The equality is correct for any `x` if and only if `any([])` is defined to be False. Similar for `all`.
Am I parsing this HTTP POST request properly?
3,275,081
2
2010-07-18T10:05:44Z
9,810,738
7
2012-03-21T18:33:46Z
[ "python", "http", "parsing", "file-upload", "twisted.web" ]
Let me start off by saying, I'm using the `twisted.web` framework. `Twisted.web`'s file uploading didn't work like I wanted it to (it only included the file data, and not any other information), `cgi.parse_multipart` doesn't work like I want it to (same thing, `twisted.web` uses this function), `cgi.FieldStorage` didn'...
My solution to this Problem was parsing the content with cgi.FieldStorage like: ``` class Root(Resource): def render_POST(self, request): self.headers = request.getAllHeaders() # For the parsing part look at [PyMOTW by Doug Hellmann][1] img = cgi.FieldStorage( fp = request.content, header...
Hiding console window of Python GUI app with py2exe
3,275,293
19
2010-07-18T11:17:52Z
3,275,327
26
2010-07-18T11:30:42Z
[ "python", "pyqt", "pyqt4", "py2exe" ]
I have a Python program uses Qt (PyQt4 in fact) and when I launch it from its main.py, I get a console window and the GUI window (on Windows, of course). Then I compile my program with py2exe and main.exe is successfully created. However, if I run main.exe (this is what users of program will do) console window of Pyth...
Yep, it is possible. If I use ``` setup(console=['__main__.py'], options={"py2exe":{"includes":["sip"]}}) ``` It creates a console app, however if I use ``` setup(windows=['__main__.py'], options={"py2exe":{"includes":["sip"]}}) ``` it does not show console on .exe file. But output is dumped on main.exe.log file i...
How can I use the python HTMLParser library to extract data from a specific div tag?
3,276,040
20
2010-07-18T15:06:04Z
3,276,119
36
2010-07-18T15:29:50Z
[ "python", "html", "parsing", "html-parsing" ]
I am trying to get a value out of a HTML page using the python HTMLParser library. The value I want to get hold of is within this html element: ``` ... <div id="remository">20</div> ... ``` This is my HTMLParser class so far: ``` class LinksParser(HTMLParser.HTMLParser): def __init__(self): HTMLParser.HTMLPars...
``` class LinksParser(HTMLParser.HTMLParser): def __init__(self): HTMLParser.HTMLParser.__init__(self) self.recording = 0 self.data = [] def handle_starttag(self, tag, attributes): if tag != 'div': return if self.recording: self.recording += 1 return for name, value in att...
How can I use the python HTMLParser library to extract data from a specific div tag?
3,276,040
20
2010-07-18T15:06:04Z
13,252,666
21
2012-11-06T14:02:29Z
[ "python", "html", "parsing", "html-parsing" ]
I am trying to get a value out of a HTML page using the python HTMLParser library. The value I want to get hold of is within this html element: ``` ... <div id="remository">20</div> ... ``` This is my HTMLParser class so far: ``` class LinksParser(HTMLParser.HTMLParser): def __init__(self): HTMLParser.HTMLPars...
Have You tried [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/bs4/doc/) ? ``` from bs4 import BeautifulSoup soup = BeautifulSoup('<div id="remository">20</div>') tag=soup.div print(tag.string) ``` This gives You `20` on output.
Extracting date from a string in Python
3,276,180
29
2010-07-18T15:46:02Z
3,276,190
26
2010-07-18T15:51:59Z
[ "python", "string", "date" ]
How can I extract the date from a string like "monkey 2010-07-10 love banana"? Thanks!
If the date is given in a fixed form, you can simply use a regular expression to extract the date and "datetime.datetime.strptime" to parse the date: ``` match = re.search(r'\d{4}-\d{2}-\d{2}', text) date = datetime.strptime(match.group(), '%Y-%m-%d').date() ``` Otherwise, if the date is given in an arbitrary form, y...
Extracting date from a string in Python
3,276,180
29
2010-07-18T15:46:02Z
3,276,459
62
2010-07-18T17:09:45Z
[ "python", "string", "date" ]
How can I extract the date from a string like "monkey 2010-07-10 love banana"? Thanks!
Using [python-dateutil](http://labix.org/python-dateutil): ``` In [1]: import dateutil.parser as dparser In [18]: dparser.parse("monkey 2010-07-10 love banana",fuzzy=True) Out[18]: datetime.datetime(2010, 7, 10, 0, 0) ``` Invalid dates raise a `ValueError`: ``` In [19]: dparser.parse("monkey 2010-07-32 love banana"...
Does python yield imply continue?
3,276,528
7
2010-07-18T17:34:00Z
3,276,541
13
2010-07-18T17:38:46Z
[ "python", "generator", "yield" ]
I have a for loop that checks a series of conditions. On each iteration, it should yield output for only one of the conditions. The final yield is a default, in case none of the conditions are true. Do I have to put a *continue* after each block of yields? ``` def function(): for ii in aa: if condition1(ii)...
Instead of using the `continue` statement I would suggest using the `elif` and `else` statments: ``` def function(): for ii in aa: if condition1(ii): yield something1 yield something2 yield something3 elif condition2(ii): yield something4 else: #de...
Does python yield imply continue?
3,276,528
7
2010-07-18T17:34:00Z
3,276,545
9
2010-07-18T17:39:56Z
[ "python", "generator", "yield" ]
I have a for loop that checks a series of conditions. On each iteration, it should yield output for only one of the conditions. The final yield is a default, in case none of the conditions are true. Do I have to put a *continue* after each block of yields? ``` def function(): for ii in aa: if condition1(ii)...
NO, yield doesn't imply continue, it just starts at next line, next time. A simple example demonstrates that ``` def f(): for i in range(3): yield i print i, list(f()) ``` This prints 0,1,2 but if yield continues, it won't
Does python yield imply continue?
3,276,528
7
2010-07-18T17:34:00Z
3,276,570
7
2010-07-18T17:47:48Z
[ "python", "generator", "yield" ]
I have a for loop that checks a series of conditions. On each iteration, it should yield output for only one of the conditions. The final yield is a default, in case none of the conditions are true. Do I have to put a *continue* after each block of yields? ``` def function(): for ii in aa: if condition1(ii)...
`yield` in Python stops execution and returns the value. When the iterator is invoked again it continues execution directly after the `yield` statement. For instance, a generator defined as: ``` def function(): yield 1 yield 2 ``` would return `1` then `2` sequentially. In other words, the `continue` is requi...
Fabric auto-login in Windows
3,277,022
7
2010-07-18T20:00:34Z
3,277,137
9
2010-07-18T20:28:40Z
[ "python", "windows", "ssh", "fabric", "paramiko" ]
Relevant question: * <http://stackoverflow.com/questions/2339735/fabric-password> I configured Putty to login with private-public keys (no password) using this guide: <http://www.codelathe.com/blog/index.php/2009/02/20/ssh-without-password-using-putty/> It works. Now I want to run Fabric with no password prompt. Th...
Adding the following to your `fabfile.py` should work: ``` env.user = "your_username" env.key_filename = ["/path/to/keyfile"] ``` See the [fabric docs](http://docs.fabfile.org/0.9.0/usage/env.html#key-filename).
extend/append list
3,277,216
2
2010-07-18T20:54:02Z
3,277,235
11
2010-07-18T20:58:25Z
[ "python" ]
I would like to either extend or append a list to the content of another list: I've got the following: ``` l = (('AA', 1.11,'DD',1.2), ('BB', 2.22, 'EE', 2.3), ('CC', 3.33, 'FF', 3.45)) ls = [('XX', 7.77), ('YY', 8.88), ('ZZ', 9.99)] m = ['first', 'second', 'third'] for i in range(len(l)): result = [] for n in...
All you need is [zip](http://docs.python.org/library/functions.html#zip): ``` l = (('AA', 1.11), ('BB', 2.22), ('CC', 3.33)) ls = [('XX', 7.77), ('YY', 8.88), ('ZZ', 9.99)] for x,y in zip(l,ls): print(list(x+y)) # ['AA', 1.1100000000000001, 'XX', 7.7699999999999996] # ['BB', 2.2200000000000002, 'YY', 8.880000000...
Speeding up regular expressions in Python
3,277,239
4
2010-07-18T21:01:01Z
3,277,381
8
2010-07-18T21:44:07Z
[ "python", "regex", "optimization" ]
I need to quickly extract text from HTML files. I am using the following regular expressions instead of a full-fledged parser since I need to be fast rather than accurate (I have more than a terabyte of text). The profiler shows that most of the time in my script is spent in the re.sub procedure. What are good ways of ...
First, use an HTML parser built for this, like BeautifulSoup: <http://www.crummy.com/software/BeautifulSoup/> Then, you can identify remaining particular slow spots with the profiler: <http://docs.python.org/library/profile.html> And for learning about regular expressions, I've found Mastering Regular Expressions v...
How does Python's super() work with multiple inheritance?
3,277,367
373
2010-07-18T21:40:25Z
3,277,399
36
2010-07-18T21:50:34Z
[ "python", "multiple-inheritance" ]
I'm pretty much new in Python object oriented programming and I have trouble understanding the `super()` function (new style classes) especially when it comes to multiple inheritance. For example if you have something like: ``` class First(object): def __init__(self): print "first" class Second(object): ...
This is known as the [Diamond Problem](http://en.wikipedia.org/wiki/Diamond_problem), the page has an entry on Python, but in short, Python will call the superclass's methods from left to right.
How does Python's super() work with multiple inheritance?
3,277,367
373
2010-07-18T21:40:25Z
3,277,407
315
2010-07-18T21:52:52Z
[ "python", "multiple-inheritance" ]
I'm pretty much new in Python object oriented programming and I have trouble understanding the `super()` function (new style classes) especially when it comes to multiple inheritance. For example if you have something like: ``` class First(object): def __init__(self): print "first" class Second(object): ...
This is detailed with a reasonable amount of detail by Guido himself at <http://python-history.blogspot.com/2010/06/method-resolution-order.html> (including two earlier attempts). But, briefly: in your example, Third() will call `First.__init__`. For such simple situations, Python will look for the attribute (in this ...
How does Python's super() work with multiple inheritance?
3,277,367
373
2010-07-18T21:40:25Z
16,310,777
105
2013-04-30T23:54:10Z
[ "python", "multiple-inheritance" ]
I'm pretty much new in Python object oriented programming and I have trouble understanding the `super()` function (new style classes) especially when it comes to multiple inheritance. For example if you have something like: ``` class First(object): def __init__(self): print "first" class Second(object): ...
Your code, and the other answers, are all buggy. They are missing the super() calls in the first two classes that are required for co-operative subclassing to work. Here is a fixed version of the code: ``` class First(object): def __init__(self): super(First, self).__init__() print("first") class Second(ob...
How does Python's super() work with multiple inheritance?
3,277,367
373
2010-07-18T21:40:25Z
25,352,819
9
2014-08-17T19:22:31Z
[ "python", "multiple-inheritance" ]
I'm pretty much new in Python object oriented programming and I have trouble understanding the `super()` function (new style classes) especially when it comes to multiple inheritance. For example if you have something like: ``` class First(object): def __init__(self): print "first" class Second(object): ...
This is to how I solved to issue of having multiple inheritance with different variables for initialization and having multiple MixIns with the same function call. I had to explicitly add variables to passed \*\*kwargs and add a MixIn interface to be an endpoint for super calls. Here `A` is an extendable base class an...
How does Python's super() work with multiple inheritance?
3,277,367
373
2010-07-18T21:40:25Z
30,187,306
48
2015-05-12T09:51:32Z
[ "python", "multiple-inheritance" ]
I'm pretty much new in Python object oriented programming and I have trouble understanding the `super()` function (new style classes) especially when it comes to multiple inheritance. For example if you have something like: ``` class First(object): def __init__(self): print "first" class Second(object): ...
I wanted to elaborate [the answer by lifeless](http://stackoverflow.com/a/16310777/889617 "the answer by lifeless") a bit because when I started reading about how to use super() in a multiple inheritance hierarchy in Python, I did't get it immediately. What you need to understand is that `super(MyClass, self).__init__...
Django comment moderation error: AlreadyModerated at /
3,277,474
4
2010-07-18T22:15:34Z
3,343,654
8
2010-07-27T12:37:29Z
[ "python", "django" ]
I'm trying to add the comments framework to a weblog I'm creating in Django. Adding the comments system appears to be working fine until I attempt to enable [comment moderation](http://docs.djangoproject.com/en/1.2/ref/contrib/comments/moderation/). I add the following code to my models.py as per the instructions on t...
Just had a similar problem today, but I think I've solved it :) In my case the issue was that django was loading models.py twice and therefore trying to register the model for comment moderation twice as well. I fixed this by modifying the code from: ``` moderator.register(Post, PostModerator) ``` to: ``` if Post no...
How to read a file line by line into a list with Python
3,277,503
891
2010-07-18T22:25:01Z
3,277,511
125
2010-07-18T22:27:24Z
[ "python", "string", "file" ]
How do I read every line of a file in Python and store each line as an element in list? I want to read the file line by line and each line is appended to the end of the list.
This will yield an "array" of lines from the file. ``` lines = tuple(open(filename, 'r')) ```
How to read a file line by line into a list with Python
3,277,503
891
2010-07-18T22:25:01Z
3,277,512
231
2010-07-18T22:27:26Z
[ "python", "string", "file" ]
How do I read every line of a file in Python and store each line as an element in list? I want to read the file line by line and each line is appended to the end of the list.
This is more explicit than necessary, but does what you want. ``` with open("file.txt", "r") as ins: array = [] for line in ins: array.append(line) ```
How to read a file line by line into a list with Python
3,277,503
891
2010-07-18T22:25:01Z
3,277,515
562
2010-07-18T22:28:10Z
[ "python", "string", "file" ]
How do I read every line of a file in Python and store each line as an element in list? I want to read the file line by line and each line is appended to the end of the list.
See [Input and Ouput](http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files): ``` with open('filename') as f: lines = f.readlines() ``` or with stripping the newline character: ``` lines = [line.rstrip('\n') for line in open('filename')] ``` Editor's note: This answer's original whitespace-...