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 argument counting
11,926,995
2
2012-08-13T00:38:05Z
11,927,004
7
2012-08-13T00:39:25Z
[ "python", "command-line-arguments" ]
I just got into arguments in Python and I find it strange the way the arguments system works in Python (I'm not sure about other languages). For example: ``` from sys import argv arg1, arg2, arg3 = argv print "First argument: ", arg1 print "Second argument: ", arg2 print "Third argument: ", arg3 ``` When I run this...
Yes, Python uses zero-based indexing as you surmised (and as many other programming languages also do). `sys.argv` is a list of strings. `sys.argv[0]` will contain the name of the script, and subsequent entries in this list of strings will contain command line arguments provided to the script. I was going to provide...
Subclass variables with the same name of superclass ones
11,927,055
4
2012-08-13T00:48:06Z
11,927,108
7
2012-08-13T00:58:49Z
[ "python", "subclass" ]
Is it possible for no override for happen? For example: ``` class A: def __init__(self, name): self.name = name class B(A): def __init__(self, name): A.__init__(self, name) self.name = name + "yes" ``` Is there any way for `self.name` in class B to be independent from that of Class A'...
Prefixing a name with two underscores results in name mangling, which seems to be what you want. for example ``` class A: def __init__(self, name): self.__name = name def print_name(self): print self.__name class B(A): def __init__(self, name): A.__init__(self, name) self...
python mysqldb multiple cursors for one connection
11,927,146
15
2012-08-13T01:08:00Z
11,927,168
14
2012-08-13T01:12:33Z
[ "python", "python-2.7", "mysql-python" ]
When you have one connection object, can you make multiple cursors to that one single connection and execute queries with these cursors at the same time? Or would each cursor wait for the previous cursor to finish its query? ``` connection type: database=MySQLdb.connect(...) cursor: curs=database.cursor() que...
You'll need to open multiple connections. Mysqldb is threadsafe, so each connection will be able to access their respective cursors, queries and result sets without having an effect on the other connections but each thread or process will need its own connection.
How to configure Logging in Python
11,927,278
15
2012-08-13T01:36:51Z
11,927,374
17
2012-08-13T01:57:27Z
[ "python", "python-2.7", "logging" ]
I am new to Python and just starting one project. I am used to use `log4j` in Java and I would like to log all modules and classes in Python as I do in Java. In Java I have one log configuration file in src folder named `log4j.properties` like below: ``` log4j.rootLogger=DEBUG, Console, fileout log4j.appender.Consol...
Actually in Python it looks pretty much similar. There are different ways to do it. I usually create a logger class which is very simple: ``` import os import logging import settings # alternativly from whereever import settings class Logger(object): def __init__(self, name): name = name.replace('.l...
How to give a pandas/matplotlib bar graph custom colors
11,927,715
27
2012-08-13T03:02:57Z
11,927,922
43
2012-08-13T03:39:34Z
[ "python", "matplotlib", "pandas" ]
I just started using pandas/matplotlib as a replacement for Excel to generate stacked bar charts. I am running into an issue (1) there are only 5 colors in the default colormap, so if I have more than 5 categories then the colors repeat. How can I specify more colors? Ideally, a gradient with a start color and an end ...
You can specify the `color` option as a list directly to the `plot` function. ``` from matplotlib import pyplot as plt from itertools import cycle, islice import pandas, numpy as np # I find np.random.randint to be better # Make the data x = [{i:np.random.randint(1,5)} for i in range(10)] df = pandas.DataFrame(x) #...
How do I find out the anchor in the URI in Pyramid?
11,927,755
2
2012-08-13T03:10:13Z
11,927,979
8
2012-08-13T03:47:57Z
[ "python", "uri", "anchor", "pyramid" ]
Simply put, in Pyramid, when someone requests a page e.g.: ``` /foo/#bar ``` How do I find out what the anchor is? In this case, it would be `bar`. This seems like it should be trivial, but I'm not sure how to retrieve this information in Pyramid. `request.current_route_path()`, `request.url` and `request.path` woul...
The fragment is never sent to the server by the client; you will need to use JavaScript to process it on the client side.
Why a function called `main` doesn't have any special significance?
11,929,211
2
2012-08-13T06:33:45Z
11,929,246
9
2012-08-13T06:37:40Z
[ "python", "main" ]
In Python why a function called `main` doesn't have any special significance like it has in C and Java? What if a programmer switches from C or Java to Python. Should he keep using `main` in Python also like in C or Java as it's his style now to do the programming or in a broad sense it is somehow harmful for doing pr...
Such a programmer should do this: ``` if __name__ == "__main__": # run stuff ``` The variable `__name__` is set to `"__main__"` if the module is not imported.
Why a function called `main` doesn't have any special significance?
11,929,211
2
2012-08-13T06:33:45Z
11,929,314
9
2012-08-13T06:42:54Z
[ "python", "main" ]
In Python why a function called `main` doesn't have any special significance like it has in C and Java? What if a programmer switches from C or Java to Python. Should he keep using `main` in Python also like in C or Java as it's his style now to do the programming or in a broad sense it is somehow harmful for doing pr...
You should also be asking, why in C and Java does `main` have a special significance. It's just a choice on the part of the language designer. `main` could well have been called `start` or `begin` but somebody chose `main` and it stuck. In Python there is no reason why you can't call a function `main` and have it be t...
python: how accurate math.sqrt(x) function is?
11,929,422
2
2012-08-13T06:52:42Z
11,929,550
7
2012-08-13T07:03:45Z
[ "c#", "java", "python" ]
Consider the following code snippet in Python: ``` m = int(math.sqrt(n)) ``` For n = 25, it should give m = 5 (and it does in my shell). But from my C experience I know that using such expression is a bad idea, as sqrt function may return a slightly lower value than the real value, and then after rounding i may get m...
For proper rounding, use `round()`; it rounds to the nearest whole number, but returns a float. Then you may construct an `int` from the result. (Most probably your code is not performance-critical and you will never notice any slowdown associated with `round()`. If you do, you probably should be using numpy anyway.)
Why is seeding the random generator not stable between versions of Python?
11,929,701
17
2012-08-13T07:16:17Z
11,929,775
13
2012-08-13T07:21:31Z
[ "python", "random", "seed" ]
I am trying to reproduce a random sequence from python's `random.random()` on a different system with a different python3 version installed. This should be easy as the [documentation says](http://docs.python.org/py3k/library/random.html?highlight=random#notes-on-reproducibility): > Most of the random module’s algor...
I was looking through [What's New in Python 3.2](http://docs.python.org/dev/whatsnew/3.2.html) (because of this question), and I found: > The random.seed() function and method *now* salt string seeds with an sha512 hash function. To access the previous version of seed in order to reproduce Python 3.1 sequences, set th...
Unzip nested zip files in python
11,930,515
6
2012-08-13T08:20:28Z
11,930,556
7
2012-08-13T08:24:02Z
[ "python", "zip" ]
I am looking for a way to unzip nested zip files in python. For example, consider the following structure (hypothetical names for ease): * Folder + ZipfileA.zip - ZipfileA1.zip - ZipfileA2.zip + ZipfileB.zip - ZipfileB1.zip - ZipfileB2.zip ...etc. I am trying to access text files that are within t...
Unfortunately decompressing zip files requires random access to the archive, and the `ZipFile` methods (not to mention the DEFLATE algorithm itself) only provide streams. It is therefore impossible to decompress nested zip files without extracting them.
Index of \n in Python list
11,931,599
4
2012-08-13T09:35:54Z
11,931,632
12
2012-08-13T09:38:29Z
[ "python", "list", "indexing" ]
Okay, here I have another problem, I need to find position of `\n` alone in my list. ``` list = ['abc', '\n', 'def', 'ghi', '\n', 'jkl'] ``` So, I need to get the position of all '\n' entries from this list. I used ``` a=list.index('\n') ``` but got only one value as '1'. How to get both positions? e.g. I will ge...
You'll need to iterate over the elements. This can be easily done by using a list comprehension and `enumerate` for the indexes: ``` indexes = [i for i, val in enumerate(list) if val == '\n'] ``` Demo: ``` >>> lst = ['abc', '\n', 'def', 'ghi', '\n', 'jkl'] >>> [i for i, val in enumerate(lst) if val == '\n'] [1, 4] `...
Can't start uWSGI server without virtualenv (ImportError)
11,932,393
5
2012-08-13T10:23:53Z
15,707,326
12
2013-03-29T16:30:17Z
[ "python", "django", "virtualenv", "wsgi", "uwsgi" ]
I'm running django+nginx+uwsgi. For some reason I cannot start uWSGI without setting home option, pointing to virtual environment. Whenever I start uWSGI without it, it says that it cannot find module django.core.wsgi, like if python path was empty (but django 1.4 is installed system-wide). How can i fix it?
Since I hit my head on this problem too, let's write an answer for all. :) The problem is that, when starting in emperor mode (system wide), the uwsgi master process can't (or won't) load the correct environ for python (PYTHONPATH). Using virtualenv you specify the environ. Without it you need to set the `pythonpath` v...
nested list comprehensions
11,934,468
2
2012-08-13T12:41:21Z
11,934,483
12
2012-08-13T12:42:16Z
[ "python", "list", "syntax", "list-comprehension" ]
I tried to use the value of an outer list comprehension in an inner one: ``` [ x for x in range(y) for y in range(3) ] ``` But unfortunately this raises a NameError because the name `y` is unknown (although the outer list comprehension specifies it). Is this a limitation of Python (2.7.3 and 3.2.3 tried) or is there...
You are talking about list *comprehensions*, not generator expressions. You need to swap your for loops: ``` [ x for y in range(3) for x in range(y) ] ``` You need to read these as if they were nested in a regular loop: ``` for y in range(3): for x in range(y): x ``` List comprehensions with multiple l...
Text File Parsing with Python
11,936,967
6
2012-08-13T15:00:20Z
11,937,041
8
2012-08-13T15:03:49Z
[ "python", "parsing", "text", "file-io", "python-2.7" ]
I am trying to parse a series of text files and save them as CSV files using Python (2.7.3). All text files have a 4 line long header which needs to be stripped out. The data lines have various delimiters including " (quote), - (dash), : column, and blank space. I found it a pain to code it in C++ with all these differ...
I would use a for loop to iterate over the lines in the text file: ``` for line in my_text: outputfile.writelines(data_parser(line, reps)) ``` If you want to read the file line-by-line instead of loading the whole thing at the start of the script you could do something like this: ``` inputfile = open('test.dat')...
Text File Parsing with Python
11,936,967
6
2012-08-13T15:00:20Z
11,937,398
7
2012-08-13T15:24:40Z
[ "python", "parsing", "text", "file-io", "python-2.7" ]
I am trying to parse a series of text files and save them as CSV files using Python (2.7.3). All text files have a 4 line long header which needs to be stripped out. The data lines have various delimiters including " (quote), - (dash), : column, and blank space. I found it a pain to code it in C++ with all these differ...
From the accepted answer, it looks like your desired behaviour is to turn ``` skip 0 skip 1 skip 2 skip 3 "2012-06-23 03:09:13.23",4323584,-1.911224,-0.4657288,-0.1166382,-0.24823,0.256485,"NAN",-0.3489428,-0.130449,-0.2440527,-0.2942413,0.04944348,0.4337797,-1.105218,-1.201882,-0.5962594,-0.586636 ``` into ``` 2012...
Python, flask and creating a dual language app
11,937,876
5
2012-08-13T15:52:49Z
11,937,937
9
2012-08-13T15:56:21Z
[ "python", "flask", "multilingual", "gettext" ]
I need to create a web app that can support dual languages namely English and Japanese. I don't need a translator, just a workflow for displaying text based on a user preference. Is there such a framework where I don't have to reinvent the weel? Or do I have to create two separate sites?
Multilingual websites are generally created using [gettext](http://docs.python.org/library/gettext.html) (which is supported in many systems, including Django and also Flask). I have not used it personally but [Flask-Babel](http://packages.python.org/Flask-Babel/) appears to be the package that you need. The basic ide...
How to use PIL (Python Image Library) rotate image and let black background to be transparency
11,937,985
5
2012-08-13T15:59:27Z
11,938,647
12
2012-08-13T16:44:52Z
[ "python", "python-imaging-library" ]
I want to rotate a gray "test" image and paste it onto a blue background image. Now I just can remove the black color after rotate my gray "test" image, but their is now a white color section. How can I use Python to change the "white" color section to blue? Here is my code, can someone help me? I'd appreciate it. ``...
I have the impression that your code could be simplified as follows: ``` from PIL import Image src_im = Image.open("winter3.jpg") angle = 45 size = 100, 100 dst_im = Image.new("RGBA", (196,283), "blue" ) im = src_im.convert('RGBA') rot = im.rotate( angle, expand=1 ).resize(size) dst_im.paste( rot, (50, 50), rot ) ds...
Sorting in pyqt tablewidget
11,938,459
2
2012-08-13T16:32:53Z
11,941,099
7
2012-08-13T19:37:25Z
[ "python", "pyqt", "qtablewidget" ]
How can I sort a coloumn in pyqt by the highest number? Currently I have `setSortingEnabled(True)` and that only sorts it by the most numbers (ex. 1,1,1,1,2,2,2,3,3) i want to do it by the highest number for example (ex. 58,25,15,10). Thanks! Data Update: ``` def setmydata(self): for n, key in enumerate(self.data...
Its sorting alpha-numerically (so, in terms of strings, '1', '10', '11', '12', '2', '20', '21', '22', '3', '4' etc. is the proper sort order. It appears that for a QTableWidgetItem, if you use the setData(Qt.EditRole, value) method, the sort order will work. Depending on your version of Qt (I assume) you may have to ov...
New project: Python 2 or Python 3?
11,938,786
17
2012-08-13T16:54:20Z
11,938,804
13
2012-08-13T16:55:32Z
[ "python", "python-3.x" ]
I'm starting a new open-source software in Python, and I'm wondering whether I should use Python 2.x or Python 3.x. It will include a heavy GUI, complex scientific algorithms dealing with large amounts of data. I'll need at least Numpy, Scipy, PyQT4, PyOpenGL, h5py, optionaly Matplotlib. It should first be released in...
This wiki discusses exactly your question: [Should I use Python 2 or Python 3 for my development activity?](http://wiki.python.org/moin/Python2orPython3/) This is a very large subjective part to this question which depends on exactly your specific situation and constraints. IMO, however, if you can't be *sure* that a...
Parsing UTF-8/unicode strings with lxml HTML
11,938,924
16
2012-08-13T17:03:16Z
11,939,224
18
2012-08-13T17:23:30Z
[ "python", "parsing", "unicode", "utf-8", "lxml" ]
I have been trying to parse with etree.HTML() a text encoded as UTF-8 without success. ``` → python Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05) [GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from lxml imp...
Ok and just found. Writing the question on StackOverflow helps often. `etree.HTML()` is trying to guess the encoding according to the meta in the document ``` <meta http-equiv="Content-Type" content="text/html; charset=EUC-JP"/> ``` In this case, I have converted manually the document to `utf-8`, which means it is n...
deleting entries in a dictionary based on a condition
11,939,207
3
2012-08-13T17:22:22Z
11,939,238
13
2012-08-13T17:24:23Z
[ "python", "dictionary" ]
I have a dictionary with names as key and (age, Date of Birth) tuple as the value for those keys. E.g. ``` dict = {'Adam' : (10, '2002-08-13'), 'Eve' : (40, '1972-08-13')} ``` I want to delete all the keys which have age > 30 for their age in value tuple, how can I do that? I am accessing age of each key usi...
The usual way is to create a new dictionary containing only the items you want to keep: ``` new_data = {k: v for k, v in data.iteritems() if v[0] <= 30} ``` In Python 3.x, use `items()` instead of `iteritems()`. If you need to change the original dictionary in place, you can use a `for`-loop: ``` for k, v in data.i...
Python: functions in a class and memory
11,939,462
5
2012-08-13T17:42:41Z
11,939,499
10
2012-08-13T17:46:00Z
[ "python", "function", "memory", "instances" ]
If I have a class with several functions: ``` class Example: def func1(self): print 'Hi1' def func2(self): print 'Hi2' def func3(self): print 'Hi3' ``` If I create several instances of 'Example', does each instance store its own copies of the functions in the class? Or does Python...
When instantiating a class, no new function objects are created, neither for instance methods nor for static methods. When accessing an instance method via `obj.func1`, a new wrapper object called a "bound method" is created, which will be only kept as long as needed. The wrapper object is ligh-weight and contains basi...
concatenate lists in python
11,939,649
2
2012-08-13T17:56:22Z
11,939,683
9
2012-08-13T17:57:42Z
[ "python", "list", "multidimensional-array" ]
I have a 3x2 list called `x` and a 1x2 list called `y`: ``` x=[[1,2],[3,4],[5,6]] ``` and ``` y=[10,20] ``` **my question is how to concatenate `y` to the end of `x` to end up with a 4x2 list like:** ``` x=[[1,2],[3,4],[5,6],[10,20]] ``` I've tried this: ``` xx=[x,y] ``` but it gives me this which is not a 4x2 ...
``` >>> x = [[1, 2], [3, 4], [5, 6]] >>> x [[1, 2], [3, 4], [5, 6]] >>> x.append([10, 20]) >>> x [[1, 2], [3, 4], [5, 6], [10, 20]] ``` Or: ``` >>> x = [[1, 2], [3, 4], [5, 6]] >>> x [[1, 2], [3, 4], [5, 6]] >>> x += [[10, 20]] # a list with a list as its only element >>> x [[1, 2], [3, 4], [5, 6], [10, 20]] ```
concatenate lists in python
11,939,649
2
2012-08-13T17:56:22Z
11,939,700
9
2012-08-13T17:58:55Z
[ "python", "list", "multidimensional-array" ]
I have a 3x2 list called `x` and a 1x2 list called `y`: ``` x=[[1,2],[3,4],[5,6]] ``` and ``` y=[10,20] ``` **my question is how to concatenate `y` to the end of `x` to end up with a 4x2 list like:** ``` x=[[1,2],[3,4],[5,6],[10,20]] ``` I've tried this: ``` xx=[x,y] ``` but it gives me this which is not a 4x2 ...
Given: ``` x = [[1,2],[3,4],[5,6]] y = [10,20] ``` this: ``` x.append(y) ``` will give you: ``` [[1, 2], [3, 4], [5, 6], [10, 20]] ``` **Note** however that this *modifies* `x`. If you *don't* want to modify `x`, this is another way: ``` xx = x + [y[:]] ``` setting `xx` to: ``` [[1, 2], [3, 4], [5, 6], [10,...
django URLValidator produced bogus errors
11,940,288
9
2012-08-13T18:36:11Z
11,940,521
8
2012-08-13T18:56:10Z
[ "python", "django", "url-validation" ]
I'm using the Django `URLValidator` in the following way in a form: ``` def clean_url(self): validate = URLValidator(verify_exists=True) url = self.cleaned_data.get('url') try: logger.info(url) validate(url) except ValidationError, e: logger.info(e) raise forms.Validati...
Look at [the source for `URLValidator`](https://github.com/django/django/blob/stable/1.4.x/django/core/validators.py#L94); if you specify `check_exists`, it makes a `HEAD` request to the URL to check if it's valid: ``` req = urllib2.Request(url, None, headers) req.get_method = lambda: 'HEAD' ... opener.open(req, timeo...
Selecting rows from a Pandas dataframe with a compound (hierarchical) index
11,941,492
29
2012-08-13T20:07:07Z
11,941,772
7
2012-08-13T20:26:38Z
[ "python", "ipython", "pandas" ]
I'm suspicious that this is trivial, but I yet to discover the incantation that will let me select rows from a Pandas dataframe based on the values of a hierarchical key. So, for example, imagine we have the following dataframe: ``` import pandas df = pandas.DataFrame({'group1': ['a','a','a','b','b','b'], ...
Syntax like the following will work: ``` df.ix['a'] df.ix['a'].ix['c'] ``` since `group1` and `group2` are indices. Please forgive my previous attempt! To get at the second index only, I think you have to swap indices: ``` df.swaplevel(0,1).ix['c'] ``` But I'm sure Wes will correct me if I'm wrong.
Selecting rows from a Pandas dataframe with a compound (hierarchical) index
11,941,492
29
2012-08-13T20:07:07Z
11,942,697
43
2012-08-13T21:37:08Z
[ "python", "ipython", "pandas" ]
I'm suspicious that this is trivial, but I yet to discover the incantation that will let me select rows from a Pandas dataframe based on the values of a hierarchical key. So, for example, imagine we have the following dataframe: ``` import pandas df = pandas.DataFrame({'group1': ['a','a','a','b','b','b'], ...
Try using `xs` to be very precise: ``` In [5]: df.xs('a', level=0) Out[5]: value1 value2 group2 c 1.1 7.1 c 2.0 8.0 d 3.0 9.0 In [6]: df.xs('c', level='group2') Out[6]: value1 value2 group1 a 1.1 7.1 a 2.0...
How to avoid "RuntimeError: dictionary changed size during iteration" error?
11,941,817
43
2012-08-13T20:30:07Z
11,941,855
96
2012-08-13T20:33:21Z
[ "python", "list", "dictionary", "loops" ]
I have checked all of the other questions with the same error yet found no helpful solution =/ I have a dictionary of lists: ``` d = {'a': [1], 'b': [1, 2], 'c': [], 'd':[]} ``` in which some of the values are empty. At the end of creating these lists, I want to remove these empty lists before returning my dictionar...
In Python 2.x calling `keys` makes a copy of the key that you can iterate over while modifying the `dict`: ``` for i in d.keys(): ``` Note that this doesn't work in Python 3.x because `keys` returns an iterator instead of a list. Another way is to use `list` to force a copy of the keys to be made. This one also work...
How to avoid "RuntimeError: dictionary changed size during iteration" error?
11,941,817
43
2012-08-13T20:30:07Z
11,941,913
12
2012-08-13T20:38:00Z
[ "python", "list", "dictionary", "loops" ]
I have checked all of the other questions with the same error yet found no helpful solution =/ I have a dictionary of lists: ``` d = {'a': [1], 'b': [1, 2], 'c': [], 'd':[]} ``` in which some of the values are empty. At the end of creating these lists, I want to remove these empty lists before returning my dictionar...
Just use dictionary comprehension to copy the relevant items into a new dict ``` >>> d {'a': [1], 'c': [], 'b': [1, 2], 'd': []} >>> d = { k : v for k,v in d.iteritems() if v} >>> d {'a': [1], 'b': [1, 2]} ```
How to avoid "RuntimeError: dictionary changed size during iteration" error?
11,941,817
43
2012-08-13T20:30:07Z
11,941,982
9
2012-08-13T20:42:10Z
[ "python", "list", "dictionary", "loops" ]
I have checked all of the other questions with the same error yet found no helpful solution =/ I have a dictionary of lists: ``` d = {'a': [1], 'b': [1, 2], 'c': [], 'd':[]} ``` in which some of the values are empty. At the end of creating these lists, I want to remove these empty lists before returning my dictionar...
I would try to avoid inserting empty lists in the first place, but, would generally use: ``` d = {k: v for k,v in d.iteritems() if v} # re-bind to non-empty ``` If prior to 2.7: ``` d = dict( (k, v) for k,v in d.iteritems() if v ) ``` or just: ``` empty_key_vals = list(k for k in k,v in d.iteritems() if v) for k i...
"TypeError: (Integer) is not JSON serializable" when serializing JSON in Python?
11,942,364
37
2012-08-13T21:10:04Z
11,942,689
64
2012-08-13T21:36:25Z
[ "python", "json", "encoding", "typeerror" ]
I am trying to send a simple dictionary to a json file from python, but I keep getting the "TypeError: 1425 is not JSON serializable" message. ``` import json alerts = {'upper':[1425],'lower':[576],'level':[2],'datetime':['2012-08-08 15:30']} afile = open('test.json','w') afile.write(json.dumps(alerts,encoding='UTF-8'...
I found my problem. The issue was that my integers were actually type numpy.int64.
Splitting string into strings
11,942,429
2
2012-08-13T21:15:20Z
11,942,456
8
2012-08-13T21:17:23Z
[ "python" ]
Is there any way to split a string into many (not just 2) strings at a character, allowing blank strings, with the string names and order known? For example: `john..doe.1985` would split into `first = 'john'`, `middle = ''`, `last = 'doe'`, and `dob = 1985`?
You can use `split` method and iterable unpacking: ``` >>> first, middle, last, str_dob = "john..doe.1985".split(".") >>> dob = int(str_dob) >>> first 'john' >>> middle '' >>> last 'doe' >>> dob 1985 ```
Splitting string into strings
11,942,429
2
2012-08-13T21:15:20Z
11,942,465
7
2012-08-13T21:18:04Z
[ "python" ]
Is there any way to split a string into many (not just 2) strings at a character, allowing blank strings, with the string names and order known? For example: `john..doe.1985` would split into `first = 'john'`, `middle = ''`, `last = 'doe'`, and `dob = 1985`?
``` >>> first, middle, last, dob = 'john..doe.1985'.split('.') >>> first 'john' >>> middle '' >>> last 'doe' >>> dob '1985' ```
Why are the children failing to die?
11,942,654
11
2012-08-13T21:33:02Z
11,942,692
7
2012-08-13T21:36:54Z
[ "python", "linux", "multiprocessing" ]
I expected the `terminate()` method to kill the two processes: ``` import multiprocessing import time def foo(): while True: time.sleep(1) def bar(): while True: time.sleep(1) if __name__ == '__main__': while True: p_foo = multiprocessing.Process(target=foo, name='foo') p...
Because [terminate](http://docs.python.org/library/multiprocessing.html#multiprocessing.Process.terminate) function just send SIGTERM signal to process, but [signals are asynchronous](http://www.enderunix.org/docs/signals.pdf), so you can sleep for some time, or [wait](https://docs.python.org/2/library/multiprocessing....
Numpy multi-dimensional array indexing swaps axis order
11,942,747
6
2012-08-13T21:41:39Z
11,943,534
8
2012-08-13T23:07:33Z
[ "python", "numpy" ]
I am working with multi-dimensional Numpy arrays. I have noticed some inconsistent behavior when accessing these arrays with other index arrays. For example: ``` import numpy as np start = np.zeros((7,5,3)) a = start[:,:,np.arange(2)] b = start[0,:,np.arange(2)] c = start[0,:,:2] print 'a:', a.shape print ...
Syntactically, this looks like an inconsistency, but semantically, you're doing two very different things here. In your definition of `a` and `b`, you're doing [advanced indexing](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing), sometimes called [fancy indexing](http://www.scipy.org/Te...
Github-Flavored-Markdown in Python
11,943,089
16
2012-08-13T22:12:54Z
11,946,195
15
2012-08-14T05:24:13Z
[ "python", "github", "markdown" ]
Does anyone knows of a working Python GFM implementation? Currently I'm using a [javascript renderer](http://www.freedomsponsors.org/core/issue/1/allow-formatting-controls-on-comment-boxes). It works, but an actual Python renderer would be the right tool for the job. (FS is a Django app) I tried combining [this](http...
GitHub uses [Redcarpet](https://github.com/vmg/redcarpet) which is really a Ruby binding built by github for [Sundown](https://github.com/vmg/sundown). There's a binding for Sundown in Python called [Misaka](https://github.com/FSX/misaka). If you want to have something closer to the renderer github uses but in python ...
Python: how to put constructors in map() function?
11,943,831
3
2012-08-13T23:48:47Z
11,943,868
12
2012-08-13T23:52:49Z
[ "python", "functional-programming" ]
Say I have a class, with a constructor that takes an integer. I have a list of integers. How do I use `map()` to create a list of objects of this class, each constructed with its respective integer?
As any other function? ``` >>> class Num(object): ... def __init__(self, i): ... self.i = i ... >>> print map(Num, range(10)) [<__main__.Num object at 0x100493450>, <__main__.Num object at 0x100493490>, <__main__.Num object at 0x1004934d0>, <__main__.Num object at 0x100493510>, <__main__.Num object at...
How do you write a save method for forms in django?
11,943,912
7
2012-08-13T23:57:15Z
11,944,327
7
2012-08-14T00:51:57Z
[ "python", "django", "django-models", "django-forms" ]
I have two models in Django: User (pre-defined by Django) and UserProfile. The two are connected via a foreign key. I'm creating a form that allows a customer to edit their user profile. As such, this form will be based on both models mentioned. How do I create a save() method for this form? What are the steps/require...
this could help you ``` def save(self): data = self.cleaned_data user = User(email=data['email'], first_name=data['first_name'], last_name=data['last_name'], password1=data['password1'], password2=data['password2']) user.save() userProfile = UserProfile(user=user,gender=data['genger'], ...
Python how to get sum of numbers in a list that has strings in it as well
11,943,980
2
2012-08-14T00:06:37Z
11,944,048
7
2012-08-14T00:14:46Z
[ "python", "list", "dictionary", "sum" ]
I have a dict, `d = {'a': [4,'Adam', 2], 'b': [3,'John', 4], 'c': [4,'Adam', 3], 'd': [4,'Bill', 3], 'e': [4,'Bob'], 'f': [4, 'Joe'], 'g': [4, 'Bill']}` Is there any quick way to get a sum of the numbers in each of the lists in the dictionary? For example, `a` should return `6`, `b` should return `7`, so on. Curren...
Here is a fairly straight forward way using a dictionary comprehension: ``` sums = {k: sum(i for i in v if isinstance(i, int)) for k, v in d.items()} ``` Or on Python 2.6 and below: ``` sums = dict((k, sum(i for i in v if isinstance(i, int))) for k, v in d.items()) ``` Example: ``` >>> {k: sum(i for i in v if isin...
python count business weeks
11,944,826
5
2012-08-14T02:08:06Z
11,944,910
7
2012-08-14T02:18:55Z
[ "python", "datetime" ]
Given a start date, how can I determine how many "business weeks" it's been with Python? I can't just divide by 7 because that won't give me the correct answer. An example would be a start date of Aug 1 2012 to the current date (Aug 13 2012) would output 3 weeks. I'm basically trying to figure out from the start of t...
Try using [datetime.weekday](http://docs.python.org/library/datetime.html#datetime.datetime.weekday), [datetime.isoweekday](http://docs.python.org/library/datetime.html#datetime.datetime.isoweekday) to get the current day of the week or use the more complete [datetime.isocalendar](http://docs.python.org/library/datetim...
Call functions from re.sub
11,944,978
13
2012-08-14T02:27:21Z
11,945,011
23
2012-08-14T02:31:56Z
[ "python", "regex", "windows", "function" ]
This is a simple example: ``` import re math='<m>3+5</m>' print re.sub(r'<(.)>(\d+?)\+(\d+?)</\1>', int(r'\2') + int(r'\3'), math) ``` It gives me this error: ``` ValueError: invalid literal for int() with base 10: '\\2' ``` It sends `\\2` instead of `3` and `5`. Why? How do I solve it?
If you want to use a function with `re.sub` you need to pass a *function*, not an expression. As documented [here](http://docs.python.org/library/re.html#re.sub), your function should take the match object as an argument and returns the replacement string. You can access the groups with the usual `.group(n)` methods an...
What are good practices for avoiding crashes / hangs in PyQt?
11,945,183
27
2012-08-14T02:56:36Z
11,945,184
43
2012-08-14T02:56:36Z
[ "python", "pyqt", "pyqt4" ]
I love both python and Qt, but it's pretty obvious to me that Qt was not designed with python in mind. There are numerous ways to crash a PyQt / PySide application, many of which are extraordinarily difficult to debug, even with the proper tools. I would like to know: what are good practices for avoiding crashes and l...
# General Programming Practices * If you must use multi-threaded code, never-ever access the GUI from a non-GUI thread. Always instead send a message to the GUI thread by emitting a signal or some other thread-safe mechanism. * Be careful with Model/View anything. TableView, TreeView, etc. They are difficult to progra...
What is the equivalent of "none" in django templates?
11,945,321
40
2012-08-14T03:17:29Z
11,945,876
64
2012-08-14T04:40:52Z
[ "python", "django", "django-forms", "django-templates", "django-views" ]
I want to see if a field/variable is none within a Django template. What is the correct syntax for that? This is what I currently have: ``` {% if profile.user.first_name is null %} <p> -- </p> {% elif %} {{ profile.user.first_name }} {{ profile.user.last_name }} {% endif%} ``` In the example above, what would I ...
`None, False and True` all are available within template tags and filters. `None, False`, the empty string (`'', "", """"""`) and empty lists/tuples all evaluate to `False` when evaluated by `if`, so you can easily do ``` {% if profile.user.first_name == None %} {% if not profile.user.first_name %} ``` A hint: @fabio...
What is the equivalent of "none" in django templates?
11,945,321
40
2012-08-14T03:17:29Z
28,880,611
14
2015-03-05T14:46:27Z
[ "python", "django", "django-forms", "django-templates", "django-views" ]
I want to see if a field/variable is none within a Django template. What is the correct syntax for that? This is what I currently have: ``` {% if profile.user.first_name is null %} <p> -- </p> {% elif %} {{ profile.user.first_name }} {{ profile.user.last_name }} {% endif%} ``` In the example above, what would I ...
You can also use another built-in template `default_if_none` ``` {{ profile.user.first_name|default_if_none:"--" }} ```
Forcing application/json MIME type in a view (Flask)
11,945,523
16
2012-08-14T03:49:53Z
11,945,643
12
2012-08-14T04:06:24Z
[ "python", "json", "mime-types", "flask" ]
I can't figure out how to force the MIME type `application/json` for a view in Flask. Here is a simple view I've thrown together for demonstration purposes: ``` @app.route("/") def testView(): ret = '{"data": "JSON string example"}' return ret ``` The JSON string (held in variable `ret`) is gathered from else...
Looks like you can use the Response object directly. Please see one of the comments - [Forcing application/json MIME type in a view (Flask)](http://stackoverflow.com/questions/11945523/forcing-application-json-mime-type-in-a-view-flask/11945643#comment28246877_11945643)
Forcing application/json MIME type in a view (Flask)
11,945,523
16
2012-08-14T03:49:53Z
12,280,155
16
2012-09-05T11:11:09Z
[ "python", "json", "mime-types", "flask" ]
I can't figure out how to force the MIME type `application/json` for a view in Flask. Here is a simple view I've thrown together for demonstration purposes: ``` @app.route("/") def testView(): ret = '{"data": "JSON string example"}' return ret ``` The JSON string (held in variable `ret`) is gathered from else...
If you you use ``` from flask import jsonify ``` and then in your code ``` return jsonify(somedict) ``` then jsonify() automatically sets the mime type to 'application/json'
Countletters(sorted)
11,946,764
3
2012-08-14T06:19:21Z
11,946,840
13
2012-08-14T06:26:41Z
[ "python", "string", "count" ]
Following is my coding for count letters and i need the output as ``` [('e', 1), ('g', 2), ('l', 1), ('o', 2)] ``` and my out put is ``` [('e', 1), ('g', 2), ('g', 2), ('l', 1), ('o', 2), ('o', 2)] ``` This is my code ``` def countLetters(word): word=list(word) word.sort() trans=[] for j in word: ...
Why not just use a [`Counter`](http://docs.python.org/library/collections.html#collections.Counter)? **Example:** ``` from collections import Counter c = Counter("Foobar") print sorted(c.items()) ``` **Output:** > [('F', 1), ('a', 1), ('b', 1), ('o', 2), ('r', 1)] --- Another way is to use a `dict`, or better, a...
Python date format?
11,947,253
3
2012-08-14T06:58:14Z
11,947,302
9
2012-08-14T07:02:25Z
[ "python", "date" ]
I'm really hoping you can help me with this. I have a date outputted by a python program that I need to be able to access in another program. The problem is that I have no idea how this date is formatted: ``` Format Date 129893779638930000 - 2012-08-13 17:32:43 ``` It is both date and time, and I'm rea...
`129893678626216000` looks like the unix timestamp in 1e-8 seconds (tens of nanoseconds): `1,298,936,786.262,160,00`. It would represent: ``` >>> from datetime import datetime >>> datetime.utcfromtimestamp(129893678626216000/1e8) datetime.datetime(2011, 2, 28, 23, 46, 26, 262160) ``` **EDIT:** However your informatio...
schedule number of web dynos by time of day
11,949,240
12
2012-08-14T09:15:27Z
11,961,899
13
2012-08-14T22:46:27Z
[ "python", "django", "dynamic", "heroku" ]
Is there a way to use the Heroku scheduler to start and stop web dynos for specific periods of the day? Like say during business hours 2 dynos and at night only 1 dyno? I really would like to avoid putting the normal user/pass credentials into the app itself, so I'm looking for a secure way to do this (apart from doin...
You can scale heroku dynos on a schedule by creating a script that uses the Heroku API. You then make an entry in your Procfile and call it via the Heroku Scheduler add-on. Here's how: First you'll need to add the 'heroku' python module to your `requirements.txt`: > heroku==0.1.2 Next, create a config var that conta...
How do I use Tkinter in Python to create line-wrapped text that fills the width of the window?
11,949,391
7
2012-08-14T09:25:28Z
11,951,708
12
2012-08-14T11:53:31Z
[ "python", "tkinter" ]
The Label widget doesn't line-wrap. The Message widget will line-wrap text, but forces it to be roughly square. Here's an example. ``` from Tkinter import * root = Tk() root.title("hello") Message(root, text=48*'xxxxx ').grid(row=0, column=0, columnspan=3) Label(root, text='Name:').grid(row=1, column=0) Entry(root,...
The Tkinter label widget does wrap. It is just that the default setting is no wrapping. To get the text on a label to wrap set the "wraplength" parameter, the units for this are screen units so try wraplength=50 and adjust as necessary. You will also need to set "justify" to LEFT, RIGHT or CENTER. Hope that helps.
Multiple substitutions of numbers in string using regex python
11,949,499
6
2012-08-14T09:32:45Z
11,949,561
7
2012-08-14T09:36:51Z
[ "python", "regex", "string" ]
When i changed two words in a string with other two words using re.sub i got the output. But when i tried that with numbers output is not coming correctly ``` >>> import re >>> a='this is the string i want to change' >>> re.sub('(.*)is(.*)want(.*)','\\1%s\\2%s\\3' %('was','wanted'),a) 'this was the string i wanted to ...
What happens is that you're passing in the replacement `r'\1was\212345\3'`, and Python cannot determine whether you want the backreference number 2, 21, 211, ... . It just picks the largest one, 212345, which is obviously not a group index in your expression. Therefore, Python decides you meant the bytestring literal `...
What is the difference between a function, an unbound method and a bound method?
11,949,808
35
2012-08-14T09:53:23Z
11,950,080
32
2012-08-14T10:09:53Z
[ "python", "oop", "function", "methods" ]
I'm asking this question because of a discussion on the comment thread of [this answer](http://stackoverflow.com/a/11934332/1523776). I'm 90% of the way to getting my head round it. ``` In [1]: class C(object): # a class ...: def f1(self): pass ...: In [2]: c = C() # an instance ``` `f1` exists in three d...
A *function* is created by the `def` statement, or by `lambda`. Under Python 2, when a function appears within the body of a `class` statement (or is passed to a `type` class construction call), it is transformed into an *unbound method*. (Python 3 doesn't have unbound methods; see below.) When a function is accessed o...
Safe way to parse user-supplied mathematical formula in Python
11,951,701
21
2012-08-14T11:52:59Z
11,952,343
12
2012-08-14T12:31:52Z
[ "python" ]
Is there a math expressions parser + evaluator for Python? I am not the first to ask this question, but answers usually point to `eval()`. For instance, one could do this: ``` >>> safe_list = ['math','acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypo...
Check out [Paul McGuire's pyparsing](http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CGgQFjAA&url=http://pyparsing.wikispaces.com/&ei=IEUqUOaZNYHr6wGSsoGIAw&usg=AFQjCNHYfzwvzIxYKcHuYSR5TCAIrvtEqw). He has written both the general parser and a [grammar for arithmetic expressions](http://pyparsing.wik...
Safe way to parse user-supplied mathematical formula in Python
11,951,701
21
2012-08-14T11:52:59Z
11,952,618
8
2012-08-14T12:51:02Z
[ "python" ]
Is there a math expressions parser + evaluator for Python? I am not the first to ask this question, but answers usually point to `eval()`. For instance, one could do this: ``` >>> safe_list = ['math','acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypo...
I'd suggest using [`ast.parse`](http://docs.python.org/library/ast#ast.parse) and then whitelisting the parse tree. ``` tree = ast.parse(s, mode='eval') valid = all(isinstance(node, whitelist) for node in ast.walk(tree)) if valid: result = eval(compile(tree, filename='', mode='eval'), {"__builtin...
xml.etree or xml.dom?
11,952,713
3
2012-08-14T12:55:13Z
11,952,860
9
2012-08-14T13:03:26Z
[ "python", "xml" ]
I am trying to read some xml, but I'm not sure which library I should use. What is better xml.etree or xml.dom, and why? Please, explain your answers and give arguments. Also, do you think one of them is going to get deprecated? Which one?
Neither will be deprecated. [ElementTree](http://effbot.org/zone/element-index.htm) (xml.etree) is a pythonic API to access XML. [DOM](https://en.wikipedia.org/wiki/Document_Object_Model) (xml.dom) is a cross-platform, language independent standard. Use ElementTree unless you have a compelling reason to use the XML D...
Binding an objects value within a function (closure)
11,953,330
3
2012-08-14T13:27:51Z
11,953,356
7
2012-08-14T13:29:41Z
[ "python", "closures", "sml" ]
In SML (a functional programming language that I learned before Python), I can do the following: ``` val x = 3; fun f() = x; f(); >>> 3 val x = 7; f(); >>> 3 ``` In Python, however, the first call will give 3 and the second one will give 7. ``` x = 3 def f(): return x f() >>> 3 x = 7 f() >>> 7 ``` How do I bind the...
You can use a keyword argument: ``` x = 3 def f( x=x ): return x x = 7 f() # 3 ``` Keyword arguments are assigned *when the function is created*. Other variables are looked up in the function's scope *when the function is run*. (If they're not found in the function's scope, python looks for the variable in the...
PyInstaller "ImportError: No module named Pyinstaller"
11,953,618
8
2012-08-14T13:43:18Z
12,980,437
12
2012-10-19T18:38:27Z
[ "python", "pyinstaller" ]
This is the code that gets produced when I run python configure.py. ``` dan@Q430-Q530:~/pyinstaller-2.0/PyInstaller$ python configure.py Traceback (most recent call last): File "configure.py", line 28, in <module> from PyInstaller import HOMEPATH, PLATFORM ImportError: No module named PyInstaller ``` So, curren...
With PyInstaller 2.0, you do not need to run configure or pyinstaller files. (Read PyInstaller 2.0 Document which comes with the installation files.) To build your project; in the /your/path/to/pyinstaller/ directory, just run: "python pyinstaller.py [opts] yourprogram.py"
Opening and closing a subwindow on pygtk
11,953,864
2
2012-08-14T13:56:01Z
11,956,382
8
2012-08-14T16:06:21Z
[ "python", "gtk", "window", "pygtk" ]
I'm trying to create an application with pygtk that opens a subwindow, but I'm having some trouble with the creation/showing and the destruction/hiding process of this window. As a test, I've made a simple application that opens a main window with a single button that, when clicked, opens a subwindow with three buttons...
Connect to the `delete-event` signal instead of `destroy`. The `destroy` signal can't be blocked. Also, make sure you `return True` from your `delete-event` handler. This means that you have handled the event, and further handling will be blocked. If you don't, then the default handler will still be called after yours...
Error when Installing Pygame on Mountain Lion
11,954,497
10
2012-08-14T14:26:59Z
12,075,938
19
2012-08-22T14:58:01Z
[ "python", "osx", "pygame", "osx-mountain-lion" ]
I've been trying to get Pygame running on Mac OS X Mountain Lion and have had problems installing it. I have installed the following packages using homebrew: * sdl * sdl\_image * sdl\_mixer * sdl\_ttf * smpeg and when trying to compile Pygame (using the latest Mac OS X command line tools provided with Xcode 4.4) I ge...
I was beating my head against the wall on the same thing. I'm still so irritated that I'm thinking about installing Linux on my MacBook Air, but we'll see. I built it from source, after making the modification to source listed here: <https://bitbucket.org/pygame/pygame/changeset/e296ada67fad> Basically, in src/scale\...
How to read Excel files from a stream (not a disk-backed file) in Python?
11,955,300
2
2012-08-14T15:05:53Z
14,418,409
28
2013-01-19T20:15:08Z
[ "python", "html", "forms", "request", "xlrd" ]
XLRD is installed and tested: ``` >>> import xlrd >>> workbook = xlrd.open_workbook('Sample.xls') ``` When I read the file through html form like below, I'm able to access all the values. ``` xls_file = request.params['xls_file'] print xls_file.filename, xls_file.type ``` I'm using Pylons module, request comes ...
xlrd does support providing data directly without a filepath, just use the file\_contents argument: ``` xlrd.open_workbook(file_contents=fileobj.read()) ``` For more info see the docs: <https://secure.simplistix.co.uk/svn/xlrd/trunk/xlrd/doc/xlrd.html?p=4966#__init__.open_workbook-function>
Idiomatic Python logging: format string + args list vs. inline string formatting - which is preferred?
11,955,787
9
2012-08-14T15:31:13Z
11,955,929
10
2012-08-14T15:39:04Z
[ "python", "logging", "coding-style", "idioms" ]
Is it advantageous to call logging functions with format string + args list vs. formatting inline? I've seen (and written) logging code that uses inline string formatting: ``` logging.warn("%s %s %s" % (arg1, arg2, arg3)) ``` and yet I assume it's *better* (performance-wise, and more idiomatic) to use: ``` logging....
IMHO, for messages that are very likely to be displayed, such as those given to `error` or `warn` it does not make much of a difference. For messages that are less likely displayed, I would definitely go for the second version, mainly for performance reasons. I often give large objects as a parameter to `info`, which ...
What is the path for TEMPLATE_DIRS in django settings.py when using virtualenv
11,956,385
5
2012-08-14T16:06:32Z
11,957,283
12
2012-08-14T17:03:00Z
[ "python", "virtualenv" ]
I am using virtualenv and I want to know what the `TEMPLATE_DIRS` in `settings.py` should be, for example if I make a templates folder in the root of my project folder.
You need to specify the absolute path to your template folder. Always use forward slashes, even on Windows. For example, if your project folder is "/home/djangouser/projects/myproject" (Linux) or 'C:\projects\myproject\' (Windows), your TEMPLATE\_DIRS looks like this: ``` # for Linux TEMPLATE_DIRS = ( ...
Python: intersection of nested lists where order matters
11,957,040
7
2012-08-14T16:47:13Z
11,957,338
7
2012-08-14T17:06:20Z
[ "python", "list", "intersection", "nested-lists" ]
I would like to find the intersection between nested lists while maintaining the order. ``` taxa = [['E_pyrifoliae_Ep1_96', 'Bacteria', 'Proteobacteria', 'Gammaproteobacteria', 'Enterobacteriales', 'Enterobacteriaceae', 'Erwinia'], ['E_amylovora_CFBP1430', 'Bacteria', 'Proteobacteria', 'Gammaproteobacteria', 'Enterob...
Find the intersection, then reimpose order. ``` intersection_set = set.intersection(*map(set, taxa)) intersection_lst = [t for t in taxa[0] if t in intersection_set] ``` Or, if you are inordinately fond on one-liners: ``` sorted(set.intersection(*map(set, taxa)), key=lambda x: taxa[0].index(x)) ```
"Unused import warning" and pylint
11,957,106
12
2012-08-14T16:51:08Z
11,957,525
8
2012-08-14T17:21:48Z
[ "python", "warnings", "pylint" ]
So I'm working on a project in Python and trying to keep it up to standards with pylint and just generally . So, I have a source file, (We'll just call it a.py) ``` #a.py import loggingsetup def foo(): log.info("This is a log message") ``` But, I want to control what the logging looks like, so in loggingsetup I h...
The approach I would use is to use `loggingsetup` as a sort of wrapper for `logging`. ``` import logging # set up logging config here from logging import * ``` Then in your other modules you: ``` import loggingsetup as logging ``` You might want to use a name other than `loggingsetup` in this case, e.g. `tweaked_...
"Unused import warning" and pylint
11,957,106
12
2012-08-14T16:51:08Z
12,036,086
19
2012-08-20T10:32:49Z
[ "python", "warnings", "pylint" ]
So I'm working on a project in Python and trying to keep it up to standards with pylint and just generally . So, I have a source file, (We'll just call it a.py) ``` #a.py import loggingsetup def foo(): log.info("This is a log message") ``` But, I want to control what the logging looks like, so in loggingsetup I h...
In such cases, you can still explicitly tell pylint that this unused import in intended: ``` import loggingsetup # pylint: disable=unused-import ``` Notice the instruction is on the same line as the import so W0611 is only disabled for this line, and not for all the block below.
Matplotlib LaTeX: Inconsistent Behaviour with Greek Letters (Specifically \rho)
11,957,371
8
2012-08-14T17:08:48Z
11,957,424
13
2012-08-14T17:12:51Z
[ "python", "latex", "matplotlib" ]
I'm trying to add some axis-labels to a graph which contains the Greek letter 'rho'. To do this I want to use the LaTeX capability of Matplotlib but it seems to have a problem with the \rho symbol. Here is a minimal example: ``` import matplotlib.pyplot as plt from matplotlib import rc,rcParams rc('text',usetex=True...
I think you are supposed to use raw strings, and use the $ signs as well. Try: ``` plt.xlabel(r'$\rho A_i$') ```
MongoDB / Pymongo Query with Datetime
11,957,595
6
2012-08-14T17:26:52Z
11,957,746
10
2012-08-14T17:38:03Z
[ "python", "mongodb", "datetime", "pymongo" ]
I am trying to retrieve the data I have inserted into mongodb via pymongo. My code for insert is below (after parsing via regex) ``` if connection is not None: db.model.insert({"time": datetime.datetime(int(int3), int(int1), int(int2), int(int4), ...
Repeating existing basic tutorial documentation: ``` start = datetime.datetime(2012, 2, 2, 6, 35, 6, 764) end = datetime.datetime(2012, 2, 2, 6, 55, 3, 381) for doc in db.wing_model.find({'time': {'$gte': start, '$lt': end}}): print doc ``` > Finally, why does the same query return different cursor object > loca...
python regex findall and multiline
11,958,728
5
2012-08-14T18:43:28Z
11,958,803
11
2012-08-14T18:47:51Z
[ "python", "regex" ]
python 2.6.8 ``` s= ''' foo bar baz ''' >>>re.findall(r'^\S*',s,re.MULTILINE) ['', 'foo', 'bar', 'baz', ''] >>>ptrn = re.compile(r'^\S*',re.MULTILINE) >>>ptrn.findall(s) ['', 'foo', 'bar', 'baz', ''] >>>ptrn.findall(s,re.MULTILINE) ['baz', ''] ``` Why is there a difference between using MULTILINE flag in findall?
When calling the `findall()` method on a regex object, the second parameter is not the `flags` argument (because that has already been used when compiling the regex) but the `pos` argument, telling the regex engine at which point in the string to start matching. `re.MULTILINE` is just an integer (that happens to be `8...
How to add something to PYTHONPATH?
11,960,602
9
2012-08-14T20:56:09Z
11,960,723
9
2012-08-14T21:05:35Z
[ "python", "django", "django-haystack", "pythonpath", "pysolr" ]
I downloaded a package (called pysolr 2.0.15) to my computer to be used with Haystack. The instructions asks me to add pysolr to my PYTHONPATH. What exactly does that mean? After extracting the pysolr files, I ran the command python setup.py install and that's about it. What did that do and do I need to do anything el...
The pythonpath tells python were to look for modules, for example you might have written a library that you want to use in several applications and stored it in the path /mylibs/python/ you would then have to add that path to the pythonpath for python to find it. If you've downloaded a python module or library (I'm no...
Python 3: apply an operator over an iterable
11,961,950
2
2012-08-14T22:51:49Z
11,962,001
7
2012-08-14T22:56:49Z
[ "python", "python-3.x", "operators", "iterable" ]
`sum(iterable)` is effectively: ``` def sum(iterable): s = 0 for x in iterable: s = s.__add__(x) return s ``` Does Python have a built-in function that accomplishes this without setting the initial value? ``` # add is interchangeable with sub, mul, etc. def chain_add(iterable): iterator = ite...
Try looking into the python reduce function: <http://docs.python.org/library/functions.html#reduce> You pass in a function, an iterable, and an optional initializer and it would apply the function cumulatively to all the values. For example: ``` import functools def f(x,y): return x+y print functools.reduce(f, ...
'ObjectId' object has no attribute 'getTimeStamp'
11,961,952
10
2012-08-14T22:52:03Z
11,962,000
24
2012-08-14T22:56:45Z
[ "python", "mongodb", "pymongo" ]
I'm trying to get the timestamp from an ObjectID, but Mongo keeps giving me this error. Am I missing an import? What's the best way to convert the timestamp to a standard date format? ``` video['date'] = video['_id'].getTimeStamp() ```
Where'd you see `getTimeStamp()` as a method? According to the [docs](http://api.mongodb.org/python/current/api/bson/objectid.html) it should just be: ``` video['date'] = video['_id'].generation_time ```
Installing python dateutil
11,962,714
26
2012-08-15T00:34:04Z
11,962,736
59
2012-08-15T00:39:19Z
[ "python", "django", "python-dateutil" ]
I tried to install python dateutil for my django tastypie but unsuccessful, <http://labix.org/python-dateutil#head-2f49784d6b27bae60cde1cff6a535663cf87497b> I downloaded the tar file in c:/python27 and unzipped it, I get the following error msg, ``` **C:\Python27\Scripts>**easy_install dateutil-1.5 Searching for da...
This will install `tastypie` and its dependencies: ``` $ easy_install pip $ pip install django-tastypie ``` To get only dateutil: ``` $ pip install python-dateutil ```
Installing python dateutil
11,962,714
26
2012-08-15T00:34:04Z
11,962,820
12
2012-08-15T00:54:22Z
[ "python", "django", "python-dateutil" ]
I tried to install python dateutil for my django tastypie but unsuccessful, <http://labix.org/python-dateutil#head-2f49784d6b27bae60cde1cff6a535663cf87497b> I downloaded the tar file in c:/python27 and unzipped it, I get the following error msg, ``` **C:\Python27\Scripts>**easy_install dateutil-1.5 Searching for da...
I am not sure if this is different on Windows, but it does not appear you are referencing an actual link (see the **Reading** line). Instead, try this: ``` easy_install python-dateutil ``` That will (hopefully) get the package you need. Also, see [this](http://stackoverflow.com/questions/879156/how-to-install-python-...
Running python script from inside virtualenv bin is not working
11,963,019
13
2012-08-15T01:33:49Z
11,963,127
20
2012-08-15T01:51:21Z
[ "python", "virtualenv" ]
I have a script I want to be available globally. I've started it with the standard hashbang: ``` #! /usr/bin/env python ``` And linked it into the bin directory of my virtualenv: ``` ~/environments/project/env/bin/myscript ``` And added that directory to my path. When I run the command: ``` myscript ``` I get an ...
Putting the script into the bin of your virtualenv, and then adding that bin location to your global PATH will not automatically source your virtualenv. You do need to source it first to make it active. All that your system knows is to check that extra path for the executable and run it. There isn't anything in that s...
Python / Scipy "invalid index to scalar variable"
11,963,067
3
2012-08-15T01:40:40Z
11,963,412
7
2012-08-15T02:36:14Z
[ "python", "optimization", "numpy", "scipy" ]
I am using the Scipy optimization module, specifically **fmin\_tnc** and **fmin\_l\_bfgs\_b**. However, I am receiving the message "IndexError: invalid index to scalar variable" when using either one. What is the cause of this error? And what is the meaning of this error message? My practice code: ``` def f01(para)...
fmin\_l\_bfgs\_b expects that your function returns the function value **and** the gradient. You return only the function value. If you only return the function value and don't provide a gradient, then you need to set approx\_grad=True so that fmin\_l\_bfgs\_b uses a numerical approximation to it. See the description...
List comprehension vs generator expression's weird timeit results?
11,964,130
19
2012-08-15T04:29:00Z
11,964,164
8
2012-08-15T04:33:05Z
[ "python", "list", "list-comprehension", "timeit", "generator-expression" ]
I was answering this [question](http://stackoverflow.com/questions/11963711/what-is-the-most-efficient-way-to-search-nested-lists-in-python), I preferred generator expression here and used this, which I thought would be faster as generator doesn't need to create the whole list first: ``` >>> lis=[['a','b','c'],['d','e...
Contrary to the popular belief, list comprehensions are pretty fine for moderate ranges. Iterator protocol implies calls for iterator.next(), and function calls in Python are expensive. Of course at some point the generators memory/cpu trade-off will start to pay, but for small sets list comprehensions are very effici...
List comprehension vs generator expression's weird timeit results?
11,964,130
19
2012-08-15T04:29:00Z
11,964,301
11
2012-08-15T04:54:37Z
[ "python", "list", "list-comprehension", "timeit", "generator-expression" ]
I was answering this [question](http://stackoverflow.com/questions/11963711/what-is-the-most-efficient-way-to-search-nested-lists-in-python), I preferred generator expression here and used this, which I thought would be faster as generator doesn't need to create the whole list first: ``` >>> lis=[['a','b','c'],['d','e...
Completely depends on the data. Generators have a fixed setup time that must be amortized over how many items are called; List comprehensions are faster initially but will slow substantially as more memory is used with larger data sets. Recall that as cPython lists are expanded, the list is resized in growth pattern ...
List comprehension vs generator expression's weird timeit results?
11,964,130
19
2012-08-15T04:29:00Z
11,964,478
17
2012-08-15T05:21:44Z
[ "python", "list", "list-comprehension", "timeit", "generator-expression" ]
I was answering this [question](http://stackoverflow.com/questions/11963711/what-is-the-most-efficient-way-to-search-nested-lists-in-python), I preferred generator expression here and used this, which I thought would be faster as generator doesn't need to create the whole list first: ``` >>> lis=[['a','b','c'],['d','e...
Expanding on [Paulo](http://stackoverflow.com/a/11964164/577088)'s answer, generator expressions are often slower than list comprehensions because of the overhead of function calls. In this case, the short-circuiting behavior of `in` offsets that slowness if the item is found fairly early, but otherwise, the pattern ho...
Check at once the boolean values from a set of variables
11,964,979
4
2012-08-15T06:30:56Z
11,964,992
8
2012-08-15T06:32:16Z
[ "python", "boolean" ]
I am having around 10 boolean variables, I need to set a new boolean variable `x=True` if all those ten variable values are True.If one of them is False then set `x= False` I can do this in a manner ``` if (a and b and c and d and e and f...): x = True else: x=False ``` which obviously looks very ugly.Please ...
Assuming you have the bools in a list/tuple: ``` x = all(list_of_bools) ``` or just as suggested by @minopret ``` x= all((a, b, c, d, e, f)) ``` example: ``` >>> list_of_bools = [True, True, True, False] >>> all(list_of_bools) False >>> list_of_bools = [True, True, True, True] >>> all(list_of_bools) True ```
TypeError: object.__new__() takes no parameters
11,964,981
9
2012-08-15T06:31:11Z
11,965,011
16
2012-08-15T06:33:49Z
[ "python" ]
I have been working on Python The Hard Way and am getting the above error and have no clue why. I took out most of the filler text that I thought I could. Sorry if it is a little long. ``` from sys import exit from random import randint class Game(object): def __int__(self, start): self.quips = [ ...
You misspelled `__init__`: ``` def __int__(self, start): ^ no "i" ```
Using virtualenv with sublime text 2
11,965,707
26
2012-08-15T07:47:28Z
12,546,096
13
2012-09-22T17:29:06Z
[ "python", "virtualenv", "sublimetext2" ]
I am using sublime text 2 for python development along with virtualenv! The standard sublime text 2 build system uses the standard python install rather than my virtualenv where my packages are installed. How can I get sublime text 2 to build using my virtualenv? I currently use the terminal to activate my environme...
In windows this works for me: ``` "build_systems": [ { "name": "Run Tests", "working_dir": "/path/to/to/your/django_project", "cmd": ["/path/to/your/virtualenv/bin/python.exe", "manage.py", "test"] } ] ```
Using virtualenv with sublime text 2
11,965,707
26
2012-08-15T07:47:28Z
14,194,410
14
2013-01-07T10:53:26Z
[ "python", "virtualenv", "sublimetext2" ]
I am using sublime text 2 for python development along with virtualenv! The standard sublime text 2 build system uses the standard python install rather than my virtualenv where my packages are installed. How can I get sublime text 2 to build using my virtualenv? I currently use the terminal to activate my environme...
You can also set the path for the build system to the `bin` directory of your virtualenv, like so: ``` "build_systems": [ { "selector": "source.python", "env": {"PYTHONPATH":"/Users/user/project"}, "path":"/Users/user/work/myvirtualenv/bin:$PATH", "name": "Run virtualenv python", ...
Using virtualenv with sublime text 2
11,965,707
26
2012-08-15T07:47:28Z
15,913,663
12
2013-04-09T22:25:28Z
[ "python", "virtualenv", "sublimetext2" ]
I am using sublime text 2 for python development along with virtualenv! The standard sublime text 2 build system uses the standard python install rather than my virtualenv where my packages are installed. How can I get sublime text 2 to build using my virtualenv? I currently use the terminal to activate my environme...
Sublime's Build System supports variables which can be used with Sublime project files to make this a bit more portable across projects. If your virtual environments are in a standard spot, create a new project file (Project -> Save Project As) into the root directory of your project just above your virtual environmen...
Python concatenate list
11,967,516
5
2012-08-15T10:12:44Z
11,967,537
8
2012-08-15T10:14:26Z
[ "python", "string", "list" ]
I'm new to python and this is just to automate something on my PC. I want to concatenate all the items in a list. The problem is that ``` ''.join(list) ``` won't work as it isn't a list of strings. This site <http://www.skymind.com/~ocrow/python_string/> says the most efficient way to do it is ``` ''.join([`num` fo...
You need to turn everything in the list into strings, using the [`str()` constructor](http://docs.python.org/library/functions.html#str): ``` ''.join(str(elem) for elem in lst) ``` Note that it's generally not a good idea to use `list` for a variable name, it'll shadow the built-in `list` constructor. I've used a ge...
Create a temporary compressed file
11,967,720
9
2012-08-15T10:26:52Z
11,967,760
7
2012-08-15T10:29:25Z
[ "python", "django" ]
I need to create a temporary file to send it, I have tried : ``` # Create a temporary file --> I think it is ok (file not seen) temporaryfile = NamedTemporaryFile(delete=False, dir=COMPRESSED_ROOT) # The path to archive --> It's ok root_dir = "something" # Create a compressed file --> It bugs data = open(f.write(mak...
First of all, you don't need to create a `NamedTemporaryFile` to use `make_archive`; all you want is a unique filename for the `make_archive` file to create. ## `.write` doesn't return a filename To focus on that error: You are assuming that the return value of `f.write` is a filename you can open; just seek to the s...
Create a temporary compressed file
11,967,720
9
2012-08-15T10:26:52Z
11,971,561
13
2012-08-15T14:48:26Z
[ "python", "django" ]
I need to create a temporary file to send it, I have tried : ``` # Create a temporary file --> I think it is ok (file not seen) temporaryfile = NamedTemporaryFile(delete=False, dir=COMPRESSED_ROOT) # The path to archive --> It's ok root_dir = "something" # Create a compressed file --> It bugs data = open(f.write(mak...
I actually just needed to do something similar and I wanted to avoid file I/O entirely, if possible. Here's what I came up with: ``` import tempfile import zipfile with tempfile.SpooledTemporaryFile() as tmp: with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED) as archive: archive.writestr('something.txt'...
python multithreading wait till all threads finished
11,968,689
28
2012-08-15T11:44:54Z
11,968,818
48
2012-08-15T11:54:27Z
[ "python", "multithreading" ]
This may have been asked in a similar context but I was unable to find an answer after about 20 minutes of searching, so I will ask. I have written a Python script (lets say: scriptA.py) and a script (lets say scriptB.py) In scriptB I want to call scriptA multiple times with different arguments, each time takes about...
You need to use [join](http://docs.python.org/library/threading.html#threading.Thread.join) method of `Thread` object in the end of the script. ``` t1 = Thread(target=call_script, args=(scriptA + argumentsA)) t2 = Thread(target=call_script, args=(scriptA + argumentsB)) t3 = Thread(target=call_script, args=(scriptA + a...
python multithreading wait till all threads finished
11,968,689
28
2012-08-15T11:44:54Z
11,968,881
69
2012-08-15T12:00:03Z
[ "python", "multithreading" ]
This may have been asked in a similar context but I was unable to find an answer after about 20 minutes of searching, so I will ask. I have written a Python script (lets say: scriptA.py) and a script (lets say scriptB.py) In scriptB I want to call scriptA multiple times with different arguments, each time takes about...
Put the threads in a list: ``` threads = [] t = Thread(...) threads.append(t) ...repeat as often as necessary... # Start all threads for x in threads: x.start() # Wait for all of them to finish for x in threads: x.join() ```
Printing all combinations, python
11,968,790
4
2012-08-15T11:51:43Z
11,968,824
11
2012-08-15T11:54:56Z
[ "python", "combinations" ]
say I have 3 different variables and each has 2 possible values, so in total I have 8 different combinations. Is there a python library function, or an algorithm that I can use to print all possible combinations? Thanks
I think you're looking for [product](http://docs.python.org/library/itertools.html#itertools.product): ``` a = [1, 2] b = [100, 200] c = [1000, 2000] import itertools for p in itertools.product(a, b, c): print p ``` prints: ``` (1, 100, 1000) (1, 100, 2000) (1, 200, 1000) (1, 200, 2000) (2, 100, 1000) (2, 100, ...
List files in ONLY the current directory
11,968,976
101
2012-08-15T12:07:20Z
11,969,008
25
2012-08-15T12:09:25Z
[ "python" ]
In Python, I only want to list all the files in the current directory ONLY. I do not want files listed from any subdirectory or parent. There do seem to be similar solutions out there, but they don't seem to work for me. Here's my code snippet: ``` import os for subdir, dirs, files in os.walk('./'): for file in f...
You can use `os.listdir` for this purpose. If you only want *files* and not *directories*, you can filter the results using `os.path.isfile`. example: ``` files = os.listdir(os.curdir) #files and directories ``` or ``` files = filter(os.path.isfile, os.listdir( os.curdir ) ) # files only files = [ f for f in os.l...
List files in ONLY the current directory
11,968,976
101
2012-08-15T12:07:20Z
11,969,014
183
2012-08-15T12:09:55Z
[ "python" ]
In Python, I only want to list all the files in the current directory ONLY. I do not want files listed from any subdirectory or parent. There do seem to be similar solutions out there, but they don't seem to work for me. Here's my code snippet: ``` import os for subdir, dirs, files in os.walk('./'): for file in f...
Just use [`os.listdir`](http://docs.python.org/library/os#os.listdir) and [`os.path.isfile`](http://docs.python.org/library/os.path.html#os.path.isfile) instead of [`os.walk`](http://docs.python.org/library/os#os.walk). **Example:** ``` files = [f for f in os.listdir('.') if os.path.isfile(f)] for f in files: # d...
Remove lines that contain certain string
11,968,998
3
2012-08-15T12:08:54Z
11,969,474
16
2012-08-15T12:43:47Z
[ "python", "line" ]
I'm trying to read a text from a text file, read lines, delete lines that contain specific string (in this case 'bad' and 'naughty'). The code I wrote goes like this: ``` infile = file('./oldfile.txt') newopen = open('./newfile.txt', 'w') for line in infile : if 'bad' in line: line = line.replace('.' , '...
You can make your code simpler and more readable like this ``` bad_words = ['bad', 'naughty'] with open('oldfile.txt') as oldfile, open('newfile.txt', 'w') as newfile: for line in oldfile: if not any(bad_word in line for bad_word in bad_words): newfile.write(line) ``` using a [Context Manager...
Matplotlib : quiver and imshow superimposed, how can I set two colorbars?
11,970,186
9
2012-08-15T13:31:18Z
11,972,234
7
2012-08-15T15:23:59Z
[ "python", "matplotlib", "visualization", "data-visualization", "colorbar" ]
I have a figure that consists of an image displayed by `imshow()`, a contour and a vector field set by `quiver()`. I have colored the vector field based on another scalar quantity. On the right of my figure, I have made a `colorbar()`. This `colorbar()` represents the values displayed by `imshow()` (which can be positi...
Simply call `colorbar` twice, right after each plotting call. Pylab will create a new colorbar matching to the latest plot. Note that, as in your example, the quiver values range from 0,1 while the imshow takes negative values. For clarity (not shown in this example), I would use different colormaps to distinguish the ...
Modify data as part of an alembic upgrade
11,970,555
18
2012-08-15T13:53:18Z
11,995,593
12
2012-08-16T21:19:00Z
[ "python", "sqlalchemy", "alembic" ]
I would like to modify some database data as part of an alembic upgrade. I thought I could just add any code in the upgrade of my migration, but the following fails: ``` def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.add_column('smsdelivery', sa.Column('sms_message_part_id', sa....
It is difficult to understand what exactly you are trying to achieve from the code excerpt your provided. But I'll try to guess. So the following answer will be based on my guess. Line 4 - you import things (DBSession, SmsDelivery, SmsMessagePart) form your modules and then you are trying to operate with these objects...
Modify data as part of an alembic upgrade
11,970,555
18
2012-08-15T13:53:18Z
18,863,270
11
2013-09-18T03:16:37Z
[ "python", "sqlalchemy", "alembic" ]
I would like to modify some database data as part of an alembic upgrade. I thought I could just add any code in the upgrade of my migration, but the following fails: ``` def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.add_column('smsdelivery', sa.Column('sms_message_part_id', sa....
Its worth noting that if you do this, you probably want to freeze a copy of your orm model *inside* the migration, like this: ``` class MyType(Base): __tablename__ = 'existing_table' __table_args__ = {'extend_existing': True} id = Column(Integer, ...) .. def upgrade(): Base.metadata.bind = op.get_bind() ...
Amazon Elastic MapReduce - SIGTERM
11,970,646
6
2012-08-15T13:59:33Z
12,071,979
10
2012-08-22T11:21:26Z
[ "python", "hadoop-streaming", "elastic-map-reduce", "amazon-emr" ]
I have an EMR streaming job (Python) which normally works fine (e.g. 10 machines processing 200 inputs). However, when I run it against large data sets (12 machines processing a total of 6000 inputs, at about 20 seconds per input), after 2.5 hours of crunching I get the following error: ``` java.lang.RuntimeException:...
I figured out what was happening, so here's some information if anyone else experiences similar problems. The key to me was to look at the "jobtracker" logs. These live in your task's logs/ folder on S3, under: ``` <logs folder>/daemons/<id of node running jobtracker>/hadoop-hadoop-jobtracker-XXX.log. ``` There were...
MultiLevel index to columns : getting value_counts as columns in pandas
11,971,381
5
2012-08-15T14:39:44Z
11,972,498
8
2012-08-15T15:40:50Z
[ "python", "ipython", "pandas" ]
In a very general sense, the problem I am looking to solve is changing one component of a multi-level index into columns. That is, I have a Series that contains a multilevel index and I want the lowest level of the index changed into columns in a dataframe. Here is the *actual* example problem I'm trying to solve, Her...
I think you want: ``` dfgb['bar'].value_counts().unstack().fillna(0.) ```
Is there a way to efficiently invert an array of matrices with numpy?
11,972,102
4
2012-08-15T15:16:32Z
11,999,063
9
2012-08-17T02:34:07Z
[ "python", "numpy", "linear-algebra", "matrix-inverse" ]
Normally I would invert an array of 3x3 matrices in a `for` loop like in the example below. Unfortunately `for` loops are slow. Is there a faster, more efficient way to do this? ``` import numpy as np A = np.random.rand(3,3,100) Ainv = np.zeros_like(A) for i in range(100): Ainv[:,:,i] = np.linalg.inv(A[:,:,i]) ```
It turns out that you're getting burned two levels down in the numpy.linalg code. If you look at numpy.linalg.inv, you can see it's just a call to numpy.linalg.solve(A, inv(A.shape[0]). This has the effect of recreating the identity matrix in each iteration of your for loop. Since all your arrays are the same size, tha...
SQLAlchemy and UnicodeDecodeError
11,972,363
7
2012-08-15T15:31:39Z
11,982,120
20
2012-08-16T06:55:33Z
[ "python", "mysql", "unicode", "encoding", "sqlalchemy" ]
I'm getting ``` UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128) ``` when I pass text coming from a MySQL database, which I am accessing using SQLAlchemy, to this function: ``` re.compile(ur"<([^>]+)>", flags=re.UNICODE).sub(u" ", s) ``` The database encoding is utf-...
I have solved the issue. The `title` column was being returned by SQLAlchemy as a `str` and not `Unicode`. I thought adding `encoding='utf8'` as an argument to `create_engine` would take care of this, however, the right way to do it is to pass it in the database URI: `mysql://me@myserver/mydatabase?charset=utf8` . Tha...