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 How to capitalize nth letter of a string
15,858,065
2
2013-04-07T01:53:45Z
15,858,079
8
2013-04-07T01:56:19Z
[ "python", "string", "capitalize" ]
I tried this: [*Capitalize a string*](http://stackoverflow.com/questions/352478/capitalize-a-string). Can anybody provide a simple script/snippet for guideline? Python documentation has [`capitalize()`](http://docs.python.org/2/library/stdtypes.html?highlight=capitalize#str.capitalize) function which makes first lette...
``` my_string[:n] + my_string[n].upper() + my_string[n + 1:] ``` Or a more efficient version that isn't a [Schlemiel the Painter's algorithm](https://en.wikipedia.org/wiki/Schlemiel_the_Painter%27s_algorithm): ``` ''.join([my_string[:n], my_string[n].upper(), my_string[n + 1:]]) ```
How can I send variables to Jinja template from a Flask decorator?
15,858,947
18
2013-04-07T04:45:08Z
15,860,142
7
2013-04-07T07:54:57Z
[ "python", "templates", "flask", "decorator", "jinja2" ]
Many routes around my blueprinted flask app will need to send 'sidebar data' to jinja. I'm looking for the most efficient way to do this. Their has to be something better than importing my 'generate\_sidebar\_data()' function into every blueprint, repeatedly saying: ``` var1, var2, var3 = generate_sidebar_data() ``` ...
You can use context processor (<http://flask.pocoo.org/docs/api/#flask.Flask.context_processor>): ``` def include_sidebar_data(fn): @blueprit.context_processor def additional_context(): # this code work if endpoint equals to view function name if request.endpoint != fn.__name__: ret...
How can I send variables to Jinja template from a Flask decorator?
15,858,947
18
2013-04-07T04:45:08Z
15,862,998
13
2013-04-07T13:37:14Z
[ "python", "templates", "flask", "decorator", "jinja2" ]
Many routes around my blueprinted flask app will need to send 'sidebar data' to jinja. I'm looking for the most efficient way to do this. Their has to be something better than importing my 'generate\_sidebar\_data()' function into every blueprint, repeatedly saying: ``` var1, var2, var3 = generate_sidebar_data() ``` ...
I'm going to propose something even simpler than using a decorator or template method or anything like that: ``` def render_sidebar_template(tmpl_name, **kwargs): (var1, var2, var3) = generate_sidebar_data() return render_template(tmpl_name, var1=var1, var2=var2, var3=var3, **kwargs) ``` Yup, just a function....
python: how to convert a valid uuid from String to UUID?
15,859,156
15
2013-04-07T05:21:05Z
15,859,179
29
2013-04-07T05:24:12Z
[ "python", "uuid" ]
I receive the data as ``` { "name": "Unknown", "parent": "Uncategorized", "uuid": "06335e84-2872-4914-8c5d-3ed07d2a2f16" }, ``` and I need to convert the `uuid` from `String` to `uuid` I did not find a way on the [python docs](http://docs.python.org/library/uuid.html), or am I missing ...
Just pass it to `uuid.UUID`: ``` import uuid o = { "name": "Unknown", "parent": "Uncategorized", "uuid": "06335e84-2872-4914-8c5d-3ed07d2a2f16" } print uuid.UUID(o['uuid']).hex ```
In python, can I redirect the output of print function to stderr?
15,860,372
5
2013-04-07T08:25:31Z
15,860,430
8
2013-04-07T08:31:39Z
[ "python", "python-2.7", "stderr" ]
There're lots of `print` function (`python 2.7`) in my program. Is there any way I can add a few lines then all the output can be redirected to `stderr`? What I want is python codes but not linux pipeline. For example, my program is like: ``` print 'hello world' ``` I would like to add some codes like: ``` redirect...
Do this in your method: ``` import sys sys.stdout = sys.stderr ```
Access index of last element in data frame
15,862,034
9
2013-04-07T11:51:50Z
15,863,028
11
2013-04-07T13:40:31Z
[ "python", "pandas" ]
I've looking around for this but I can't seem to find it (though it must be extremely trivial). The problem that I have is that I would like to retrieve the value of a column for the first and last entries of a data frame. But if I do: ``` df.ix[0]['date'] ``` I get: ``` datetime.datetime(2011, 1, 10, 16, 0) ``` b...
The former answer is now superseded by [`.iloc`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.iloc.html): ``` >>> df = pd.DataFrame({"date": range(10, 64, 8)}) >>> df.index += 17 >>> df date 17 10 18 18 19 26 20 34 21 42 22 50 23 58 >>> df["date"].iloc[0] 10 >>> df["date...
Python regular expression match whole word
15,863,066
7
2013-04-07T13:44:01Z
15,863,102
13
2013-04-07T13:47:35Z
[ "python", "regex" ]
I'm having trouble finding the correct regular expression for the scenario below: Lets say: ``` a = "this is a sample" ``` I want to match whole word - for example match `"hi"` should return False since `"hi"` is not a word and `"is"` should return True since there is no alpha character on the left and on the right ...
Try ``` re.search(r'\bis\b', your_string) ``` From [the docs](http://docs.python.org/2/library/re.html): > \b Matches the empty string, but only at the beginning or end of a word. Note that the `re` module uses a naive definition of "word" as a "sequence of alphanumeric or underscore characters", where "alphanumeri...
Python equivalent of MATLAB's "ismember" function
15,864,082
12
2013-04-07T15:25:54Z
15,864,429
10
2013-04-07T15:59:41Z
[ "python", "matlab", "optimization", "numpy" ]
After many attempts trying optimize code, it seems that one last resource would be to attempt to run the code below using multiple cores. I don't know exactly how to convert/re-structure my code so that it can run much faster using multiple cores. I will appreciate if I could get guidance to achieve the end goal. The e...
Before worrying about multiple cores, I would eliminate the linear scan in your ismember function by using a dictionary: ``` def ismember(a, b): bind = {} for i, elt in enumerate(b): if elt not in bind: bind[elt] = i return [bind.get(itm, None) for itm in a] # None can be replaced by a...
python difflib comparing files
15,864,641
5
2013-04-07T16:19:46Z
15,864,920
10
2013-04-07T16:44:43Z
[ "python", "text", "difflib" ]
I am trying to use difflib to produce diff for two text files containing tweets. Here is the code: ``` #!/usr/bin/env python # difflib_test import difflib file1 = open('/home/saad/Code/test/new_tweets', 'r') file2 = open('/home/saad/PTITVProgs', 'r') diff = difflib.context_diff(file1.readlines(), file2.readlines()...
There are multiple diff styles and different functions exist for them in the `difflib` library. `unified_diff`, `ndiff` and `context_diff`. If you don't want the line number summaries, `ndiff` function gives a Differ-style delta: ``` import difflib f1 = '''1 2 3 4 5''' f2 = '''1 3 4 5 6''' diff = difflib.ndiff(f1,f...
python difflib comparing files
15,864,641
5
2013-04-07T16:19:46Z
15,864,963
15
2013-04-07T16:47:50Z
[ "python", "text", "difflib" ]
I am trying to use difflib to produce diff for two text files containing tweets. Here is the code: ``` #!/usr/bin/env python # difflib_test import difflib file1 = open('/home/saad/Code/test/new_tweets', 'r') file2 = open('/home/saad/PTITVProgs', 'r') diff = difflib.context_diff(file1.readlines(), file2.readlines()...
Just parse output of diff like this (change '- ' to '+ ' if needed): ``` #!/usr/bin/env python # difflib_test import difflib file1 = open('/home/saad/Code/test/new_tweets', 'r') file2 = open('/home/saad/PTITVProgs', 'r') diff = difflib.ndiff(file1.readlines(), file2.readlines()) delta = ''.join(x[2:] for x in diff...
PYQT4 - How do I compile and import a qrc file into my program?
15,864,762
10
2013-04-07T16:30:16Z
15,867,095
14
2013-04-07T19:56:55Z
[ "python", "pyqt", "pyqt4", "resource-files" ]
I'm having trouble importing a resource file. I'm using pyqt4 with monkey studio and I am trying to import a png image. When I run the program I get an import error like > ImportError: No module named icon\_rc I know that I have to compile it using pyrcc4 but I don't understand how to do this can anybody help please....
There really isn't much to explain here, you have a resource file (e.g. `icon.qrc`), then you call `pyrcc4 -o icon_rc.py icon.qrc` which will create a module `icon_rc.py` which you then can import in your project. It's all documented [here](http://pyqt.sourceforge.net/Docs/PyQt4/resources.html).
PYQT4 - How do I compile and import a qrc file into my program?
15,864,762
10
2013-04-07T16:30:16Z
15,884,165
20
2013-04-08T16:20:08Z
[ "python", "pyqt", "pyqt4", "resource-files" ]
I'm having trouble importing a resource file. I'm using pyqt4 with monkey studio and I am trying to import a png image. When I run the program I get an import error like > ImportError: No module named icon\_rc I know that I have to compile it using pyrcc4 but I don't understand how to do this can anybody help please....
i managed to find out how to do it now. i went to cmd and typed this command. ``` pyrcc4 -py3 F:\computing\Payrollv22\icon.qrc -o icon_rc.py ``` it compiled the file successfully and it was able to import the py file to my project and run it with no problem, thank you for your help too.
Create composite index from a Django model
15,866,076
8
2013-04-07T18:24:30Z
20,138,248
16
2013-11-22T06:15:18Z
[ "python", "django", "django-models" ]
I have the following model: ``` from django.db import models class PopulationData(models.Model): slot = models.IntegerField(db_index=True) sample = models.IntegerField() value = models.FloatField() class Meta: unique_together = (('slot', 'sample'),) ``` And I would like to create also a comp...
Starting from django-1.5 you can make compound index using index\_together meta option: <https://docs.djangoproject.com/en/dev/ref/models/options/#index-together>
basic help to call python from unix
15,867,283
3
2013-04-07T20:14:44Z
15,867,312
7
2013-04-07T20:17:19Z
[ "python", "unix" ]
Hi I am pretty new to python so I have been playing around with it. I recently created 2 files for some process I am working on which seems to be working while running python but doing nothing when write python name.py argv at the unix command line. It is probably something basic and I would appreciate some help. 1st f...
You're defining a function called `main`, but never call it. Do: ``` import os import sys def main(): ... if __name__ == '__main__': main() ``` See [here](http://stackoverflow.com/questions/419163/what-does-if-name-main-do) for more details about this idiom.
Getting NameError with Django 1.5 and IPython
15,867,678
5
2013-04-07T20:53:10Z
15,867,798
7
2013-04-07T21:04:53Z
[ "python", "django", "django-forms", "ipython" ]
I'm running Django 1.5.1, Python 2.7.2, and IPython 0.13.2. If I do "python ./manage.py shell" from within my Django project directory, I get the following error: ``` from django import forms class CommentForm(forms.Form): name = forms.CharField() NameError: name 'forms' is not defined. ``` I know forms is defin...
django 1.5 doesn't start IPython properly. This is [fixed in master](https://github.com/django/django/commit/3570ff734e93f493e023b912c9a97101f605f7f5), but the fix was not backported to 1.5.1. If you manually apply that patch to core/management/commands/shell.py, IPython should work as expected.
What is the name of this operator “ _ ” in Python?
15,867,715
12
2013-04-07T20:56:45Z
15,867,736
12
2013-04-07T20:58:54Z
[ "python" ]
I was reading [Hidden features of Python](http://stackoverflow.com/questions/101268/hidden-features-of-python?page=5&tab=oldest#tab-top) and I came across this [answer](http://stackoverflow.com/a/3254039/1031955). Right from the post: > When using the interactive shell, "\_" contains the value of the last > printed i...
It's neither an operator nor a function. It's a *variable* that automatically gets assigned the result of each expression executed by the shell.
List to array conversion
15,868,512
21
2013-04-07T22:17:57Z
15,868,531
57
2013-04-07T22:20:26Z
[ "python", "arrays", "list", "numpy" ]
I have a list in python and I want to convert it to an array to be able to use `ravel()` function.
Use [`numpy.asarray`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.asarray.html): ``` import numpy as np myarray = np.asarray(mylist) ```
Python Socket Listening
15,869,158
7
2013-04-07T23:37:29Z
16,512,082
10
2013-05-12T21:10:23Z
[ "python", "sockets", "python-2.7" ]
**All of the below mentioned is on windows machines using python 2.7** Hello, I am currently attempting to listen on a socket for data send by a remote program. This data is then printed to the screen and user input is requested that is then returned to remote program. In testing I have been able to have the remote p...
Playing around with this for a while finally got it working nice with a telnet session locally using python 2.7. What it does is it sets up a thread that runs when the client connects listening for client stuff. When the client sends a return ("\r\n" might have to change that if your interacting with a Linux system?)...
What is the advantage of setting zip_safe to True when packaging a Python project?
15,869,473
18
2013-04-08T00:21:51Z
16,541,150
9
2013-05-14T10:46:08Z
[ "python", "packaging", "setuptools" ]
The setuptools documentation only states: > For maximum performance, Python packages are best installed as zip files. Not all packages, however, are capable of running in compressed form, because they may expect to be able to access either source code or data files as normal operating system files. So, setuptools can ...
Zip files take up less space on disk, which also means they're more quickly read from disk. Since most things are I/O bound, the overhead in decompressing the packaging may be less than the overhead in reading a larger file from disk. Moreover, it's likely that a single, small-ish zip file is stored sequentially on dis...
Can you overwrite a variable that is defined by the result of a function without clearing first in python?
15,869,722
2
2013-04-08T00:59:21Z
15,869,746
7
2013-04-08T01:03:36Z
[ "python", "function", "variables", "python-2.7", "overwrite" ]
So, I was wondering if there was a way to clear and overwrite/rewrite a variable in one step without having to clear it before hand. This is what I have for example: ``` def rate(t,w): return (t + cos(t)) sum = 0 for i in range(k): sum += rate(t+h*i,w) print sum ``` but then if I want to reuse this functio...
You do not need to clear the variable in the second example. Delete the line, and see that the program still works. In Python the assignment (`=`) operator binds names to objects: ``` a = 2 * 4 ``` In this line the computation `2 * 4` creates an `int` object with the value 8. The `=` operator then binds it to the na...
Implementing Flask-Login with multiple User Classes
15,871,391
8
2013-04-08T04:41:02Z
15,884,811
18
2013-04-08T16:59:50Z
[ "python", "flask", "flask-sqlalchemy", "flask-login" ]
I am writing an app that has multiple classes that function as Users (for example, a School Account and a Staff account). I'm trying to use Flask-Login to make this easy but I'm not quite sure how to make it so that when a user logs in, I can have my app check to see whether or not the username belongs to a School acco...
You can define each User with a specific role. For example, user 'x' can be SCHOOL while user 'y' can be 'STAFF'. ``` class User(db.Model): __tablename__ = 'User' id = db.Column(db.Integer,primary_key=True) username = db.Column(db.String(80),unique=True) pwd_hash = db.Column(db.String(200)) email ...
Is there a cleaner way than using for loops
15,873,350
3
2013-04-08T07:15:54Z
15,873,545
7
2013-04-08T07:26:42Z
[ "python", "numpy" ]
I would like to know if there are any other ways to loop and manipulate data located in separate arrays. ``` import numpy as np a = np.arange(2) b = np.arange(5) c = np.arange(5) l1 = [] for x in a: l2 = [] for y in b: l3 = [] y = x + 1 for z in c: z = x + y ...
This code does exactly what you are doing. ``` def method(lst, range1, range2): for i in lst: yield [[(i, i+1, 1+(i*2))]*range2]*range1 ``` Can even be turned into a generator expression: ``` def gen_method(lst, r1, r2): return ([[(i, i+1, 1+(i*2))]*r2]*r1 for i in lst) ``` Test it yourself if you l...
sublist to dictionary
15,875,678
3
2013-04-08T09:28:25Z
15,875,704
7
2013-04-08T09:29:25Z
[ "python", "list", "dictionary", "sublist" ]
So I have: ``` a = [["Hello", "Bye"], ["Morning", "Night"], ["Cat", "Dog"]] ``` And I want to convert it to a dictionary. I tried using: ``` i = iter(a) b = dict(zip(a[0::2], a[1::2])) ``` But it gave me an error: `TypeError: unhashable type: 'list'`
Simply: ``` >>> a = [["Hello", "Bye"], ["Morning", "Night"], ["Cat", "Dog"]] >>> dict(a) {'Cat': 'Dog', 'Hello': 'Bye', 'Morning': 'Night'} ``` I love python's simplicity You can see [here](http://docs.python.org/2/library/stdtypes.html#dict) for all the ways to construct a dictionary: > To illustrate, the followin...
TypeError: 'filter' object is not subscriptable
15,876,259
6
2013-04-08T09:57:30Z
15,876,294
11
2013-04-08T09:59:24Z
[ "python", "python-idle" ]
I am receiving the error ``` TypeError: 'filter' object is not subscriptable ``` When trying to run the following block of code ``` bonds_unique = {} for bond in bonds_new: if bond[0] < 0: ghost_atom = -(bond[0]) - 1 bond_index = 0 elif bond[1] < 0: ghost_atom = -(bond[1]) - 1 ...
`filter()` in python 3 does *not* return a list, but a iterable `filter` object. Call `next()` on it to get the *first* filtered item: ``` bond[bond_index] = old_to_new[sheet.index(next(image)) + 1 ] ``` There is no need to convert it to a list, as you only use the first value.
Finding Minimum in Python Arrays
15,877,379
2
2013-04-08T10:57:47Z
15,877,463
7
2013-04-08T11:02:59Z
[ "python", "arrays", "sorting" ]
I have two arrays say `x = [110, 10, 1000 ....]` and `y = ['adas', 'asdasqe', 'ae1e' ....]` Both of these arrays are of the same length. My problem is that or printing the 10 values of `y` such that the corresponding values of `x` are the 10 largest. In an average test case, `x` and `y` are 4000-5000 in length. So sp...
If you want the ten top elements from a list of several thousands, you can try [`heapq`](http://docs.python.org/2/library/heapq.html): ``` import heapq heapq.nlargest(10, zip(x, y)) ```
run python script as cgi apache server
15,878,010
5
2013-04-08T11:34:18Z
15,882,918
10
2013-04-08T15:19:34Z
[ "python", "apache", "cgi" ]
I am trying to make a python script run as cgi, using an Apache server. My script looks something like this: ``` #!/usr/bin/python import cgi if __name__ == "__main__": print("Content-type: text/html") print("<HTML>") print("<HEAD>") ``` I have done the necessary configurations in httpd.conf(in my opinio...
I think you are missing a print statement after ``` print("Content-type: text/html") ``` The output of a CGI script should consist of two sections, separated by a blank line. The first section contains a number of headers, telling the client what kind of data is following. The second section is usually HTML, which a...
What is the difference between ndarray and array in numpy?
15,879,315
64
2013-04-08T12:41:55Z
15,879,428
14
2013-04-08T12:46:32Z
[ "python", "arrays", "numpy", "multidimensional-array" ]
what is the difference between ndarray and array in numpy? And where can I find the implementations in the numpy source code? Thanks! Edit: This is about numpy.ndarray and numpy.array, not about list. The question is not a duplicate of the one suggested.
`numpy.array` is a function that returns a `numpy.ndarray`. There is no object type numpy.array.
What is the difference between ndarray and array in numpy?
15,879,315
64
2013-04-08T12:41:55Z
15,879,527
44
2013-04-08T12:51:01Z
[ "python", "arrays", "numpy", "multidimensional-array" ]
what is the difference between ndarray and array in numpy? And where can I find the implementations in the numpy source code? Thanks! Edit: This is about numpy.ndarray and numpy.array, not about list. The question is not a duplicate of the one suggested.
Well, `np.array` is just a convenience function to create an `ndarray`, it is not a class itself. You can also create an array using `np.ndarray`, but it is not the recommended way. From the docstring of `np.ndarray`: > Arrays should be constructed using `array`, `zeros` or `empty` ... The parameters given here refer...
Concatenate lists in JINJA2
15,879,983
10
2013-04-08T13:11:49Z
15,880,282
11
2013-04-08T13:25:13Z
[ "python", "jinja2" ]
How can I concatenate two list variables in jinja2? E.G. ``` GRP1 = [1, 2, 3] GRP2 = [4, 5, 6] {# This works fine: #} {% for M in GRP1 %} Value is {{M}} {% endfor %} {# But this does not: #} {% for M in GRP1 + GRP2 %} Value is {{M}} {% endfor %} ``` So, I have tried to concatenate the two lists using + (l...
AFAIK you can't do it using native Jinja2 templating. You're better off creating a new combined iterable and passing that to your template, eg: ``` from itertools import chain x = xrange(3) y = xrange(3, 7) z = chain(x, y) # pass this to your template for i in z: print i ``` As per comments, you can explicitly c...
Matplotlib: Aligning y-ticks to the left
15,882,249
7
2013-04-08T14:49:55Z
15,883,858
8
2013-04-08T16:03:31Z
[ "python", "matplotlib" ]
I have tick labels of variable length, and I want to align them to the left (i.e. to have a space between the shorter ones and the y axis). Is there any reasonable way to do this? Using horizontal alignment 'left' aligns them to the left, but they all start at the axis, so they end up inside the plot. So an alternative...
You will just need to add a `pad`. See [matplotlib ticks position relative to axis](http://stackoverflow.com/questions/14711338/matplotlib-ticks-position-relative-to-axis/14712375#14712375) ``` yax = ax.get_yaxis() yax.set_tick_params(pad=pad) ``` [(doc)](http://matplotlib.org/api/axis_api.html#matplotlib.axis.Axis.s...
Matplotlib.animation: how to remove white margin
15,882,395
4
2013-04-08T14:56:48Z
15,883,620
7
2013-04-08T15:52:05Z
[ "python", "animation", "video", "matplotlib" ]
I try to generate a movie using the matplotlib movie writer. If I do that, I always get a white margin around the video. Has anyone an idea how to remove that margin? Adjusted example from <http://matplotlib.org/examples/animation/moviewriter.html> ``` # This example uses a MovieWriter directly to grab individual fra...
Passing `None` as an arguement to `subplots_adjust` does not do what you think it does [(doc)](http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure.subplots_adjust). It means 'use the deault value'. To do what you want use the following instead: ``` fig.subplots_adjust(left=0, bottom=0, right=1, top=1, w...
How is the __name__ variable in a Python module defined?
15,883,526
12
2013-04-08T15:47:29Z
15,883,682
11
2013-04-08T15:54:59Z
[ "python", "python-module", "python-internals" ]
I'm aware of [the standard example](http://docs.python.org/2/tutorial/modules.html#executing-modules-as-scripts): if you execute a module directly then it's `__name__` global variable is defined as `"__main__"`. However, nowhere in the documentation can I find a precise description of how `__name__` is defined in the g...
It is set to the absolute name of the module as imported. If you imported it as `foo.bar`, then `__name__` is set to `'foo.bar'`. The name is determined in the [`import.c`](http://hg.python.org/cpython/file/tip/Python/import.c) module, but because that module handles various different types of imports (including zip i...
python flask - serving static files
15,883,874
10
2013-04-08T16:04:49Z
15,884,072
16
2013-04-08T16:14:56Z
[ "python", "flask" ]
I'm trying to serve a static file using flask. I don't know how to use the url\_for function. All my routes generating dynamic content are working fine, I've imported url\_for, but when I have this code: ``` @app.route('/') def home(): return url_for('static', filename='hi.html') ``` Along with my 'hi.html' file ...
`url_for` just returns, precisely, the URL for that file. It sounds like you want to `redirect` to the URL for that file. Instead, you are just sending the text of the URL to the client as a response. ``` from flask import url_for, redirect @app.route('/') def home(): return redirect(url_for('static', filename='h...
TKinter in a Virtualenv
15,884,075
18
2013-04-08T16:15:00Z
15,937,719
33
2013-04-10T22:36:07Z
[ "python", "tkinter", "virtualenv" ]
Trying to run python code with TKinter-based widgets from a virtualenv. ``` user@computer:~/myproject$ env/bin/python Python 2.7.3 (default, Sep 26 2012, 21:51:14) [GCC 4.7.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import Tkinter Traceback (most recent call l...
Set the environment variable TCL\_LIBRARY in your `activate` script. On Windows (Python 2.7 with Tcl 8.5), just add this line to `Scripts\activate.bat`: ``` set "TCL_LIBRARY=C:\Python27\tcl\tcl8.5" ``` @Jasper van den Bosch's edit: On Ubuntu, the modification to the script `activate` is the following: ``` TK_LIBRARY...
Python , Printing Hex removes first 0?
15,884,677
7
2013-04-08T16:52:15Z
15,884,750
16
2013-04-08T16:56:42Z
[ "python", "hex" ]
take a look at this: ``` fc = '0x' for i in b[0x15c:0x15f]: fc += hex(ord(i))[2:] ``` Lets say this code found the hex 00 04 0f , instead of writing it that way , it removes the first 0 , and writes : 04f any help?
This is happening because `hex()` will not include any leading zeros, for example: ``` >>> hex(15)[2:] 'f' ``` To make sure you always get two characters, you can use [`str.zfill()`](http://docs.python.org/2/library/stdtypes.html#str.zfill) to add a leading zero when necessary: ``` >>> hex(15)[2:].zfill(2) '0f' ``` ...
Django uploads: Discard uploaded duplicates, use existing file (md5 based check)
15,885,201
18
2013-04-08T17:22:04Z
15,900,958
23
2013-04-09T11:45:21Z
[ "python", "django", "django-models", "django-file-upload" ]
I have a model with a `FileField`, which holds user uploaded files. Since I want to save space, I would like to avoid duplicates. **What I'd like to achieve:** 1. **Calculate** the uploaded files **md5 checksum** 2. Store the file with the **file name based on its md5sum** 3. If a file with that name is already there...
Thanks to alTus answer, I was able to figure out that writing a **[custom storage class](https://docs.djangoproject.com/en/dev/howto/custom-file-storage/)** is the key, and it was easier than expected. * I just omit calling the superclasses `_save` method to write the file if it is already there and I just return the ...
How to extract all UPPER from a string? Python
15,886,340
4
2013-04-08T18:30:43Z
15,886,375
14
2013-04-08T18:32:56Z
[ "python", "string", "extract", "uppercase", "lowercase" ]
``` #input my_string = 'abcdefgABCDEFGHIJKLMNOP' ``` how would one extract all the UPPER from a string? ``` #output my_upper = 'ABCDEFGHIJKLMNOP' ```
Using list comprehension: ``` >>> s = 'abcdefgABCDEFGHIJKLMNOP' >>> ''.join([c for c in s if c.isupper()]) 'ABCDEFGHIJKLMNOP' ``` Using generator expression: ``` >>> ''.join(c for c in s if c.isupper()) 'ABCDEFGHIJKLMNOP ``` You can also do it using regular expressions: ``` >>> re.sub('[^A-Z]', '', s) 'ABCDEFGHIJK...
Dropping all collections in Mongoengine
15,886,469
8
2013-04-08T18:38:33Z
15,886,728
12
2013-04-08T18:53:31Z
[ "python", "mongodb", "mongoengine" ]
I have searched the api, but can't find anything relating to the dropping of a database without iterating through the collections manually. Is there a simpler way of calling `db.dropDatabase()` through mongoengine? Its not a big deal to iterate through just wanted a simpler way.
How about doing it this way? ``` from mongoengine import connect db = connect('test') db.drop_database('test') ``` Alternatively, you can get connection object from `_get_db()` method: ``` from mongoengine import connect from mongoengine.connection import _get_db connect('test') db = _get_db() db.connection.drop_...
Python string splitting
15,886,857
2
2013-04-08T19:01:31Z
15,886,925
8
2013-04-08T19:05:25Z
[ "python", "string", "hex" ]
I need to take a hex pair, such as `7A` and break it into `7` and `A` as separate variables for further manipulation. What would be the proper method to go about splitting this string, as I'm not trying to remove any characters, and I don't have any delimiters?
You can use [list](http://www.tutorialspoint.com/python/python_lists.htm): `list('7A')` which will return a list containing 7 and A: ``` ['7', 'A'] #Note that the single quote will not appear when you print the content :) ``` (`list('7A')[0]` contains 7 and `list('7A')[1]` contains A) Or by: ``` [x for x in '7A'] ...
Getting exception details in Python
15,887,038
6
2013-04-08T19:12:52Z
15,890,953
10
2013-04-08T23:44:20Z
[ "python", "exception", "error-handling", "python-3.3" ]
I have to open & write to about 10 different files all within the same loop. e.g: ``` for i in range(0,10): try: a=5 file1 = open("file1.txt",'w+') file2 = open("file2.txt",'w+') #... etc print(str(a),file=file1) print(str(a)+"hi",file=file2) # ... etc e...
You can use [`sys.exc_info`](http://docs.python.org/3/library/sys.html#sys.exc_info) to get information about the exception currently being handled, including the exception object itself. An `IOError` exception contains all of the information you need, including the filename, the errno, and a string describing the erro...
What is `scipy.i`?
15,887,538
7
2013-04-08T19:43:50Z
15,887,776
10
2013-04-08T19:55:45Z
[ "python", "scipy" ]
Out of random keyboard bashing, I ended up noticing that there is a variable in `SciPy` called `i`, which is assigned to the string `'6'`. (May be different on other machines?) I tried using built-in help functions, but there is nothing assigned to `scipy.i` as it only refers to a string. I also searched the docs and...
Oh, this is cute. From the scipy `__init__.py`: ``` # Emit a warning if numpy is too old majver, minver = [float(i) for i in _num.version.version.split('.')[:2]] ``` In Python 2, list comprehensions "leak" their loop variables into the enclosing scope. And thus: ``` >>> import numpy as _num >>> _num.version.version ...
Converting a one-item list to an integer
15,887,885
4
2013-04-08T20:01:45Z
15,887,903
9
2013-04-08T20:03:13Z
[ "python" ]
I've been asked to accept a list of integers (x), add the first value and the last value in the list, and then return an integer with the sum. I've used the following code to do that, but the problem I have is that when I try to evaluate the sum it's actually a one-item list instead of an integer. I've tried to cast it...
# Use indexes You're slicing the list, which return lists. Here, you should use indexes instead: ``` firstDigit = x[0] lastDigit = x[-1] ``` --- # Why is slicing wrong for you: When you do `x[0:1]`, you're taking the **list of items** from the beginning of the list to the first interval. ``` item0, item1, item2,...
Multiprocess Daemon Not Terminating on Parent Exit
15,887,994
10
2013-04-08T20:08:00Z
15,888,236
8
2013-04-08T20:21:32Z
[ "python", "multiprocessing" ]
I have a Python 2.7 multiprocessing Process which will not exit on parent process exit. I've set the daemon flag which should force it to exit on parent death. The docs state that: "When a process exits, it attempts to terminate all of its daemonic child processes." ``` p = Process(target=_serverLaunchHelper, args=ar...
> When a process exits, it attempts to terminate all of its daemonic child processes. The key word here is "attempts". Also, "exits". Depending on your platform and implementation, it may be that the only way to get daemonic child processes terminated is to do so explicitly. If the parent process exits normally, it g...
Is it possible to insert a row at an arbitrary position in a dataframe using pandas?
15,888,648
11
2013-04-08T20:45:01Z
15,889,056
11
2013-04-08T21:10:49Z
[ "python", "pandas" ]
I have a DataFrame object similar to this one: ``` onset length 1 2.215 1.3 2 23.107 1.3 3 41.815 1.3 4 61.606 1.3 ... ``` What I would like to do is insert a row at a position specified by some index value and update the following indices accordingly. E.g.: ``` onset ...
You could slice and use concat to get what you want. ``` line = DataFrame({"onset": 30.0, "length": 1.3}, index=[3]) df2 = concat([df.ix[:2], line, df.ix[3:]]).reset_index(drop=True) ``` This will produce the dataframe in your example output. As far as I'm aware, concat is the best method to achieve an insert type op...
How to find the cumulative sum of numbers in a list?
15,889,131
19
2013-04-08T21:15:02Z
15,889,203
35
2013-04-08T21:19:42Z
[ "python", "list", "indexing", "numbers", "sum" ]
``` time_interval=[4,6,12] ``` I want to sum up the numbers like `[4+0, 4+6, 4+6+12]` in order to get the list `t=[4,10,22]`. I tried: ``` x=0 for i in (time_interval): t1=time_interval[0] t2=time_interval[1]+t1 t3=time_interval[2]+t2 print(t1,t2,t3) 4 10 22 4 10 22 4 10 22 ```
In Python 2 you can define your own generator function like this: ``` def accumu(lis): total = 0 for x in lis: total += x yield total In [4]: list(accumu([4,6,12])) Out[4]: [4, 10, 22] ``` And in Python 3.2+ you can use [`itertools.accumulate()`](http://docs.python.org/3/library/itertools.htm...
How to find the cumulative sum of numbers in a list?
15,889,131
19
2013-04-08T21:15:02Z
15,889,366
39
2013-04-08T21:31:07Z
[ "python", "list", "indexing", "numbers", "sum" ]
``` time_interval=[4,6,12] ``` I want to sum up the numbers like `[4+0, 4+6, 4+6+12]` in order to get the list `t=[4,10,22]`. I tried: ``` x=0 for i in (time_interval): t1=time_interval[0] t2=time_interval[1]+t1 t3=time_interval[2]+t2 print(t1,t2,t3) 4 10 22 4 10 22 4 10 22 ```
If you're doing much numerical work with arrays like this, I'd suggest [`numpy`](https://docs.scipy.org/doc/numpy/user/whatisnumpy.html), which comes with a cumulative sum function [`cumsum`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.cumsum.html): ``` import numpy as np a = [4,6,12] np.cumsum(a) #ar...
Creating one Django Form to save two models
15,889,794
7
2013-04-08T22:00:21Z
15,892,615
10
2013-04-09T03:08:39Z
[ "python", "django", "django-models", "django-forms" ]
I have the regular Django `User` model and a `UserDetails` model (`OneToOneField` with `User`), which serves as an extension to the `User` model. (I tried Django 1.5's feature and it was a headache with strangely horrible documentation, so I stuck with the `OneToOneField` option) So, in my quest to build a custom regi...
``` from django.forms.models import model_to_dict, fields_for_model class UserDetailsForm(ModelForm): def __init__(self, instance=None, *args, **kwargs): _fields = ('first_name', 'last_name', 'email',) _initial = model_to_dict(instance.user, _fields) if instance is not None else {} super(U...
Python: Namespaces with Module Imports
15,890,014
8
2013-04-08T22:17:28Z
15,890,156
9
2013-04-08T22:28:55Z
[ "python", "import", "module", "namespaces", "local" ]
I am learning Python and am still a beginner, although I have been studying it for about a year now. I am trying to write a module of functions which is called within a main module. Each of the functions in the called module needs the math module to run. I am wondering if there is a way to do this without importing the...
As the traceback shows, the problem isn't in `main.py`, but in `module1.py`: ``` Traceback (most recent call last): File "Z:\Python\main.py", line 10, in <module> module1.cool() File "Z:\Python\module1.py", line 3, in cool print pi NameError: global name 'pi' is not defined ``` In other words, *in `module...
ValueError: math domain error
15,890,503
27
2013-04-08T22:58:46Z
15,890,593
38
2013-04-08T23:06:46Z
[ "python", "runtime-error", "logarithm" ]
I was just testing an example from *Numerical Methods in Engineering with Python*. ``` from numpy import zeros, array from math import sin, log from newtonRaphson2 import * def f(x): f = zeros(len(x)) f[0] = sin(x[0]) + x[1]**2 + log(x[2]) - 7.0 f[1] = 3.0*x[0] + 2.0**x[1] - x[2]**3 + 1.0 f[2] = x[0] ...
Your code is doing a `log` of a negative number. That's mathematically undefined, so Python's `log` function raises an exception. Here's an example: ``` >>> from math import log >>> log(-1) Traceback (most recent call last): File "<pyshell#59>", line 1, in <module> log(-1) ValueError: math domain error ``` With...
How can you split a list every x elements and add those x amount of elements to an new list?
15,890,743
3
2013-04-08T23:19:40Z
15,890,829
9
2013-04-08T23:29:39Z
[ "python", "list", "loops", "indexing", "split" ]
I have a list of multiple integers and strings ['-200', ' 0', ' 200', ' 400', ' green', '0', '0', '200', '400', ' yellow', '200', '0', '200', '400', ' red'] I'm having difficulty separating the list every 5 elements and creating a new list with just 5 elements inside. However, i don't want 3 different lists, i just wan...
You want something like: ``` composite_list = [my_list[x:x+5] for x in range(0, len(my_list),5)] print (composite_list) ``` Output: ``` [['-200', ' 0', ' 200', ' 400', ' green'], ['0', '0', '200', '400', ' yellow'], ['200', '0', '200', '400', ' red']] ``` What do you mean by a "new" 5 elements? If you want to app...
Multiple operators between operands
15,890,745
5
2013-04-08T23:19:44Z
15,890,787
10
2013-04-08T23:23:59Z
[ "python" ]
Can someone explain why the Python interpreter (2.7.3) gives the following: ``` >>> 5 -+-+-+ 2 3 ``` Is this ever useful, and for what purpose?
You can use `dis` here to see how the expression was actually evaluated: ``` In [29]: def func(): ....: return 5 -+-+-+ 2 ....: In [30]: import dis In [31]: dis.dis(func) 2 0 LOAD_CONST 1 (5) 3 LOAD_CONST 2 (2) 6 UNARY_POSITIVE ...
Pandas: change data type of columns
15,891,038
161
2013-04-08T23:53:30Z
16,134,561
223
2013-04-21T18:15:27Z
[ "python", "pandas" ]
I want to convert a table, represented as a list of lists, into a Pandas DataFrame. As an extremely simplified example: ``` a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']] df = pd.DataFrame(a) ``` What is the best way to convert the columns to the appropriate types, in this case columns 2 and 3 into f...
How about this? ``` a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']] df = pd.DataFrame(a, columns=['one', 'two', 'three']) df Out[16]: one two three 0 a 1.2 4.2 1 b 70 0.03 2 x 5 0 df.dtypes Out[17]: one object two object three object df[['two', 'three']] = df[['tw...
Pandas: change data type of columns
15,891,038
161
2013-04-08T23:53:30Z
28,648,923
127
2015-02-21T17:37:02Z
[ "python", "pandas" ]
I want to convert a table, represented as a list of lists, into a Pandas DataFrame. As an extremely simplified example: ``` a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']] df = pd.DataFrame(a) ``` What is the best way to convert the columns to the appropriate types, in this case columns 2 and 3 into f...
You can use [`pd.to_numeric`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_numeric.html) (introduced in version 0.17) to convert a column or a Series to a numeric type. The function can also be applied over multiple columns of a DataFrame using `apply`. Importantly, the function also takes an `error...
My python function won't return or update the value
15,891,199
2
2013-04-09T00:12:42Z
15,891,223
8
2013-04-09T00:16:07Z
[ "python", "function", "return", "return-value" ]
``` def getMove(win,playerX,playerY): #Define variables. movePos = 75 moveNeg = -75 running = 1 #Run while loop constantly to update mouse's coordinates. while(running): mouseCoord = win.getMouse() mouseX = mouseCoord.getX() mouseY = mouseCoord.getY() print "Mo...
In python, integers are immutable - when you assign a new integer value to a variable, you are just making the variable point to a new integer, not changing what the old integer it pointed to's value was. (An example of a mutable object in python is the list, which you can modify and all variables pointing to that lis...
How can I check if a type is a subtype of a type in Python?
15,892,237
3
2013-04-09T02:22:59Z
15,892,265
12
2013-04-09T02:26:32Z
[ "python" ]
How can I check if a type is a subtype of a type in Python? I am not referring to instances of a type, but comparing type instances themselves. For example: ``` class A(object): ... class B(A): ... class C(object) ... # Check that instance is a subclass instance: isinstance(A(), A) --> True isinstance(B...
Maybe [issubclass](http://docs.python.org/2/library/functions.html#issubclass)? ``` >>> class A(object): pass >>> class B(A): pass >>> class C(object): pass >>> issubclass(A, A) True >>> issubclass(B, A) True >>> issubclass(C, A) False ```
python logging module is not writing anything to file
15,892,946
8
2013-04-09T03:47:21Z
15,893,388
10
2013-04-09T04:34:45Z
[ "python", "file", "logging" ]
I'm trying to write a server that logs exceptions both to the console and to a file. I pulled some code off the cookbook. Here it is: ``` logger = logging.getLogger('server_logger') logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages fh = logging.FileHandler('server.log') fh.setLevel(lo...
Try calling ``` logger.error('This should go to both console and file') ``` instead of ``` logging.error('this will go to the default logger which you have not changed the config of') ```
Wrong math with Python?
15,894,182
77
2013-04-09T05:46:40Z
15,894,199
136
2013-04-09T05:47:41Z
[ "python", "math" ]
Just starting out with Python, so this is probably my mistake, but... I'm trying out Python. I like to use it as a calculator, and I'm slowly working through some tutorials. I ran into something weird today. I wanted to find out 2013\*2013, but I wrote the wrong thing and wrote 2013\*013, and got this: ``` >>> 2013*...
Because of octal arithmetic, 013 is actually the integer 11. ``` >>> 013 11 ``` With a leading zero, `013` is interpreted as a base-8 number and 1\*81 + 3\*80 = 11. Note: this behaviour was [changed in python 3](http://docs.python.org/release/3.0.1/whatsnew/2.6.html#pep-3127-integer-literal-support-and-syntax). Here...
Wrong math with Python?
15,894,182
77
2013-04-09T05:46:40Z
15,894,264
36
2013-04-09T05:52:22Z
[ "python", "math" ]
Just starting out with Python, so this is probably my mistake, but... I'm trying out Python. I like to use it as a calculator, and I'm slowly working through some tutorials. I ran into something weird today. I wanted to find out 2013\*2013, but I wrote the wrong thing and wrote 2013\*013, and got this: ``` >>> 2013*...
`013` is an octal integer literal (equivalent to the decimal integer literal `11`), due to the leading 0. ``` >>> 2013*013 22143 >>> 2013*11 22143 >>> 2013*13 26169 ``` It is very common (certainly in most of the languages I'm familiar with) to have octal integer literals start with `0` and hexadecimal integer litera...
Wrong math with Python?
15,894,182
77
2013-04-09T05:46:40Z
15,913,517
7
2013-04-09T22:12:22Z
[ "python", "math" ]
Just starting out with Python, so this is probably my mistake, but... I'm trying out Python. I like to use it as a calculator, and I'm slowly working through some tutorials. I ran into something weird today. I wanted to find out 2013\*2013, but I wrote the wrong thing and wrote 2013\*013, and got this: ``` >>> 2013*...
Python's 'leading zero' syntax for octal literals is a common gotcha: ``` Python 2.7.3 >>> 010 8 ``` The syntax was changed in Python 3.x <http://docs.python.org/3.0/whatsnew/3.0.html#integers>
Python super() inheritance and needed arguments
15,896,265
12
2013-04-09T07:51:05Z
15,896,594
14
2013-04-09T08:09:09Z
[ "python", "inheritance" ]
Considering: ``` class Parent(object): def altered(self): print "PARENT altered()" class Child(Parent): def altered(self): print "CHILD, BEFORE PARENT altered()" super(Child, self).altered() # what are the arguments needed? Why Child and self? print "CHILD, AFTER PARENT a...
`super` figures out which is the next class in the Method Resolution Order. The two arguments you pass in are what lets it figure that out - `self` gives it the entire MRO via an attribute; the current class tells it where you are along the MRO *right now*. So what super is actually doing is basically: ``` def super(c...
How to parse Django templates for template tags
15,896,408
9
2013-04-09T07:58:13Z
15,956,318
9
2013-04-11T18:38:18Z
[ "python", "django" ]
## Situation I'm writing a checker program that checks Django templates. For example I want to check if all Django templates that use `url` template tag, use it with quotes on first parameter so that it is Django 1.5 compatible. Also I want to check that they have included `{% load url from future %}` in their templat...
You say... > I want to check if all Django templates that use url > template tag, use it with quotes on first parameter so that it is > Django 1.5 compatible. ...and... > I don't want to use regular expressions. ...because... > the result of that might become a huge spaghetti code ...but, frankly, writing a parse...
Improving error messages with pyparsing
15,897,094
10
2013-04-09T08:36:23Z
15,897,602
9
2013-04-09T08:59:22Z
[ "python", "pyparsing" ]
**Edit:** I did a first version, which Eike helped me to advance quite a bit on it. I'm now stuck to a more specific problem, which I will describe bellow. You can have a look at the original question in the [history](http://stackoverflow.com/posts/15897602/revisions) --- I'm using pyparsing to parse a small language...
Pyparsing will always have somewhat bad error messages, because it backtracks. The error message is generated in the last rule that the parser tries. The parser can't know where the error really is, it only knows that there is no matching rule. For good error messages you need a parser that gives up early. These parse...
efficient Term Document Matrix with NLTK
15,899,861
8
2013-04-09T10:46:56Z
15,932,715
11
2013-04-10T17:39:39Z
[ "python", "pandas", "nltk", "term-document-matrix" ]
I am trying to create a term document matrix with NLTK and pandas. I wrote the following function: ``` def fnDTM_Corpus(xCorpus): import pandas as pd '''to create a Term Document Matrix from a NLTK Corpus''' fd_list = [] for x in range(0, len(xCorpus.fileids())): fd_list.append(nltk.FreqDist(xC...
Thanks to Radim and Larsmans. My objective was to have a DTM like the one you get in R tm. I decided to use scikit-learn and partly inspired by [this blog entry](http://slendrmeans.wordpress.com/2012/12/28/will-it-python-machine-learning-for-hackers-chapter-4-priority-emai-ranking/). This the code I came up with. **I ...
efficient Term Document Matrix with NLTK
15,899,861
8
2013-04-09T10:46:56Z
28,727,111
13
2015-02-25T18:43:07Z
[ "python", "pandas", "nltk", "term-document-matrix" ]
I am trying to create a term document matrix with NLTK and pandas. I wrote the following function: ``` def fnDTM_Corpus(xCorpus): import pandas as pd '''to create a Term Document Matrix from a NLTK Corpus''' fd_list = [] for x in range(0, len(xCorpus.fileids())): fd_list.append(nltk.FreqDist(xC...
I know the OP wanted to create a tdm in NLTK, but the `textmining` package (`pip install textmining`) makes it dead simple: ``` import textmining def termdocumentmatrix_example(): # Create some very short sample documents doc1 = 'John and Bob are brothers.' doc2 = 'John went to the store. The store was cl...
Python Request Post with param data
15,900,338
33
2013-04-09T11:12:56Z
15,900,453
69
2013-04-09T11:19:20Z
[ "python", "python-requests" ]
This is the raw request for an API call: ``` POST http://192.168.3.45:8080/api/v2/event/log?sessionKey=b299d17b896417a7b18f46544d40adb734240cc2&format=json HTTP/1.1 Accept-Encoding: gzip,deflate Content-Type: application/json Content-Length: 86 Host: 192.168.3.45:8080 Connection: Keep-Alive User-Agent: Apache-HttpClie...
`params` is for GET-style URL parameters, `data` is for POST-style body information. It is perfectly legal to provide *both* types of information in a request, and your request does so too, but you encoded the URL parameters into the URL already. Your raw post contains *JSON* data though, you better use the `json` mod...
Include specific special-methods in sphinx
15,903,577
12
2013-04-09T13:41:02Z
16,399,554
10
2013-05-06T13:12:57Z
[ "python", "python-sphinx" ]
I have a bunch of classes which use "special-methods": ``` class Foo(object): "Foo docstring" attr1 = "Attribute!" #: first attribute attr2 = "Another Attribute!" #: second attribute def __init__(self): self.x = 12 def say_hello(self): """ say_hello(self) -> None Issue a ...
You can add: ``` :special-members: :exclude-members: __dict__,__weakref__ ``` To the `.rst` file in order to show special members, except `__dict__` and `__weakref__`
Running selenium browser on server (Flask/Python/Heroku)
15,904,035
10
2013-04-09T14:01:51Z
18,603,161
8
2013-09-03T23:41:23Z
[ "python", "heroku", "selenium", "web-scraping", "flask" ]
I am scraping some websites that seem to have pretty good protection against it. The only way I can get it to work is to use Selenium to load the page and then scrape stuff from that. Currently this works on my local computer (a firefox windows opens and closed when I access my page and it's HTML is processed further ...
Heroku, wonderful as it is, has a major limitation in that one cannot use custom software or in many cases, libraries. In providing an easy to use, centrally-controlled, managed stack, Heroku strips their servers down to prevent other usage. What this boils down to is there is no Xorg on a Heroku dyno. Lack of Xorg an...
matplotlib bar graph black - how do I remove bar borders
15,904,042
28
2013-04-09T14:02:08Z
15,904,277
50
2013-04-09T14:11:31Z
[ "python", "graph", "matplotlib", "border" ]
I'm using pyplot.bar but I'm plotting so many points that the color of the bars is always black. This is because the borders of the bars are black and there are so many of them that they are all squished together so that all you see is the borders (black). Is there a way to remove the bar borders so that I can see the ...
Set the `edgecolor` to `"none"`: `bar(..., edgecolor = "none")`
Speed up python loop
15,904,282
5
2013-04-09T14:11:50Z
15,904,329
12
2013-04-09T14:13:43Z
[ "python", "performance", "for-loop" ]
I'm trying to speed up the following python code: ``` for j in range(4,len(var_s),3): mag_list.append(float(var_s[j])) mag_list = [value for value in mag_list if value != 99.] med_mag = np.median(mag_list) ``` Is there a nice way to combine the two for-loops into one? This way, it is really slow. What I need is t...
You could probably try: ``` mag_list = [value for value in var_s[4::3] if value != 99.] ``` depending on `var_s`, you might do better using `itertools.islice(var_s,4,None,3)`, but that would definitely need to be timed to know. Perhaps you'd do even better if you stuck with numpy the whole way: ``` vs = np.array(va...
How to add a header to a csv file in Python?
15,907,200
6
2013-04-09T16:17:05Z
15,907,232
10
2013-04-09T16:18:52Z
[ "python", "csv" ]
I've tried many solutions to add a header to my csv file, but nothing's working properly. Here they are : 1. I used the writerow method, but my data are overwriting the first row. 2. I used the DictWriter method, but I don't know how to fill it correctly. Here is my code: ``` csv = csv.DictWriter(open(directory...
All you need to do is call [`DictWriter.writeheader()`](http://docs.python.org/2/library/csv.html#csv.DictWriter.writeheader) without arguments: ``` with open(os.path.join(directory, 'csv.csv'), 'wb') as csvfile: writer = csv.DictWriter(csvfile, fieldnames = ["stuff1", "stuff2", "stuff3"], delimiter = ';') wri...
lxml: insert tag at a given position
15,909,647
5
2013-04-09T18:25:36Z
15,918,818
8
2013-04-10T06:47:14Z
[ "python", "lxml" ]
I have an xml file, similar to this: ``` <tag attrib1='I'> <subtag1 subattrib1='1'> <subtext>text1</subtext> </subtag1> <subtag3 subattrib3='3'> <subtext>text3</subtext> </subtag3> </tag> ``` I would like to insert a new subElement, so the result would be something like this ``` <tag attrib1='I'> <...
You can use the [addnext()](http://lxml.de/api/lxml.etree._Element-class.html#addnext) method: ``` from lxml import etree XML= """ <tag attrib1='I'> <subtag1 subattrib1='1'> <subtext>text1</subtext> </subtag1> <subtag3 subattrib3='3'> <subtext>text3</subtext> </subtag3> </tag>""" parser = etree.XMLPa...
Use mock MongoDB server for unit test
15,915,031
15
2013-04-10T00:42:02Z
16,017,141
11
2013-04-15T14:00:03Z
[ "python", "mongodb", "python-2.7", "pymongo" ]
I have to implement nosetests for Python code using a MongoDB store. Is there any python library which permits me initializing a mock in-memory MongoDB server? I am using continuous integration. So, I want my tests to be independent of any MongoDB running server. Is there a way to mock mongoDM Server in memory to test...
You could try: <https://github.com/vmalloc/mongomock>, which aims to be a small library for mocking pymongo collection objects for testing purposes. However, I'm not sure that the cost of just running mongodb would be prohibitive compared to ensuring some mocking library is feature complete.
What was Blender created in?
15,916,324
5
2013-04-10T03:19:29Z
15,916,574
9
2013-04-10T03:48:09Z
[ "python", "opengl", "blender", "cad" ]
Does Blender use OpenGl or DirectX? Or is it all done from scratch?
You can look at the [blender source code](http://www.blender.org/download/source-code/) and see it's written in both python and C/C++ -- less python, more C. OpenGL is referenced frequently in the code, while DirectX only rarely. So there ya go.
How to return the highest value from a multi dimensional array?
15,917,076
6
2013-04-10T04:40:29Z
15,917,132
8
2013-04-10T04:46:07Z
[ "python", "numpy" ]
Say I have a multi dimensional array like the following: ``` [ [.1, .2, .9], [.3, .4, .5], [.2, .4, .8] ] ``` What would be the best\* way to return a single dimension array that contains the highest value from each sub-array (`[.9,.5,.8]`)? I assume I could do it manually doing something like below: ``` ne...
`map` with `max` is cleaner IMO. ``` >>> arr = [ ... [.1, .2, .9], ... [.3, .4, .5], ... [.2, .4, .8] ... ] >>> map(max, arr) [0.9, 0.5, 0.8] ``` [map documentation](http://docs.python.org/2/library/functions.html#map).
Python file objects, closing, and destructors
15,917,502
6
2013-04-10T05:17:40Z
15,968,516
14
2013-04-12T10:05:23Z
[ "python", "file-io", "destructor" ]
The description of `tempfile.NamedTemporaryFile()` says: > If *delete* is true (the default), the file is deleted as soon as it > is closed. In some circumstances, this means that the file is not deleted after the Python interpreter ends. For example, when running the following test under `py.test`, the temporary fil...
On Windows, NamedTemporaryFile uses a Windows-specific extension (os.O\_TEMPORARY) to ensure that the file is deleted when it is closed. This probably also works if the process is killed in any way. However there is no obvious equivalent on POSIX, most likely because on POSIX you can simply delete files that are still ...
How can I assign/update subset of tensor shared variable in Theano?
15,917,849
21
2013-04-10T05:42:09Z
19,216,429
27
2013-10-07T02:56:48Z
[ "python", "numpy", "theano" ]
When compiling a function in `theano`, a shared variable(say X) can be updated by specifying `updates=[(X, new_value)]`. Now I am trying to update only subset of a shared variable: ``` from theano import tensor as T from theano import function import numpy X = T.shared(numpy.array([0,1,2,3,4])) Y = T.vector() f = fun...
Use [set\_subtensor](http://deeplearning.net/software/theano/library/tensor/basic.html#theano.tensor.set_subtensor) or [inc\_subtensor](http://deeplearning.net/software/theano/library/tensor/basic.html#theano.tensor.inc_subtensor): ``` from theano import tensor as T from theano import function, shared import numpy X ...
Python detect string byte encoding
15,918,314
13
2013-04-10T06:14:47Z
15,918,519
17
2013-04-10T06:27:35Z
[ "python", "string", "unicode", "encoding", "byte" ]
I've got about 1000 filenames read by os.listdir() some of them are encoded 'utf-8' and some are 'cp1252'. I want to decode all of them to unicode for further processing in my script. Is there a way to get the source encoding to correctly decode into unicode? Example: ``` for item in os.listdir(rootPath): #Conv...
if your files either in `cp1252` and `utf-8`, then there is an easy way. ``` import logging def force_decode(string, codecs=['utf8', 'cp1252']): for i in codecs: try: return string.decode(i) except: pass logging.warn("cannot decode url %s" % ([string])) for item in os....
how to insert jpeg image into excel sheet in unix
15,920,989
3
2013-04-10T08:42:05Z
15,922,887
7
2013-04-10T10:08:20Z
[ "python", "excel", "unix", "xlwt" ]
I am able to insert bmp images using `insert_bitmap` command of the `xlwt` module in python using the following code: ``` import xlwt from PIL import Image book = xlwt.Workbook() sheet3 = book.add_sheet('diagrams') Image.open('violations.png').convert("RGB").save('violations.bmp') sheet3.insert_bitmap('vio...
From looking at the code it looks like xlwt only supports 24bit bitmap images. The [XlsxWriter](https://xlsxwriter.readthedocs.org/en/latest/index.html) Python module can insert PNG images (or JPEG or Bitmap). Here is an example: ``` from xlsxwriter.workbook import Workbook # Create an new Excel file and add a work...
How to create a system tray popup message with python? (Windows)
15,921,203
19
2013-04-10T08:51:59Z
15,921,588
19
2013-04-10T09:10:44Z
[ "python", "popup", "system-tray" ]
I'd like to know how to create a system tray popup message with python. I have seen those in lots of softaware, but yet difficult to find resources to do it easily with any language. Anyone knows some library for doing this in Python?
With the help of the [`pywin32` library](https://sourceforge.net/projects/pywin32/) you can use the following example code I found [here](https://gist.github.com/BoppreH/4000505): ``` from win32api import * from win32gui import * import win32con import sys, os import struct import time class WindowsBalloonTip: de...
Creating own POS Tagger
15,921,417
4
2013-04-10T09:01:50Z
15,983,182
13
2013-04-13T01:24:19Z
[ "java", "python", "c", "nlp", "stanford-nlp" ]
I have found the [Stanford POS Tagger](http://nlp.stanford.edu/software/tagger.shtml) pretty good, but somehow I found myself in need of creating my own POS tagger. For the last two weeks, I am rambling here and there, on whether to start from parsing tree, or once we have a pos tagger than we can parse tree, using ug...
It depends on what your ultimate goal is. **If the goal is to perform syntax analysis,** i.e. to determine the subject, the predicate, its arguments, its modifiers etc., and then to possibly even perform a semantic analysis, then you should not worry about the POS tagger. Instead you should first look at the various m...
ValueError: object too deep for desired array while using convolution
15,923,081
4
2013-04-10T10:17:51Z
15,923,228
17
2013-04-10T10:23:33Z
[ "python", "numpy" ]
Hi I'm trying to do this: ``` h =[0.2,0.2,0.2,0.2,0.2]; Y = np.convolve(Y, h, "same") ``` Y looks like this: ![screenshot](http://i.stack.imgur.com/bVYmZ.jpg) While doing this I get this error : > ValueError: object too deep for desired array Why is this ? My guess is because somehow the convolve function does ...
The `Y` array in your screenshot is not a 1D array, it's a 2D array with 300 rows and 1 column, as indicated by its `shape` being `(300, 1)`. To convert it to a 1D array, slice it as `Y[:, 0]` or reshape it with`np.reshape(a, len(a))`.
Python Dictionary vs If Statement Speed
15,923,766
5
2013-04-10T10:50:18Z
15,925,086
7
2013-04-10T11:53:36Z
[ "python", "if-statement", "dictionary", "switch-statement" ]
I have found a few links talking about switch cases being faster in c++ than if else because it can be optimized in compilation. I then found some suggestions people had that using a dictionary may be faster than an If statement. However, most of the conversation are about someones work end just end up discussing that ...
> However, most of the conversation are about someones work end just end > up discussing that they should optimize other parts of the code first > and it wont matter unless your doing millions of if else. Can anyone > explain why this is? Generally, you should only bother to optimize code if you really need to, i.e. i...
Random row selection in Pandas dataframe
15,923,826
20
2013-04-10T10:52:47Z
15,923,878
21
2013-04-10T10:55:57Z
[ "python", "pandas" ]
Is there a way to select random rows from a DataFrame in Pandas. In R, using the car package, there is a useful function `some(x, n)` which is similar to head but selects, in this example, 10 rows at random from x. I have also looked at the slicing documentation and there seems to be nothing equivalent.
Something like this? ``` import random def some(x, n): return x.ix[random.sample(x.index, n)] ```
Random row selection in Pandas dataframe
15,923,826
20
2013-04-10T10:52:47Z
32,606,673
27
2015-09-16T10:57:30Z
[ "python", "pandas" ]
Is there a way to select random rows from a DataFrame in Pandas. In R, using the car package, there is a useful function `some(x, n)` which is similar to head but selects, in this example, 10 rows at random from x. I have also looked at the slicing documentation and there seems to be nothing equivalent.
With pandas version `0.16.x`, there is now a `DataFrame.sample` [method built-in](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sample.html): ``` import pandas df = pandas.DataFrame(data) # Randomly sample 70% of your dataframe df_0.7 = df.sample(frac=0.7) # Randomly sample 7 elements from ...
Arcpy: Dictionary syntax error "can't assign to function call"
15,924,150
3
2013-04-10T11:07:39Z
15,925,201
7
2013-04-10T11:59:06Z
[ "python", "arcpy" ]
I'm trying to find the maximum value of "CrudeRate" and its associated "State\_name" using the following code: ``` import arcpy arcpy.env.workspace = "C:\\" shp = r"C:\\USCancer2000.dbf" rows = arcpy.SearchCursor(shp) CrudeRate= "CrudeRate" State_name= "State_name" out_dict = {} for row in rows: for C in CrudeRa...
You need to use brackets instead of parentesis when assigning a dict value. ``` out_dict[C] = max(lst) ```
Unknown format code 'f' for object of type 'unicode'
15,924,879
10
2013-04-10T11:43:37Z
15,925,170
9
2013-04-10T11:57:23Z
[ "python", "django" ]
can someone tell me what is wrong with this code... ``` def format_money_value(num): return u'{0:.2f}'.format(num) ``` It gives me the following error: ``` Unknown format code 'f' for object of type 'unicode' ``` I'm running Django 1.5 Thank you
In your case `num` is a unicode string, which does not support the `f` format modifier: ``` >>> '{0:.2f}'.format(u"5.0") Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: Unknown format code 'f' for object of type 'unicode' ``` You can fix the error making the conversion to `float` ...
Opposite of numpy.unwrap
15,927,755
12
2013-04-10T13:49:48Z
15,927,914
14
2013-04-10T13:56:43Z
[ "python", "numpy" ]
In Python numpy, there is an [unwrap](http://docs.scipy.org/doc/numpy/reference/generated/numpy.unwrap.html) function that: > Unwrap radian phase p by changing absolute jumps greater than discont > to their 2\*pi complement along the given axis. Now, I'd like to do the opposite function. How can I *wrap* an array of ...
``` phases = ( phases + np.pi) % (2 * np.pi ) - np.pi ```
Opposite of numpy.unwrap
15,927,755
12
2013-04-10T13:49:48Z
29,237,626
7
2015-03-24T16:11:57Z
[ "python", "numpy" ]
In Python numpy, there is an [unwrap](http://docs.scipy.org/doc/numpy/reference/generated/numpy.unwrap.html) function that: > Unwrap radian phase p by changing absolute jumps greater than discont > to their 2\*pi complement along the given axis. Now, I'd like to do the opposite function. How can I *wrap* an array of ...
``` import numpy as np phases = np.arctan2(np.sin(phases), np.cos(phases)) ``` This works because sin(phases)/cos(phases) == tan(phases). We get back phases (modulo 2π) by using the inverse-tangent function. Mathematically, the inverse-tangent function is multivalued, so in programming languages it is usually defined...
Matplotlib - How to make the marker face color transparent without making the line transparent
15,928,539
21
2013-04-10T14:22:05Z
15,931,575
19
2013-04-10T16:37:17Z
[ "python", "matplotlib" ]
I know how to set the transparency of a line in matplotlib. For example, the following code makes the line and the markers transparent. ``` import numpy as np import matplotlib.pyplot as plt vec = np.random.uniform(0, 10, 50) f = plt.figure(1) ax = f.add_subplot(111) ax.plot(vec, color='#999999', marker='s', alpha=0....
## See @Pelson's answer below for the correct way to do this with one line. You can do this in a hacky way by sticky taping together two independent `Line2D` objects. ``` th = np.linspace(0, 2 * np.pi, 64) y = np.sin(th) ax = plt.gca() lin, = ax.plot(th, y, lw=5) mark, = ax.plot(th, y, marker='o', alpha=.5, ms=10) ...
Matplotlib - How to make the marker face color transparent without making the line transparent
15,928,539
21
2013-04-10T14:22:05Z
15,936,516
18
2013-04-10T21:12:27Z
[ "python", "matplotlib" ]
I know how to set the transparency of a line in matplotlib. For example, the following code makes the line and the markers transparent. ``` import numpy as np import matplotlib.pyplot as plt vec = np.random.uniform(0, 10, 50) f = plt.figure(1) ax = f.add_subplot(111) ax.plot(vec, color='#999999', marker='s', alpha=0....
After reading the source code of `matplotlib.line`, it turns out there is a code path (at least in Agg, but probably all backends) which allows you to do this. Whether this was ever intentional behaviour, I'm not sure, but it certainly works at the moment. The key is *not* to define an alpha value for the line, but to ...
numerical ODE solving in python
15,928,750
8
2013-04-10T14:31:39Z
15,929,381
15
2013-04-10T14:56:33Z
[ "python", "plot", "numerical-methods", "differential-equations" ]
I am new to Python so at this moment in time, I can only very basic problems. How do I numerically solve an ODE in Python? Consider ![equation to solve](http://i.stack.imgur.com/ACR45.gif) ``` \ddot{u}(\phi) = -u + \sqrt{u} ``` with the following conditions ``` u(0) = 1.49907 ``` and ``` \dot{u}(0) = 0 ``` wit...
``` import scipy.integrate as integrate import matplotlib.pyplot as plt import numpy as np pi = np.pi sqrt = np.sqrt cos = np.cos sin = np.sin def deriv_z(z, phi): u, udot = z return [udot, -u + sqrt(u)] phi = np.linspace(0, 7.0*pi, 2000) zinit = [1.49907, 0] z = integrate.odeint(deriv_z, zinit, phi) u, udot...
how to run an exe file with the arguments using python
15,928,956
4
2013-04-10T14:40:12Z
15,929,730
7
2013-04-10T15:10:11Z
[ "python", "windows", "python-2.7", "subprocess" ]
Suppose I have a file `RegressionSystem.exe`. I want to execute this executable with a `-config` argument. The commandline should be like: ``` RegressionSystem.exe -config filename ``` I have tried like: ``` regression_exe_path = os.path.join(get_path_for_regression,'Debug','RegressionSystem.exe') config = os.path.j...
You can also use [`subprocess.call()`](http://docs.python.org/2/library/subprocess.html#using-the-subprocess-module) if you want. For example, ``` import subprocess FNULL = open(os.devnull, 'w') #use this if you want to suppress output to stdout from the subprocess filename = "my_file.dat" args = "RegressionSystem....
DNS query using Google App Engine socket
15,929,065
8
2013-04-10T14:44:52Z
15,943,383
7
2013-04-11T07:51:26Z
[ "python", "google-app-engine", "dns" ]
I'm trying to use the new socket support for Google App Engine in order to perform some DNS queries. I'm using [dnspython](http://www.dnspython.org/) to perform the query, and the code works fine outside GAE. The code is the following: ``` class DnsQuery(webapp2.RequestHandler): def get(self): domain = s...
This is a bug and will be fixed ASAP. As a workaround, pass in the source='' argument to dns.resolver.query. tcp=True is not necessary.
Writing a tokenizer in Python
15,929,233
14
2013-04-10T14:51:00Z
16,133,011
9
2013-04-21T15:47:26Z
[ "python", "regex", "token", "tokenize", "nltk" ]
I want to design a custom tokenizer module in Python that lets users specify what tokenizer(s) to use for the input. For instance, consider the following input: > Q: What is a good way to achieve this? A: I am not so sure. I think I > will use Python. I want to be able to provide [NLTK's sentence tokenization](http:/...
As tokenizing is easy in Python, I'm wondering what your module is planned to provide. I mean when starting a piece of software a good design rather comes from thinking about the usage scenarios than considering data structures first. Your examples for expected output are a bit confusing. I assume you want the tokeniz...
Need help getting started with Boost.Python
15,929,566
9
2013-04-10T15:03:44Z
16,040,822
11
2013-04-16T15:19:16Z
[ "c++", "python", "boost", "boost-python" ]
I'm trying to build my first Boost.Python example. ``` #include <iostream> #include <boost/python.hpp> using namespace boost::python; class Hello { public: std::string greet() { std::cout << "Hello World" << std::endl; } }; BOOST_PYTHON_MODULE(hello) { class_<Hello>("Hello") .def("gre...
When this particular linker error occurs, it is often the result of the application building against one version of Python, such as Python 3.x header files, while the `boost_python` library was built against a difference version, such as 2.x. In [`boost/python/module_init.hpp`](http://svn.boost.org/svn/boost/tags/rele...
Querying ElasticSearch with Python Requests not working fine
15,930,235
7
2013-04-10T15:32:25Z
15,982,559
14
2013-04-12T23:44:46Z
[ "python", "elasticsearch", "python-requests" ]
I'm trying to do full-text search on a mongodb db with the Elastic Search engine but I ran into a problem: no matters what search term I provide(or if I use query1 or query2), the engine always returns the same results. I think the problem is in the way I make the requests, but I don't know how to solve it. Here is th...
The `params` parameter is not for data being sent. If you're trying to send data to the server you should specifically be using the data parameter. If you're trying to send query parameters, then you shouldn't be JSON-encoding them and just give it to params as a dict. I suspect your first request should be the follow...
Python 'AttributeError: 'function' object has no attribute 'min''
15,930,454
3
2013-04-10T15:42:48Z
15,930,701
8
2013-04-10T15:55:04Z
[ "python", "numpy", "attributes", "attributeerror" ]
Firstly, apologies for how obvious these two questions seem to be; I'm very very new to this and don't have a clue what I'm doing. I'm trying to write something to apply the Scipy function for spline interpolation to an array of values. My code currently looks like this: ``` import numpy as np import scipy as sp from...
If this line ``` new_x = np.linspace(x.min(), x.max(), new_length) ``` is generating the error message ``` AttributeError: 'function' object has no attribute 'min' ``` then `x` is a function, and functions (in general) don't have `min` attributes, so you can't call `some_function.min()`. What is `x`? In your code, ...
How to install the Python development headers on Mac OS X?
15,931,331
18
2013-04-10T16:24:55Z
21,772,920
10
2014-02-14T07:07:32Z
[ "python", "osx", "header", "homebrew" ]
For a project using Boost.Python (see [this other question](http://stackoverflow.com/questions/15929566/need-help-getting-started-with-boost-python)) I need the Python development headers containing e.g. `pyconfig.h`. These are apparently missing from my system. I've installed Python 3 via Homebrew: ``` cls ~ $ brew ...
The latest Python 3 formula links a program called `python3-config`. You can use it to find the headers like this: `python3-config --include` On my machine, this outputs: ``` -I/usr/local/Cellar/python3/3.3.4/Frameworks/Python.framework/Versions/3.3/include/python3.3m -I/usr/local/Cellar/python3/3.3.4/Frameworks/Pyt...
How do I catch a numpy warning like it's an exception (not just for testing)?
15,933,741
57
2013-04-10T18:36:21Z
15,934,081
78
2013-04-10T18:53:50Z
[ "python", "exception", "numpy", "warnings", "divide-by-zero" ]
I have to make a Lagrange polynomial in Python for a project I'm doing. I'm doing a barycentric style one to avoid using an explicit for-loop as opposed to a Newton's divided difference style one. The problem I have is that I need to catch a division by zero, but Python (or maybe numpy) just makes it a warning instead ...
It seems that your configuration is using the `print` option for [`numpy.seterr`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.seterr.html): ``` >>> import numpy as np >>> np.array([1])/0 #'warn' mode __main__:1: RuntimeWarning: divide by zero encountered in divide array([0]) >>> np.seterr(all='print') ...
SQLAlchemy - can you add custom methods to the query object?
15,936,111
15
2013-04-10T20:50:21Z
15,962,062
28
2013-04-12T02:22:59Z
[ "python", "sqlalchemy" ]
Is there a way to create custom methods to the query object so you can do something like this? ``` User.query.all_active() ``` Where `all_active()` is essentially `.filter(User.is_active == True)` And be able to filter off of it? ``` User.query.all_active().filter(User.age == 30) ```
You can subclass the base `Query` class to add your own methods: ``` from sqlalchemy.orm import Query class MyQuery(Query): def all_active(self): return self.filter(User.is_active == True) ``` You then tell SQLAlchemy to use this new query class when you create the session ([docs here](http://docs.sqlalchemy....