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 force errorbars to render last with Matplotlib
14,003,572
13
2012-12-22T14:17:17Z
14,007,175
14
2012-12-22T22:40:37Z
[ "python", "matplotlib" ]
I am trying over-plot some empirical data with error bars on top of my modelled data. The error bars seem to be rendering first and are consequently getting over written (see below) I have tried using zorder but I still get the same result. The code I am using is ``` for i in range(1,len(pf)): pf[i,:]...
This looks like it is a bug in `matplotlib` where the `zorder` argument of the `errorbar` is not correctly passed to the vertical lines part of error bars. replicates your problem : ``` import matplotlib.pyplot as plt fig = plt.figure() ax = plt.gca() [ax.plot(rand(50),color='0.75') for j in range(122)]; ax.errorbar(...
python function *args and **kwargs with other specified keyword arguments
14,003,939
8
2012-12-22T15:14:48Z
14,004,227
12
2012-12-22T15:57:07Z
[ "python", "methods", "args", "kwargs" ]
I have a Python class with a method which should accept arguments and keyword arguments this way ``` class plot: def __init__(self, x, y): self.x = x self.y = y def set_axis(self, *args, xlabel="x", ylabel="y", **kwargs): for arg in args: <do something> for key in k...
You would use a different pattern: ``` def set_axis(self, *args, **kwargs): xlabel = kwargs.get('xlabel', 'x') ylabel = kwargs.get('ylabel', 'y') ``` This allows you to use \* and \*\* while keeping the fallback values if keyword arguments aren't defined.
python function *args and **kwargs with other specified keyword arguments
14,003,939
8
2012-12-22T15:14:48Z
14,004,251
11
2012-12-22T15:59:40Z
[ "python", "methods", "args", "kwargs" ]
I have a Python class with a method which should accept arguments and keyword arguments this way ``` class plot: def __init__(self, x, y): self.x = x self.y = y def set_axis(self, *args, xlabel="x", ylabel="y", **kwargs): for arg in args: <do something> for key in k...
In Python 3 this works: ``` Python 3.2.3 (default, Oct 19 2012, 19:53:16) >>> def set_axis(self, *args, xlabel="x", ylabel="y", **kwargs): ... print(args, xlabel, ylabel, kwargs) ... >>> set_axis(None, "test1", "test2", xlabel="new_x", my_kwarg="test3") ('test1', 'test2') new_x y {'my_kwarg': 'test3'} >>> ```
Good Practice: Organizing views.py in Django Apps
14,006,028
5
2012-12-22T19:47:52Z
14,006,174
14
2012-12-22T20:07:07Z
[ "python", "django", "views", "models" ]
I am learning Django. My background is from PHP and Java with experience using Model View Controller frameworks. I have always had a seperate file for each of my views, models, and templates - but the Django tutorial only mentions having one views.py and models.py. That seems to be okay if you have a small application...
There is no problem with having multiple files containing views and models. In fact all you need is module `views` and module `models`. In python the module is either file that ends with `.py` or folder that contains file `__init__.py`. The app can look something like: ``` app_folder - views | - __init__....
Python: sending data between two computers via sockets
14,007,227
7
2012-12-22T22:48:04Z
14,007,510
7
2012-12-22T23:39:03Z
[ "python", "sockets", "tcp", "connection" ]
I am working on a script that would transmit the data between two distinct computers with access to the internet. I am using python's socket standard module. It works fine when I run both client and server on single computer but I am not able to make the things work when they run on different computers. Here is a part...
This does probably not have to do with your code which looks okay. I rather think that this is a problem with the IP addresses that you're using. If the computers are on different networks you need to make sure that the IP address that you're passing is the one accessible to the net. Basically what this means is that ...
Python Regex instantly replace groups
14,007,545
15
2012-12-22T23:45:57Z
14,007,559
42
2012-12-22T23:48:38Z
[ "python", "regex", "regex-group" ]
Is there any way to directly replace all groups in regex-syntax. The normal way: ``` re.match(r"(?:aaa)(_bbb)", string1).group(1) ``` Yet I want to achieve something like this: ``` re.match(r"(\d.*?)\s(\d.*?)", "(CALL_GROUP_1) (CALL_GROUP_2)") ``` So I just want to build the new string instantaneous if possible by...
Have a look at [`re.sub`](http://docs.python.org/2/library/re.html#re.sub): ``` result = re.sub(r"(\d.*?)\s(\d.*?)", r"\1 \2", string1) ``` This is Python's regex substitution (replace) function. The replacement string can be filled with so-called backreferences (backslash, group number) which are replaced with what ...
Optimizing Python code for efficiency
14,008,421
3
2012-12-23T03:38:55Z
14,008,432
9
2012-12-23T03:40:36Z
[ "python", "python-3.x" ]
Profiling this code shows the bulk of the time is spent on the log operation. Is there another way to write this in Python 3 for more efficiency? Replacing the loop with a list comprehension was actually less efficient and so was map because of lambdas. ``` def log_total(data): total = 0.0 log = log(data) ...
I'd factor the `log` out of your summation and cache your sum: ``` harmonic_series = sum(1. / i for i in range(1, 10001)) # Thanks, @mgilson def log_total(data): return log(data) * harmonic_series ``` You could also use [PyPy](http://pypy.org/) to speed it up even more.
How to extract numbers from filename in Python?
14,008,440
5
2012-12-23T03:42:14Z
14,008,454
12
2012-12-23T03:45:56Z
[ "python" ]
I need to extract just the numbers from file names such as: GapPoints1.shp GapPoints23.shp GapPoints109.shp How can I extract just the numbers from these files using Python? I'll need to incorporate this into a `for` loop.
you can use regular expressions: ``` regex = re.compile(r'\d+') ``` Then to get the strings that match: ``` regex.findall(filename) ``` This will return a list of strings which contain the numbers. If you actually want integers, you could use `int`: ``` [int(x) for x in regex.findall(filename)] ``` If there's onl...
Please explain this algorithm to get all permutations of a String
14,008,521
7
2012-12-23T04:06:43Z
14,008,544
36
2012-12-23T04:11:32Z
[ "python", "string", "recursion", "permutation" ]
The following code generates all the permutations for a string: ``` def permutations(word): if len(word)<=1: return [word] #get all permutations of length N-1 perms=permutations(word[1:]) char=word[0] result=[] #iterate over all permutations of length N-1 for perm in perms: ...
The algorithm is: * Remove the first letter * Find all the permutations of the remaining letters (recursive step) * Reinsert the letter that was removed in every possible location. The base case for the recursion is a single letter. There is only one way to permute a single letter. **Worked example** Imagine the st...
Exif reading library
14,009,148
4
2012-12-23T06:33:46Z
14,046,303
11
2012-12-26T21:11:11Z
[ "python", "image", "python-3.x", "exif" ]
Is there an exif library out there for Python 3.x? It seems every exif library I run into is for Python 2.x only. I don't need anything too fancy. Just reading the values is enough.
Option 1. Use pyexiv2. See: [pyexiv2 Bug #824440: Python 3 support](https://bugs.launchpad.net/pyexiv2/+bug/824440) You need boost-python for py3k and also to manually apply the patch posted at the end of the bug above, but aside from that it works. Probably easiest to get up and running under latest Ubuntu. Option 2....
How to use malt parser in python nltk
14,009,330
12
2012-12-23T07:18:02Z
14,065,146
17
2012-12-28T05:46:52Z
[ "python", "parsing", "nlp", "nltk" ]
As a part of my academic project I need to parse a bunch of arbitrary sentences into a dependency graph. After a searching a lot I got the solution that I can use Malt Parser for parsing text with its pre trained grammer. I have downloaded pre-trained model (engmalt.linear-1.7.mco) from <http://www.maltparser.org/mco/...
# Edited Note that is answer is no longer working because of the updated version of the MaltParser API in NLTK since August 2015. This answer is kept for legacy sake. Please see this answers to get MaltParser working with NLTK: * [Step by step to getting malt parser in NLTK to work?](http://stackoverflow.com/questio...
Define pyqt4 signals with a list as argument
14,010,731
6
2012-12-23T11:52:30Z
14,010,987
12
2012-12-23T12:35:49Z
[ "python", "signals", "pyqt4", "signals-slots" ]
According to <http://pyqt.sourceforge.net/Docs/PyQt4/new_style_signals_slots.html> I can define a pyqt4-signal with takes an integer argument by `mysignal = pyqtSignal(int)`. How can I define a signal which takes an integer and a list of strings or more generally of an object called `myobject` as argument.
The following code creates a signal which takes two arguments: an integers and a list of objects. The UI contains just a button. The signal is emitted when the button is clicked. ``` from PyQt4.QtGui import * from PyQt4.QtCore import * class Foo(object): pass class MyWidget(QWidget): mysignal = pyqtSignal(in...
How to use python mysqldb to insert many rows at once
14,011,160
15
2012-12-23T13:02:08Z
14,011,206
26
2012-12-23T13:07:45Z
[ "python", "mysql", "mysql-python" ]
I have a list of lists, e.g `[['a','b'],['c','d']]`. I have a table called `T` and two fields `F1`, `F2`. The first item in the field list maps to `F1`, second to `F2`. How can I insert rows for each inner list in a single command or call, rather than using a for loop like this? ``` for i in [['a','b'],['c','d']]: ...
From [MySQLdb User's Guide](http://mysql-python.sourceforge.net/MySQLdb.html): ``` c.executemany( """INSERT INTO breakfast (name, spam, eggs, sausage, price) VALUES (%s, %s, %s, %s, %s)""", [ ("Spam and Sausage Lover's Plate", 5, 1, 8, 7.95 ), ("Not So Much Spam Plate", 3, 2, 0, 3.95 ), ...
Parseval's theorem in Python
14,011,506
11
2012-12-23T13:54:35Z
14,012,538
15
2012-12-23T16:18:38Z
[ "python", "math", "numpy", "scipy", "fft" ]
I'm trying to get some grip on Python's fft functionality, and one of the weird things that I've stumbled on is that [Parseval's theorem](http://en.wikipedia.org/wiki/Parseval%27s_theorem) doesn't seem to apply, as it gives a difference of about 50 now, while it should be 0. ``` import numpy as np import matplotlib.py...
Your **normalization factor** is coming from trying to apply Parseval's theorem for the Fourier transform of a continuous signal to a discrete sequence. On the side panel of [the wikipedia article on the Discrete Fourier transform](http://en.wikipedia.org/wiki/Discrete_Fourier_transform) there is some discussion on the...
Sorting a networkx graph object Python
14,011,600
4
2012-12-23T14:08:01Z
14,011,791
7
2012-12-23T14:33:08Z
[ "python", "networkx" ]
I want to sort a graph object that I have read through networkx library in Python, in the increasing order of edgeweight. It seems that the `sort` command of python won't apply to graph objects. I am sure there is a easy way to sort this object, but I am not sure how. Any help will be appreciated. For example, my firs...
``` import networkx as nx edgelist = [ (1, 3, {'weight':5250}), (1, 4, {'weight': 74}), (1, 5, {'weight': 3659})] G = nx.Graph(edgelist) for a, b, data in sorted(G.edges(data=True), key=lambda (a, b, data): data['weight']): print('{a} {b} {w}'.format(a=a, b=b, w=data['weight'])) ``` yields ``` 1 4 74...
Django - referencing static files in templates
14,013,436
7
2012-12-23T18:17:22Z
14,017,104
14
2012-12-24T04:33:48Z
[ "python", "django", "templates", "twitter-bootstrap", "static" ]
I'm having difficulty referencing static files in my templates. I am using Twitter Bootstrap and have the bootstrap files (css, img, js) sitting at mysite/static. I have set the `STATIC_URL`, `STATIC_ROOT` and `TEMPLATE_CONTEXT_PROCESSORS` according to [this tutorial](https://docs.djangoproject.com/en/dev/howto/static...
It should be `{% load static from staticfiles %}` And then something like `<link href="{% static 'bootstrap/css/bootstrap.css' %}" rel="stylesheet" type="text/css">` **Update for Completeness** *Folder Structure* * proj + app1 + app2 + myproj\_public + static - css * bootstrap.css - js ...
Django - "no module named django.core.management"
14,013,728
64
2012-12-23T18:52:41Z
14,013,820
42
2012-12-23T19:02:22Z
[ "python", "django" ]
I get the following error when trying to run Django from the command line. ``` File manage.py, line 8, in <module>      from django.core.management import execute_from_command_line ImportError: No module named django.core.management ``` Any ideas on how to solve this?
It sounds like you do not have django installed. You should check the directory produced by this command: ``` python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()" ``` To see if you have the django packages in there. If there's no django folder inside of site-packages, then you do not ha...
Django - "no module named django.core.management"
14,013,728
64
2012-12-23T18:52:41Z
18,572,598
22
2013-09-02T11:50:07Z
[ "python", "django" ]
I get the following error when trying to run Django from the command line. ``` File manage.py, line 8, in <module>      from django.core.management import execute_from_command_line ImportError: No module named django.core.management ``` Any ideas on how to solve this?
I got the same error and I fixed it in this manner: I had to activate my virtual environment using the following command ``` source python2.7/bin/activate ```
Django - "no module named django.core.management"
14,013,728
64
2012-12-23T18:52:41Z
19,196,519
15
2013-10-05T10:09:07Z
[ "python", "django" ]
I get the following error when trying to run Django from the command line. ``` File manage.py, line 8, in <module>      from django.core.management import execute_from_command_line ImportError: No module named django.core.management ``` Any ideas on how to solve this?
Most probably in your `manage.py` the first line starts with `!/usr/bin/python` which means you are using the system global python rather than the one in your virtual environment. so replace ``` /usr/bin/python ``` with ``` ~/projectpath/venv/bin/python ``` and you should be good.
Django - "no module named django.core.management"
14,013,728
64
2012-12-23T18:52:41Z
19,351,891
10
2013-10-14T00:29:15Z
[ "python", "django" ]
I get the following error when trying to run Django from the command line. ``` File manage.py, line 8, in <module>      from django.core.management import execute_from_command_line ImportError: No module named django.core.management ``` Any ideas on how to solve this?
Are you using a Virtual Environment with Virtual Wrapper? Are you on a Mac? If so try this: Enter the following into your command line to start up the virtual environment and then work on it 1.) ``` source virtualenvwrapper.sh ``` or ``` source /usr/local/bin/virtualenvwrapper.sh ``` 2.) ``` workon [environment...
Django - "no module named django.core.management"
14,013,728
64
2012-12-23T18:52:41Z
24,787,342
7
2014-07-16T17:44:40Z
[ "python", "django" ]
I get the following error when trying to run Django from the command line. ``` File manage.py, line 8, in <module>      from django.core.management import execute_from_command_line ImportError: No module named django.core.management ``` Any ideas on how to solve this?
well, I faced the same error today after installing virtualenv and django. For me it was that I had used sudo (**sudo pip install django**) for installing django, and I was trying to run the **manage.py runserver** without **sudo**. I just added sudo and it worked. :)
Django - "no module named django.core.management"
14,013,728
64
2012-12-23T18:52:41Z
29,103,702
17
2015-03-17T15:51:04Z
[ "python", "django" ]
I get the following error when trying to run Django from the command line. ``` File manage.py, line 8, in <module>      from django.core.management import execute_from_command_line ImportError: No module named django.core.management ``` Any ideas on how to solve this?
``` sudo pip install django --upgrade ``` did the trick for me.
How to change window size?
14,014,955
12
2012-12-23T21:45:26Z
30,332,167
21
2015-05-19T17:21:40Z
[ "python", "kivy" ]
I'm starting to write a program using [`kivy`](http://kivy.org/#home), but I have some problems understand how it deals with sizes. For example: ``` import kivy kivy.require('1.5.1') from kivy.app import App from kivy.uix.button import Button class MyApp(App): def build(self): return Button(text='Some text') M...
There're currently two ways: * Before the window is created: ``` import kivy kivy.require('1.9.0') from kivy.config import Config Config.set('graphics', 'width', '200') Config.set('graphics', 'height', '200') ``` * Dynamically after the Window was created: ``` from kivy.core.window import Window ...
reloading module which has been imported to another module
14,015,405
11
2012-12-23T23:05:57Z
14,015,429
9
2012-12-23T23:10:43Z
[ "python", "import", "module", "reload" ]
Let's face it, the whole business of reloading python code after changing it is a mess. I figured out awhile back that calling `import <module>` at the interpreter is better than `from <module> import <class/function>`, because then I can call `reload(module)` to get updated code. But I have more complicated issues no...
To reload a module, you have to use `reload`, and you have to use it on the module you want to reload. Reloading a module doesn't recursively reload all modules imported by that module. It just reloads that one module. When a module is imported, a reference to it is stored, and later imports of that module re-use the ...
reloading module which has been imported to another module
14,015,405
11
2012-12-23T23:05:57Z
17,370,179
8
2013-06-28T17:13:04Z
[ "python", "import", "module", "reload" ]
Let's face it, the whole business of reloading python code after changing it is a mess. I figured out awhile back that calling `import <module>` at the interpreter is better than `from <module> import <class/function>`, because then I can call `reload(module)` to get updated code. But I have more complicated issues no...
Have a look into IPython. It has the [autoreload](http://ipython.org/ipython-doc/stable/config/extensions/autoreload.html) extension that automatically reloads modules during the interpreter session before calling functions within. I cite the example from the landing page: ``` In [1]: %load_ext autoreload In [2]: %au...
How to create a new unknown or dynamic/expando object in Python
14,015,592
12
2012-12-23T23:41:47Z
14,015,611
24
2012-12-23T23:44:46Z
[ "python", "oop", "class", "object", "expandoobject" ]
In python how can we create a new object without having a predefined Class and later dynamically add properties to it ? example: ``` dynamic_object = Dynamic() dynamic_object.dynamic_property_a = "abc" dynamic_object.dynamic_property_b = "abcdefg" ``` What is the best way to do it? **EDIT** Because many people advi...
Just define your own class to do it: ``` class Expando(object): pass ex = Expando() ex.foo = 17 ex.bar = "Hello" ```
How to create a new unknown or dynamic/expando object in Python
14,015,592
12
2012-12-23T23:41:47Z
14,016,216
9
2012-12-24T01:46:45Z
[ "python", "oop", "class", "object", "expandoobject" ]
In python how can we create a new object without having a predefined Class and later dynamically add properties to it ? example: ``` dynamic_object = Dynamic() dynamic_object.dynamic_property_a = "abc" dynamic_object.dynamic_property_b = "abcdefg" ``` What is the best way to do it? **EDIT** Because many people advi...
Using an object just to hold values isn't the most Pythonic style of programming. It's common in programming languages that don't have good associative containers, but in Python, you can use use a dictionary: ``` my_dict = {} # empty dict instance my_dict["foo"] = "bar" my_dict["num"] = 42 ``` You can also use a "di...
Django - syncdb doesn't create tables
14,016,064
8
2012-12-24T01:18:23Z
14,016,120
15
2012-12-24T01:28:53Z
[ "python", "django" ]
I added a many-to-many field to an existing model and was expecting `syncdb` to create a new table, but there's nothing there. This is what the model looks like: ``` class Author(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailFiel...
The syncdb command does not create many to many tables for existing models by design. This decision is explained on [ticket 2229](https://code.djangoproject.com/ticket/2229). That leaves you with a few options. * If you don't have any data in your Book model, drop the table and rerun syncdb. Django will recreate the ...
How do I write a Latex formula in the legend of a plot using Matplotlib inside a .py file?
14,016,217
6
2012-12-24T01:46:43Z
14,016,651
8
2012-12-24T03:14:54Z
[ "python", "matplotlib", "latex" ]
I am writing a script in Python (.py file) and I am using Matplotlib to plot an array. I want to add a legend with a formula to the plot, but I haven't been able to do it. I have done this before in IPython or the terminal. In this case, writing something like this: ``` legend(ur'$The_formula$') ``` worked perfectly....
It is easiest way is to assign the label when you plot the data, ex: ``` import matplotlib.pyplot as plt ax = plt.gca() # or any other way to get an axis object ax.plot(x, y, label=r'$\sin (x)$') ax.legend() ```
Python - find integer index of rows with NaN in pandas
14,016,247
35
2012-12-24T01:53:49Z
14,016,590
19
2012-12-24T03:02:12Z
[ "python", "pandas" ]
I have a pandas DataFrame like this: ``` a b 2011-01-01 00:00:00 1.883381 -0.416629 2011-01-01 01:00:00 0.149948 -1.782170 2011-01-01 02:00:00 -0.407604 0.314168 2011-01-01 03:00:00 1.452354 NaN 2011-01-01 04:00:00 -1.224869 -0.947457 2011-01-01 05:00:00 0.498326 0.070416 2011-01-01 06:...
For DataFrame `df`: ``` import numpy as np index = df['b'].index[df['b'].apply(np.isnan)] ``` will give you back the `MultiIndex` that you can use to index back into `df`, e.g.: ``` df['a'].ix[index[0]] >>> 1.452354 ``` For the integer index: ``` df_index = df.index.values.tolist() [df_index.index(i) for i in inde...
Python - find integer index of rows with NaN in pandas
14,016,247
35
2012-12-24T01:53:49Z
14,033,137
76
2012-12-25T18:41:23Z
[ "python", "pandas" ]
I have a pandas DataFrame like this: ``` a b 2011-01-01 00:00:00 1.883381 -0.416629 2011-01-01 01:00:00 0.149948 -1.782170 2011-01-01 02:00:00 -0.407604 0.314168 2011-01-01 03:00:00 1.452354 NaN 2011-01-01 04:00:00 -1.224869 -0.947457 2011-01-01 05:00:00 0.498326 0.070416 2011-01-01 06:...
Here is a simpler solution: `inds = pd.isnull(df).any(1).nonzero()[0]` ``` In [9]: df Out[9]: 0 1 0 0.450319 0.062595 1 -0.673058 0.156073 2 -0.871179 -0.118575 3 0.594188 NaN 4 -1.017903 -0.484744 5 0.860375 0.239265 6 -0.640070 NaN 7 -0.535802 1.632932 8 0.876523 -0.153634 9 -...
Detect and print if no command line argument is provided
14,016,742
2
2012-12-24T03:31:33Z
14,016,856
7
2012-12-24T03:51:17Z
[ "python" ]
This is the program I have: ``` from sys import argv script, arg1 = argv def program(usr_input, arg1): if(usr_input == arg1): print "CLI argument and user input are identical" else: print "CLI argument and user input aren't identical" if arg1 != "": usr_input = raw_input("enter somethin...
I would recommend just checking the program args in the `__main__` location of your script, as an entry point to the entire application. ``` import sys def program(*args): # do whatever pass if __name__ == "__main__": try: arg1 = sys.argv[1] except IndexError: print "Usage: myprogram....
Port MATLAB bounding ellipsoid code to Python
14,016,898
9
2012-12-24T03:58:45Z
14,025,140
10
2012-12-24T19:42:40Z
[ "python", "matlab", "porting", "linear-programming", "bounding-box" ]
MATLAB code exists to find the so-called "minimum volume enclosing ellipsoid" (e.g. [here](http://stackoverflow.com/a/1768440/1205799), also [here](http://www.mathworks.com/matlabcentral/fileexchange/9542-minimum-volume-enclosing-ellipsoid/content/MinVolEllipse.m)). I'll paste the relevant part for convenience: ``` fu...
Using Octave, I found that after the while-loop in MinVolEllipse ends, ``` u = 0.0053531 0.2384227 0.2476188 0.0367063 0.0257947 0.2124423 0.0838103 0.1498518 ``` This agrees with the result for `u` found by the Python function `mvee`. More debugging print statements on the Octave side yield ...
How to convert a number in Python to 8 binary bytes (64-bit long)?
14,017,540
2
2012-12-24T05:46:32Z
14,017,565
8
2012-12-24T05:49:37Z
[ "python", "python-2.x" ]
How do I convert a number in Python to 8 binary bytes (64-bit long)? I have a blueprint of a network message, part of which is a number represented with eight bytes.
Use [struct.pack](http://docs.python.org/2/library/struct.html#format-strings): ``` >>> import struct >>> struct.pack('!Q', 123) '\x00\x00\x00\x00\x00\x00\x00{' ``` The first argument is a [format string](http://docs.python.org/2/library/struct.html#format-strings) which controls the encoding. `!` means network byte ...
Python optional parameter
14,017,996
39
2012-12-24T06:41:24Z
14,018,011
15
2012-12-24T06:43:07Z
[ "python", "python-2.7" ]
Is there a way in python to pass optional parameters to a function while calling it and in the function definition have some code based on "only if the optional parameter is passed"
``` def my_func(mandatory_arg, optional_arg=100): print mandatory_arg, optional_arg ``` <http://docs.python.org/2/tutorial/controlflow.html#default-argument-values> I find this more readable than using `**kwargs`. To determine if the argument was passed at all, I usually have a utility object which I use as the ...
Python optional parameter
14,017,996
39
2012-12-24T06:41:24Z
14,018,432
44
2012-12-24T07:29:19Z
[ "python", "python-2.7" ]
Is there a way in python to pass optional parameters to a function while calling it and in the function definition have some code based on "only if the optional parameter is passed"
The [Python 2 documentation, *7.6. Function definitions*](http://docs.python.org/2/reference/compound_stmts.html#function-definitions) gives you a couple of ways to detect whether a caller supplied an optional parameter. First, you can use special formal parameter syntax `*`. If the function definition has a formal pa...
Python optional parameter
14,017,996
39
2012-12-24T06:41:24Z
31,139,183
7
2015-06-30T13:07:59Z
[ "python", "python-2.7" ]
Is there a way in python to pass optional parameters to a function while calling it and in the function definition have some code based on "only if the optional parameter is passed"
``` def op(a=4,b=6): add = a+b print add i)op() [o/p: will be (4+6)=10] ii)op(99) [o/p: will be (99+6)=105] iii)op(1,1) [o/p: will be (1+1)=2] ```
Popen.returncode not working in Python?
14,018,107
4
2012-12-24T06:54:23Z
14,018,655
9
2012-12-24T07:52:37Z
[ "python" ]
I have a price of code which transfers file from server to local machine. However, the directory the user enters may not be always correct. If the user enters the incorrect directory I am trying to show the error. If the `returncode` is not None I will show the error. But this doesn't work. No matter what the program t...
`subprocess.Popen` returns an object (result variable in your case). You need to call the `poll` or the `wait` method of this object to set the returncode status. Then you can check the `result.returncode` See <http://docs.python.org/2/library/subprocess.html#subprocess.Popen.returncode> > The child return code, set ...
prevent subprocess.Popen from displaying output in python
14,023,566
5
2012-12-24T16:15:43Z
14,023,693
11
2012-12-24T16:31:23Z
[ "python", "subprocess" ]
So I am trying to store the output of a command into a variable. I do not want it to display output while running the command though... The code I have right now is as follows... ``` def getoutput(*args): myargs=args listargs=[l.split(' ',1) for l in myargs] import subprocess output=subprocess.Popen(l...
What you are seeing is standard-error output, not standard-output output. Stderr redirection is controlled by the `stderr` constructor argument. It defaults to `None`, which means no redirection occurs, which is why you see this output. Usually it's a good idea to keep stderr output since it aids debugging and doesn't...
Flask URL Route: Route Several URLs to the same function
14,023,664
6
2012-12-24T16:27:03Z
14,023,701
20
2012-12-24T16:32:31Z
[ "python", "url-routing", "flask" ]
I am working with Flask 0.9. Now I want to route three urls to the same function: ``` /item/<int:appitemid> /item/<int:appitemid>/ /item/<int:appitemid>/<anything can be here> ``` The `<anything can be here>` part will never be used in the function. I have to copy the same function twice to achieve this goal: ```...
Why not just use a parameter that can potentially be empty, with a default value of `None`? ``` @app.route('/item/<int:appitemid>/') @app.route('/item/<int:appitemid>/<path:anythingcanbehere>') def show_item(appitemid, anythingcanbehere=None): ```
Why does my function only see some of my globals?
14,023,861
2
2012-12-24T16:51:39Z
14,023,881
7
2012-12-24T16:54:26Z
[ "python", "scope" ]
Ok, I'm a C, VisualBasic, and Fortran programmer (yes we do still exist). I am missing a paradigm piece of Python 3.2. In the code below, why doesn't my function `start_DAQ` see all my globals? The function seems to make its own local variables for `do_DAQ`, `data_index`, and `start_time`, but not `store_button`. I've ...
Add the following to your function: ``` def start_DAQ(): global do_DAQ global data_index global start_time do_DAQ = True data_index=0 start_time = time.time() store_button.config(state = tk.DISABLED) ``` Python implements name hiding in local scope upon write. When you try to read a glob...
Function that takes a nested list of strings and returns a new nested list with all strings capitalized?
14,024,325
6
2012-12-24T17:54:28Z
14,024,345
11
2012-12-24T17:57:45Z
[ "python", "function", "capitalize" ]
This will capitalize them but only if there are no nested lists. ``` t = ['this','that', ['other']] def capitalize_nested(t): res = [] for s in t: res.append(s.capitalize()) return res print capitalize_nested(t) ``` I can't figure out how to get it to print out a nested list having all of the st...
Use a recursive solution (and using list comprehensions also helps make it more compact): ``` def capitalize_nested(t): if isinstance(t, list): return [capitalize_nested(s) for s in t] else: return t.capitalize() ``` For example: ``` print capitalize_nested(['this', 'that', ['other']]) # ['Th...
Querying the same table more than once in SQLAlchemy
14,025,424
2
2012-12-24T20:22:40Z
14,026,113
7
2012-12-24T22:23:10Z
[ "python", "sqlalchemy", "pyramid" ]
I'm using SQLAlchemy in Pyramid application and have the following pair of tables. ``` from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String, nullable=False, de...
You need to create [aliased tables](http://docs.sqlalchemy.org/en/rel_0_8/orm/tutorial.html#using-aliases): ``` from sqlalchemy.orm import aliased agent = aliased(User, name='agent') manager = aliased(User, name='manager') DBSession.query( agent.name, manager.name, MyStats.kpi_one, MyStats.kpi_two ).filte...
Assertion Error in columns in DataFrame with hierarchical indexing
14,025,879
11
2012-12-24T21:38:40Z
14,060,360
8
2012-12-27T19:46:05Z
[ "python", "pandas", "hierarchical" ]
Another pandas question: I have this table with hierarchical indexing: ``` In [51]: from pandas import DataFrame f = DataFrame({'a': ['1','2','3'], 'b': ['2','3','4']}) f.columns = [['level1 item1', 'level1 item2'],['', 'level2 item2'], ['level3 item1', 'level3 item2']] f Out[51]: level1 item1 level1 item2 ...
I pushed a fix for this yesterday. Here's the new behavior on github master: ``` In [1]: paste from pandas import DataFrame f = DataFrame({'a': ['1','2','3'], 'b': ['2','3','4']}) f.columns = [['level1 item1', 'level1 item2'],['', 'level2 item2'], ['level3 item1', 'level3 item2']] f ## -- End pasted text -- Out[1]: ...
Organizing a large python script
14,026,316
4
2012-12-24T22:58:07Z
14,026,342
7
2012-12-24T23:03:00Z
[ "python", "python-2.7" ]
I've been working on a general utility script for a while now that basically just accepts user input to preform some task like opening a program. In this program, I define a name "command" as a raw\_input and then use if statements to check the list for a command (small example below). Constantly using if statements i...
You can keep the commands in a dictionary with a tuple, and do something like this to store the commands. ``` command = {} command['skype'] = 'C:\Program Files (x86)\Skype\Phone', 'Skype.exe' command['explorer'] = 'C:\Windows\', 'Explorer.exe' ``` You could then do the following to execute the correct command based o...
How do I get the url parameter in a Flask view
14,026,704
19
2012-12-25T00:19:19Z
14,026,779
34
2012-12-25T00:35:27Z
[ "python", "html", "flask" ]
I am trying to get the url parameters from a flask view: ``` www.domain.com/?f=x**2 ``` How do I get `x**2` from the `url` in a Flask view?
You can retrieve query string variables using ``` request.args.get('myParam') ``` or ``` request.args['myParam'] ``` Where `myParam` is the variable in the query string you're trying to receive.
Django model: Filtering by user, always
14,026,750
4
2012-12-25T00:29:01Z
14,026,770
8
2012-12-25T00:33:38Z
[ "python", "django", "django-models" ]
How do I achieve the following.... Every time the points object is displayed in a template it must always be filtered by the current user. So, within the model I tried the code below. Is this possible? how can I achieve the above? Models.py ``` from django.db import models from django.contrib.auth.models import Use...
you could ensure that your views have a user by using [`@login_required`](https://docs.djangoproject.com/en/dev/topics/auth/#the-login-required-decorator) decorator then you could could query for points by user in your view `user_points = Points.objects.filter(user=request.user)` or using the reverse [FK lookup](ht...
What does pylint's "Too few public methods" message mean
14,027,417
32
2012-12-25T03:22:03Z
14,027,686
47
2012-12-25T04:30:49Z
[ "python", "pylint" ]
I'm running pylint on some code, and receiving the error "Too few public methods (0/2)". What does this message mean? The [pylint docs](http://docs.pylint.org/features.html#id22) are not helpful: > Used when class has too few public methods, so be sure it's really worth it.
The error basically says that classes aren't meant to *just* store data, as you're basically treating the class as a dictionary. Classes should have at least a few methods to operate on the data that they hold. If your class looks like this: ``` class MyClass(object): def __init__(self, foo, bar): self.fo...
Flask routes order matters?
14,027,614
2
2012-12-25T04:13:26Z
14,027,626
7
2012-12-25T04:17:11Z
[ "python", "google-app-engine", "flask", "jinja2", "werkzeug" ]
I'm just started to play with Flask, so in all likelihood this is a seriously noobish question. This app is running on Google App Engine SDK 1.7.4. Flask 0.9, Werkzeug 0.9 and Jinja2 2.6. The following code works as expected: ``` from flask import Flask from flask import render_template app = Flask(__name__) @app.r...
You're creating two functions with the same name (`hello`). Rename the second one: ``` @app.route('/') def index(): return "Main page" ```
SQLAlchemy - Update ForeignKey when setting the relationship
14,027,876
5
2012-12-25T05:09:17Z
14,032,090
7
2012-12-25T15:52:37Z
[ "python", "sqlalchemy" ]
I have a class: ``` class ExampleClass(Base): __tablename__ = 'chart' id = Column(Integer, primary_key=True) element_id = Column(Integer, ForeignKey('anotherTable.id')) element = relationship(AnotherClass) element2_id = Column(Integer, ForeignKey('anotherTable2.id')) element2 = relationship(Ano...
First off, all the examples below assume that your `ExampleClass` instance is at least in the [pending](http://docs.sqlalchemy.org/en/rel_0_8/orm/session.html#quickie-intro-to-object-states) state if not the "persistent" state (that is, `session.add(a)`). In other words, if you aren't yet interacting with a `Session` a...
How / Where to download Pylab for Python 2.7 on Win32?
14,027,958
11
2012-12-25T05:27:49Z
14,027,982
17
2012-12-25T05:33:55Z
[ "python", "python-2.7", "matplotlib" ]
I have googled all over, and don't see where to get pylab. What am I missing? Thanks!
I believe there are two "versions" of pylab floating around/being referred to. The first is a part of `matplotlib` -- you just [install matplotlib](http://matplotlib.org/users/installing.html) and do either `import pylab` or `import matplotlib.pyplot as pyplot`. (More info on [pylab vs pyplot](http://stackoverflow.com...
Pickle to file instead of using database
14,029,077
5
2012-12-25T08:44:02Z
14,029,166
9
2012-12-25T08:56:06Z
[ "python", "mysql", "pickle" ]
I'm writing a basic membership web app in python. Is it always bad practice to abandon databases completely and simply pickle a python dictionary to a file (http://docs.python.org/2/library/pickle.html)? The program should never have to deal with more than ca. 500 members, and will only keep a few fields about each me...
No, if you can keep all the data in memory a database is not necessary, and just pickling everything could work. Notable drawbacks with pickling is that it is not secure, somebody can replace your data with something else including executable code and that it's Python-only. With a database you also typically update th...
Python putting an if-elif-else statement on one line
14,029,245
33
2012-12-25T09:09:13Z
14,029,300
44
2012-12-25T09:16:46Z
[ "python", "syntax" ]
I have read the links below, but it doesn't address my question. [Ternary conditional operator in Python](http://stackoverflow.com/questions/394809/python-ternary-operator) (the question is about condensing if-else statement to one line) Is there an easier way of writing an if-elif-else statement so it fits on one l...
No, it's not possible (at least not with arbitrary statements), nor is it desirable. Fitting everything on one line would most likely violate [PEP-8](http://www.python.org/dev/peps/pep-0008/) where it is mandated that lines should not exceed 80 characters in length. It's also against the Zen of Python: "Readability co...
Python putting an if-elif-else statement on one line
14,029,245
33
2012-12-25T09:09:13Z
14,029,436
25
2012-12-25T09:36:08Z
[ "python", "syntax" ]
I have read the links below, but it doesn't address my question. [Ternary conditional operator in Python](http://stackoverflow.com/questions/394809/python-ternary-operator) (the question is about condensing if-else statement to one line) Is there an easier way of writing an if-elif-else statement so it fits on one l...
If you only need different expressions for different cases then this may work for you: ``` expr1 if condition1 else expr2 if condition2 else expr ``` For example: ``` a = "neg" if b<0 else "pos" if b>0 else "zero" ```
JSON dump big list containing dict, text, datetime and ints gives "TypeError: 'str' does not support the buffer interface"
14,031,879
4
2012-12-25T15:24:01Z
14,031,943
14
2012-12-25T15:34:23Z
[ "python", "json", "string", "typeerror" ]
Using Python 3.2 64 bit on Windows 7 64 bit. ``` f = open("raw_data/results.json", "wb") json.dump(dictio, f) f.close() ``` Gives error: ``` Traceback (most recent call last): File ".\calc_stats_friendly_data.py", line 22, in <module> main() File ".\calc_stats_friendly_data.py", line 18, in main json.dum...
You're opening the file for binary writing. Open it using `"w"` as a mode only.
Flask Optional URL parameters
14,032,066
96
2012-12-25T15:50:30Z
14,032,302
125
2012-12-25T16:26:59Z
[ "python", "flask" ]
Is it possible to directly declare a flask url optional parameter, currently I'm proceeding the following way: ``` @user.route('/<userId>') @user.route('/<userId>/<username>') def show(userId,username=None): ................. ``` is there anything that can allow me to directly say that "username" is optional?
Another way is to write ``` @user.route('/<user_id>', defaults={'username': None}) @user.route('/<user_id>/<username>') def show(user_id, username): pass ``` But I guess that you want to write a single route and mark `username` as optional? If that's the case, I don't think it's possible.
Flask Optional URL parameters
14,032,066
96
2012-12-25T15:50:30Z
16,569,475
81
2013-05-15T15:42:59Z
[ "python", "flask" ]
Is it possible to directly declare a flask url optional parameter, currently I'm proceeding the following way: ``` @user.route('/<userId>') @user.route('/<userId>/<username>') def show(userId,username=None): ................. ``` is there anything that can allow me to directly say that "username" is optional?
Almost the same as Audrius cooked up some months ago, but you might find it a bit more readable with the defaults in the function head - the way you are used to with python: ``` @app.route('/<user_id>') @app.route('/<user_id>/<username>') def show(user_id, username='Anonymous'): return user_id + ':' + username ```
Flask Optional URL parameters
14,032,066
96
2012-12-25T15:50:30Z
26,379,214
20
2014-10-15T09:39:18Z
[ "python", "flask" ]
Is it possible to directly declare a flask url optional parameter, currently I'm proceeding the following way: ``` @user.route('/<userId>') @user.route('/<userId>/<username>') def show(userId,username=None): ................. ``` is there anything that can allow me to directly say that "username" is optional?
If you are using Flask-Restful like me, it is also possible this way: ``` api.add_resource(UserAPI, '/<userId>', '/<userId>/<username>', endpoint = 'user') ``` a then in your Resource class: ``` class UserAPI(Resource): def get(self, userId, username=None): pass ```
Python data structure sort list alphabetically
14,032,521
45
2012-12-25T17:04:55Z
14,032,557
61
2012-12-25T17:10:51Z
[ "python", "list", "sorting", "alphabetical" ]
I am a bit confused regarding data structure in python; `()`,`[]`, and `{}`. I am trying to sort out a simple list, probably since I cannot identify the type of data I am failing to sort it. My list is simple: `['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue']` My question is what type of data this is, and...
`[]` denotes a [list](http://docs.python.org/2.7/tutorial/introduction.html#lists), `()` denotes a [tuple](http://docs.python.org/2.7/tutorial/datastructures.html#tuples-and-sequences) and `{}` denotes a [dictionary](http://docs.python.org/2.7/tutorial/datastructures.html#dictionaries). You should take a look at the [o...
Python data structure sort list alphabetically
14,032,521
45
2012-12-25T17:04:55Z
14,032,628
11
2012-12-25T17:21:18Z
[ "python", "list", "sorting", "alphabetical" ]
I am a bit confused regarding data structure in python; `()`,`[]`, and `{}`. I am trying to sort out a simple list, probably since I cannot identify the type of data I am failing to sort it. My list is simple: `['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue']` My question is what type of data this is, and...
Python has a built-in function called [`sorted`](http://docs.python.org/2/library/functions.html#sorted), which will give you a sorted list from any iterable you feed it (such as a list (`[1,2,3]`); a dict (`{1:2,3:4}`, although it will just return a sorted list of the keys; a set (`{1,2,3,4`); or a tuple (`(1,2,3,4)`)...
rasterizing matplotlib axis contents (but not frame, labels)
14,032,763
5
2012-12-25T17:43:23Z
14,035,897
9
2012-12-26T04:06:56Z
[ "python", "matplotlib", "plot", "vector-graphics", "rasterizing" ]
For an article I am generating plots of deformed finite element meshes, which I visualize using matplotlib's polycollection. The images are saved as pdf. Problems arise for high density meshes, for which the naive approach results in files that are too large and rendering too intensive to be practical. For these mesh...
Just pass the `rasterized=True` keyword to your collection constructor. Example: ``` col = collections.PolyCollection(<arguments>, rasterized=True) ``` This allows a selective rasterization of that element only (e.g., if you did a normal plot on top of it, it would be vectorized by default). Most commands like `plot`...
Python: Is it possible to access the return value inside the `finally` clause?
14,034,156
9
2012-12-25T21:36:20Z
14,034,169
12
2012-12-25T21:38:00Z
[ "python", "return-value", "finally" ]
I have a return statement inside a `try` clause: ``` def f(): try: return whatever() finally: pass # How do I get what `whatever()` returned in here? ``` Is it possible to get the return value inside the `finally` clause? This is more of a theoretical question, so I'm not looking for a workar...
No, it isn't - the `finally` clause's content is independent from return mechanics; if you do want to see what value is returned you'd have to do as you mentioned and explicitly save it somewhere that's in-scope.
Import netCDF file to Pandas dataframe
14,035,148
7
2012-12-26T01:20:26Z
14,492,358
10
2013-01-24T01:18:17Z
[ "python", "dataframe", "pandas", "netcdf" ]
Merry Christmas. Im still very new to Python and Pandas so help is appreciated. I am trying to read in a netCDF file, which I can do and then import that into a Pandas Dataframe. The netcDF file is 2D so I just want to 'dump it in'. I have tried the DataFrame method but it doesn't recognize the object. Presumably I n...
If your NetCDF file (or OPeNDAP dataset) follows CF Metadata conventions you can take advantage of them by using the NetCDF4-Python package, which makes accessing them in Pandas really easy. (I'm using the Enthought Python Distribution which includes both Pandas and NetCDF4-Python). In the example below, the NetCDF fi...
How do I locate the rabbit?
14,036,944
3
2012-12-26T06:47:26Z
14,037,115
13
2012-12-26T07:03:27Z
[ "python", "opencv", "python-imaging-library", "object-detection" ]
I am trying to follow the rabbit in the game winterbells. Here are some screenshots![rabbit](http://i.stack.imgur.com/vny9c.png)![rabbit](http://i.stack.imgur.com/TYK9H.png)![rabbit](http://i.stack.imgur.com/bBMSS.png) Originally I thought that I could follow a color that only the rabbit had, but it seems that all the...
The simplest way would be to just classify the shapes by area. Here's one solution with SimpleCV: ``` >>> from SimpleCV import * >>> image = Image('image.png') >>> binarized = image.binarize(220).invert() >>> binarized.show() ``` ![enter image description here](http://i.stack.imgur.com/IqAeT.png) Now, this is much e...
Writing a Python list of lists to a csv file
14,037,540
60
2012-12-26T07:43:47Z
14,037,564
96
2012-12-26T07:46:09Z
[ "python", "file", "csv", "file-io", "python-2.7" ]
I have a long list of lists of the following form --- ``` a = [[1.2,'abc',3],[1.2,'werew',4],........,[1.4,'qew',2]] ``` i.e. the values in the list are of different types -- float,int, strings.How do I write it into a csv file so that my output csv file looks like ``` 1.2,abc,3 1.2,werew,4 . . . 1.4,qew,2 ```
Python's built-in [CSV module](http://docs.python.org/2/library/csv.html) can handle this easily: ``` import csv with open("output.csv", "wb") as f: writer = csv.writer(f) writer.writerows(a) ``` This assumes your list is defined as `a`, as it is in your question. You can tweak the exact format of the output...
Writing a Python list of lists to a csv file
14,037,540
60
2012-12-26T07:43:47Z
14,037,583
8
2012-12-26T07:48:26Z
[ "python", "file", "csv", "file-io", "python-2.7" ]
I have a long list of lists of the following form --- ``` a = [[1.2,'abc',3],[1.2,'werew',4],........,[1.4,'qew',2]] ``` i.e. the values in the list are of different types -- float,int, strings.How do I write it into a csv file so that my output csv file looks like ``` 1.2,abc,3 1.2,werew,4 . . . 1.4,qew,2 ```
``` import csv with open(file_path, 'a') as outcsv: #configure writer to write standard csv file writer = csv.writer(outcsv, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\n') writer.writerow(['number', 'text', 'number']) for item in list: #Write item to outcsv ...
How do I write Flask's excellent debug log message to a file in production?
14,037,975
32
2012-12-26T08:35:36Z
14,042,671
40
2012-12-26T15:36:32Z
[ "python", "logging", "flask" ]
I have a Flask application that works well and produces the occasional error. When my application is in debug mode using: ``` if __name__ == '__main__': app.run(debug=True) ``` I get useful error messages such as: ``` Traceback (most recent call last): File "./main.py", line 871, in index_route KeyError: 'sta...
I don't know why it's not working but I can tell how am doing this. First of all, you don't need to set the level of app.logger. So remove this line `app.logger.setLevel()`. You want to save exception and return error page for every view. It is a lot of work to write this code everywhere. Flask provides a method to d...
How do I write Flask's excellent debug log message to a file in production?
14,037,975
32
2012-12-26T08:35:36Z
20,570,063
30
2013-12-13T15:26:41Z
[ "python", "logging", "flask" ]
I have a Flask application that works well and produces the occasional error. When my application is in debug mode using: ``` if __name__ == '__main__': app.run(debug=True) ``` I get useful error messages such as: ``` Traceback (most recent call last): File "./main.py", line 871, in index_route KeyError: 'sta...
For those who read this later on. I think it is better idea to push more useful info into error messages. URL, client IP, user-agent etc. Flask logs exceptions internally (in `app.debug==False` mode) with `Flask.log_exception` function. So, instead of logging things manually in `@app.errorhandler` I do something like ...
Does unused imports in python hamper performance?
14,038,691
18
2012-12-26T09:44:55Z
14,038,726
15
2012-12-26T09:47:01Z
[ "python" ]
Is there any effect of unused imports in a python script? Any sort of answer is appreciated.
You pollute your namespace with names that could interfere with your variables and occupy some memory. Also you will have a longer startup time as the program has to load the module. In any case, I would not become too neurotic with this, as if you are writing code you could end up writing and deleting `import os` c...
My first step in Python
14,041,020
2
2012-12-26T13:07:17Z
14,041,173
7
2012-12-26T13:19:25Z
[ "python" ]
I'm trying to start learning Python, but I became confused from the first step. I'm getting started with `Hello, World`, but when I try to run the script, I get: > Syntax Error: Non-UTF-8 code starting with '`\xe9`' in file `C:\Documents and Settings\Home\workspace\Yassine frist stared\src\firstModule.py` on line 5 bu...
add to the first line is ``` # -*- coding: utf-8 -*- ```
Paginate Django formset
14,041,381
4
2012-12-26T13:38:49Z
14,128,835
9
2013-01-02T20:41:29Z
[ "python", "django", "paginator", "formsets" ]
I have a model formset that I want to display 10 forms at a time using Django's Paginator, but it can't be done like `paginator = Paginator(formset, 10)`. What's the correct way to do this, if there is a way?
This is a generic example of the solution I found to my problem: In the `forms.py` file: ``` class MyForm(ModelForm): class Meta: model = MyModel fields = ('description',) ``` In the `views.py` file: ``` FormSet = modelformset_factory(MyModel, form=MyForm, extra=0) if request.method == 'POST': ...
using cx_freeze on flask app
14,041,450
7
2012-12-26T13:44:31Z
14,069,859
14
2012-12-28T12:52:50Z
[ "python", "flask", "cx-freeze" ]
I am using Flask to develop a python app. At the moment, I want this app to be run locally. It runs locally fine through python, but when I use cx\_freeze to turn it into an exe for Windows, I can no longer use the Flask.render\_template() method. The moment I try to execute a render\_template, I get an http 500 error,...
After many false trails trawling through the Flask and Jinga modules, I finally found the problem. CXFreeze does not recognize that jinja2.ext is a dependency, and was not including it. I fixed this by including `import jinja2.ext` in one of the python files. CXFreeze then added `ext.pyc` to library.zip\jinja. (Copy...
Python PIL Detect if an image is completely black or white
14,041,562
4
2012-12-26T13:52:53Z
14,041,871
8
2012-12-26T14:19:54Z
[ "python", "python-imaging-library" ]
Using the Python Imaging Library PIL how can someone detect if an image has all it's pixels black or white? *~Update~* Condition: **Not** iterate through each pixel!
``` if not img.getbbox(): ``` ... will test to see whether an image is completely black. (`Image.getbbox()` returns the falsy `None` if there are no non-black pixels in the image, otherwise it returns a tuple of points, which is truthy.) To test whether an image is completely white, invert it first: ``` if not ImageC...
Flask authentication with Flask-Security
14,041,672
3
2012-12-26T14:02:33Z
14,043,786
7
2012-12-26T17:12:35Z
[ "python", "authentication", "flask" ]
Trying to enable login in flask with flask-security. The following code works fine (I import in `__init__.py`) ``` from flask import Blueprint, render_template, request, redirect, url_for from coursly import app from coursly.models import * from flask.ext.security import Security, LoginForm, SQLAlchemyUserDatastore u...
Figured it out. Turns out Flask-security already has `/login` `/logout` built in and my login function was largely ignored. It wasn't used during normal app execution. Except `url_for` was still processed hence the BuildError. I was trying to use an outdated example from <https://github.com/dracule/FlaskBootstrapSecur...
print variable and a string in python
14,041,791
21
2012-12-26T14:12:14Z
14,041,800
18
2012-12-26T14:13:03Z
[ "python", "printing" ]
Alright, I know how to print variables and strings. But how can I print something like "My string" card.price (it is my variable). I mean, here is my code: `print "I have " (and here I would like to print my variable card.price)`.
By printing multiple values separated by a comma: ``` print "I have", card.price ``` The [print statement](http://docs.python.org/2/reference/simple_stmts.html#the-print-statement) will output each expression separated by spaces, followed by a newline. If you need more complex formatting, use the [`''.format()` meth...
import error due to bs4 vs BeautifulSoup
14,042,023
5
2012-12-26T14:33:24Z
14,044,031
9
2012-12-26T17:36:52Z
[ "python", "beautifulsoup", "lxml", "bs4" ]
I am trying to use `beautifulsoup` compatible `lxml` and it is giving me an error: ``` from lxml.html.soupparser import fromstring Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Library/Python/2.7/site-packages/lxml/html/soupparser.py", line 7, in <module> from BeautifulSoup impo...
The error is caused by `soupparser.py` trying to import BeautifulSoup version 3 while you have version 4 installed. The module name was changed from `BeautifulSoup` to `bs4` in version 4. You can trick `soupparser.py` into importing version 4 by mapping the `bs4` module to `BeautifulSoup` in [`sys.modules`](http://doc...
checking status of process with subprocess.Popen in Python
14,043,030
5
2012-12-26T16:04:14Z
14,043,126
15
2012-12-26T16:12:29Z
[ "python", "multiprocessing" ]
If I invoke a process with `subprocess.Popen` in Python as follows: `myproc = subprocess.Popen(...).communicate()` what is the correct way to see its status? Not its output to stdout or stderr, but its exit status once it's finished (e.g. 0 for success or another for failure)?
`returncode` is indeed the answer, but the solution doesn't need to be complicated. ``` process = subprocess.Popen(...) stdoutdata, stderrdata = process.communicate() print process.returncode ``` More info in the [Python `subprocess` docs](http://docs.python.org/2/library/subprocess.html#subprocess.Popen.returncode).
Python 2,3 Convert Integer to "bytes" Cleanly
14,043,886
12
2012-12-26T17:22:27Z
14,044,431
9
2012-12-26T18:13:19Z
[ "python" ]
The shortest ways I have found: ``` n = 5 #Python 2 s = str(n) i = int(s) #Python 3 s = bytes(str(n),"ascii") i = int(s) ``` I am particularly concerned with two factors: readability and portability. The second method, for Python 3, is ugly. However, I think it may be backwards compatible. Is there a shorter, clea...
To convert a string to a sequence of bytes in either Python 2 or Python 3, you use the string's `encode` method. If you don't supply an encoding parameter `'ascii'` is used, which will always be good enough for numeric digits. ``` s = str(n).encode() ``` * Python 2: <http://ideone.com/Y05zVY> * Python 3: <http://ideo...
Python 2,3 Convert Integer to "bytes" Cleanly
14,043,886
12
2012-12-26T17:22:27Z
22,074,428
7
2014-02-27T16:26:07Z
[ "python" ]
The shortest ways I have found: ``` n = 5 #Python 2 s = str(n) i = int(s) #Python 3 s = bytes(str(n),"ascii") i = int(s) ``` I am particularly concerned with two factors: readability and portability. The second method, for Python 3, is ugly. However, I think it may be backwards compatible. Is there a shorter, clea...
Converting an **int** to a **byte** in Python **3**: ``` n = 5 bytes( [n] ) >>> b'\x05' ``` ;) guess that'll be better than messing around with strings source: <http://docs.python.org/3/library/stdtypes.html#binaryseq>
Python 2,3 Convert Integer to "bytes" Cleanly
14,043,886
12
2012-12-26T17:22:27Z
26,920,983
13
2014-11-14T00:26:19Z
[ "python" ]
The shortest ways I have found: ``` n = 5 #Python 2 s = str(n) i = int(s) #Python 3 s = bytes(str(n),"ascii") i = int(s) ``` I am particularly concerned with two factors: readability and portability. The second method, for Python 3, is ugly. However, I think it may be backwards compatible. Is there a shorter, clea...
You can use the [struct's pack](https://docs.python.org/2/library/struct.html#struct.pack): ``` In [11]: struct.pack(">I", 1) Out[11]: '\x00\x00\x00\x01' ``` The ">" is the [byte-order (big-endian)](https://docs.python.org/2/library/struct.html#byte-order-size-and-alignment) and the "I" is the [format character](http...
Python 2,3 Convert Integer to "bytes" Cleanly
14,043,886
12
2012-12-26T17:22:27Z
29,182,294
8
2015-03-21T11:41:30Z
[ "python" ]
The shortest ways I have found: ``` n = 5 #Python 2 s = str(n) i = int(s) #Python 3 s = bytes(str(n),"ascii") i = int(s) ``` I am particularly concerned with two factors: readability and portability. The second method, for Python 3, is ugly. However, I think it may be backwards compatible. Is there a shorter, clea...
I have found the only reliable, portable method to be ``` bytes(bytearray([n])) ``` Just bytes([n]) does not work in python 2. Taking the scenic route through bytearray seems like the only reasonable solution.
python time offset
14,043,934
9
2012-12-26T17:25:42Z
14,043,939
18
2012-12-26T17:26:26Z
[ "python", "time" ]
How can I apply an offset on the current time in python? In other terms, be able to get the current time minus x hours and/or minus m minutes and/or minus s secondes and/or minus ms milliseconds for instance ``` curent time = 18:26:00.000 offset = 01:10:00.000 =>resulting time = 17:16:00.000 ```
Use a [`datetime.datetime()`](http://docs.python.org/2/library/datetime.html#datetime-objects), then add or subtract [`datetime.timedelta()` instances](http://docs.python.org/2/library/datetime.html#timedelta-objects). ``` >>> import datetime >>> t = datetime.datetime.now() >>> t - datetime.timedelta(hours=1, minutes=...
Animated sprite from few images
14,044,147
5
2012-12-26T17:46:58Z
14,044,210
9
2012-12-26T17:53:00Z
[ "python", "animation", "sprite", "pygame" ]
I've been searching for some good tutorial about making simple sprite animation from few images in Python using Pygame. I still haven't found what I'm looking for. My question is simple: how to make an animated sprite from few images (for an example: making few images of explosion with dimensions 20x20px to be as one ...
You could try modifying your sprite so that it swaps out its image for a different one inside `update`. That way, when the sprite is rendered, it'll look animated. **Edit**: Here's a quick example I drew up: ``` import pygame import sys def load_image(name): image = pygame.image.load(name) return image cla...
Python unittest - setUpClass() is giving me trouble - why can't I inherit like this?
14,044,474
17
2012-12-26T18:17:06Z
14,044,585
29
2012-12-26T18:27:25Z
[ "python", "unit-testing" ]
I have unittest code like the following: ``` import unittest class MyUnitTest(unittest.TestCase): def setUpClass(self): do_something_expensive_for_all_sets_of_tests() class MyFirstSetOfTests(MyUnitTest): def setUpClass(self): super(MyFirstSetOfTests, self).setUpClass() do_something_ex...
`setUpClass` *must* be a class method. From the [documentation](http://docs.python.org/2/library/unittest.html#unittest.TestCase.setUpClass): > A class method called before tests in an individual class run. `setUpClass` is called with the class as the only argument and must be decorated as a `classmethod()`: > > @clas...
How to pass a variable to {% url %} tag in django?
14,045,221
3
2012-12-26T19:25:05Z
14,045,407
11
2012-12-26T19:43:36Z
[ "python", "django", "templates", "url" ]
I have 2 views: a and b they all render to one template T. There are also a\_2 and b\_2 views. And T template should generate urls to the a\_2 and b\_2 views. however I cannot use {% url %} because I cannot pass url name as a parametr. I cannot generate the whole url in views because i should do it multiple times (on...
This is fixed in django 1.5. In versions prior to 1.5 you need to use ``` {% extends 'base.html' %} {% load url from future %} {% url 'name_as_a_string' %} {% url name_stored_in_variable %} ``` From <https://docs.djangoproject.com/en/dev/releases/1.5/> > One deprecated feature worth noting is the shift to “new-...
Dynamically add class member using string to name it
14,045,265
3
2012-12-26T19:29:41Z
14,045,298
9
2012-12-26T19:32:41Z
[ "python", "class", "dynamic", "member" ]
In Python, I'm quite aware of the fact that one may add members to classes after their definition. But, is there a way to name a member using the content of a string? For example, I may do this: ``` class A: pass A.foo = 10 a = A() print a.foo ``` But is there some way to do this: ``` name = "foo" class A: ...
Use `setattr`: ``` setattr(A, 'foo', 10) ```
Closures: What is a good use case example? Why not a functor? And is it worth the negatives?
14,045,403
8
2012-12-26T19:43:17Z
14,045,467
10
2012-12-26T19:48:29Z
[ "python", "ruby", "closures", "functor" ]
I recently dove into Python. Previous, I had programmed mostly numerical and data analysis code in C++ and Matlab. I saw a lot of discussions about Python and Ruby and closures. Almost all examples looked like this: ``` >>> def makeAdder(y): ... def myAdder(x): ... return x + y ... return myAdder ... >>> f = make...
Readability. Your Python example shows how much more obvious and easy to read the closure version is compared to the functor. We also neatly avoid making a class that does nothing but act like a function - this smells of redundancy. If nothing else, when we are *doing* something, [it makes sense to describe it as an ...
Why would mock be adding __nonzero__ method calls?
14,046,237
6
2012-12-26T21:03:28Z
14,046,295
11
2012-12-26T21:09:26Z
[ "python", "unit-testing", "mocking" ]
I've got a bit of code that makes a call to a series of methods on each item in a collection, and each method returns a boolean value indicating success = True/failure = False. ``` def monkey(some_collection, arg1, arg2): for item in some_collection: if not item.foo(arg1, arg2): continue ...
When you do `if not x:`, you are probably thinking `if x is False`. Python doesn't actually do this - it does `if bool(x) is False` (this is Python's *truthiness* concept - that values evaluate to `True` or `False`), and `bool(x)` is actually a call to `x.__nonzero__()` (or `x.__bool__()` in 3.x). This is to provide ...
Python Pyplot Bar Plot bars disapear when using log scale
14,047,068
9
2012-12-26T22:32:29Z
14,047,203
18
2012-12-26T22:45:49Z
[ "python", "matplotlib", "plot" ]
I have the following data: ``` 20120219,\\n,43166053 20120220,\\n,46813269 20120221,\\n,47277204 20120222,\\n,46344556 20120223,\\n,26926236 20120224,\\n,6472506 20120225,\\n,39580476 20120226,\\n,55968342 20120227,\\n,32889948 20120228,\\n,32116361 20120229,\\n,32424829 20120301,\\n,56123889 20120302,\\n,67102459 201...
The `bar` function has a `log` argument that needs to be set to true when using a logarithmic scale: <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar>
Why do python print statements that contain 'end=' arguments behave differently in while-loops?
14,047,372
5
2012-12-26T23:02:58Z
14,047,385
15
2012-12-26T23:04:53Z
[ "python", "while-loop" ]
I'm running python version 2.7.3 on MacOSX. Consider this block of code: ``` from __future__ import print_function import time x = 0 while x < 5: print(x) x += 1 time.sleep(1) ``` If I run this script, I observe the output I expect: The numbers `0` through `4` with a `\n` character appended to each numbe...
Because the output stream is line-buffered - since it's not explicitly being flushed in between print statements, it waits until it sees a newline to flush the output. You can force flushing via `sys.stdout.flush()`. Alternatively if you run Python with the `-u` flag, it will disable line buffering.
Why do python print statements that contain 'end=' arguments behave differently in while-loops?
14,047,372
5
2012-12-26T23:02:58Z
14,047,415
7
2012-12-26T23:08:18Z
[ "python", "while-loop" ]
I'm running python version 2.7.3 on MacOSX. Consider this block of code: ``` from __future__ import print_function import time x = 0 while x < 5: print(x) x += 1 time.sleep(1) ``` If I run this script, I observe the output I expect: The numbers `0` through `4` with a `\n` character appended to each numbe...
This is just python buffering stdout. [This answer](http://stackoverflow.com/questions/107705/python-output-buffering) has some more info. You can flush it like this: ``` import sys from __future__ import print_function import time x = 0 while x < 5: print(x, end='') x += 1 sys.stdout.flush() time.sle...
executing Python script in PHP and exchanging data between the two
14,047,979
16
2012-12-27T00:30:23Z
14,048,046
40
2012-12-27T00:41:10Z
[ "php", "python" ]
Is it possible to run a Python script within PHP and transferring variables from each other ? I have a class that scraps websites for data in a certain global way. i want to make it go a lot more specific and already have pythons scripts specific to several website. I am looking for a way to incorporate those inside ...
You can generally communicate between languages by using common language formats, and using `stdin` and `stdout` to communicate the data. **Example with PHP/Python using a shell argument to send the initial data via JSON** PHP: ``` // This is the data you want to pass to Python $data = array('as', 'df', 'gh'); // E...
executing Python script in PHP and exchanging data between the two
14,047,979
16
2012-12-27T00:30:23Z
14,048,296
9
2012-12-27T01:22:27Z
[ "php", "python" ]
Is it possible to run a Python script within PHP and transferring variables from each other ? I have a class that scraps websites for data in a certain global way. i want to make it go a lot more specific and already have pythons scripts specific to several website. I am looking for a way to incorporate those inside ...
You are looking for "interprocess communication" (IPC) - you could use something like XML-RPC, which basically lets you call a function in a remote process, and handles the translation of all the argument data-types between languages (so you could call a PHP function from Python, or vice versa - as long as the argument...
Compact Python for() Loop
14,048,164
3
2012-12-27T01:00:04Z
14,048,173
8
2012-12-27T01:02:20Z
[ "python" ]
How do I rearrange the following code into a simplified list comprehension? ``` for i in xrange(len(list)): if list[i].startswith('c'): list[i] = prefix + list[i] ``` I tried the following but it did not seem to work: ``` [prefix + list[i] for i in xrange(len(list)) if list[i].startswith('c')] ``` The f...
You need to use the [`ternary operator`](http://docs.python.org/2/reference/expressions.html#conditional-expressions) here: ``` [prefix + i if i.startswith('c') else i for i in my_list] ``` Note that this doesn't changes the original `my_list`, it simply returns a new list. You can simply asssign the list comprehens...
Python using dict .get() method where value = 0
14,048,246
2
2012-12-27T01:14:38Z
14,048,264
10
2012-12-27T01:16:41Z
[ "python", "dictionary" ]
(Python 2.7.2) I would like to better understand why the default value is returned when using a dictionaries .get() method to find a key when the value mapped to the key is 0. Consider the following ``` x = {1:0} print x.get('1', 'a') 'a' ``` The same happens for an empty string, set, etc. but if I do: ``` print...
`1` != `'1'`; an `int` isn't equal to a `str`. ``` >>> x = {1:0} >>> >>> print x.get('1', 'a') a >>> print x.get(1, 'a') 0 ```
Is it possible to handle an arbitrarily large string in Python? (created via the * operator)
14,048,733
5
2012-12-27T02:35:52Z
14,048,765
10
2012-12-27T02:40:53Z
[ "python", "string" ]
We can build strings of fixed structure but arbitrary length with the \* operator, with the following: ``` length = 10 print "0" * length ``` This returns what is expected, `0000000000`. The problem arises when length is excessively large, resulting in an overflow error: ``` length = 10000000000000000000000000000000...
No, you cannot create large strings like the one in your example in *any* programming language. Strings contain each character on its own. And 1046 bytes is most likely way more data than anyone will ever store. You could take way over a trillion Google datacenters (assuming Google has 1 YiB of storage which is surely ...
How can I use python finding particular json value by key?
14,048,948
10
2012-12-27T03:15:58Z
14,049,167
7
2012-12-27T03:53:19Z
[ "python", "json" ]
There is a json like this: ``` { "P1": "ss", "Id": 1234, "P2": { "P1": "cccc" }, "P3": [ { "P1": "aaa" } ] } ``` How can i find all `P1`'s value without it iterating all json? PS:`P1` can be anywhere in json. If no method can do this, can you tell me how to iterate the json?
I had the same issue just the other day. I wound up just searching through the entire object and accounted for both lists and dicts. The following snippets allows you to search for the *first* occurrence of a multiple keys. ``` import json def deep_search(needles, haystack): found = {} if type(needles) != typ...
How can I use python finding particular json value by key?
14,048,948
10
2012-12-27T03:15:58Z
14,059,645
7
2012-12-27T18:46:59Z
[ "python", "json" ]
There is a json like this: ``` { "P1": "ss", "Id": 1234, "P2": { "P1": "cccc" }, "P3": [ { "P1": "aaa" } ] } ``` How can i find all `P1`'s value without it iterating all json? PS:`P1` can be anywhere in json. If no method can do this, can you tell me how to iterate the json?
As I said in my other answer, I don't think there is a way of finding all values associated with the`"P1"`key without iterating over the whole structure. However I've come up with even better way to do that which came to me while looking at the [accepted answer](http://stackoverflow.com/a/6633651/355230) to a different...
Is declaring [almost] everything with self. alright (Python)?
14,049,028
2
2012-12-27T03:31:41Z
14,049,045
13
2012-12-27T03:34:46Z
[ "python", "self" ]
I have a habit to declare new variables with `self.` in front to make it available to all methods. This is because sometimes I thought I don't need the variable in other methods. But halfway through I realized that I need it to be accessible in other methods. Then I have to add `self.` in front of all that variable. S...
Set a property on `self` only when the value is part of the overall object state. If it's only part of the method state, then it should be method-local, and should not be a property of `self`.
Selenium Webdriver finding an element in a sub-element
14,049,983
21
2012-12-27T05:50:10Z
14,050,503
34
2012-12-27T06:38:35Z
[ "python", "xpath", "selenium" ]
I am trying to search for an element in a sub-element with Selenium (Version 2.28.0), but selenium des not seem to limit its search to the sub-element. Am I doing this wrong or is there a way to use element.find to search a sub-element? For an example I created a simple test webpage with this code: ``` <!DOCTYPE html...
When you start your XPath expression with `//`, it search from root of document ignoring your parent element. You should prepend expression with `.` ``` element2 = driver.find_element_by_xpath("//div[@title='div2']") element2.find_element_by_xpath(".//p[@class='test']").text ```