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
Truncate Python DateTime
5,476,065
109
2011-03-29T16:52:20Z
5,476,114
21
2011-03-29T16:55:34Z
[ "python", "datetime" ]
What is a classy way to way truncate a python datetime object? In this particular case, to the day. So basically setting hour, minute, seconds, and microseconds to 0. I would like the output to also be a datetime object, not a string.
Use a `date` not a `datetime` if you dont care about the time. ``` >>> now = datetime.now() >>> now.date() datetime.date(2011, 3, 29) ``` You can update a datetime like this: ``` >>> now.replace(minute=0, hour=0, second=0, microsecond=0) datetime.datetime(2011, 3, 29, 0, 0) ```
Truncate Python DateTime
5,476,065
109
2011-03-29T16:52:20Z
5,476,166
177
2011-03-29T17:00:58Z
[ "python", "datetime" ]
What is a classy way to way truncate a python datetime object? In this particular case, to the day. So basically setting hour, minute, seconds, and microseconds to 0. I would like the output to also be a datetime object, not a string.
I think this is what you're looking for... ``` >>> dt = datetime.datetime.now() >>> dt = dt.replace(hour=0, minute=0, second=0, microsecond=0) # Returns a copy >>> dt datetime.datetime(2011, 3, 29, 0, 0) ``` But if you really don't care about the time aspect of things, then you should really only be passing around `d...
Truncate Python DateTime
5,476,065
109
2011-03-29T16:52:20Z
5,476,268
12
2011-03-29T17:10:07Z
[ "python", "datetime" ]
What is a classy way to way truncate a python datetime object? In this particular case, to the day. So basically setting hour, minute, seconds, and microseconds to 0. I would like the output to also be a datetime object, not a string.
You cannot truncate a datetime object because [it is immutable](http://docs.python.org/library/datetime.html#available-types). However, here is one way to construct a new datetime with 0 hour, minute, second, and microsecond fields, without throwing away the original date or tzinfo: ``` now.replace(hour=0, minute=0, ...
Truncate Python DateTime
5,476,065
109
2011-03-29T16:52:20Z
31,757,606
9
2015-08-01T02:29:24Z
[ "python", "datetime" ]
What is a classy way to way truncate a python datetime object? In this particular case, to the day. So basically setting hour, minute, seconds, and microseconds to 0. I would like the output to also be a datetime object, not a string.
## Four years later: another way, avoiding `replace` I know the accepted answer from four years ago works, but this seems a tad lighter than using `replace`: ``` dt = datetime.date.today() dt = datetime.datetime(dt.year, dt.month, dt.day) ``` **Notes** * When you create a `datetime` object without passing time prop...
Where can I inspect Python's math functions?
5,476,189
17
2011-03-29T17:03:09Z
5,476,394
8
2011-03-29T17:20:22Z
[ "python", "math", "sqrt" ]
I would like to look at the way Python does computes square roots, so I tried to find the definition for `math.sqrt()`, but I can't find it anywhere. I have looked in `_math.c`, `mathmodule.c`, and elsewhere. I know that python uses C's math functions, but are these somewhere in the Python distribution, or are they li...
It depends on the implementation. CPython is using math functions from the standard C library. Jython is most likely using Java's math methods. And so on. In fact, Python has nothing to do with the actual implementation of math functions. Those are more related to IEEE 754 which is used almost exclusively to represent...
How can I get around declaring an unused variable in a for loop?
5,477,134
37
2011-03-29T18:26:00Z
5,477,153
60
2011-03-29T18:27:43Z
[ "python" ]
If I have a list comprehension (for example) like this: ``` ['' for x in myList] ``` Effectively making a new list that has an empty string for every element in a list, I never use the `x`. Is there a cleaner way of writing this so I don't have to declare the unused `x` variable?
`_` is a standard placeholder name for ignored members in a for-loop and tuple assignment, e.g. ``` ['' for _ in myList] [a+d for a, _, _, d, _ in fiveTuples] ``` BTW your list could be written without list comprehension (assuming you want to make a list of immutable members like strings, integers etc.). ``` [''] *...
How can I get around declaring an unused variable in a for loop?
5,477,134
37
2011-03-29T18:26:00Z
5,477,160
12
2011-03-29T18:28:33Z
[ "python" ]
If I have a list comprehension (for example) like this: ``` ['' for x in myList] ``` Effectively making a new list that has an empty string for every element in a list, I never use the `x`. Is there a cleaner way of writing this so I don't have to declare the unused `x` variable?
No. As the Zen puts it: Special cases aren't special enough to break the rules. The special case being loops not using the items of the thing being iterated and the rule being that there's a "target" to unpack to. You can, however, use `_` as variable name, which is usually understood as "intentionally unused" (even P...
Chi square numpy.polyfit (numpy)
5,477,359
7
2011-03-29T18:43:49Z
5,484,165
15
2011-03-30T08:57:29Z
[ "python", "numpy", "least-squares" ]
Could someone explain how to get Chi^2/doF using numpy.polyfit?
Assume you have some data points ``` x = numpy.array([0.0, 1.0, 2.0, 3.0]) y = numpy.array([3.6, 1.3, 0.2, 0.9]) ``` To fit a parabola to those points, use `numpy.polyfit()`: ``` p = numpy.polyfit(x, y, 2) ``` To get the chi-squared value for this fit, evaluate the polynomial at the `x` values of your data points, ...
django 1.3 UserProfile matching query does not exist
5,477,925
5
2011-03-29T19:37:23Z
5,478,127
7
2011-03-29T19:53:23Z
[ "python", "django", "authentication", "user" ]
I have a small problem with User model, the model looks like this: ``` #! -*- coding: utf-8 -*- from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): url = models.URLField(max_length = 70, blank = True, verbose_name = 'WWW') home_address = models.TextFi...
Are you sure that UserProfile object for that user exists? Django doesn't automatically create it for you. What you probably want is this: ``` u = User.objects.get(id=1) zm, created = UserProfile.objects.get_or_create(user = u) ``` If you're sure the profile exists (and you've properly set AUTH\_PROFILE\_MODULE), th...
Python time measure function
5,478,351
58
2011-03-29T20:12:39Z
5,478,448
126
2011-03-29T20:21:20Z
[ "python", "time", "callback" ]
I want to create a python function to test the time spent in each function and print its name with its time, how i can print the function name and if there is another way to do so please tell me ``` def measureTime(a): start = time.clock() a() elapsed = time.clock() elapsed = elapsed - start print...
First and foremost, I highly suggest using a [profiler](http://docs.python.org/library/profile.html) or atleast use [timeit](http://docs.python.org/library/timeit.html). However if you wanted to write your own timing method strictly to learn, here is somewhere to get started using a decorator. ``` def timing(f): ...
Python time measure function
5,478,351
58
2011-03-29T20:12:39Z
20,924,212
24
2014-01-04T17:27:04Z
[ "python", "time", "callback" ]
I want to create a python function to test the time spent in each function and print its name with its time, how i can print the function name and if there is another way to do so please tell me ``` def measureTime(a): start = time.clock() a() elapsed = time.clock() elapsed = elapsed - start print...
After playing with the `timeit` module, I don't like its interface, which is not so elegant compared to the following two method. The following code is in Python 3. ## The decorator method This is almost the same with @Mike's method. Here I add `kwargs` and `functools` wrap to make it better. ``` def timeit(func): ...
Making a Django form class with a dynamic number of fields
5,478,432
30
2011-03-29T20:20:01Z
5,478,634
46
2011-03-29T20:38:43Z
[ "python", "django", "forms" ]
I'm working on something like an online store. I'm making a form in which the customer buys an item, and she can choose how many of these item she would like to buy. But, on every item that she buys she needs to choose what its color would be. So there's a non-constant number of fields: If the customer buys 3 items, sh...
Jacob Kaplan-Moss has an extensive writeup on dynamic form fields: <http://jacobian.org/writing/dynamic-form-generation/> Essentially, you add more items to the form's fields member variable during instantiation.
Making a Django form class with a dynamic number of fields
5,478,432
30
2011-03-29T20:20:01Z
5,479,472
19
2011-03-29T22:02:35Z
[ "python", "django", "forms" ]
I'm working on something like an online store. I'm making a form in which the customer buys an item, and she can choose how many of these item she would like to buy. But, on every item that she buys she needs to choose what its color would be. So there's a non-constant number of fields: If the customer buys 3 items, sh...
Here's another option: how about a [formset](http://docs.djangoproject.com/en/dev/topics/forms/formsets/)? Since your fields are all the same, that's precisely what formsets are used for. The django admin uses `FormSet`s + a bit of javascript to add arbitrary length inlines. ``` class ColorForm(forms.Form): color...
Django: Can't render STATIC_URL from settings in template
5,478,855
26
2011-03-29T21:00:02Z
5,478,944
52
2011-03-29T21:08:07Z
[ "python", "django" ]
<http://docs.djangoproject.com/en/dev/howto/static-files/> This suggests that I can use `STATIC_URL` in my template to get the value from settings.py. Template looks like this: ``` <link href="{{STATIC_URL}}stylesheets/tabs.css" rel="stylesheet" type="text/css" media="screen" /> ``` Settings.py looks like this: `...
You have to use `context_instance=RequestContext(request)` in your `render_to_response`, for example: ``` return render_to_response('my_template.html', my_data_dictionary, context_instance=RequestContext(request)) ``` Or use the new shortcut [render](http://docs.dja...
Why do I get TypeError in Threading in Python
5,479,033
16
2011-03-29T21:16:34Z
5,479,093
45
2011-03-29T21:20:47Z
[ "python", "multithreading" ]
I've got the following code which is based off an example i found here on SO, but when i run it i get an error. Please help, i'm sure its very simple: ``` def listener(port): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(('',port)) sock.settimeout(1) # n second(s) timeout try: ...
The error is coming from the following line: ``` threading.Thread(target=listener, args=(port)).start() ``` The `args` parameter needs to be a sequence, I think your intention is to use a tuple, but wrapping a single value in parentheses does not accomplish this. Here is what you need to change it to: ``` threading....
Why do I get TypeError in Threading in Python
5,479,033
16
2011-03-29T21:16:34Z
5,479,094
8
2011-03-29T21:21:02Z
[ "python", "multithreading" ]
I've got the following code which is based off an example i found here on SO, but when i run it i get an error. Please help, i'm sure its very simple: ``` def listener(port): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(('',port)) sock.settimeout(1) # n second(s) timeout try: ...
In the last line, `args=(port)` is equivalent to `args=port`. You need to put `port` into a proper tuple like this: `args=(port,)`.
Is there a Python module to "thaw" data frozen using Perl's Storable?
5,479,162
6
2011-03-29T21:28:29Z
5,479,224
10
2011-03-29T21:34:44Z
[ "python", "perl", "serialization" ]
I have a legacy database which contains simple data structures (no CODE refs thank goodness) that have been written using the `nfreeze` method of the [`Storable`](http://search.cpan.org/~ams/Storable/Storable.pm) module in Perl. Now I have a need to load this data into a Python application. Does anyone know of a Pytho...
It's not immediately clear to me how far along this project is, but it appears to aim to do what you want: <http://gitorious.org/python-storable>
summarize text or simplify text
5,479,333
17
2011-03-29T21:46:29Z
5,479,497
13
2011-03-29T22:04:56Z
[ "python", "nlp", "text-processing" ]
Is there any library, preferably in python but at least open source, that can summarize and or simplify natural-language text?
I'm not sure if there is currently any libraries that do this, as text summarization, or at least **understandable** text summarization isn't something that will be easily accomplished by a simple plug & play library. Here are a few links that I managed to find regarding projects / resources that are related to text s...
summarize text or simplify text
5,479,333
17
2011-03-29T21:46:29Z
19,956,247
12
2013-11-13T14:25:43Z
[ "python", "nlp", "text-processing" ]
Is there any library, preferably in python but at least open source, that can summarize and or simplify natural-language text?
Maybe you can try [sumy](https://github.com/miso-belica/sumy). It's a quite small library that I wrote in Python. There are implemented Luhn's and Edmundson's approaches, LSA method, LexRank and TextRank algorithms. It's Apache2 licensed and supports Czech, Slovak, English and German languages. Feel free to open an is...
Python + MongoDB - Cursor iteration too slow
5,480,340
7
2011-03-29T23:52:25Z
5,480,476
9
2011-03-30T00:13:16Z
[ "python", "performance", "mongodb", "cursor", "iteration" ]
I'm actually working in a search engine project. We are working with python + mongoDb. I'm having the following problem: I have a pymongo cursor after excecuting a find() command to the mongo db. The pymongo cursor have around 20k results. I have noticed that the iteration over the pymongo cursor is really slow...
Remember the pymongo driver is not giving you back all 20k results at once. It is making network calls to the mongodb backend for more items as you iterate. Of course it wont be as fast as a list of strings. However, I'd suggest trying to adjust the cursor batch\_size [as outlined in the api docs](http://api.mongodb.or...
Python + MongoDB - Cursor iteration too slow
5,480,340
7
2011-03-29T23:52:25Z
8,976,768
10
2012-01-23T18:34:35Z
[ "python", "performance", "mongodb", "cursor", "iteration" ]
I'm actually working in a search engine project. We are working with python + mongoDb. I'm having the following problem: I have a pymongo cursor after excecuting a find() command to the mongo db. The pymongo cursor have around 20k results. I have noticed that the iteration over the pymongo cursor is really slow...
Is your pymongo installation using the included [C extensions](http://api.mongodb.org/python/current/installation.html#dependencies-for-installing-c-extensions-on-unix)? ``` >>> import pymongo >>> pymongo.has_c() True ``` I spent most of last week trying to debug a moderate-sized query and corresponding processing th...
NumPy: calculate averages with NaNs removed
5,480,694
33
2011-03-30T00:50:18Z
5,480,765
12
2011-03-30T01:02:26Z
[ "python", "numpy", null ]
How can I calculate matrix mean values along a matrix, but to remove `nan` values from calculation? (For R people, think `na.rm = TRUE`). Here is my [non-]working example: ``` import numpy as np dat = np.array([[1, 2, 3], [4, 5, np.nan], [np.nan, 6, np.nan], [np.nan, np...
Assuming you've also got SciPy installed: <http://www.scipy.org/doc/api_docs/SciPy.stats.stats.html#nanmean>
NumPy: calculate averages with NaNs removed
5,480,694
33
2011-03-30T00:50:18Z
5,480,784
32
2011-03-30T01:04:52Z
[ "python", "numpy", null ]
How can I calculate matrix mean values along a matrix, but to remove `nan` values from calculation? (For R people, think `na.rm = TRUE`). Here is my [non-]working example: ``` import numpy as np dat = np.array([[1, 2, 3], [4, 5, np.nan], [np.nan, 6, np.nan], [np.nan, np...
I think what you want is a masked array: ``` dat = np.array([[1,2,3], [4,5,nan], [nan,6,nan], [nan,nan,nan]]) mdat = np.ma.masked_array(dat,np.isnan(dat)) mm = np.mean(mdat,axis=1) print mm.filled(np.nan) # the desired answer ``` **Edit:** Combining all of the timing data ``` from timeit import Timer setupst...
NumPy: calculate averages with NaNs removed
5,480,694
33
2011-03-30T00:50:18Z
5,480,815
16
2011-03-30T01:10:10Z
[ "python", "numpy", null ]
How can I calculate matrix mean values along a matrix, but to remove `nan` values from calculation? (For R people, think `na.rm = TRUE`). Here is my [non-]working example: ``` import numpy as np dat = np.array([[1, 2, 3], [4, 5, np.nan], [np.nan, 6, np.nan], [np.nan, np...
If performance matters, you should use `bottleneck.nanmean()` instead: <http://pypi.python.org/pypi/Bottleneck>
NumPy: calculate averages with NaNs removed
5,480,694
33
2011-03-30T00:50:18Z
5,484,050
7
2011-03-30T08:47:29Z
[ "python", "numpy", null ]
How can I calculate matrix mean values along a matrix, but to remove `nan` values from calculation? (For R people, think `na.rm = TRUE`). Here is my [non-]working example: ``` import numpy as np dat = np.array([[1, 2, 3], [4, 5, np.nan], [np.nan, 6, np.nan], [np.nan, np...
A masked array with the nans filtered out can also be created on the fly: ``` print np.ma.masked_invalid(dat).mean(1) ```
NumPy: calculate averages with NaNs removed
5,480,694
33
2011-03-30T00:50:18Z
8,045,609
8
2011-11-08T03:29:02Z
[ "python", "numpy", null ]
How can I calculate matrix mean values along a matrix, but to remove `nan` values from calculation? (For R people, think `na.rm = TRUE`). Here is my [non-]working example: ``` import numpy as np dat = np.array([[1, 2, 3], [4, 5, np.nan], [np.nan, 6, np.nan], [np.nan, np...
You can always find a workaround in something like: ``` numpy.nansum(dat, axis=1) / numpy.sum(numpy.isfinite(dat), axis=1) ``` Numpy 2.0's `numpy.mean` has a `skipna` option which should take care of that.
multiprocessing Pool.imap broken?
5,481,104
3
2011-03-30T02:06:58Z
5,481,610
7
2011-03-30T03:41:21Z
[ "python", "multiprocessing" ]
I've tried both the multiprocessing included in the python2.6 Ubuntu package (`__version__` says 0.70a1) and the latest from PyPI (2.6.2.1). In both cases I don't know how to use imap correctly - it causes the entire interpreter to stop responding to ctrl-C's (map works fine though). pdb shows `next()` is hanging on th...
First notice that this works: ``` import multiprocessing as mp import multiprocessing.util as util pool=mp.Pool(1) print list(pool.imap(abs, range(3))) ``` The difference is that `pool` does not get finalized when the call to `pool.imap()` ends. In contrast, ``` print(list(mp.Pool(1).imap(abs, range(3)))) ``` caus...
Custom jinja2 filter for iterator
5,481,205
4
2011-03-30T02:25:39Z
5,481,272
11
2011-03-30T02:37:03Z
[ "python", "jinja2" ]
How do I most efficiently write a custom filter for Jinja2 that applies to an iterable like the built-in 'sort' filter, for use in a for loop in the template? For example: ``` {% for item in iterable|customsort(somearg) %} ... {% endfor %} ``` See <http://jinja.pocoo.org/docs/api/#writing-filters> for general docume...
The same way you'd write any other filter. Here's an example that should get you started: ``` from jinja2 import Environment, Undefined def custom_sort(iterable, somearg): if iterable is None or isinstance(iterable, Undefined): return iterable # Do custom sorting of iterable here return iterable...
How do I measure the execution time of python unit tests with nosetests?
5,481,282
26
2011-03-30T02:39:13Z
5,481,328
25
2011-03-30T02:48:11Z
[ "python", "nosetests" ]
Is there a way to time the execution time of individual Python tests which are run by nosetests ?
You might try the nose plug-in posted here: <https://github.com/mahmoudimus/nose-timer> (or available via pip / PyPi). You can also use the built-in plugin `--with-profile` to do more serious profiling.
How do I measure the execution time of python unit tests with nosetests?
5,481,282
26
2011-03-30T02:39:13Z
17,726,623
8
2013-07-18T14:41:46Z
[ "python", "nosetests" ]
Is there a way to time the execution time of individual Python tests which are run by nosetests ?
Alternatively: ``` python -m cProfile -o profile.out `which nosetests` . ``` The output from can be viewed using, for example, [runsnakerun](http://www.vrplumber.com/programming/runsnakerun/), which makes it visually very obvious where your performance problems are. (e.g. it might be in a common method that many test...
Python dynamically add decorator to class' methods by decorating class
5,481,623
8
2011-03-30T03:43:19Z
5,481,729
16
2011-03-30T04:01:30Z
[ "python", "aop", "decorator" ]
say I have a class: ``` class x: def first_x_method(self): print 'doing first_x_method stuff...' def second_x_method(self): print 'doing second_x_method stuff...' ``` and this decorator ``` class logger: @staticmethod def log(func): def wrapped(*args, **kwargs): ...
Unless there is a definite reason to use a class as a decorator, I think it is usually easier to use functions to define decorators. Here is one way to create a class decorator `trace`, which decorates all methods of a class with the `log` decorator: ``` import inspect def log(func): def wrapped(*args, **kwargs)...
Why can't I find any pywin32 documentation/resources
5,481,686
33
2011-03-30T03:54:39Z
5,481,747
10
2011-03-30T04:04:58Z
[ "python", "pywin32", "pywin" ]
Maybe I am going crazy. I have been googling for a while now and cannot find pywin32 documentation or even a little synopsis of what the module is (I am aware its for win32 api stuff). Is there any pywin32 documentation or resources? Maybe some examples?
There is a documentation for [pywin32 on ActiveState](http://docs.activestate.com/activepython/2.7/pywin32/PyWin32.HTML) : and also a [modules description](http://docs.activestate.com/activepython/2.7/pywin32/modules.html) and the [list of objects](http://docs.activestate.com/activepython/2.7/pywin32/objects.html)
Why can't I find any pywin32 documentation/resources
5,481,686
33
2011-03-30T03:54:39Z
8,339,515
33
2011-12-01T10:06:15Z
[ "python", "pywin32", "pywin" ]
Maybe I am going crazy. I have been googling for a while now and cannot find pywin32 documentation or even a little synopsis of what the module is (I am aware its for win32 api stuff). Is there any pywin32 documentation or resources? Maybe some examples?
The PyWin32 installation includes a `.chm` help file at `[Pythonpath]\Lib\site-packages\PyWin32.chm`. The same info is online at <http://timgolden.me.uk/pywin32-docs/index.html> And as P2bM states, you can also look at [ActiveState's PyWin32 documentation](http://docs.activestate.com/activepython/2.7/pywin32/PyWin32....
Secondary axis with twinx(): how to add to legend?
5,484,922
107
2011-03-30T10:10:56Z
5,487,005
137
2011-03-30T13:32:09Z
[ "python", "matplotlib", "axis", "legend" ]
I have a plot with two y-axes, using `twinx()`. I also give labels to the lines, and want to show them with `legend()`, but I only succeed to get the labels of one axis in the legend: ``` import numpy as np import matplotlib.pyplot as plt from matplotlib import rc rc('mathtext', default='regular') fig = plt.figure() ...
You can easily add a second legend by adding the line: ``` ax2.legend(loc=0) ``` You'll get this: ![enter image description here](http://i.stack.imgur.com/DLZkF.png) But if you want all labels on one legend then you should do something like this: ``` import numpy as np import matplotlib.pyplot as plt from matplotl...
Secondary axis with twinx(): how to add to legend?
5,484,922
107
2011-03-30T10:10:56Z
10,129,461
68
2012-04-12T18:21:22Z
[ "python", "matplotlib", "axis", "legend" ]
I have a plot with two y-axes, using `twinx()`. I also give labels to the lines, and want to show them with `legend()`, but I only succeed to get the labels of one axis in the legend: ``` import numpy as np import matplotlib.pyplot as plt from matplotlib import rc rc('mathtext', default='regular') fig = plt.figure() ...
I'm not sure if this functionality is new, but you can also use the get\_legend\_handles\_labels() method rather than keeping track of lines and labels yourself: ``` import numpy as np import matplotlib.pyplot as plt from matplotlib import rc rc('mathtext', default='regular') pi = np.pi # fake data time = np.linspac...
Secondary axis with twinx(): how to add to legend?
5,484,922
107
2011-03-30T10:10:56Z
23,647,410
7
2014-05-14T06:43:22Z
[ "python", "matplotlib", "axis", "legend" ]
I have a plot with two y-axes, using `twinx()`. I also give labels to the lines, and want to show them with `legend()`, but I only succeed to get the labels of one axis in the legend: ``` import numpy as np import matplotlib.pyplot as plt from matplotlib import rc rc('mathtext', default='regular') fig = plt.figure() ...
You can easily get what you want by adding the line: ``` ax.plot(0, 0, '-r', label = 'temp') ``` This would plot nothing but add a label to lengend for ax. I think this is a much easier way. It's not nessary to track lines automaticly when you have only a few lines in ax2, as fixing by hand would be quite easy. Any...
Removing an item from a priority queue
5,484,929
4
2011-03-30T10:11:30Z
5,484,964
8
2011-03-30T10:15:28Z
[ "python", "data-structures" ]
In Python, the [`heapq`](http://docs.python.org/library/heapq.html) module provides a priority queue. It has methods for inserting and popping items. How do you remove an item that you have inserted that is not the lowest priority from the queue? (Alternative recipes for doing this using alternative other collection...
The `heapq` module uses standard Python lists as underlying data structure, so you can just use the standard `list` method `remove()` and `heapify()` again after this. Note that this will need linear time though. ``` # Create example data and heapify a = range(10) a.reverse() heapq.heapify(a) print a # remove an elem...
How can this Python Scrabble word finder be made faster?
5,485,654
23
2011-03-30T11:26:52Z
5,521,619
11
2011-04-02T06:33:36Z
[ "python", "optimization" ]
I have no real need to improve it, it's just for fun. Right now it's taking about a second on a list of about 200K words. I've tried to optimize it as much as I know how (using generators instead of list comprehensions made a big difference), and I've run out of ideas. Do you have any? ``` #!/usr/bin/env python # le...
Without going too far from your basic code, here are some fairly simple optimizations: First, change your word reader to be: ``` def word_reader(filename, L): L2 = L+2 # returns an iterator return (word.strip() for word in open(filename) \ if len(word) < L2 and len(word) > 2) ``` and call it as ``` ...
Mod_wsgi pylons (ckan) installation not working
5,485,790
5
2011-03-30T11:39:25Z
5,497,336
9
2011-03-31T08:52:36Z
[ "python", "apache", "apache2", "pylons", "mod-wsgi" ]
I am setting up CKAN, a pylons application according to these instructions: <http://packages.python.org/ckan/deployment.html> But when I point to the server (no DNS setup yet) using IP or hostname, I only see apache's greeting page, sugesting the ckan app is not being loaded. here is my mod\_wsgi script: ``` import ...
Since you're deploying on apache, ensure that you are not in interactive debug mode - which uses EvalException. In your Pylons config file (ckan.emap.fgv.br.ini) ensure you have this: ``` [app:main] set debug = false ```
Rolling median in python
5,486,226
4
2011-03-30T12:26:50Z
5,486,256
9
2011-03-30T12:29:49Z
[ "python", "finance", "quantitative-finance", "pandas" ]
I have some stock data based on daily close values. I need to be able to insert these values into a python list and get a median for the last 30 closes. Is there a python library that does this? Thank you~ Yueer
In pure Python, having your data in a Python list `a`, you could do ``` median = sum(sorted(a[-30:])[14:16]) / 2.0 ``` (This assumes `a` has at least 30 items.) Using the NumPy package, you could use ``` median = numpy.median(a[-30:]) ```
How to remove stop words using nltk or python
5,486,337
44
2011-03-30T12:36:26Z
5,486,509
12
2011-03-30T12:51:52Z
[ "python", "nltk", "stop-words" ]
So I have a dataset that I would like to remove stop words from using ``` stopwords.words('english') ``` I'm struggling how to use this within my code to just simply take out these words. I have a list of the words from this dataset already, the part i'm struggling with is comparing to this list and removing the stop...
I suppose you have a list of words (word\_list) from which you want to remove stopwords. You could do something like this: ``` filtered_word_list = word_list[:] #make a copy of the word_list for word in word_list: # iterate over word_list if word in stopwords.words('english'): filtered_word_list.remove(word) # ...
How to remove stop words using nltk or python
5,486,337
44
2011-03-30T12:36:26Z
5,486,535
74
2011-03-30T12:53:40Z
[ "python", "nltk", "stop-words" ]
So I have a dataset that I would like to remove stop words from using ``` stopwords.words('english') ``` I'm struggling how to use this within my code to just simply take out these words. I have a list of the words from this dataset already, the part i'm struggling with is comparing to this list and removing the stop...
``` from nltk.corpus import stopwords # ... filtered_words = [word for word in word_list if word not in stopwords.words('english')] ```
How to remove stop words using nltk or python
5,486,337
44
2011-03-30T12:36:26Z
9,880,768
16
2012-03-26T22:25:10Z
[ "python", "nltk", "stop-words" ]
So I have a dataset that I would like to remove stop words from using ``` stopwords.words('english') ``` I'm struggling how to use this within my code to just simply take out these words. I have a list of the words from this dataset already, the part i'm struggling with is comparing to this list and removing the stop...
You could also do a set diff, for example: ``` list(set(nltk.regexp_tokenize(sentence, pattern, gaps=True)) - set(nltk.corpus.stopwords.words('english'))) ```
Python: select() doesn't signal all input from pipe
5,486,717
9
2011-03-30T13:09:31Z
5,491,460
15
2011-03-30T19:46:12Z
[ "python", "select", "pipe" ]
I am trying to load an external command line program with Python and communicate with it via pipes. The progam takes text input via stdin and produces text output in lines to stdout. Communication should be asynchronous using select(). The problem is, that not all output of the program is signalled in select(). Usuall...
Note that internally `file.readlines([size])` loops and invokes the `read()` syscall more than once, attempting to fill an internal buffer of `size`. The first call to `read()` will immediately return, since select() indicated the fd was readable. However the 2nd call will block until data is available, which defeats t...
How to execute a command prompt command from python
5,486,725
7
2011-03-30T13:10:03Z
5,486,837
12
2011-03-30T13:19:06Z
[ "python", "windows" ]
I tried something like this, but with no effect: ``` command = "cmd.exe" proc = subprocess.Popen(command, stdin = subprocess.PIPE, stdout = subprocess.PIPE) proc.stdin.write("dir c:\\") ```
how about simply: ``` import os os.system('dir c:\\') ```
Django user registration form best practices
5,487,050
10
2011-03-30T13:36:08Z
5,488,025
9
2011-03-30T14:55:35Z
[ "python", "django" ]
Django way of customizing the user creation is by adding UserProfile model, however when I am performing user registration, I would like the user to fill all the details, including the ones in the user profile as well. Using forms.ModelForm seems like the easiest way, however I am dealing here with two models. What is...
[`UserCreationForm`](https://docs.djangoproject.com/en/1.8/topics/auth/default/#django.contrib.auth.forms.UserCreationForm) may come in handy.
Coordinates of item on numpy array
5,487,437
7
2011-03-30T14:08:12Z
5,487,492
13
2011-03-30T14:12:12Z
[ "python", "geometry", "numpy" ]
I have a numpy array: ``` [[ 0. 1. 2. 3. 4.] [ 7. 8. 9. 10. 4.] [ 14. 15. 16. 17. 4.] [ 1. 20. 21. 22. 23.] [ 27. 28. 1. 20. 29.]] ``` which I want to quickly find the coordinates of specific values and avoid python loops on the array. For example number `4` is on: ``` row 0 and c...
If `a` is your array, then you could use: ``` ii = np.nonzero(a == 4) ``` or ``` ii = np.where(a == 4) ``` If you really want a tuple, you can convert from the tuple of arrays to the tuple of tuples, but the return value from the numpy functions is convient for then doing other operations on your array. Conversion...
Coordinates of item on numpy array
5,487,437
7
2011-03-30T14:08:12Z
5,487,500
10
2011-03-30T14:12:45Z
[ "python", "geometry", "numpy" ]
I have a numpy array: ``` [[ 0. 1. 2. 3. 4.] [ 7. 8. 9. 10. 4.] [ 14. 15. 16. 17. 4.] [ 1. 20. 21. 22. 23.] [ 27. 28. 1. 20. 29.]] ``` which I want to quickly find the coordinates of specific values and avoid python loops on the array. For example number `4` is on: ``` row 0 and c...
``` a = numpy.array([[ 0., 1., 2., 3., 4.], [ 7., 8., 9., 10., 4.], [ 14., 15., 16., 17., 4.], [ 1., 20., 21., 22., 23.], [ 27., 28., 1., 20., 29.]]) print numpy.argwhere(a == 4.) ``` prints ``` [[0 4] [1 4] [2 4]] ``` The usual caveat...
Call a method of an object with arguments in Python
5,488,155
5
2011-03-30T15:06:28Z
5,488,187
24
2011-03-30T15:08:17Z
[ "python", "reflection", "methods" ]
I want to be able to call different methods on a Python class with dynamic function name, e.g. ``` class Obj(object): def A(self, x): print "A %s" % x def B(self, x): print "B %s" % x o = Obj() # normal route o.A(1) # A 1 o.B(1) # B 1 # dynamically foo(o, "A", 1) # A 1; equiv. to o.A(1) f...
Well, `getattr` indeed seems to be what you want: ``` getattr(o, "A")(1) ``` is equivalent to ``` o.A(1) ```
Numpy.Array in Python list?
5,488,307
8
2011-03-30T15:17:15Z
5,488,351
13
2011-03-30T15:19:36Z
[ "python", "numpy" ]
I've got a list (used as a stack) of numpy arrays. Now I want to check if an array is already in the list. Had it been tuples for instance, I would simply have written something equivalent to `(1,1) in [(1,1),(2,2)]`. However, this does not work for numpy arrays; `np.array([1,1]) in [np.array([1,1]), np.array([2,2])]` ...
To test if an array equal to `a` is contained in the list `my_list`, use ``` any((a == x).all() for x in my_list) ```
Why did I get this [1, 2, 4, 8, 16, 1, 16, 8, 4, 2, 1]?
5,488,959
7
2011-03-30T16:07:43Z
5,489,501
13
2011-03-30T16:56:01Z
[ "python", "algorithm", "language-agnostic", "math", "number-theory" ]
Through much trial and error I found the following lines of python code, ``` for N in range(2**1,2**3): print [(2**n % (3*2**(2*N - n))) % (2**N-1) for n in range(2*N+1)] ``` which produce the following output, ``` [1, 2, 1, 2, 1] [1, 2, 4, 1, 4, 2, 1] [1, 2, 4, 8, 1, 8, 4, 2, 1] [1, 2, 4, 8, 16, 1, 16, 8, 4, 2,...
First of all, as others have said, there are much simpler implementations possible, and you should probably use these. But to answer your question, here's why you get this result: **When n<N:** 2n % (3\*22N-n) = 2n, because 2n < 3\*22N-n. Then 2n % (2N-1) = 2n, giving the expected result. **When n=N**: 2N % (3\*22...
Python; exception aware map()
5,489,445
9
2011-03-30T16:50:54Z
5,489,561
10
2011-03-30T17:02:17Z
[ "python", "exception", "exception-handling", "functional-programming", "map-function" ]
I'm doing some pyplotting of *generic data* and converting it from a power value to a dB value. Due to the system these values come from, 0 is used as a 'the useful data ends here' indicator (the nature of the mathematics, not a defined value). My usual way of dealing with these is wrapping the conversion in a try/exc...
Perhaps there's some trick in the plotting library, but a much better options seems not generating such data to begin with. It's not that `map` saves you thirty lines of code... Use `itertools.takewhile(lambda y: y != NO_VALUE, (f(y) for y in yvals))` (and wrap it in a call to `list` if the plotting library requires a...
Check if a function has a decorator
5,489,649
11
2011-03-30T17:09:34Z
5,489,931
14
2011-03-30T17:36:02Z
[ "python", "django", "decorator", "login-required" ]
My question is a general one, but specifically my application is the login\_required decorator for Django. I'm curious if there is a way to check if a view/function has a specific decorator (in this case the login\_required decorator) I am redirecting after logging a user out, and I want to redirect to the main page ...
Build your own `login_required` decorator and have it mark the function as decorated--probably the best place to mark it would be in the `func_dict`. ``` from django.contrib.auth.decorators import login_required as django_l_r # Here you're defining your own decorator called `login_required` # it uses Django's built i...
Python: Counting repeating values of a dictionary
5,490,078
4
2011-03-30T17:48:34Z
5,490,145
8
2011-03-30T17:53:30Z
[ "python", "dictionary", "count", "repeat" ]
I have a dictionary as follows: ``` dictA = { ('unit1','test1') : 'alpha' , ('unit1','test2') : 'beta', ('unit2','test1') : 'alpha', ('unit2','test2') : 'gamma' , ('unit3','test1') : 'delta' , ('unit3','test2') : 'gamma' } ``` How can I count the number of repeating values per each test independent of units? i.e. ...
In Python 2.7 or 3.1 or above, you can use `collections.Counter`: ``` from collections import Counter counts = Counter((k[1], v) for k, v in dictA.iteritems()) print(counts) ``` prints ``` Counter({('test1', 'alpha'): 2, ('test2', 'gamma'): 2, ('test2', 'beta'): 1, ('test1', 'delta'): 1}) ```
plotting 3d scatter in matplotlib
5,490,288
13
2011-03-30T18:05:52Z
5,537,197
15
2011-04-04T10:25:55Z
[ "python", "numpy", "matplotlib", "scipy", "data-visualization" ]
I have a collection of Nx3 matrices in scipy/numpy and I'd like to make a 3 dimensional scatter of it, where the X and Y axes are determined by the values of first and second columns of the matrix, the height of each bar is the third column in the matrix, and the number of bars is determined by N. Each matrix represen...
Try replacing 'ax.scatter' with ax.plot', possibly with the 'o' parameter to get similar circles. This fixes the transparency and the legend. ``` import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib.pyplot as plt from numpy.random import random mpl.rcParams['legend.fon...
What alternatives are there to numpy on Google App Engine?
5,490,723
5
2011-03-30T18:45:16Z
7,741,443
12
2011-10-12T14:12:17Z
[ "python", "google-app-engine", "numpy" ]
What alternatives can you recommend to numpy to use on the Google App Engine? Specifically I'm interested in matrix manipulations on large matrices.
The Python 2.7 runtime [includes NumPy 1.6.1](https://developers.google.com/appengine/docs/python/tools/libraries27).
How to convert EST/EDT to GMT?
5,491,276
4
2011-03-30T19:30:02Z
5,491,705
9
2011-03-30T20:08:24Z
[ "python", "gmt" ]
I have a few records inside a column which represent either EST or EDT Time. I need to convert these times to GMT time. The format of the time are: ``` 10/1/2010 0:0:0 10/1/2010 0:6:0 ... 10/1/2010 23:54:0 ... 10/3/2010 0:0:0 ... ``` Can someone help me out here? thanks
The easiest, most reliable way I know to convert between timezones is to use the third-party [pytz](http://pytz.sourceforge.net/) module: ``` import pytz import datetime as dt utc=pytz.utc eastern=pytz.timezone('US/Eastern') fmt='%Y-%m-%d %H:%M:%S %Z%z' text='''\ 10/1/2010 0:0:0 10/1/2010 0:6:0 10/1/2010 23:54...
sorting list in python
5,491,913
7
2011-03-30T20:25:07Z
5,491,962
12
2011-03-30T20:28:33Z
[ "python", "list", "sorting", "prefix" ]
if I have a list of strings e.g. `["a143.txt", "a9.txt", ]` how can I sort it in ascending order by the numbers in the list, rather than by the string. I.e. I want `"a9.txt"` to appear before `"a143.txt"` since `9 < 143`. thanks.
It's called "natural sort order", From <http://www.codinghorror.com/blog/2007/12/sorting-for-humans-natural-sort-order.html> Try this: ``` import re def sort_nicely( l ): """ Sort the given list in the way that humans expect. """ convert = lambda text: int(text) if text.isdigit() else text alphanum_key ...
Python: Unpredictable memory error when downloading large files
5,492,797
4
2011-03-30T21:40:40Z
5,492,819
8
2011-03-30T21:42:56Z
[ "python", "download", "out-of-memory" ]
I wrote a python script which I am using to download a large number of video files (50-400 MB each) from an HTTP server. It has worked well so far on long lists of downloads, but for some reason it rarely has a memory error. The machine has about 1 GB of RAM free, but I don't think it's ever maxed out on RAM while run...
Your problem is here: `f.read()`. That line attempts to download the entire file into memory. Instead of that, read in chunks (`chunk = f.read(4096)`), and save the pieces to temporary file.
What are the best Python Finite State Machine implementations
5,492,980
36
2011-03-30T22:01:22Z
8,117,912
19
2011-11-14T06:06:15Z
[ "python", "fsm" ]
These are the Python FSM Implementations I have found so far... * [Fysom](https://github.com/mriehl/fysom) - A slick FSM implementation that provides function callbacks for each state. * [Skip Montanero's FSM](http://www.smontanaro.net/python/) * [FSM with Decorators](http://wiki.python.org/moin/State%20Machine%20via%...
When I was doing a web project, I found Jake Gordon's [javascript-state-machine](https://github.com/jakesgordon/javascript-state-machine) quite useful. A while later, I needed an FSM for python and I couldn't find anything matching the javascript one in terms of simplicity and flexibility so I ported it to python. It's...
What are the best Python Finite State Machine implementations
5,492,980
36
2011-03-30T22:01:22Z
39,131,298
7
2016-08-24T19:10:30Z
[ "python", "fsm" ]
These are the Python FSM Implementations I have found so far... * [Fysom](https://github.com/mriehl/fysom) - A slick FSM implementation that provides function callbacks for each state. * [Skip Montanero's FSM](http://www.smontanaro.net/python/) * [FSM with Decorators](http://wiki.python.org/moin/State%20Machine%20via%...
At the time the question was asked, tyarkonis [transitions](https://github.com/tyarkoni/transitions "transitions") package was not developed yet. But meanwhile it has gotten quite some traction on github. Beside active community, I like about it * substantial and well written documentation * tests included * states an...
Lxml element equality with namespaces
5,493,744
5
2011-03-30T23:40:08Z
5,494,365
14
2011-03-31T01:26:36Z
[ "python", "lxml", "xml-namespaces" ]
I am attempting to use Lxml to parse the contents of a .docx document. I understand that lxml replaces namespace prefixes with the actual namespace, however this makes it a real pain to check what kind of element tag I am working with. I would like to be able to do something like ``` if (someElement.tag == "w:p"): ```...
Perhaps use [local-name()](http://www.w3.org/TR/xpath/#function-local-name): ``` import lxml.etree as ET tree = ET.fromstring('<root xmlns:f="foo"><f:test/></root>') elt=tree[0] print(elt.xpath('local-name()')) # test ```
Django: 'current_tags' is not a valid tag library
5,493,776
51
2011-03-30T23:45:28Z
5,494,367
65
2011-03-31T01:27:24Z
[ "python", "django", "portability" ]
I have a small Django project I received from a friend. The code works perfectly on his system. However, on my system I get the following error message when running the server: > **TemplateSyntaxError at /** > > 'current\_tags' is not a valid tag library: Template library current\_tags not found, tried django.template...
I would suggest the following: 1. (Most likely) You haven't installed one of the dependencies of your tag library. Check the imports inside the `current_tags.py` module. 2. Make sure the application that includes the tag library is registered in `settings.py` under `INSTALLED_APPS`. 3. Make sure that you can successfu...
Django: 'current_tags' is not a valid tag library
5,493,776
51
2011-03-30T23:45:28Z
7,291,331
54
2011-09-03T05:23:13Z
[ "python", "django", "portability" ]
I have a small Django project I received from a friend. The code works perfectly on his system. However, on my system I get the following error message when running the server: > **TemplateSyntaxError at /** > > 'current\_tags' is not a valid tag library: Template library current\_tags not found, tried django.template...
I had this problem and fixed it by adding a blank `__init__.py` file in my appname/templatetags/ directory.
Django: 'current_tags' is not a valid tag library
5,493,776
51
2011-03-30T23:45:28Z
12,806,062
39
2012-10-09T18:21:29Z
[ "python", "django", "portability" ]
I have a small Django project I received from a friend. The code works perfectly on his system. However, on my system I get the following error message when running the server: > **TemplateSyntaxError at /** > > 'current\_tags' is not a valid tag library: Template library current\_tags not found, tried django.template...
Possibilities are many: 1. You haven't reset your **dev server**. 2. You have **dependency loop** in templatetag file. 3. You **misspelled** something (directory, folder, template name in 'load', etc.). 4. You forgot about adding the app to **INSTALLED\_APPS**.
Why doesn't memory get released to system after large queries (or series of queries) in django?
5,494,178
19
2011-03-31T00:51:01Z
5,495,318
22
2011-03-31T04:25:16Z
[ "python", "django", "memory-leaks" ]
First off, `DEBUG = False` in settings.py, so no, `connections['default'].queries` is not growing and growing until it uses up all of memory. Lets start off with the fact that I've loaded the `User` table from `django.contrib.auth.models.User` with 10000 users (each named 'test#' where # is a number between 1 and 1000...
I decided to move my comments into an answer to make things clearer. Since Python 2.5, the CPython memory allocation tracks internal memory usage by the small object allocator, and attempts to return completely free arenas to the underlying OS. This works most of the time, but the fact that objects can't be moved arou...
Use arbitrary wx objects as a column in a wx.ListCtrl
5,495,053
6
2011-03-31T03:34:02Z
5,496,218
8
2011-03-31T06:53:22Z
[ "python", "wxpython", "listctrl" ]
I have a `wx.ListCtrl` that has the `wx.LC_REPORT` bit set. It has 3 columns. I want the first column to be populated with a check box for each other entry. I tried using the `ListCtrl.InsertItem` method, but it only takes one argument (`info`) and I can't find any docs as to what that argument needs to be. I've tried ...
Have a look at `wx.lib.mixins.listctrl`. ``` import wx import wx.lib.mixins.listctrl as listmix class TestListCtrl(wx.ListCtrl, listmix.CheckListCtrlMixin, listmix.ListCtrlAutoWidthMixin): def __init__(self, *args, **kwargs): wx.ListCtrl.__init__(self, *args, **kwargs) listmix.CheckListCtrlMixin._...
How to read the first byte of a subprocess's stdout and then discard the rest in Python?
5,495,078
29
2011-03-31T03:38:03Z
12,926,181
66
2012-10-17T02:21:42Z
[ "python", "stream", "subprocess" ]
I'd like to read the first byte of a subprocess' stdout to know that it has started running. After that I'd like to discard all further output, so that I don't have to worry about the buffer. What is the best way to do this? **Clarification:** I'd like the subprocess to continue running alongside my program, I don't ...
If you're using Python 3.3+, you can use the `DEVNULL` special value for `stdout` and `stderr` to discard subprocess output. ``` from subprocess import Popen, DEVNULL process = Popen(["mycmd", "myarg"], stdout=DEVNULL, stderr=DEVNULL) ``` Or if you're using Python 2.4+, you can simulate this with: ``` import os fro...
Implementation of e-mail verification in Django
5,495,317
8
2011-03-31T04:25:08Z
5,495,334
8
2011-03-31T04:28:24Z
[ "python", "django", "django-models", "django-templates", "django-settings" ]
I have created a Django app. I have a registration page(simple HTML form) in the app,and it has an e-mail field while registering. Now i wanted to implement an email verification when the user registers. Like sending an email to the user (to email given in registration form). By googling i found there is a Django metho...
Check out [**`django-registration`**](https://bitbucket.org/ubernostrum/django-registration/) as a pluggable app. Also you can use the code as a reference if you want to roll your own. ***response to comment:*** django-registration would be perfect for you. It doesn't come with html templates, you'll just have to ad...
More elegant way of declaring multiple variables at the same time
5,495,332
47
2011-03-31T04:28:09Z
5,495,350
23
2011-03-31T04:31:43Z
[ "python", "variables", "declaration" ]
To declare multiple variables at the "same time" I would do: ``` a, b = True, False ``` But if I had to declare much more variables, it turns less and less elegant: ``` a, b, c, d, e, f, g, h, i, j = True, True, True, True, True, False, True ,True , True, True ``` Is there a better / elegant / convenient way to do ...
Use a list/dictionary or define your own class to encapsulate the stuff you're defining, but if you need all those variables you can do: ``` a = b = c = d = e = g = h = i = j = True f = False ```
More elegant way of declaring multiple variables at the same time
5,495,332
47
2011-03-31T04:28:09Z
5,495,556
28
2011-03-31T05:08:26Z
[ "python", "variables", "declaration" ]
To declare multiple variables at the "same time" I would do: ``` a, b = True, False ``` But if I had to declare much more variables, it turns less and less elegant: ``` a, b, c, d, e, f, g, h, i, j = True, True, True, True, True, False, True ,True , True, True ``` Is there a better / elegant / convenient way to do ...
As others have suggested, it's unlikely that using 10 different local variables with Boolean values is the best way to write your routine (especially if they really have one-letter names :) Depending on what you're doing, it may make sense to use a dictionary instead. For example, if you want to set up Boolean preset ...
More elegant way of declaring multiple variables at the same time
5,495,332
47
2011-03-31T04:28:09Z
11,717,045
103
2012-07-30T07:27:39Z
[ "python", "variables", "declaration" ]
To declare multiple variables at the "same time" I would do: ``` a, b = True, False ``` But if I had to declare much more variables, it turns less and less elegant: ``` a, b, c, d, e, f, g, h, i, j = True, True, True, True, True, False, True ,True , True, True ``` Is there a better / elegant / convenient way to do ...
``` a, b, c, d, e, g, h, i, j = (True,)*9 f = False ```
convert python programme to windows executable
5,495,333
5
2011-03-31T04:28:17Z
5,495,418
7
2011-03-31T04:44:27Z
[ "python", "windows-7", "py2exe" ]
i m trying to create windows executable from python program which has GUI . i m using following script ``` from distutils.core import setup import py2exe setup(console=['gui.py']) ``` it gives following error ``` Warning (from warnings module): File "C:\Python27\lib\distutils\dist.py", line 267 warnings.warn(...
The problem is that you are compiling this script from the Python IDLE. This is not how it is done with `py2exe`. If you have used `Disutils` before, you might have seen this: `python setup.py install`. And same is the case of `py2exe`, you run it from the command line and not the IDLE. So open up `cmd` and then issu...
Matplotlib 3D Scatter Plot with Colorbar
5,495,451
12
2011-03-31T04:50:04Z
5,495,912
11
2011-03-31T06:09:05Z
[ "python", "3d", "matplotlib", "scatter-plot" ]
Borrowing from the [example](http://matplotlib.sourceforge.net/mpl_toolkits/mplot3d/tutorial.html#scatter-plots) on the Matplotlib documentation page and slightly modifying the code, ``` import numpy as np from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt def randrange(n, vmin, vmax): return...
This produces a colorbar (though possibly not the one you need): Replace this line: ``` ax.scatter(xs, ys, zs, c=cs, marker=m) ``` with ``` p = ax.scatter(xs, ys, zs, c=cs, marker=m) ``` then use ``` fig.colorbar(p) ``` near the end
Using Basic HTTP access authentication in Django testing framework
5,495,452
22
2011-03-31T04:50:05Z
5,495,459
35
2011-03-31T04:50:51Z
[ "python", "django", "unit-testing", "http-authentication", "django-testing" ]
For some of my Django views I've created a decorator that performs Basic HTTP access authentication. However, while writing test cases in Django, it took me a while to work out how to authenticate to the view. Here's how I did it. I hope somebody finds this useful.
Here's how I did it: ``` from django.test import Client import base64 auth_headers = { 'HTTP_AUTHORIZATION': 'Basic ' + base64.b64encode('username:password'), } c = Client() response = c.get('/my-protected-url/', **auth_headers) ``` Note: You will also need to create a user.
Using Basic HTTP access authentication in Django testing framework
5,495,452
22
2011-03-31T04:50:05Z
9,088,563
18
2012-01-31T23:22:02Z
[ "python", "django", "unit-testing", "http-authentication", "django-testing" ]
For some of my Django views I've created a decorator that performs Basic HTTP access authentication. However, while writing test cases in Django, it took me a while to work out how to authenticate to the view. Here's how I did it. I hope somebody finds this useful.
In your Django TestCase you can update the client defaults to contain your HTTP basic auth credentials. ``` import base64 from django.test import TestCase class TestMyStuff(TestCase): def setUp(self): credentials = base64.b64encode('username:password') self.client.defaults['HTTP_AUTHORIZATION'] =...
random byte string in python
5,495,492
12
2011-03-31T04:56:10Z
5,495,587
24
2011-03-31T05:14:52Z
[ "python", "string", "random", "hex" ]
i have buf="\x00\xFF\xFF\xFF\xFF\x00" how can i get the "\xFF\xFF\xFF\xFF" randomize
``` >>> import os >>> "\x00"+os.urandom(4)+"\x00" '\x00!\xc0zK\x00' ```
Replacing values greater than a limit in a numpy array
5,495,573
4
2011-03-31T05:12:21Z
5,495,867
7
2011-03-31T06:03:26Z
[ "python", "arrays", "numpy" ]
I have an array n x m, and maximum values for each column. What's the best way to replace values greater than the maximum, besides checking each element? For example: ``` def check_limits(bad_array, maxs): good_array = np.copy(bad_array) for i_line in xrange(bad_array.shape[0]): for i_column in xrange...
Use [**putmask**](http://docs.scipy.org/doc/numpy/reference/generated/numpy.putmask.html): ``` import numpy as np a = np.array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) m = np.array([7,6,5,4]) # This is what you need: np.putmask(a, a >= m, m - 1) # a is now: np.array([[0,...
How to call a Python Script from PHP?
5,497,540
7
2011-03-31T09:11:03Z
5,497,559
18
2011-03-31T09:12:30Z
[ "php", "python" ]
I have some code written in PHP, but I have developed a script written in Python. It is possible to call this Python script from the PHP code? If yes, how can I pass parameters to the Python script from the PHP? I have tried to find answers to this but I haven't find them. Can someone give me a clue?
You use the system function: <http://php.net/manual/en/function.system.php> Something like this: ``` $mystring = system('python myscript.py myargs', $retval); ```
Attempted relative import in non-package (after 2to3)
5,497,951
15
2011-03-31T09:46:14Z
5,498,078
12
2011-03-31T09:56:50Z
[ "python", "python-3.x", "py2to3" ]
After converting to Python 3.x using `2to3` (see my [previous question](http://stackoverflow.com/questions/5497013/convert-code-from-python-2-x-to-3-x/5497070#5497070)), I get this error during the build: ``` File "setup.py", line 28, in <module> from . import mof_compiler ValueError: Attempted relative import i...
Since there is no `__init__.py`, the working directory is a non-package. You don't need a relative import. Or. You need an `__init__.py` to make a package.
pylab.hist(data, normed=1). Normalization seems to work incorrect
5,498,008
17
2011-03-31T09:51:06Z
5,498,113
19
2011-03-31T10:01:08Z
[ "python", "graph", "numpy", "matplotlib" ]
I'm trying to create a histogram with argument normed=1 For instance: ``` import pylab data = ([1,1,2,3,3,3,3,3,4,5.1]) pylab.hist(data, normed=1) pylab.show() ``` I expected that the sum of the bins would be 1. But instead, one of the bin is bigger then 1. What this normalization did? And how to create a histo...
According to [documentation](http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html#numpy.histogram) *normed: If True, the result is the value of the probability density function at the bin, normalized such that the integral over the range is 1. Note that the sum of the histogram values will not be eq...
pylab.hist(data, normed=1). Normalization seems to work incorrect
5,498,008
17
2011-03-31T09:51:06Z
16,399,741
23
2013-05-06T13:24:03Z
[ "python", "graph", "numpy", "matplotlib" ]
I'm trying to create a histogram with argument normed=1 For instance: ``` import pylab data = ([1,1,2,3,3,3,3,3,4,5.1]) pylab.hist(data, normed=1) pylab.show() ``` I expected that the sum of the bins would be 1. But instead, one of the bin is bigger then 1. What this normalization did? And how to create a histo...
See my other post for how to make the sum of all bins in a histogram equal to one: <http://stackoverflow.com/a/16399202/1542814> Copy & Paste: ``` weights = np.ones_like(myarray)/float(len(myarray)) plt.hist(myarray, weights=weights) ``` where myarray contains your data
Forgotten password implementation in Django
5,498,361
3
2011-03-31T10:23:48Z
5,498,571
20
2011-03-31T10:42:01Z
[ "python", "django", "django-models", "django-templates", "django-views" ]
I am trying to implement a forgot password functionality in my django application. I have given a seperate forgottenPassword.html, where user can give his email id ; and if that email is registered(found in database) , corresponding password of that email is fetched and sent to his email id.This is what i am trying to ...
There is (by design) **no way** to do this. You cannot get the password for a user, because it is only stored in the database as a secure hash, and there is no way of reversing that hash. However, Django does provide a built-in *reset* password implementation in contrib.auth - see [the documentation](http://docs.djang...
Creating graph with date and time in axis labels with matplotlib
5,498,510
23
2011-03-31T10:36:21Z
5,502,162
33
2011-03-31T15:16:13Z
[ "python", "matplotlib", "datetime-format" ]
I have my data in an array of the following structure, ``` [[1293606162197, 0, 0], [1293605477994, 63, 0], [1293605478057, 0, 0], [1293605478072, 2735, 1249], [1293606162213, 0, 0], [1293606162229, 0, 0]] ``` The first column is epoch time (in `ms`), second is `y1` and third is `y2`. I need a plot with the time ...
I hope this helps. I've always had a hard time with matplotlib's dates. Matplotlib requires a [float format](http://matplotlib.sourceforge.net/api/pyplot_api.html) which is days since epoch. The helper functions `num2date` and `date2num` along with python builtin `datetime` can be used to convert to/from. The formattin...
Python indentation \ context level to log prefix length
5,498,907
9
2011-03-31T11:13:25Z
5,499,238
8
2011-03-31T11:41:16Z
[ "python", "logging" ]
my idea is to make context logging scheme as showed on the example below: ``` [ DEBUG] Parsing dialogs files [ DEBUG] ... [DialogGroup_001] [ DEBUG] ...... Indexing dialog xml file [c:\001_dlg.xml] [ DEBUG] ......... dialog [LobbyA] [ DEBUG] ............ speech nodes [3] [ DEBUG] ............... [LobbyA_01...
Searching through the docs, I don't really see a way to get current indentation level. The best you can do, is get the current function nesting level, like this: ``` len(traceback.extract_stack()); ``` Example: ``` import traceback; def test(): print len(traceback.extract_stack()); print len(traceback.extract...
Python indentation \ context level to log prefix length
5,498,907
9
2011-03-31T11:13:25Z
5,500,099
10
2011-03-31T12:50:17Z
[ "python", "logging" ]
my idea is to make context logging scheme as showed on the example below: ``` [ DEBUG] Parsing dialogs files [ DEBUG] ... [DialogGroup_001] [ DEBUG] ...... Indexing dialog xml file [c:\001_dlg.xml] [ DEBUG] ......... dialog [LobbyA] [ DEBUG] ............ speech nodes [3] [ DEBUG] ............... [LobbyA_01...
Perhaps you can use [inspect.getouterframes](http://docs.python.org/library/inspect.html#inspect.getouterframes) to find the indentation level: ``` import inspect import logging logger=logging.getLogger(__name__) def debug(msg): frame,filename,line_number,function_name,lines,index=inspect.getouterframes( ...
How do I compare the value in a list to the first value of a nested list and return the nested list results?
5,499,286
3
2011-03-31T11:45:01Z
5,499,335
7
2011-03-31T11:48:46Z
[ "python", "compare", "nested-lists" ]
I have the following two lists. List 1 ``` (a,b,h,g,e,t,w,x) ``` List two ``` ((a,yellow),(h,green),(t,red),(w,teal)) ``` I want to return the following ``` ((a,yellow),(b,null),(h,green),(e,null),(t,red),(w,teal),(x,null)) for x in List_1: for y in list_2: if x == y print y ...
Give this a go: ``` a = ('a', 'b', 'h', 'g', 'e', 't', 'w', 'x') b = (('a', 'yellow'), ('h', 'green'), ('t', 'red'), ('w', 'teal')) B = dict(b) print [(x, B.get(x, 'null')) for x in a] ```
Python - ElementTree- cannot use absolute path on element
5,501,118
13
2011-03-31T14:02:43Z
5,501,441
25
2011-03-31T14:27:50Z
[ "python", "xpath", "elementtree" ]
I'm getting this error in ElementTree when I try to run the code below: ``` SyntaxError: cannot use absolute path on element ``` My XML document looks like this: ``` <Scripts> <Script> <StepList> <Step> <StepText> </StepText> <StepText> </StepText> </Step> </StepList> <...
Turns out I needed to say target.findall(".//StepText"). I guess anything without the '.' is considered an absolute path? Updated working code: ``` def search(): root = ET.parse(INPUT_FILE_PATH) for target in root.findall("//Script"): stepTexts = target.findall(".//StepText") for stepText in s...
How to display picture and get mouse click coordinate on it
5,501,192
12
2011-03-31T14:06:30Z
5,502,111
18
2011-03-31T15:11:54Z
[ "python", "mouseevent", "image" ]
I am wondering if it is possible in Python (Windows) to show some picture, then click with the mouse on this picture and get the coordinates of this click relative to picture edges. Thanks!
Yes it is possible and pretty easy once you understand tkinter, here's a quick script: ``` from Tkinter import * from tkFileDialog import askopenfilename import Image, ImageTk if __name__ == "__main__": root = Tk() #setting up a tkinter canvas with scrollbars frame = Frame(root, bd=2, relief=SUNKEN) ...
Any Python password-generators that are readable and pronounceable?
5,501,477
10
2011-03-31T14:29:45Z
5,502,875
15
2011-03-31T16:08:20Z
[ "python", "passwords" ]
It's simple enough to generate a random string in Python (such as [Python entropy](http://stackoverflow.com/questions/5480131/will-python-systemrandom-os-urandom-always-have-enough-entropy-for-good-crypto) shows). But are there any Python projects out there, which will generate password strings that are both *somewhat*...
If you're really just looking for something "better than I can make up" and "pronounceable," then maybe just use `random.sample()` to pull from a list of consonant-vowel-consonant pseudosyllables: ``` import string import itertools import random initial_consonants = (set(string.ascii_lowercase) - set('aeiou') ...
How to create a list with the characters of a string?
5,501,641
6
2011-03-31T14:41:08Z
5,501,658
10
2011-03-31T14:42:24Z
[ "python", "string", "list" ]
Is it possible to transform a string into a list, like this: ``` "5+6" ``` into ``` ["5", "+", "6"] ```
``` list('5+6') ``` returns ``` ['5', '+', '6'] ```
python: iterate a specific range in a list
5,501,725
16
2011-03-31T14:47:21Z
5,501,744
24
2011-03-31T14:48:44Z
[ "python", "iteration" ]
Lets say I have a list: ``` listOfStuff =([a,b], [c,d], [e,f], [f,g]) ``` What I want to do is iterate through the middle 2 components in a way similar to the following code: ``` for item in listOfStuff(range(2,3)) print item ``` The end result should be: ``` [c,d] [e,f] ``` This code currently does not work, ...
``` listOfStuff =([a,b], [c,d], [e,f], [f,g]) for item in listOfStuff[1:3]: print item ``` You have to iterate over a slice of your tuple. The `1` is the first element you need and `3` (actually 2+1) is the first element you don't need. Elements in a list are numerated from 0: ``` listOfStuff =([a,b], [c,d], [e...
join two lists of dictionaries on a single key
5,501,810
14
2011-03-31T14:53:36Z
5,501,893
22
2011-03-31T14:58:19Z
[ "python" ]
Given `n` lists with `m` dictionaries as their elements, I would like to produce a new list, with a joined set of dictionaries. Each dictionary is guaranteed to have a key called "index", but could have an arbitrary set of keys beyond that. The non-index keys will never overlap across lists. For example, imagine the fo...
``` from collections import defaultdict l1 = [{"index":1, "b":2}, {"index":2, "b":3}, {"index":3, "green":"eggs"}] l2 = [{"index":1, "c":4}, {"index":2, "c":5}] d = defaultdict(dict) for l in (l1, l2): for elem in l: d[elem['index']].update(elem) l3 = d.values() # l3 is now: [{'b': 2, 'c': 4, 'index': 1...
connecting c/c++ and python
5,502,787
3
2011-03-31T16:01:31Z
5,502,808
7
2011-03-31T16:03:17Z
[ "c++", "python", "c", "connection", "io" ]
What I am trying to do is that I want to read a file using python, and then with the data in the file, create a variable in c/c++(I don't want to read var from the file :) ). Is this possible? If this is possible, then how would you do it? Thank you guys!
Maybe [Boost.Python](http://www.boost.org/doc/libs/1_46_1/libs/python/doc/) can help. You could expose a C++ function to your Python script. Something like that: ``` void do_sth_with_processed_data(const std::string& data) { // … } BOOST_PYTHON_MODULE(do_sth) { def("do_sth_with_processed_data", do_sth_with_pro...
xauth using python-oauth2
5,503,260
7
2011-03-31T16:38:32Z
5,541,641
10
2011-04-04T16:45:21Z
[ "python", "sample", "xauth" ]
I am trying to implement xauth for instapaper using python-oauth2. I am able to find samples for oauth but I didnt find any for xauth. Can someone share samples or the api documentation?
here is the code that worked for me finally --- ``` consumer_key=<key> consumer_secret=<secret> access_token_url = 'https://www.instapaper.com/api/1/oauth/access_token' consumer = oauth.Consumer(consumer_key, consumer_secret) client = oauth.Client(consumer) client.add_credentials(instaaccount,instapassword) params ...
Can you translate this debugging macro from C++ to python?
5,503,363
2
2011-03-31T16:49:21Z
5,503,763
7
2011-03-31T17:22:38Z
[ "c++", "python", "debugging", "logging", "macros" ]
I use this very helpful macro when developing in C++: ``` #define DD(a) std::cout << #a " = [ " << a << " ]" << std::endl;std::cout.flush(); ``` Could you help me implement the same idea in python? I don't know how the `#a` could be implemented with a python function...
As [@Andrea Spadaccini](http://stackoverflow.com/questions/5503363/can-you-translate-this-debugging-macro-from-c-to-python/5503502#5503502) and [@adirau](http://stackoverflow.com/questions/5503363/can-you-translate-this-debugging-macro-from-c-to-python/5503542#5503542) point out, it is not possible to reliably map valu...
python selenium example doesn't work, says no module named Keys
5,503,489
2
2011-03-31T16:59:22Z
5,601,030
9
2011-04-08T21:37:57Z
[ "python", "selenium" ]
I installed selenium via pip on a windows machine. Just tryout out the sample on the website: ``` http://pypi.python.org/pypi/selenium from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from selenium.common.keys import Keys import time browser = webdriver.Firefox() # Get lo...
From <http://code.google.com/p/selenium/issues/detail?id=1491> : > from selenium.webdriver.common.keys > import Keys
How to delete/unset a cookie in web.py
5,503,861
4
2011-03-31T17:30:52Z
5,911,897
7
2011-05-06T13:07:20Z
[ "python", "cookies", "web.py" ]
In web.py, you can get access to the request's cookies with `web.webapi.cookies()`, and you can set the value of a cookie with `web.webapi.setcookie(...)`. The documentation isn't clear on how one *deletes* a cookie, however -- do you just `setcookie` with a value of None?
You're right, it's certainly not obvious from `setcookie()`'s docstring, or from the online docs, but it is [there somewhere](http://webpy.org/cookbook/cookies): > The third (and optional) argument to `web.setcookie()`, "expires", allows you to set when you want your cookie to expire. **Any negative number will expire...
How do I use a dictionary to update fields in Django models?
5,503,925
38
2011-03-31T17:35:38Z
5,503,999
12
2011-03-31T17:41:01Z
[ "python", "database", "django" ]
Suppose I have a model like this: ``` class Book(models.Model): num_pages = ... author = ... date = ... ``` Can I create a dictionary, and then insert or update the model using it? ``` d = {"num_pages":40, author:"Jack", date:"3324"} ```
Use `**` for creating a new model. Loop through the dictionary and use `setattr()` in order to update an existing model. From Tom Christie's Django Rest Framework <https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/serializers.py> ``` for attr, value in validated_data.items(): setatt...
How do I use a dictionary to update fields in Django models?
5,503,925
38
2011-03-31T17:35:38Z
5,506,790
56
2011-03-31T21:54:17Z
[ "python", "database", "django" ]
Suppose I have a model like this: ``` class Book(models.Model): num_pages = ... author = ... date = ... ``` Can I create a dictionary, and then insert or update the model using it? ``` d = {"num_pages":40, author:"Jack", date:"3324"} ```
Here's an example of create using your dictionary d: ``` Book.objects.create(**d) ``` To update an existing model, you will need to use the QuerySet `filter` method. Assuming you know the `pk` of the Book you want to update: ``` Book.objects.filter(pk=pk).update(**d) ```