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 |
|---|---|---|---|---|---|---|---|---|---|
How to set up auto-deploy to AppEngine when pushing to Git Repository | 10,274,118 | 6 | 2012-04-23T02:26:21Z | 10,274,340 | 7 | 2012-04-23T03:05:57Z | [
"python",
"git",
"google-app-engine",
"python-2.7",
"bitbucket"
] | I've heard that other platforms support auto-deployment of their code to production when they push changes to their Git repository.
Can I set up something similar to this for AppEngine? How?
I'm using Python2.7 on Windows, and bitbucket as a repository.
Thanks! | Since app engine deploy is just a python script, why can't you just write a shell script that calls 'git push' followed by 'python appcfg.py deploy'?
Any bitbucket hooks that will send from bitbucket->appengine after you upload to app is probably a bad idea since it will require storing your app engine login credentia... |
how to export HDF5 file to NumPy using H5PY? | 10,274,476 | 10 | 2012-04-23T03:30:49Z | 10,274,506 | 21 | 2012-04-23T03:36:10Z | [
"python",
"numpy",
"hdf5",
"h5py"
] | I have an existing hdf5 file with three arrays, i want to extract one of the arrays using h5py. | `h5py` already reads files in as numpy arrays, so just:
```
with h5py.File('the_filename', 'r') as f:
my_array = f['array_name'][()]
```
The `[()]` means to read the entire array in; if you don't do that, it doesn't read the whole data but instead gives you lazy access to sub-parts (very useful when the array is ... |
Python: Elegant and efficient ways to mask a list | 10,274,774 | 5 | 2012-04-23T04:25:27Z | 10,274,789 | 14 | 2012-04-23T04:28:51Z | [
"python",
"arrays",
"list",
"masking"
] | **Example:**
```
from __future__ import division
import numpy as np
n = 8
"""masking lists"""
lst = range(n)
print lst
# the mask (filter)
msk = [(el>3) and (el<=6) for el in lst]
print msk
# use of the mask
print [lst[i] for i in xrange(len(lst)) if msk[i]]
"""masking arrays"""
ary = np.arange(n)
print ary
# the... | You are looking for [`itertools.compress`](http://docs.python.org/library/itertools.html#itertools.compress)
**Example from the docs**
Equivalent to:
```
def compress(data, selectors):
# compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F
return (d for d, s in izip(data, selectors) if s)
``` |
Does defining a non-class private function means anything in Python? | 10,275,576 | 4 | 2012-04-23T06:04:15Z | 10,276,045 | 11 | 2012-04-23T06:54:52Z | [
"function",
"python"
] | ```
def __f():
print 1
def _f():
print 1
```
I tried import and it's accessible:
```
>>> import test1
>>> test1._f()
1
```
Does it mean anything? I want to write some helper functions which aren't class-based. Then I want to hide certain low-level, concrete functions, and leaving only high-level function (view ... | The single leading underscore is a Python naming convention. A number of tools rely on that convention. For example *help()* will ignore single underscored names. Using `from somemodule import *` will also ignore single underscored names.
The double leading underscore triggers name mangling (prefixing the name with th... |
get the list of checkbox post in django views | 10,276,753 | 16 | 2012-04-23T07:50:22Z | 10,276,802 | 32 | 2012-04-23T07:55:36Z | [
"python",
"django",
"django-templates"
] | I have this code in my template:
```
{% for email in emails %}
{%if email%}
<input type="checkbox" name="email" value="{{email}}" /> {{email}}<br />
{% endif %}
{% endfor %}
```
so the output in the template is:
```
email1@sample.com
email2@sample.com
email3@sample.com
...
```
in my views I printed my requ... | Use [request.POST.getlist](https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.QueryDict.getlist):
> Returns the data with the requested key, as a Python list. Returns an empty list if the key doesnât exist and no default value was provided. Itâs guaranteed to return a list of some sort unless ... |
Unicode and `decode()` in Python | 10,277,256 | 8 | 2012-04-23T08:35:08Z | 10,277,613 | 12 | 2012-04-23T09:05:06Z | [
"python",
"unicode",
"decode",
"codec"
] | ```
>>> a = "æ" # chinese
>>> b = unicode(a,"gb2312")
>>> a.__class__
<type 'str'>
>>> b.__class__
<type 'unicode'> # b is unicode
>>> a
'\xce\xd2'
>>> b
u'\u6211'
>>> c = u"æ"
>>> c.__class__
<type 'unicode'> # c is unicode
>>> c
u'\xce\xd2'
```
`b` and `c` are all unicode, but `>>> b` outputs `... | When you enter `"æ"`, the Python interpreter gets from the terminal a representation of that character in your local character set, which it stores in a string byte-for-byte because of the `""`. On my UTF-8 system, that's `'\xe6\x88\x91'`. On yours, it's `'\xce\xd2'` because you use GB2312. That explains the value of... |
Python mock patch a function within another function | 10,277,397 | 14 | 2012-04-23T08:47:35Z | 10,277,673 | 15 | 2012-04-23T09:10:03Z | [
"python",
"unit-testing",
"testing",
"mocking",
"patch"
] | ```
def f1():
return 10, True
def f2():
num, stat = f1()
return 2*num, stat
```
How do I use python's mock library to patch `f1()` and return a custom result so I could test `f2()`?
**Edited:**
Is there something wrong with my test? This doesn't seem to be working, all the tests failed with AssertionErro... | Assuming that you're using this [mock](http://www.voidspace.org.uk/python/mock/index.html) libary:
```
def f1():
return 10, True
def f2():
num, stat = f1()
return 2*num, stat
import mock
print f2() # Unchanged f1 -> prints (20, True)
with mock.patch('__main__.f1') as MockClass: # replace f1 wit... |
how to get request object in django unit testing? | 10,277,748 | 29 | 2012-04-23T09:16:01Z | 10,277,819 | 54 | 2012-04-23T09:21:37Z | [
"python",
"django",
"django-testing"
] | I have a function as
```
def getEvents(eid, request):
......
```
Now I want to write unit test for the above function separately (without calling the view).
So how should I call the above in `TestCase`. Is it possible to create request ? | See [this solution](https://docs.djangoproject.com/en/1.4/topics/testing/#django.test.client.RequestFactory):
```
from django.utils import unittest
from django.test.client import RequestFactory
class SimpleTest(unittest.TestCase):
def setUp(self):
# Every test needs access to the request factory.
... |
how to get request object in django unit testing? | 10,277,748 | 29 | 2012-04-23T09:16:01Z | 10,277,944 | 9 | 2012-04-23T09:29:25Z | [
"python",
"django",
"django-testing"
] | I have a function as
```
def getEvents(eid, request):
......
```
Now I want to write unit test for the above function separately (without calling the view).
So how should I call the above in `TestCase`. Is it possible to create request ? | Use [`RequestFactory`](https://docs.djangoproject.com/en/1.9/topics/testing/advanced/#the-request-factory) to create a dummy request. |
Converting a month's name to its corresponding number | 10,278,509 | 2 | 2012-04-23T10:07:14Z | 10,278,624 | 11 | 2012-04-23T10:14:50Z | [
"python",
"date"
] | I have a file which contains a list of entries, with dates that contain "Jan","Feb","Mar" etc.
I want
> 569207,ngph,RUN,512,16,**2012-Jan-23 01:42**,2012-04-23 10:53
to become
> 569207,ngph,RUN,512,16,**2012-01-23 01:42**,2012-04-23 10:53.
I've written the following:
```
for line in f:
if re.search(r'J... | Two possibilities:
1. the [datetime](http://docs.python.org/library/datetime.html) module
2. DIY solution like you have
The python documentation is worth reading, you may find an easier way to do more than just answer this question.
As for the DIY solution it seems like you have a lot of repeat code, and there's no ... |
Converting a month's name to its corresponding number | 10,278,509 | 2 | 2012-04-23T10:07:14Z | 16,540,686 | 7 | 2013-05-14T10:22:17Z | [
"python",
"date"
] | I have a file which contains a list of entries, with dates that contain "Jan","Feb","Mar" etc.
I want
> 569207,ngph,RUN,512,16,**2012-Jan-23 01:42**,2012-04-23 10:53
to become
> 569207,ngph,RUN,512,16,**2012-01-23 01:42**,2012-04-23 10:53.
I've written the following:
```
for line in f:
if re.search(r'J... | datetime is the answer, for example:
```
>>> import datetime
>>> datetime.datetime.strptime('Mar 2013',"%b %Y")
datetime.datetime(2013, 3, 1, 0, 0)
```
Check the format directives at <http://docs.python.org/2/library/datetime.html> |
Python Interpreter Shell with Vi(m) integration possible? | 10,278,560 | 8 | 2012-04-23T10:10:40Z | 10,278,718 | 10 | 2012-04-23T10:20:55Z | [
"python",
"vi"
] | I love to use bpython but in Ruby there is a gem called interactive\_editor that makes it possible to combine Vi(m) with the Ruby shell which makes the Development process much more comfortable. A good introduction to interactive\_editor: <http://vimcasts.org/episodes/running-vim-within-irb/>
Are there any tools (like... | You could have a look at the vim-ipython vim plugin:
<https://github.com/ivanov/vim-ipython>
This requires you to install the ipython shell (but I recommend doing this anyway as it adds a lot of functionality to the standard python shell).
If you don't want to install ipython, I suggest having a look at the ConqueSh... |
matplotlib centered bar chart with dates | 10,279,778 | 9 | 2012-04-23T11:37:33Z | 10,281,051 | 25 | 2012-04-23T13:00:28Z | [
"python",
"datetime",
"matplotlib"
] | To get the bars where the x-axis are dates, I am doing something like this:
```
import numpy as np
import matplotlib.pyplot as plt
import datetime
x = [datetime.datetime(2010, 12, 1, 0, 0),
datetime.datetime(2011, 1, 1, 0, 0),
datetime.datetime(2011, 5, 1, 1, 0)]
y = [4, 9, 2]
ax = plt.subplot(111)
barWidth=... | I think you want `align='center'` keyword for the `bar` method.
The minor changes to your example:
```
import numpy as np
import matplotlib.pyplot as plt
import datetime
x = [datetime.datetime(2010, 12, 1, 0, 0),
datetime.datetime(2011, 1, 1, 0, 0),
datetime.datetime(2011, 5, 1, 1, 0)]
y = [4, 9, 2]
ax = pl... |
Python- Read from Multiple Files | 10,280,963 | 4 | 2012-04-23T12:54:00Z | 10,281,141 | 7 | 2012-04-23T13:06:50Z | [
"python",
"file"
] | I have 125 data files containing two columns and 21 rows of data. Please see the image below:

and I'd like to import them into a single .csv file (as 250 columns and 21 rows).
I am fairly new to python but this what I have been advised, code wise:
... | ```
import glob
results = [open(f) for f in glob.glob("*.data")]
sep = ","
# Uncomment if your Excel formats decimal numbers like 3,14 instead of 3.14
# sep = ";"
with open("res.csv", 'w') as fout:
for row in range(21):
iterator = (f.readline().strip().replace("\t", sep) for f in results)
line = se... |
How to set the working directory for a Fabric task? | 10,280,984 | 18 | 2012-04-23T12:56:01Z | 10,282,053 | 35 | 2012-04-23T14:01:35Z | [
"python",
"fabric"
] | Assuming I define a trivial task to list files on a remote server:
```
from fabric.api import run, env
env.use_ssh_config = True
def list_files():
run('ls')
```
And I execute it with:
```
fab -H server list_files
```
How can I specify the working directory for the command I'm running, other than doing:
```
r... | Use the [Context Manager `cd`](http://docs.fabfile.org/en/latest/api/core/context_managers.html#fabric.context_managers.cd):
```
from fabric.api import run, env
from fabric.context_managers import cd
env.use_ssh_config = True
def list_files():
with cd('/tmp'):
run('ls')
``` |
gcc compilation error from python | 10,281,102 | 5 | 2012-04-23T13:04:37Z | 10,644,357 | 9 | 2012-05-17T22:30:03Z | [
"python",
"gcc",
"cygwin"
] | I know that there are lots of threads on gcc, particularly "command gcc failed with exit status 1", and I've looked at them all and still have not been able to fix this. I only would use gcc or mingw32 for python-related tasks, such as using Cython or other packages that might involve compilation. However, it never see... | So, after a while, I stumbled across a post that so far has worked for me.
<http://www.develer.com/oss/GccWinBinaries>
This site provides an unofficial MinGW GCC binary (not supported/endorsed by MinGW) that is meant to integrate perfectly with Python, down to the automatic updating of paths. I installed it and bam, ... |
Python: Original 'object' class is redefined. How to get the 'object' class back? | 10,281,984 | 2 | 2012-04-23T13:57:42Z | 10,282,152 | 7 | 2012-04-23T14:06:59Z | [
"python",
"metaclass",
"python-datamodel"
] | I am using python language for Squish Automation Tool. This tool extends python with some custom objects and functions. This is what they say in the [manual](http://doc.froglogic.com/squish/4.2/rgs-py.html):
> Squish's Python-specific extension modules are loaded automatically by
> internally executing the equivalent ... | From the very page you linked:
> Squish's object module has the same name as the base class of all Python 2 new-style classes, and of all Python 3 classes. In practice this is very rarely a problem. **For Python 2 we can just create old-style classes or do `import __builtin__` and inherit from `__builtin__.object` ins... |
Attacking Python's pickle | 10,282,175 | 20 | 2012-04-23T14:08:06Z | 10,282,300 | 11 | 2012-04-23T14:14:51Z | [
"python",
"security",
"pickle"
] | I'm writing a web app that stores user input in an object. This object will be pickled.
Is it possible for a user to craft malicious input that could do something egregious when the object is unpickled?
Here's a really basic code example that ignores wonderful principles such as encapsulation but epitomizes what I'm ... | Yes and no...
No - unless there's a bug with the interpreter or the pickle module, you can't run arbitrary code via pickled text, or something like that. unless the pickled text is `eval`ed later, or you're doing stuff like creating a new object with a type mentioned in this data.
Yes - depending on what you plan to ... |
Cython installation does not find the Python.h file? | 10,282,470 | 6 | 2012-04-23T14:25:03Z | 10,282,940 | 8 | 2012-04-23T14:55:54Z | [
"python",
"cython"
] | I wanted to install cython on my ubuntu 12.04 and I entered in the terminal
```
sudo easy_install cython
```
in response, I get the following error:
```
Searching for cython
Reading http://pypi.python.org/simple/cython/
Reading http://www.cython.org
Reading http://cython.org
Best match: Cython 0.16
Downloa... | depending on how you installed python, you may need to get the dev files as well (if you installed with apt-get or Synaptic).
```
sudo apt-get install python-dev
```
or maybe
```
sudo apt-get install python2.6-dev #substitute your python version here...
```
Note that this is necessary if you need to install any C ... |
Difference between the built-in pow() and math.pow() for floats, in Python? | 10,282,674 | 50 | 2012-04-23T14:37:23Z | 10,282,852 | 43 | 2012-04-23T14:50:00Z | [
"python",
"math"
] | Is there a difference in the results returned by Python's built-in `pow(x, y)` (no third argument) and the values returned by `math.pow()`, in the case of two *float* arguments.
I am asking this question because the [documentation](http://docs.python.org/library/math.html#math.pow) for `math.pow()` implies that `pow(x... | ## Quick Check
From the signatures, we can tell that they are different:
> **pow(x, y[, z])**
>
> **math.pow(x, y)**
Also, trying it in the shell will give you a quick idea:
```
>>> pow is math.pow
False
```
## Testing the differences
Another way to understand the differences in behaviour between the two function... |
Difference between the built-in pow() and math.pow() for floats, in Python? | 10,282,674 | 50 | 2012-04-23T14:37:23Z | 10,282,880 | 10 | 2012-04-23T14:51:17Z | [
"python",
"math"
] | Is there a difference in the results returned by Python's built-in `pow(x, y)` (no third argument) and the values returned by `math.pow()`, in the case of two *float* arguments.
I am asking this question because the [documentation](http://docs.python.org/library/math.html#math.pow) for `math.pow()` implies that `pow(x... | Python's standard `pow` includes a simple hack that makes `pow(2, 3, 2)` faster than `(2 ** 3) % 2` (of course, you'll only notice that with large numbers).
Another big difference is how the two functions handle different input formats.
```
>>> pow(2, 1+0.5j)
(1.8810842093664877+0.679354250205337j)
>>> math.pow(2, 1+... |
Difference between the built-in pow() and math.pow() for floats, in Python? | 10,282,674 | 50 | 2012-04-23T14:37:23Z | 10,283,032 | 28 | 2012-04-23T15:01:30Z | [
"python",
"math"
] | Is there a difference in the results returned by Python's built-in `pow(x, y)` (no third argument) and the values returned by `math.pow()`, in the case of two *float* arguments.
I am asking this question because the [documentation](http://docs.python.org/library/math.html#math.pow) for `math.pow()` implies that `pow(x... | `math.pow()` implicitly converts its arguments to `float`:
```
>>> math.pow(Fraction(1, 3), 2)
0.1111111111111111
>>> math.pow(Decimal(10), -1)
0.1
```
but the built-in `pow` does not:
```
>>> pow(Fraction(1, 3), 2)
Fraction(1, 9)
>>> pow(Decimal(10), -1)
Decimal('0.1')
```
> My goal is to provide an implementation... |
Python factory_boy library m2m in Django model? | 10,283,544 | 10 | 2012-04-23T15:28:33Z | 11,554,465 | 7 | 2012-07-19T05:29:27Z | [
"python",
"django",
"testing",
"factory",
"fixtures"
] | I'm currently using `factory_boy` for creating fixtures in my tests.
`Factory_boy` docs only mentioned about `SubFactory` which could act like a `ForeignKey` field in a model. However, there was nothing on ManyToMany association. If I had a following Post model, how would I go about creating a factory for it?
```
clas... | You can override the `_prepare` classmethod:
```
class PostFactory(Factory):
FACTORY_FOR = Post
title = 'My title'
@classmethod
def _prepare(cls, create, **kwargs):
post = super(PostFactory, cls)._prepare(create, **kwargs)
if post.id:
post.tags = Tag.objects.all()
... |
Python factory_boy library m2m in Django model? | 10,283,544 | 10 | 2012-04-23T15:28:33Z | 12,365,334 | 10 | 2012-09-11T08:05:23Z | [
"python",
"django",
"testing",
"factory",
"fixtures"
] | I'm currently using `factory_boy` for creating fixtures in my tests.
`Factory_boy` docs only mentioned about `SubFactory` which could act like a `ForeignKey` field in a model. However, there was nothing on ManyToMany association. If I had a following Post model, how would I go about creating a factory for it?
```
clas... | What about [post\_generation hook](http://factoryboy.readthedocs.org/en/latest/post_generation.html#postgeneration-and-post-generation) - I assume You use newer version of [factory\_boy](https://github.com/rbarrois/factory_boy)?
```
import random
import factory
class PostFactory(factory.Factory):
FACTORY_FOR = Po... |
Python : Matplotlib annotate line break (with and without latex) | 10,284,847 | 7 | 2012-04-23T16:55:31Z | 10,285,743 | 7 | 2012-04-23T17:59:02Z | [
"python",
"latex",
"matplotlib"
] | I have a very basic question : how to do a line break with matplotlib in python with an "annotate" command. I tried "\" and "\n" but it does not work. And how to do this for a "Latex" annotation and for a normal text annotation ?
Thank you very much. | What exactly did you try?
Were you, by chance, using a raw string (e.g. `r"whatever"`)?
`'\n'` works perfectly, but if you're using a raw string to avoid latex sequences being interpreted as an escape, it will be interpreted by python as `'\'` and `'n'` instead of a newline.
As an example:
```
import matplotlib.pyp... |
How to build a thread-safe Request Handler with Python Tornado | 10,285,364 | 2 | 2012-04-23T17:34:09Z | 10,291,037 | 9 | 2012-04-24T02:35:03Z | [
"python",
"tornado"
] | Does Tornado make any guarantees about how many requests are concurrently handled by a single RequestHandler? I'm thinking about managing session data like this:
```
class MyHandler(tornado.web.RequestHandler):
def prepare(self):
self.session = load_session_from_memcached
def get(self):
# work with self.s... | `RequestHandler`s are instantiated per request. A single request handler instance will serve one and only one request in its lifetime
---
Edit:
Here's the link to the part of the documentation which confirms my statement above:
<http://www.tornadoweb.org/documentation/overview.html#overriding-requesthandler-methods>... |
JavaScript timestamp to Python datetime conversion | 10,286,224 | 23 | 2012-04-23T18:33:48Z | 10,286,261 | 36 | 2012-04-23T18:36:49Z | [
"javascript",
"python",
"timestamp"
] | To get timestamp in JavaScript we use
```
var ts = new Date().getTime()
```
What is the proper way to convert it to a Python `datetime` so far I use the following code
```
>>> jsts = 1335205804950
>>> dt = datetime.datetime.fromtimestamp(jsts/1000)
>>> dt
datetime.datetime(2012, 4, 24, 0, 30, 4)
```
I divide timest... | Your current method is correct, dividing by 1000 is necessary because your JavaScript returns the timestamp in milliseconds, and `datetime.datetime.fromtimestamp()` expects a timestamp in seconds.
To preserve the millisecond accuracy you can divide by `1000.0`, so you are using float division instead of integer divisi... |
How to pass a variable from app.yaml to main.py with Google App Engine Python | 10,286,436 | 4 | 2012-04-23T18:51:16Z | 10,287,422 | 9 | 2012-04-23T20:02:21Z | [
"python",
"google-app-engine"
] | I am trying to pass some configuration variables to my main.py from app.yaml. I haven't been able to locate the syntax for accessing app.yaml from the code.
For example you want to have the user put their client number in app.yaml and access it from main.py to pass into main.html. While it would be easy to create a va... | With the 1.6.5 release, App Engine support this[1]:
```
- In your app.yaml file, you can include an env_variables stanza that will set
the given environment variables in your application's runtime.
```
Information on how to use this is available at: <https://cloud.google.com/appengine/docs/python/config/appconfig#P... |
Python complexity (run-time) | 10,287,123 | 3 | 2012-04-23T19:42:25Z | 10,287,359 | 7 | 2012-04-23T19:57:55Z | [
"python",
"big-o"
] | ```
def f2(L):
sum = 0
i = 1
while i < len(L):
sum = sum + L[i]
i = i * 2
return sum
```
Let n be the size of the list L passed to this function. Which of the following most accurately describes how the runtime of this function grow as n grows?
(a) It grows linearly, like n does.
(b) I... | I am not a computer science major and I don't claim to have a strong grasp of this kind of theory, but I thought it might be relevant for someone from my perspective to try and contribute an answer.
Your function will always take time to execute, and if it is operating on a list argument of varying length, then the ti... |
Django model inheritance: Delete subclass keep superclass | 10,287,169 | 4 | 2012-04-23T19:45:03Z | 11,465,732 | 8 | 2012-07-13T07:09:33Z | [
"python",
"django",
"django-models",
"django-orm"
] | When dealing whith model inheritance in django is it possible to remove a instance of model subclass, without removing the superclass itself?
Using the [Django example](https://docs.djangoproject.com/en/dev/topics/db/models/#multi-table-inheritance), can you remove just the `Resturaunt` object and retain the `Place` o... | Yesterday I was looking for an answer to this question and I came up with this solution, which was enough for my problem but could be scaled up as needed.
Assuming you have a Restaurant and a Place django models, the way to delete a restaurant only without touching the row inside the Place's table is creating a "fake"... |
gevent StreamServer.start() does not seem to do what I expect | 10,287,629 | 5 | 2012-04-23T20:17:51Z | 10,292,950 | 9 | 2012-04-24T06:42:59Z | [
"python",
"networking",
"concurrency",
"gevent"
] | I'm trying to wrap my brain around the concepts that [gevent](http://www.gevent.org) employs. Here's an example from the gevent code repository. It's a simple echo server.
```
from gevent.server import StreamServer
# this handler will be run for each incoming connection in a dedicated greenlet
def echo(socket, addres... | 1. start() is an asynchronous function that puts a server in a listening mode. It does not prevent your program from exiting though, which is your responsibility.
2. in simple cases you can use serve\_forever(). start() becomes useful when you need to start multiple servers or do something else in addition to starting ... |
Python convert wav to mp3 | 10,287,683 | 13 | 2012-04-23T20:22:16Z | 10,290,440 | 8 | 2012-04-24T01:04:20Z | [
"python",
"audio",
"mp3",
"wav"
] | I've looked at pymedia (discontinued), pyglet(great but no converter in there) and audiotools(command line cd ripping), and none seem suitable.
In Python 2.7 , how do you do
```
convert(wavFileLocation, 'mp3')
```
If there is no python way, how would you do it in a manner which python can invoke? (e.g. Call a Cross ... | using [lame](http://lame.sourceforge.net/) (command line), you can encode wav to mp3 like this:
```
$ lame --preset insane /path/to/file.wav
```
which would create:
```
file.wav.mp3
```
in Python, you could use [subprocess](http://docs.python.org/library/subprocess.html) to call it:
```
wav = 'myfile.wav'
cmd = 'l... |
Python convert wav to mp3 | 10,287,683 | 13 | 2012-04-23T20:22:16Z | 12,391,576 | 12 | 2012-09-12T15:26:17Z | [
"python",
"audio",
"mp3",
"wav"
] | I've looked at pymedia (discontinued), pyglet(great but no converter in there) and audiotools(command line cd ripping), and none seem suitable.
In Python 2.7 , how do you do
```
convert(wavFileLocation, 'mp3')
```
If there is no python way, how would you do it in a manner which python can invoke? (e.g. Call a Cross ... | I wrote a [python library, pydub](http://pydub.com), that essentially does what Corey's Answer suggests, though it uses ffmpeg in to do the conversions in order to support more formats.
```
from pydub import AudioSegment
AudioSegment.from_wav("/input/file.wav").export("/output/file.mp3", format="mp3")
``` |
When should I implement __call__ | 10,287,914 | 16 | 2012-04-23T20:38:21Z | 10,288,019 | 18 | 2012-04-23T20:45:29Z | [
"python"
] | In python you can make instances callable by implementing the `__call__` method. For example
```
class Blah:
def __call__(self):
print "hello"
obj = Blah()
obj()
```
But I can also implement a method of my own, say 'run':
```
class Blah:
def run(self):
print "hello"
obj = Blah()
obj.run()
`... | This is hard to answer. My opinion is that you should never define `__call__` unless your actual goal is to create a function. It's not something you would do after you've already created a traditional object.
In other words, if you're starting out thinking "I'm going to create an object" you should never end up imple... |
Usage of unicode() and encode() functions in Python | 10,288,016 | 30 | 2012-04-23T20:45:11Z | 10,288,345 | 26 | 2012-04-23T21:08:53Z | [
"python",
"string",
"sqlite",
"unicode",
"encoding"
] | I have a problem with encoding of the *path* variable and inserting it to the *SQLite* database. I tried to solve it with *encode("utf-8")* function which didn't help. Then I used *unicode()* function which gives me type *unicode*.
```
print type(path) # <type 'unicode'>
path = path.replace("one", "tw... | `str` is text representation in bytes, `unicode` is text representation in characters.
You decode text from bytes to unicode and encode a unicode into bytes with some encoding.
That is:
```
>>> 'abc'.decode('utf-8') # str to unicode
u'abc'
>>> u'abc'.encode('utf-8') # unicode to str
'abc'
``` |
Usage of unicode() and encode() functions in Python | 10,288,016 | 30 | 2012-04-23T20:45:11Z | 10,288,438 | 40 | 2012-04-23T21:15:32Z | [
"python",
"string",
"sqlite",
"unicode",
"encoding"
] | I have a problem with encoding of the *path* variable and inserting it to the *SQLite* database. I tried to solve it with *encode("utf-8")* function which didn't help. Then I used *unicode()* function which gives me type *unicode*.
```
print type(path) # <type 'unicode'>
path = path.replace("one", "tw... | You are using `encode("utf-8")` incorrectly. Python byte strings (`str` type) have an encoding, Unicode does not. You can convert a Unicode string to a Python byte string using `uni.encode(encoding)`, and you can convert a byte string to a Unicode string using `s.decode(encoding)` (or equivalently, `unicode(s, encoding... |
reading a file with json data with python throw an error that I cannot identify | 10,288,752 | 2 | 2012-04-23T21:42:45Z | 10,289,756 | 13 | 2012-04-23T23:33:39Z | [
"python",
"json"
] | I have the following json file named json.txt with the following data,
```
{"id":99903727,"nickname":"TEST_MLA_OFF","registration_date":"2010-12-03T14:19:33.000-04:00","country_id":"AR","user_type":"normal","logo":null,"points":0,"site_id":"MLA","permalink":"http://perfil.mercadolibre.com.ar/TEST_MLA_OFF","seller_repu... | Even better practice is to use the `with` statement.
```
with open('json.txt', 'r') as json_file:
data = json.load(json_file)
```
This makes sure the file gets closed properly without
you worrying about it. |
Remove dtype at the end of numpy array | 10,288,757 | 4 | 2012-04-23T21:43:20Z | 10,291,030 | 7 | 2012-04-24T02:33:01Z | [
"python",
"arrays",
"numpy"
] | I'm writing a method to create an array from data file. The method looks like:
```
import numpy
def readDataFile(fileName):
try:
with open(fileName, 'r') as inputs:
data = None
for line in inputs:
line = line.strip()
items = line.split('\t')
... | The easiest fix is to use numpy's loadtxt:
```
data = numpy.loadtxt(fileName, dtype='float')
```
Just FYI, using `numpy.vstack` inside a loop is a bad idea. If you decide not to use `loadtxt`, you can replace your loop with the following to fix the dtype issue and eliminating the `numpy.vstack`.
```
data = [row.spli... |
What is a good way to order methods in a Python class? | 10,289,461 | 23 | 2012-04-23T23:02:09Z | 10,289,641 | 7 | 2012-04-23T23:22:16Z | [
"python"
] | I want to order methods in a Python class but I don't know what is the correct order.
When I extract methods in Eclipse with PyDev, Eclipse puts the extracted method on top of the modified method. But this puts the lower level details before the higher level details. According to Uncle Bob I should do the opposite so ... | There is no one correct order. Pick a system and stick with it. The one I use is:
```
class SomeClass(object):
def __magic_methods__(self):
"magic methods first, usually in alphabetical order"
def _private_method(self):
"worker methods next, also in alpha order"
def a_method(self):
... |
Force a raw_input | 10,289,477 | 3 | 2012-04-23T23:03:10Z | 10,289,490 | 12 | 2012-04-23T23:04:49Z | [
"python"
] | How would I implement the following:
```
title_selection = raw_input("Please type in the number of your title and press Enter.\n%s" % (raw_input_string))
if not title:
# repeat raw_input
``` | ```
title_selection = ''
while not title_selection:
title_selection = raw_input("Please type in the number of your title and press Enter.\n%s" % (raw_input_string))
```
It is necessary to define `title_selection` as `''` before hand, which means empty (also False).
The `not` will make `False` to True (negation). |
Force a raw_input | 10,289,477 | 3 | 2012-04-23T23:03:10Z | 10,289,513 | 11 | 2012-04-23T23:07:57Z | [
"python"
] | How would I implement the following:
```
title_selection = raw_input("Please type in the number of your title and press Enter.\n%s" % (raw_input_string))
if not title:
# repeat raw_input
``` | This is often done with a "loop-and-a-half" construct with a `break` in the middle:
```
while True:
title_selection = raw_input("Please type in the number of your title and press Enter.\n%s" % (raw_input_string))
if title_selection:
break
print "Sorry, you have to enter something."
```
This method... |
Why wouldn't this palindrome test work? | 10,290,503 | 3 | 2012-04-24T01:16:11Z | 10,290,551 | 8 | 2012-04-24T01:22:16Z | [
"python"
] | A palindrome is a string that reads the same forwards and backwards. Examples of palindromes include "lol", "abba", "radar", and "pickle elkcip". Indicate whether or not it works under all circumstances described in the following docstring: '''Return True if string s is a palindrome and return False otherwise.'''
```
... | For fun, you could also try the much simpler:
```
def palindrome(s):
return s[::-1] == s
```
(exercise left to the reader regarding how it works) |
Subprocess Popen not working with pythonw.exe | 10,290,990 | 9 | 2012-04-24T02:26:47Z | 10,338,737 | 7 | 2012-04-26T17:51:45Z | [
"python",
"subprocess"
] | I want to be able to get the contents of stdout and stderr when I run the following script on windows using pythonw.exe:
```
import subprocess
import sys
import os
import string
import time
tmpdir = 'c:/temp'
cmd = 'dir c:'
tmpfile = "tmp_%f" % (time.time())
tmpfile = os.path.normpath(os.path.join(tmpdir,tmpfile))
t... | This is possibly a bug when using pythonw.exe
pythonw.exe starts a daemon process which doesn't have the normal access to the standard file descriptors. The only thing you would need to do in your script is to specifically set the 3rd fd for stdin:
```
p = subprocess.Popen(wcmd,
startupinfo=start... |
How to use os.umask() in Python | 10,291,131 | 6 | 2012-04-24T02:48:50Z | 10,291,187 | 7 | 2012-04-24T02:57:50Z | [
"python",
"linux",
"umask"
] | I'm trying to set a umask using the os module. Please note my normal umask set in my ~/.profile is umask 0027.
In a bash shell,
```
umask 0022
```
will allow a file to be created with permissions
```
-rw-r--r--
```
However, when us import the os module and do this:
```
os.umask(0022)
[do some other code here that... | You'll probably need to show us the code that constitutes:
```
[do some other code here that creates a file]
```
The code you have works fine on my system:
```
import os
oldmask = os.umask (022)
fh1 = os.open ("qq1.junk", os.O_CREAT, 0777)
fh2 = os.open ("qq2.junk", os.O_CREAT, 0022)
os.umask (oldmask)
os.close (fh1... |
does python has its error report message like $! in perl | 10,291,648 | 5 | 2012-04-24T04:13:42Z | 10,291,719 | 8 | 2012-04-24T04:23:16Z | [
"python",
"perl"
] | I am wondering if python has its error report message equivalent to $! in perl ?
Anyone who could give me an answer will be greatly appreciated.
Added:
```
example% ./test
File "./test", line 7
test1 = test.Test(dir)
^
SyntaxError: invalid syntax
```
When Exception occurs, I got something like this. If I apply t... | Python generally uses exceptions to report errors. If some OS operation returns an error code, it raises an exception that you catch in a try-except block. For OS operations, that is OSError. The errno is contained in the exception instance.
```
from __future__ import print_function
import os
try:
os.stat("xx... |
How can I do assignments in a list comprehension? | 10,291,997 | 17 | 2012-04-24T05:05:55Z | 10,292,038 | 16 | 2012-04-24T05:11:56Z | [
"python",
"list-comprehension"
] | I want to use the assignment operator in a list comprehension. How can I do that?
The following code is invalid syntax. I mean to set `lst[0]` to an empty string `''` if it matches `pattern`:
```
[ lst[0] = '' for pattern in start_pattern if lst[0] == pattern ]
```
Thanks! | It looks like you are confusing [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions) with [looping constructs](http://docs.python.org/tutorial/controlflow.html) in Python.
A list comprehension produces -- a list! It does not lend itself to a single assignment in an existing lis... |
Fabric: unable to get environment variables within virtualenv | 10,292,057 | 2 | 2012-04-24T05:15:06Z | 17,280,079 | 9 | 2013-06-24T16:11:19Z | [
"python",
"django",
"virtualenv",
"fabric"
] | I've a Django project which runs in virtual environment.
Also there is line `export ENV=staging` in `.bashrc` file.
And in settings I try to read this using `os.getenv('ENV')` but it returns None.
settings\_staging.py
```
...
ENV = os.getenv('ENV')
...
```
.bashrc
```
...
export ENV=staging
...
```
Error
```
[dev... | There is one more case when fabric ignores .bashrc.
Often .bashrc contains following line:
```
# If not running interactively, don't do anything
[ -z "$PS1" ] && return
```
Comment it out. |
django logging - django.request logger and extra context | 10,292,082 | 8 | 2012-04-24T05:17:33Z | 10,294,761 | 14 | 2012-04-24T08:57:52Z | [
"python",
"django",
"logging",
"django-settings"
] | Am on django 1.3., python 2.6
In the django docs here
<https://docs.djangoproject.com/en/1.3/topics/logging/#django-request>
it says that messages have the following extra context: status and request.
How do you get these to show up in the debug file? i tried in my logging config something like:
```
'formatters... | You can't use `request.user` in the format string, as %-formatting doesn't handle that. You could use a format string such as
```
'[%(asctime)s] %(levelname)s %(module)s %(message)s %(user)s'
```
and, in your logging call, use something like
```
logger.debug('My message with %s', 'args', extra={'user': request.user}... |
Insert python object in mongodb | 10,292,368 | 3 | 2012-04-24T05:48:13Z | 10,292,416 | 7 | 2012-04-24T05:53:06Z | [
"python",
"json",
"mongodb"
] | Folks,
I just spent a good amount of time trying to look this up -- I ought to be missing something basic.
I have a python object, all I want to do is to insert this object in mondodb.
This is what I have:
```
from pymongo import Connection
import json
conn = Connection()
db = conn.cl_database
postings = db.posting... | What is `value` in your initial code?
It should be `dict` not class instance
This should work:
```
postings.insert(posting.__dict__)
``` |
Arbitrarily large integers in C# | 10,293,603 | 6 | 2012-04-24T07:32:01Z | 10,293,742 | 16 | 2012-04-24T07:41:50Z | [
"c#",
".net",
"python",
"biginteger"
] | How can I implement this python code in c#?
Python code:
```
print(str(int(str("e60f553e42aa44aebf1d6723b0be7541"), 16)))
```
Result:
```
305802052421002911840647389720929531201
```
But in c# I have problems with big digits.
Can you help me?
I've got different results in python and c#. Where can be mistake? | Primitive types (such as `Int32`, `Int64`) have a finite length that it's not enough for such big number. For example:
```
Data type Maximum positive value
Int32 2,147,483,647
UInt32 4,2... |
How do I access Meteor's MongoDB from another client, while Meteor is running? | 10,293,781 | 43 | 2012-04-24T07:44:31Z | 10,302,264 | 34 | 2012-04-24T16:43:10Z | [
"python",
"mongodb",
"meteor"
] | I would like to access Meteor's MongoDB from a Python client, **while Meteor is running**.
I can't start a mongod because Meteor's database is locked.
How do I access the database from another client? | Meteor starts the mongod for you on port 3002 when you run the `meteor` command, and stores the mongo data file in `.meteor/local/db`
Output from `ps aux | grep 'mongod'` shows the mongod command that meteor uses:
```
/usr/local/meteor/mongodb/bin/mongod --bind_ip 127.0.0.1 --smallfiles --port 3002 --dbpath /path/to/... |
How do I access Meteor's MongoDB from another client, while Meteor is running? | 10,293,781 | 43 | 2012-04-24T07:44:31Z | 10,306,594 | 55 | 2012-04-24T21:55:22Z | [
"python",
"mongodb",
"meteor"
] | I would like to access Meteor's MongoDB from a Python client, **while Meteor is running**.
I can't start a mongod because Meteor's database is locked.
How do I access the database from another client? | The `meteor` command provides a clean way. To get the URL for the running mongod:
```
meteor mongo -U
```
which you can parse from python. |
How to Get the Path of the executing frozen script | 10,293,808 | 4 | 2012-04-24T07:46:27Z | 10,294,435 | 7 | 2012-04-24T08:36:24Z | [
"python",
"windows",
"path",
"argv"
] | If you are running a frozen python script (frozen using py2exe) from a directory and drive different from where the script is present, what is the best way to determine the path of the executing script?
Few solutions I have tried
```
inspect.getfile(inspect.currentframe())
```
**Problem: Does not return the full pat... | Another approach which works with cxFreeze when running from another drive even using PATH:
```
import sys
if hasattr(sys, 'frozen'):
print(sys.executable)
else:
print(sys.argv[0])
```
From Python:
```
H:\Python\Examples\cxfreeze\pwdme.py
```
From command line:
```
D:\>h:\Python\Examples\cxfreeze\dist\pwd... |
Python decorator best practice, using a class vs a function | 10,294,014 | 20 | 2012-04-24T08:02:58Z | 10,300,995 | 13 | 2012-04-24T15:23:22Z | [
"python",
"python-2.7",
"decorator",
"syntactic-sugar"
] | As I've understood it there are two ways to do a Python decorator, to either use the `__call__` of a class or to define and call a function as the decorator. What's the advantages/disadvantages of these methods? Is there one preferred method?
Example 1
```
class dec1(object):
def __init__(self, f):
self.f... | It is rather subjective to say whether there are "advantages" to each method.
However, a good understanding of what goes under the hood would make it natural
for one to pick the best choice for each occasion.
A decorator (talking about function decorators), is simply a callable object that takes a function as its inp... |
How to find the screen size of two monitors using wx.displaySize() | 10,294,920 | 6 | 2012-04-24T09:07:53Z | 10,295,188 | 8 | 2012-04-24T09:28:14Z | [
"python",
"wxpython",
"dual-monitor"
] | I want to get the screen size for two monitors using wxPython.
To get the screen size of one monitor: (screenSize is [] containing x and y value).
```
screenSize = wx.DisplaySize()
```
but I want something that will work for multiple monitors like the following:
```
screenSizeMonitor1 = wx.DisplaySize()
screenSizeM... | You can use the [GetGeometry()](http://www.wxpython.org/docs/api/wx.Display-class.html#GetGeometry) method of the [wx.Display](http://www.wxpython.org/docs/api/wx.Display-class.html) class:
```
displays = (wx.Display(i) for i in range(wx.Display.GetCount()))
sizes = [display.GetGeometry().GetSize() for display in disp... |
How to set a charset in email using smtplib in Python 2.7? | 10,295,530 | 8 | 2012-04-24T09:50:17Z | 14,506,784 | 12 | 2013-01-24T17:06:03Z | [
"python",
"email",
"character-encoding",
"smtplib"
] | I'm writing a simple smtp-sender with authentification. Here's my code
```
SMTPserver, sender, destination = 'smtp.googlemail.com', 'user@gmail.com', ['reciever@gmail.com']
USERNAME, PASSWORD = "user", "password"
# typical values for text_subtype are plain, html, xml
text_subtype = 'plain'
conte... | ```
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def contains_non_ascii_characters(str):
return not all(ord(c) < 128 for c in str)
def add_header(message, header_name, header_value):
if contains_non_ascii_characters(header_value):
... |
raise statement on a conditional expression | 10,295,841 | 10 | 2012-04-24T10:09:13Z | 10,295,905 | 10 | 2012-04-24T10:14:08Z | [
"python",
"exception",
"conditional-statements",
"raise",
"zen"
] | Following "Samurai principle", I'm trying to do this on my functions but seems it's wrong...
```
return <value> if <bool> else raise <exception>
```
Is there any other "beautiful" way to do this? Thanks | Inline/ternary `if` is an expression, not a statement. Your attempt means "if bool, return value, else return the result of `raise expression`" - which is nonsense of course, because `raise exception` is itself a statement not an expression.
There's no way to do this inline, and you shouldn't want to. Do it explicitly... |
In python - Find the maximum date in a nested dictionary | 10,296,251 | 2 | 2012-04-24T10:36:24Z | 10,296,293 | 7 | 2012-04-24T10:39:48Z | [
"python"
] | I have a dictionary that looks like the below.
For the keys '10000ag2' and 10000ag1', what is the the most efficient means to find out which key has the last\_event with the maximum date?
```
{'10000ag2':
{'last_view': datetime.datetime(2012, 4, 24, 8, 27, 30),
'last_event': datetime.datetime(2012, 4, 24, 8... | ```
max(my_dict.items(), key=lambda x: x[1]['last_event'])[0]
``` |
django: Save image from url inside another model | 10,296,483 | 6 | 2012-04-24T10:53:13Z | 10,297,655 | 8 | 2012-04-24T12:17:41Z | [
"python",
"django"
] | ```
class Item(models.Model):
name = models.CharField(max_length = 200)
image = models.ImageField(upload_to = 'read', blank=True)
creative_url = models.CharField(max_length = 200)
description = RichTextField()
def save(self, *args, **kwargs):
content = urllib2.urlopen(self.creative_url).rea... | Instead of `File`, you need to use [`django.core.files.base.ContentFile`](https://docs.djangoproject.com/en/1.4/ref/files/file/#the-contentfile-class)
```
self.image.save("test.jpg", ContentFile(content), save=False)
```
`File` accepts file object or `StringIO` object having `size` property or you need to manually se... |
Matplotlib: linewidth is added to the length of a line | 10,297,220 | 17 | 2012-04-24T11:48:05Z | 10,297,860 | 38 | 2012-04-24T12:31:29Z | [
"python",
"matplotlib"
] | When I draw a line segment in matplotlib the linewidth seems to be added to the length of the line. Below my code (not the most pythonic code, but it should do the trick). Am I doing something wrong or is this just a feature of matplotlib?
```
import matplotlib.pyplot as plt
import numpy as np
L1=100
L2=75
L3=100
Y=3
... | It looks like the default `solid_capstyle` is `projecting`, which isn't the one you want:
```
plt.figure()
plt.plot([0, 100], [5, 5], linewidth=50, linestyle="-", c="blue",
solid_capstyle="butt")
plt.plot([0, 100], [15, 15], linewidth=50, linestyle="-", c="red",
solid_capstyle="round")
plt.plot([0, 1... |
mongodb cursor id not valid error | 10,298,354 | 34 | 2012-04-24T12:59:11Z | 10,298,439 | 33 | 2012-04-24T13:05:00Z | [
"python",
"mongodb"
] | I am trying to iterate through this loop:
```
for doc in coll.find()
```
I get the following error at the 100,000th plus record.
```
File "build\bdist.win32\egg\pymongo\cursor.py", line 703, in next
File "build\bdist.win32\egg\pymongo\cursor.py", line 679, in _refresh
File "build\bdist.win32\egg\pymongo\cursor.py", ... | Maybe your cursor timed out on the server. To see if this is the problem, try to set timeout=False`:
```
for doc in coll.find(timeout=False)
```
See <http://api.mongodb.org/python/1.6/api/pymongo/collection.html#pymongo.collection.Collection.find>
If it was a timeout problem one possible solution is to set the `batc... |
mongodb cursor id not valid error | 10,298,354 | 34 | 2012-04-24T12:59:11Z | 17,644,036 | 20 | 2013-07-14T21:36:50Z | [
"python",
"mongodb"
] | I am trying to iterate through this loop:
```
for doc in coll.find()
```
I get the following error at the 100,000th plus record.
```
File "build\bdist.win32\egg\pymongo\cursor.py", line 703, in next
File "build\bdist.win32\egg\pymongo\cursor.py", line 679, in _refresh
File "build\bdist.win32\egg\pymongo\cursor.py", ... | Setting `timeout=False` is a very bad practice. A better way to get rid of the cursor id timeout exception is to estimate how many documents your loop can process within 10 minutes, and come up with an conservative batch size. This way, the MongoDB client (in this case, PyMongo) will have to query the server once in a ... |
mongodb cursor id not valid error | 10,298,354 | 34 | 2012-04-24T12:59:11Z | 19,117,631 | 28 | 2013-10-01T13:34:15Z | [
"python",
"mongodb"
] | I am trying to iterate through this loop:
```
for doc in coll.find()
```
I get the following error at the 100,000th plus record.
```
File "build\bdist.win32\egg\pymongo\cursor.py", line 703, in next
File "build\bdist.win32\egg\pymongo\cursor.py", line 679, in _refresh
File "build\bdist.win32\egg\pymongo\cursor.py", ... | * Setting the `timeout=False` is dangerous and should never be used, because the connection to the cursor can remain open for unlimited time, which will affect system performance. [The docs specifically reference](http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find) the ... |
Cython and C++ inheritance | 10,298,371 | 11 | 2012-04-24T13:00:28Z | 10,525,605 | 7 | 2012-05-09T23:34:41Z | [
"c++",
"python",
"inheritance",
"cython"
] | I have 2 classes, A and B. B inherits from A.
```
//C++
class A
{
public:
int getA() {return this->a;};
A() {this->a = 42;}
private:
int a;
};
class B: public A
{
public:
B() {this->b = 111;};
int getB() {return this->b;};
private:
int b;
};
```
Now... | I make some experiments, and have quite ready answer but now i see where is the problem:
> If your extension type has a base type, the `__cinit__` method of the
> base type is automatically called before your `__cinit__` method is
> called; you cannot explicitly call the inherited `__cinit__` method.
So the real prob... |
How to pass kwargs from save to post_save signal | 10,299,034 | 13 | 2012-04-24T13:36:45Z | 10,299,274 | 23 | 2012-04-24T13:49:05Z | [
"python",
"django"
] | I'm wiring up a custom post\_save signal and noticed that I can't seem to find an easy way to pass a set of kwargs.
During the save itself (inside a custom form)
```
def save(self, commit=True):
user = super(CustomFormThing, self).save(commit=False)
#set some other attrs on user here ...
if commit:
... | Built-in signals are sent by Django, so you can't control their kwargs.
You can:
1. Define and send your own signals.
2. Store additional info in model instance. Like this
```
def save(self, commit=True):
user = super(CustomFormThing, self).save(commit=False)
#set some other attrs on user here ..... |
How to get ModelChoiceField instances in the template | 10,300,685 | 11 | 2012-04-24T15:05:42Z | 10,301,239 | 9 | 2012-04-24T15:36:26Z | [
"python",
"django",
"django-forms"
] | I have a ModelForm that contains a ModelChoiceField using the RadioSelect widget.
```
class MyAForm(forms.ModelForm):
one_property = models.ModelChoiceField(
widget=forms.RadioSelect,
queryset=MyBModel.objects.filter(visible=True),
empty_label=None)
class Meta:
model = MyAModel
... | After delving into the django source for ModelChoiceField I discovered it has a property "queryset".
I was able to use something like...
```
{% for field in form.visible_fields %}
{% if field.name == "one_property" %}
<table>
{% for choice in field.queryset %}
<tr>
<td><inp... |
Python connected components | 10,301,000 | 4 | 2012-04-24T15:23:37Z | 13,837,045 | 7 | 2012-12-12T09:52:22Z | [
"python",
"graph-algorithm",
"connected-components"
] | I'm writing a function `get_connected_components` for a class `Graph`:
```
def get_connected_components(self):
path=[]
for i in self.graph.keys():
q=self.graph[i]
while q:
print(q)
v=q.pop(0)
if not v in path:
path=path+[v]
return path
```... | I like this algorithm:
```
def connected_components(neighbors):
seen = set()
def component(node):
nodes = set([node])
while nodes:
node = nodes.pop()
seen.add(node)
nodes |= neighbors[node] - seen
yield node
for node in neighbors:
if n... |
Unable to understand results of Python code | 10,301,335 | 2 | 2012-04-24T15:42:12Z | 10,301,360 | 11 | 2012-04-24T15:44:15Z | [
"python"
] | I was learning about dictionaries in Python and I created a simple program:
```
# Create an empty dictionary called d1
d1 = {}
# Print dictionary and length
def dixnary():
print "Dictionary contents : "
print d1
print "Length = ", len(d1)
# Add items to dictionary
d1["to"] = "two"
d1["for"] = "four"
pri... | You're attempting to print the return value of a function, but the function doesn't return a value, so it returns the default value of None.
The reason why it prints out other data is that you have print commands inside of the function. Just run the function (`dixnary()`), instead of printing it (`print dixnary()`).
... |
How do you add multiple tuples(lists, whatever) to a single dictionary key without merging them? | 10,301,589 | 2 | 2012-04-24T15:58:51Z | 10,301,664 | 8 | 2012-04-24T16:03:35Z | [
"python",
"list",
"dictionary",
"tuples"
] | I've been trying to figure out how to add multiple tuples that contain multiple values to to a single key in a dictionary. But with no success so far. I can add the values to a tuple or list, but I can't figure out how to add a tuple so that the key will now have 2 tuples containing values, as opposed to one tuple with... | Use [defaultdict](http://docs.python.org/library/collections.html#collections.defaultdict) and always use append and this will be seemless.
```
from collections import defaultdict
x = defaultdict(list)
x['Key1'].append((1.000,2.003,3.0029))
``` |
Using semicolons inside timeit | 10,301,896 | 4 | 2012-04-24T16:19:17Z | 10,301,958 | 15 | 2012-04-24T16:22:48Z | [
"python",
"exception",
"timeit"
] | I can't seem to get `timeit.timeit` to work when I have exceptions in the statement argument passed as string:
```
# after the first and third semicolon, I put 4 spaces
timeit.timeit('try:; a=1;except:; pass')
```
This results in:
```
Traceback (most recent call last):
File "a.py", line 48, in <module>
... | You need to provide properly indented code with newlines, not semi-colons. Try changing it to the following:
```
timeit.timeit('try:\n a=1\nexcept:\n pass')
```
Although this may be more readable as:
```
stmt = '''\
try:
a=1
except:
pass'''
timeit.timeit(stmt)
```
Semicolons will work fine for separat... |
Why does sys.getrefcount() return 2? | 10,302,133 | 10 | 2012-04-24T16:34:34Z | 10,302,174 | 18 | 2012-04-24T16:37:18Z | [
"python",
"numpy",
"garbage-collection"
] | As I understand, sys.getrefcount() returns the number of references of an object, which "should" be 1 in the following case:
```
import sys,numpy
a=numpy.array([1.2,3.4])
print sys.getrefcount(a)
```
However, it turned out to be 2! So, if I:
```
del a
```
Will the "numpy.array([1.2,3.4]) object still be there (no g... | When you call `getrefcount()`, the reference is copied by value into the function's argument, temporarily bumping up the object's reference count. This is where the second reference comes from.
This is explained in the [documentation](http://docs.python.org/library/sys.html#sys.getrefcount):
> The count returned is g... |
Understanding Python Pickle Insecurity | 10,302,247 | 7 | 2012-04-24T16:42:23Z | 10,302,295 | 9 | 2012-04-24T16:45:00Z | [
"python",
"security",
"namespaces",
"pickle"
] | It states in the Python documentation that `pickle` is not secure and shouldn't parse untrusted user input. If you research this; almost all examples demonstrate this with a `system()` call via `os.system`.
Whats not clear to me, is how `os.system` is interpreted correctly without the `os` module being imported.
```
... | The name of the module (`os`) is part of the opcode, and `pickle` automatically imports the module:
```
# pickle.py
def find_class(self, module, name):
# Subclasses may override this
__import__(module)
mod = sys.modules[module]
klass = getattr(mod, name)
return klass
```
Note the `__import__(modul... |
Understanding Python Pickle Insecurity | 10,302,247 | 7 | 2012-04-24T16:42:23Z | 10,307,941 | 8 | 2012-04-25T00:44:28Z | [
"python",
"security",
"namespaces",
"pickle"
] | It states in the Python documentation that `pickle` is not secure and shouldn't parse untrusted user input. If you research this; almost all examples demonstrate this with a `system()` call via `os.system`.
Whats not clear to me, is how `os.system` is interpreted correctly without the `os` module being imported.
```
... | For altogether too much information on writing malicious Pickles that go much further than the standard os.system() example, see this [presentation](https://media.blackhat.com/bh-us-11/Slaviero/BH_US_11_Slaviero_Sour_Pickles_Slides.pdf) and its accompanying [paper](https://media.blackhat.com/bh-us-11/Slaviero/BH_US_11_... |
Difference in FFT between IDL and Python | 10,302,350 | 3 | 2012-04-24T16:48:16Z | 10,302,612 | 8 | 2012-04-24T17:05:54Z | [
"python",
"scipy",
"fft",
"idl",
"idl-programming-language"
] | I'm passing some simple IDL code to Python. However the returned FFT values form the SciPy/NumPy packages is different than the IDL one and I can't find out why.
Reducing it all to a simple example of 8 elements I found that the SciPy/NumPy routines return values that are 8 (2^3) times bigger than the IDL ones (a norm... | IDL and numpy use slightly different definitions of the DFT. Numpy's is (from [the documentation](http://docs.scipy.org/doc/numpy/reference/routines.fft.html#implementation-details)):


pyglet.media.riff.WAVEFormatException: AVbin is required to decode compressed media
```
...So it didn't in... | What about installing it by:
```
sudo apt-get install libavbin-dev libavbin0
```
More information about this package: <http://packages.ubuntu.com/source/avbin> |
True dynamic and anonymous functions possible in Python? | 10,303,248 | 15 | 2012-04-24T17:48:53Z | 10,303,539 | 23 | 2012-04-24T18:07:20Z | [
"python"
] | Just as a dynamic class can be created using type(name, base-classes, namespace-dict), can a dynamic function be created?
I've tried doing something along the lines of:
```
>>> f = type("f", (function,), {})
NameError: name 'function' is not defined
```
Ok, so I'll be clever, but:
```
>>> def fn():
... pass
...
... | There is `types.FunctionType` which you can use to dynamically create a function e.g.
```
def test_func(): print 'wow'
dynf = types.FunctionType(test_func.func_code, {})
dynf()
```
Output:
```
wow
```
You might object that this is not dynamic because I am using code from another function, but that was just an exam... |
True dynamic and anonymous functions possible in Python? | 10,303,248 | 15 | 2012-04-24T17:48:53Z | 10,303,548 | 8 | 2012-04-24T18:07:58Z | [
"python"
] | Just as a dynamic class can be created using type(name, base-classes, namespace-dict), can a dynamic function be created?
I've tried doing something along the lines of:
```
>>> f = type("f", (function,), {})
NameError: name 'function' is not defined
```
Ok, so I'll be clever, but:
```
>>> def fn():
... pass
...
... | You'll want to look into [`collections.Callable`](http://docs.python.org/library/collections.html?highlight=collections.callable#collections.Callable), which is just a good place to start when defining [`__call__`](http://docs.python.org/reference/datamodel.html#emulating-callable-objects).
```
from collections import... |
Print floating point values without leading zero | 10,303,797 | 24 | 2012-04-24T18:24:21Z | 10,303,901 | 18 | 2012-04-24T18:31:24Z | [
"python",
"string-formatting"
] | Trying to use a format specifier to print a float that will be less than 1 without the leading zero. I came up with a bit of a hack but I assume there is a way to just drop the leading zero in the format specifier. I couldn't find it in the docs.
Issue
```
>>> k = .1337
>>> print "%.4f" % k
'0.1337'
```
Hack
```
>>... | Here is another way:
```
>>> ("%.4f" % k).lstrip('0')
'.1337'
```
It is slightly more general than `[1:]` in that it also works with numbers >=1.
Neither method correctly handles negative numbers, however. The following is better in this respect:
```
>>> re.sub('0(?=[.])', '', ("%0.4f" % -k))
'-.1337'
```
Not part... |
Divide the number into random number of random elements? | 10,305,292 | 2 | 2012-04-24T20:09:48Z | 10,305,400 | 7 | 2012-04-24T20:19:03Z | [
"python",
"math",
"random",
"integer-division"
] | If I need to divide for example 7 into random number of elements of random size, how would I do this?
So that sometimes I would get [3,4], sometimes [2,3,1] and sometimes [2,2,1,1,0,1]?
I guess it's quite simple, but I can't seem to get the results. Here what I am trying to do code-wise (does not work):
```
def spli... | I'd go for the next:
```
>>> def decomposition(i):
while i > 0:
n = random.randint(1, i)
yield n
i -= n
>>> list(decomposition(7))
[2, 4, 1]
>>> list(decomposition(7))
[2, 1, 3, 1]
>>> list(decomposition(7))
[3, 1, 3]
>>> list(decomposition(7))
[6, 1]
>>> list(decomposition... |
Python pass tzinfo to naive datetime without pytz | 10,306,389 | 8 | 2012-04-24T21:38:29Z | 10,308,247 | 9 | 2012-04-25T01:32:04Z | [
"python",
"timezone"
] | I've been struggling for way too long on dates/timezones in Python and was thinking someone could give me a hand here.
Basically I want to do a conversion in UTC and taking into account DST changes.
I've created the following tzinfo class from one of the Python tutorials (not 100% accurate I know but it doesn't need ... | For what it's worth, the answer @skyl provided is more-or-less equivalent to what `pytz` does.
Here is the relevant `pytz` source. It just calls `replace` on the `datetime` object with the `tzinfo` kwarg:
```
def localize(self, dt, is_dst=False):
'''Convert naive time to local time'''
if dt.tzinfo is not None... |
Python: ImportError: No module named _md5 | 10,306,531 | 11 | 2012-04-24T21:51:35Z | 10,496,035 | 7 | 2012-05-08T09:30:12Z | [
"python"
] | I have python 2.5.1 installed on my Ubuntu 10.04 x86\_64 machine.
When i try to import hashlib/md5, the i get this error
```
>>> import hashlib
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.5/hashlib.py", line 133, in <module>
md5 = __get_builtin_constructor('md5... | You have to have the package libssl-dev installed before configuring and compiling python from the tarball:
```
sudo apt-get install libssl-dev
cd YOUR_PYTHON_2.5_1_SRC_DIR
make clean
./configure
make
sudo make install
```
Do you have a good reason not to use the latest version in the 2.5.X series? |
How do you iterate over two dictionaries and grab the values at the same path? | 10,306,672 | 2 | 2012-04-24T22:01:31Z | 10,306,811 | 9 | 2012-04-24T22:14:53Z | [
"dictionary",
"python"
] | I have two dictionaries, that are of similar structure...meaning they(should) have the same key structure, even within nested keys. Also, these dicts could have almost any type of nested structure...list, dict, etc... I want to be able to traverse these dictionaries, and grab the two values and return them from a funct... | You are looking for an equivalent of `zip` but for trees represented by dictionaries.
```
from collections import Mapping
def treeZip(t1,t2):
if isinstance(t1,Mapping) and isinstance(t2,Mapping):
assert set(t1)==set(t2)
for k,v1 in t1.items():
v2 = t2[k]
for tuple in treeZi... |
Python twisted reactor undefined variable | 10,306,779 | 5 | 2012-04-24T22:12:02Z | 10,307,785 | 14 | 2012-04-25T00:19:57Z | [
"python",
"twisted",
"tcpserver"
] | I'm following this tutorial:
<http://www.raywenderlich.com/3932/how-to-create-a-socket-based-iphone-app-and-server>
but when I write the
```
reactor.listenTCP(80, factory)
```
eclipse tells me that it's an undefined variable..
I installed twisted and can get autocomplete for the import, but this won't work..
Google ... | This is a known issue related to the way Eclipse/PyDev performs static analysis.
If you look closely, the `reactor` object does not actually exist in the twisted.internet module at import-time. The module is empty.
When Eclipse/PyDev tries to compile the bytecode, static analysis doesn't see the `reactor` object in t... |
scrapy newbie: tutorial. error when running scrapy crawl dmoz | 10,306,851 | 3 | 2012-04-24T22:18:58Z | 13,035,735 | 12 | 2012-10-23T17:09:30Z | [
"python",
"scrapy"
] | I've set up my PATH variables and I think I'm configuring everything right. But when I run the "scrapy crawl dmoz" within my startproject folder, I get these error messages:
```
c:\matt\testing\dmoz>scrapy crawl dmoz
2012-04-24 18:12:56-0400 [scrapy] INFO: Scrapy 0.14.0.2841 started (bot: dmoz)
2012-04-24 18:12:56-040... | I had this issue too.
It is because the scrapy tutorial asks you to place the spider you create in `/dmoz/spiders/` but scrapy is looking in `tutorial/tutorial/spiders`.
Save the `dmoz_spider.py` in `tutorial/tutorial/spiders` and the crawl should work. |
How to put a variable into Python docstring | 10,307,696 | 16 | 2012-04-25T00:07:46Z | 10,307,738 | 11 | 2012-04-25T00:13:20Z | [
"python",
"docstring"
] | So I'm trying to create a "dynamic" docstring which is something like this:
```
ANIMAL_TYPES = ["mammals", "reptiles", "other"]
def func(animalType):
""" This is a sample function.
@param animalType: "It takes one of these animal types %s" % ANIMAL_TYPES
"""
```
to basically let the docstring for `@param animal... | Triple-quoted strings are one big string. Nothing is evaluated inside them. The `%` part is all part of the string. You'd need to have it operating on the actual string.
```
def func(animalType):
"""
This is a sample function.
@param animalType: "It takes one of these animal types %(ANIMAL_TYPES)s"
""... |
How to put a variable into Python docstring | 10,307,696 | 16 | 2012-04-25T00:07:46Z | 10,308,363 | 18 | 2012-04-25T01:54:23Z | [
"python",
"docstring"
] | So I'm trying to create a "dynamic" docstring which is something like this:
```
ANIMAL_TYPES = ["mammals", "reptiles", "other"]
def func(animalType):
""" This is a sample function.
@param animalType: "It takes one of these animal types %s" % ANIMAL_TYPES
"""
```
to basically let the docstring for `@param animal... | One way to do this would be to use a decorator. I'm not sure how I feel about this; I actually searched for commentary on this method and found [this answer](http://stackoverflow.com/a/9745145/577088), which rightly notes that it could mask a design problem. But your use case *seems* sound to me at first glance.
In an... |
matplotlib legend showing double errorbars | 10,308,003 | 4 | 2012-04-25T00:54:08Z | 10,308,187 | 11 | 2012-04-25T01:25:44Z | [
"python",
"matplotlib"
] | Why is matplotlib is showing two error bars? I think it may have something to do with the asymmetric error bars.

You can reproduce the problem with this:
```
>>> import matplotlib.pyplot as plt
>>> plt.errorbar([1,2,3],[3,4,2],yerr=[[1,2,0.5]]*2, la... | you can set the number of points in legend:
```
plt.legend(numpoints=1)
``` |
Python List Comprehensions Splitting loop variable | 10,308,939 | 7 | 2012-04-25T03:26:29Z | 10,308,980 | 9 | 2012-04-25T03:31:47Z | [
"python",
"split",
"list-comprehension"
] | First please forgive me for the somewhat poor title. I wasn't quite sure how to word it. If someone could suggest a better title that would be great.
I am trying to find out if there is a way to split the value of each iteration of a list comprehension only once but use it twice in the output. An example of the proble... | You could use a list comprehension wrapped around a generator expression:
```
[(x[1],x[2]) for x in (x.split(";") for x in a.split("\n")) if x[1] != 5]
``` |
Mocking - How do I raise exception on the caller? | 10,309,132 | 14 | 2012-04-25T03:52:19Z | 10,310,532 | 20 | 2012-04-25T06:37:23Z | [
"python",
"unit-testing",
"mocking"
] | Suppose this is the code
```
def move(*args, **kwargs):
try:
shutil.move(source, destination)
except Exception as e:
raise e
```
and in my tests.py
```
@patch.object(shutil, 'move')
def test_move_catch_exception(self, mock_rmtree):
''' Tests moving a target hits exception. '''
mock... | You've got a typo in your example, missing a `'`.
Its not entirely clear what you're asking, but if I understand you correctly, you're asking how to test that a raised exception is caught inside `move`. One problem is that you're patching `shutil.rmtree`, not `shutil.move`, but you can't be certain that`shutil.rmtree`... |
Python beautifulsoup iterate over table | 10,309,550 | 8 | 2012-04-25T04:57:47Z | 10,309,647 | 23 | 2012-04-25T05:08:39Z | [
"python",
"beautifulsoup"
] | I am trying to scrape table data into a CSV file. Unfortunately, I've hit a road block and the following code simply repeats the TD from the first TR for all subsequent TRs.
```
import urllib.request
from bs4 import BeautifulSoup
f = open('out.txt','w')
url = "http://www.international.gc.ca/about-a_propos/atip-aiprp... | You're starting at the top level of your document each time you use `find()` or `find_all()`, so when you ask for, for example, all the "td"` tags you're getting all the "td" tags *in the document,* not just those in the table and row you have searched for. You might as well not search for those because they're not bei... |
Concatenate or print list elements with a trailing comma in Python | 10,311,323 | 7 | 2012-04-25T07:37:35Z | 10,311,390 | 10 | 2012-04-25T07:41:53Z | [
"python",
"string",
"list",
"join"
] | I am having a list as :
```
>>> l = ['1', '2', '3', '4']
```
if I use join statement,
```
>>> s = ', '.join(l)
```
will give me output as :
```
'1, 2, 3, 4'
```
But, what I have to do If I want output as :
```
'1, 2, 3, 4,'
```
(I know that I can use string concat but I want to know some better way)
. | String concatenation is the best way:
```
l = ['1', '2', '3', '4'] # original list
s = ', '.join(l) + ','
```
but you have other options also:
1. Mapping to comma-ended strings, then joining:
```
l = ['1', '2', '3', '4'] # original list
s = ' '.join(map(lambda x: '%s,' % x, l))
```
2. Appending empty ... |
how to fit a function using PyBrain networks? | 10,311,642 | 5 | 2012-04-25T08:00:04Z | 12,621,199 | 8 | 2012-09-27T12:17:40Z | [
"python",
"pybrain"
] | there is a function like:
y = sin(x)
I want to use PyBrain networks to fit the functions, here are what i did:
when you run it you will get what i get, the data obtained is far from what it should be.
```
from pybrain.datasets import SupervisedDataSet
from pybrain.tools.shortcuts import buildNetwork
from pybrain.super... | I suppose your problem is that this network does not fit the function well. The total number of network nodes is too low to properly fit this sin(x) function: the function is too complex. Also, for fitting any function, no more than one hidden layer is required in principle.
For instance, try to remove two hidden laye... |
Is it possible to make POST request in Flask? | 10,313,001 | 10 | 2012-04-25T09:37:34Z | 10,313,115 | 12 | 2012-04-25T09:44:16Z | [
"python",
"post",
"flask"
] | There is a need to make POST request from server side in Flask.
Let's imagine that we have:
```
@app.route("/test", methods=["POST"])
def test():
test = request.form["test"]
return "TEST: %s" % test
@app.route("/index")
def index():
# Is there something_like_this method in Flask to perform the POST reque... | Yes, to make a POST request you can use `urllib2`, see the [documentation](http://docs.python.org/library/urllib2.html#urllib2.urlopen).
I would however recommend to use the [requests](http://docs.python-requests.org/en/latest/user/quickstart/#make-a-post-request) module instead.
**EDIT**:
I suggest you refactor you... |
Python: access class variables via instance | 10,313,471 | 13 | 2012-04-25T10:06:03Z | 10,313,587 | 13 | 2012-04-25T10:11:59Z | [
"python",
"scope",
"specifications"
] | In Python, class variables can be accessed via that class instance:
```
>>> class A(object):
... x = 4
...
>>> a = A()
>>> a.x
4
```
It's easy to show that `a.x` is really resolved to `A.x`, not copied to an instance during construction:
```
>>> A.x = 5
>>> a.x
5
```
Despite the fact that this behavior is [well... | Refs the `Classes` and `Class instances` parts in <http://docs.python.org/reference/datamodel.html>
> A class has a namespace implemented by a dictionary object. Class
> attribute references are translated to lookups in this dictionary,
> e.g., C.x is translated to C.\_\_dict\_\_["x"] (although for new-style classes i... |
Python: access class variables via instance | 10,313,471 | 13 | 2012-04-25T10:06:03Z | 10,315,555 | 7 | 2012-04-25T12:25:31Z | [
"python",
"scope",
"specifications"
] | In Python, class variables can be accessed via that class instance:
```
>>> class A(object):
... x = 4
...
>>> a = A()
>>> a.x
4
```
It's easy to show that `a.x` is really resolved to `A.x`, not copied to an instance during construction:
```
>>> A.x = 5
>>> a.x
5
```
Despite the fact that this behavior is [well... | Not only can you rely on this behavior, you constantly do.
Think about methods. A method is merely a function that has been made a class attribute. You then look it up on the instance.
```
>>> def foo(self, x):
... print "foo:", self, x
...
>>> class C(object):
... method = foo # What a weird way to write th... |
"SyntaxError: unexpected EOF while parsing" on simple python print() method | 10,313,742 | 2 | 2012-04-25T10:21:58Z | 10,313,772 | 8 | 2012-04-25T10:24:15Z | [
"python"
] | I get the message "SyntaxError: unexpected EOF" on Python when typing the very simple script below. What have I done wrong and what does this message mean? Many thanks.
```
c = 5
d = c*c
print("the type of d is"+ str(type(d))
``` | You have to add `)` on the end! |
Pymongo Query with Dictionary inside Dictionary? | 10,313,762 | 4 | 2012-04-25T10:23:37Z | 10,315,861 | 7 | 2012-04-25T12:42:05Z | [
"python",
"mongodb",
"pymongo"
] | I have Document in MongoDB like this:
```
{"ONE": {"TWO": {"THREE":"5"}}}
```
I want to query mongoDb using the [Pymongo `find` API](http://api.mongodb.org/python/current/api/pymongo/collection.html), but it's not working:
```
for value in dbaccess.find({"ONE":{"TWO":{"THREE":{"$gt":"0"}}}}):
print value
```
N... | Two things:
1. If you want to treat the 5 in your document as an integer, don't enclose it in double quotes.
2. Use dot notation for querying nested documents:
`dbaccess.find("ONE.TWO.THREE": {"$gt": 0})` |
Flask url_for URLs in Javascript | 10,314,800 | 23 | 2012-04-25T11:37:48Z | 10,335,702 | 12 | 2012-04-26T14:38:27Z | [
"javascript",
"python",
"flask",
"url-for"
] | What is the recommended way to create dynamic URLs in Javascript files when using flask? In the jinja2 templates and within the python views `url_for` is used, what is the recommended way to do this in `.js` files? Since they are not interpreted by the template engine.
What basically want to do is:
```
// in comments... | The [Flask documentation](http://flask.pocoo.org/docs/patterns/jquery/#where-is-my-site) suggests using `url_for` in your HTML file to set a variable containing the root URL that you can access elsewhere. Then, you would have to manually build the view URLs on top of that, although I guess you could store them similar ... |
Flask url_for URLs in Javascript | 10,314,800 | 23 | 2012-04-25T11:37:48Z | 27,784,659 | 12 | 2015-01-05T17:25:05Z | [
"javascript",
"python",
"flask",
"url-for"
] | What is the recommended way to create dynamic URLs in Javascript files when using flask? In the jinja2 templates and within the python views `url_for` is used, what is the recommended way to do this in `.js` files? Since they are not interpreted by the template engine.
What basically want to do is:
```
// in comments... | What @dumbmatter's suggesting is pretty much considered a de facto standard way. But I thought there would be a nicer way of doing it. So I managed to develop this plugin: [Flask-JSGlue](http://stewartpark.github.io/Flask-JSGlue/).
After adding `{{ JSGlue.include() }}`, you can do the following in your source code:
`... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.