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 font size of Matplotlib axis Legend?
12,402,561
19
2012-09-13T08:43:58Z
17,093,475
27
2013-06-13T17:34:00Z
[ "python", "matplotlib", "font-size", "legend" ]
I have a code like this: ``` import matplotlib.pyplot as plt from matplotlib.pyplot import * from matplotlib.font_manager import FontProperties fontP = FontProperties() fontP.set_size('xx-small') fig=plt.figure() ax1=fig.add_subplot(111) plot([1,2,3], label="test1") ax1.legend(loc=0, ncol=1, bbox_to_anchor=(0, 0, 1, ...
This is definitely an old question, but was frustrating me too and none of the other answers changed the legend *title* fontsize at all, but instead just changed the rest of the text. So after banging my head against the matplotlib documentation for awhile I came up with this. ``` legend = ax1.legend(loc=0, ncol=1, bb...
the simple way to check if the elements of a list or set are single type?
12,402,845
4
2012-09-13T09:02:43Z
12,402,887
11
2012-09-13T09:05:07Z
[ "python" ]
i need to write a piece of code if all the elements are int or all are string then return true,else return false ``` [1,'1','a','b'] False [1,2,3,4] True ['apple','orange','melon'] True ['1', 2, 3, 4] False ``` my solution is these ``` def foo(l): t = type(l[0]) if t is not str and t is not int: retu...
This code checks generally if all elements are of the same type: ``` len(set(type(elem) for elem in elems)) == 1 ``` It answers the title of your question, but works differently than your solution (which returns false for a list of floats).
Django MySQL distinct query for getting multiple values
12,402,923
11
2012-09-13T09:07:10Z
12,403,362
16
2012-09-13T09:34:05Z
[ "python", "mysql", "django", "distinct", "django-queryset" ]
I have a **MySQL** database unfortunately used with **Django 1.4.1.** Distinct function is only working for POSTGRESQL if i get it right. I have to make a distinct query consist of multiple values while only distinct one, Like; This one works for POSTGRE but not with MYSQL, I get the following error; > DISTINCT ON f...
`.distinct([*fields])` only works in PostgresSQL. From [distinct](https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.distinct) documentation *Here's the difference. For a normal distinct() call, the database compares each field in each row when determining which rows are disti...
Python Classes: adding dynamic attributes to methods
12,403,843
2
2012-09-13T10:04:12Z
12,403,926
9
2012-09-13T10:09:23Z
[ "python", "class", "attributes" ]
Say we have a class: ``` class Foo (object): ... def __init__(self,d): ... self.d=d ... def return_d(self): ... return self.d ``` ... and a dict: ``` d={'k1':1,'k2':2} ``` ... and an instance: ``` inst=Foo(d) ``` Is there a way to dynamically add attributes to `return_d` so: `inst.return_...
You'd need to do two things: declare `return_d` as an attribute or property, and return a dict-like object that allows attribute access for dictionary keys. The following would work: ``` class AttributeDict(dict): __getattr__ = dict.__getitem__ class Foo (object): def __init__(self,d): self.d=d ...
Subclassing Python's `property`
12,405,087
17
2012-09-13T11:19:58Z
12,405,597
18
2012-09-13T11:50:20Z
[ "python", "properties" ]
In one of my classes, I have a number of properties that do very similar things on getting and setting. So I abstracted the arguments to `property` into a factory function: ``` def property_args(name): def getter(self): # do something return getattr(self, '_' + name) def setter(self, value) ...
Here is a pure Python equivalent for the code in *property()*: ``` class Property(object): "Emulate PyProperty_Type() in Objects/descrobject.c" def __init__(self, fget=None, fset=None, fdel=None, doc=None): self.fget = fget self.fset = fset self.fdel = fdel if doc is None and f...
Import a package defined by a variable
12,405,838
2
2012-09-13T12:04:43Z
12,405,872
8
2012-09-13T12:06:05Z
[ "python" ]
I want to do some package import timing tests. For this, I want to define a list of packages: ``` packages = [ 'random', 'dateutils', ... ] for package in packages: import package ``` This is of course not working because `import` tries to import package "package". How can I tell `import` to import the package p...
``` for package in packages: package = __import__(package) ``` Note that if you are importing a module from a package, such as `A.B`, `__import__('A.B')` returns package `A`, but `__import__('A.B', fromlist = [True])` returns module `B`.
Why doesn't nosetests find anything?
12,406,821
8
2012-09-13T12:57:35Z
12,497,492
8
2012-09-19T15:06:27Z
[ "python", "unit-testing" ]
I am switching from python's unittest framework to nosetests, trying to reuse my `unittest.TestCase`s After `cd`ing into my tests package I started nosetests [as described on their homepage](http://nose.readthedocs.org/en/latest/index.html): ``` ./test/$ nosetests ----------------------------------------------------...
I can see in your repo that at least some of the files are executable, so that is at least part of the problem. By default, nose won't collect those: it's trying to avoid running scripts that might do something destructive on import. Try the --exe flag, or removing the executable bit from the test files.
Python Class Members
12,409,714
16
2012-09-13T15:25:41Z
12,409,963
36
2012-09-13T15:39:02Z
[ "python", "class" ]
I am just learning Python and I come from a C background so please let me know if I have any confusion / mix up between both. Assume I have the following class: ``` class Node(object): def __init__(self, element): self.element = element self.left = self.right = None @classmethod def tree(...
One is a class attribute, while the other is an instance attribute. They are different, but they are closely related to one another in ways that make them look the same at times. It has to do with the way python looks up attributes. There's a hierarchy. In simple cases it might look like this: ``` instance -> Subclas...
Python Class Members
12,409,714
16
2012-09-13T15:25:41Z
12,410,026
7
2012-09-13T15:42:46Z
[ "python", "class" ]
I am just learning Python and I come from a C background so please let me know if I have any confusion / mix up between both. Assume I have the following class: ``` class Node(object): def __init__(self, element): self.element = element self.left = self.right = None @classmethod def tree(...
In python it is possible to have class variables and instance variables of the same name. They are located separately in memory, and are accessed quite differently. In your code: ``` class Node(object): element, left, right = None def __init__(self, element): self.element = element self.left =...
Fast way to split alpha and numeric chars in a python string
12,409,894
5
2012-09-13T15:35:42Z
12,409,980
12
2012-09-13T15:40:10Z
[ "python", "regex" ]
I am trying to work out a simple function to capture typos, e.g: ``` "Westminister15" "Westminister15London" "23Westminister15London" ``` after fixating: ``` ["Westminister", "15"] ["Westminister", "15", "London"] ["23", "Westminister", "15", "London"] ``` First attempt: ``` def fixate(query): digit_pattern ...
The problem is that Python's `re.split()` doesn't split on zero-length matches. But you can get the desired result with `re.findall()`: ``` >>> re.findall(r"[^\W\d_]+|\d+", "23Westminister15London") ['23', 'Westminister', '15', 'London'] >>> re.findall(r"[^\W\d_]+|\d+", "Westminister15London England") ['Westminister',...
Migrating virtualenv and Github between computers
12,410,113
7
2012-09-13T15:47:21Z
12,410,239
9
2012-09-13T15:54:24Z
[ "python", "git", "github", "virtualenv" ]
I primarily work these days with Python 2.7 and Django 1.3.3 (hosted on Heroku) and I have multiple projects that I maintain. I've been working on a Desktop with Ubuntu running inside of a VirtualBox, but recently had to take a trip and wanted to get everything loaded up on my notebook. But, what I quickly discovered w...
That's because you're not even supposed to move virtualenvs to different locations on one system (there's relocation support, but it's experimental), let alone from one system to another. Create a new virtualenv: * Install virtualenv on the other system * Get a `requirements.txt`, either by writing one or by storing t...
Migrating virtualenv and Github between computers
12,410,113
7
2012-09-13T15:47:21Z
12,410,296
13
2012-09-13T15:57:03Z
[ "python", "git", "github", "virtualenv" ]
I primarily work these days with Python 2.7 and Django 1.3.3 (hosted on Heroku) and I have multiple projects that I maintain. I've been working on a Desktop with Ubuntu running inside of a VirtualBox, but recently had to take a trip and wanted to get everything loaded up on my notebook. But, what I quickly discovered w...
The only workflow you should need is: ``` git clone repo_url somedir cd somedir virtualenv <name of environment directory> source <name of environment directory>/bin/activate pip install -r requirements.txt ``` This assumes that you have run `pip freeze > requirements.txt` (while the venv is activated) to list all th...
python capitalize first letter only
12,410,242
77
2012-09-13T15:54:32Z
12,410,288
90
2012-09-13T15:56:40Z
[ "python", "capitalize" ]
I am aware .capitalize() capitalizes the first letter of a string but what if the first character is a integer? this ``` 1bob 5sandy ``` to this ``` 1Bob 5Sandy ```
If the first character is an integer, it will not capitalize the first letter. ``` >>> '2s'.capitalize() '2s' ``` If you want the functionality, strip off the digits, you can use `'2'.isdigit()` to check for each character. ``` >>> s = '123sa' >>> for i, c in enumerate(s): ... if not c.isdigit(): ... bre...
python capitalize first letter only
12,410,242
77
2012-09-13T15:54:32Z
12,410,604
118
2012-09-13T16:18:06Z
[ "python", "capitalize" ]
I am aware .capitalize() capitalizes the first letter of a string but what if the first character is a integer? this ``` 1bob 5sandy ``` to this ``` 1Bob 5Sandy ```
Only because no one else has mentioned it: ``` >>> 'bob'.title() 'Bob' >>> 'sandy'.title() 'Sandy' >>> '1bob'.title() '1Bob' >>> '1sandy'.title() '1Sandy' ``` However, this would also give ``` >>> '1bob sandy'.title() '1Bob Sandy' >>> '1JoeBob'.title() '1Joebob' ``` i.e. it doesn't just capitalize the first alphabe...
python capitalize first letter only
12,410,242
77
2012-09-13T15:54:32Z
24,898,145
7
2014-07-22T21:26:39Z
[ "python", "capitalize" ]
I am aware .capitalize() capitalizes the first letter of a string but what if the first character is a integer? this ``` 1bob 5sandy ``` to this ``` 1Bob 5Sandy ```
Here is a one-liner that will uppercase the first letter and leave the case of all subsequent letters: ``` import re key = 'wordsWithOtherUppercaseLetters' key = re.sub('([a-zA-Z])', lambda x: x.groups()[0].upper(), key, 1) print key ``` This will result in `WordsWithOtherUppercaseLetters`
python capitalize first letter only
12,410,242
77
2012-09-13T15:54:32Z
32,232,764
8
2015-08-26T17:15:07Z
[ "python", "capitalize" ]
I am aware .capitalize() capitalizes the first letter of a string but what if the first character is a integer? this ``` 1bob 5sandy ``` to this ``` 1Bob 5Sandy ```
This is similar to @Anon's answer in that it keeps the rest of the string's case intact, without the need for the re module. ``` def upperfirst(x): return x[0].upper() + x[1:] x = 'thisIsCamelCase' y = upperfirst(x) print(y) # Result: 'ThisIsCamelCase' # ``` As @Xan pointed out, the function could use more er...
Pytest: how to skip the rest of tests in the class if one has failed?
12,411,431
15
2012-09-13T17:11:28Z
12,579,625
16
2012-09-25T09:06:56Z
[ "python", "automated-tests", "selenium-webdriver", "py.test" ]
I'm creating the test cases for web-tests using Jenkins, Python, Selenium2(webdriver) and Py.test frameworks. So far I'm organizing my tests in the following structure: each **Class** is the **Test Case** and each **`test_` method** is a **Test Step**. This setup works GREAT when everything is working fine, however ...
I like the general "test-step" idea. I'd term it as "incremental" testing and it makes most sense in functional testing scenarios IMHO. Here is a an implementation that doesn't depend on internal details of pytest (except for the official hook extensions): ``` import pytest def pytest_runtest_makereport(item, call):...
How do I find the exact CLI command given to the python?
12,411,643
5
2012-09-13T17:27:08Z
12,411,695
8
2012-09-13T17:29:45Z
[ "python", "command-line-arguments" ]
I want to find out from inside the script -- the exact command I used to fire it up. I tried the following: ``` #!/usr/bin/env python import sys, os print os.path.basename(sys.argv[0]), sys.argv[1:] ``` But it loses info: ``` $ 1.py -1 dfd 'gf g' "df df" 1.py ['-1', 'dfd', 'gf g', 'df df'] ``` You see -- it has a...
The information you're looking for (command params including quotes) is not available. The *shell* (bash), not python, reads and interprets quotes--by the time python or any other spawned program sees the parameters, the quotes are removed. (Except for quoted quotes, of course.) ### More detail When you type a comma...
Filter columns of only zeros from a Pandas data frame
12,411,649
8
2012-09-13T17:27:27Z
12,411,730
10
2012-09-13T17:32:12Z
[ "python", "pandas" ]
I have a Pandas Data Frame where I would like to filter out all columns which only contain zeros. For example, in the Data Frame below, I'd like to remove column 2: ``` 0 1 2 3 4 0 0.381 0.794 0.000 0.964 0.304 1 0.538 0.029 0.000 0.327 0.928 2 0.041 0.312 0.000 0.208 0.28...
The following works for me. It gives a series where column names are now the index, and the value for an index is True/False depending on whether all items in the column are 0. ``` import pandas, numpy as np # Create DataFrame "df" like yours... df.apply(lambda x: np.all(x==0)) ```
typeerror unsupported operand type(s) for %: 'list' and 'int'
12,411,661
3
2012-09-13T17:28:14Z
12,411,700
8
2012-09-13T17:30:10Z
[ "python", "list", "int", "typeerror" ]
Here's the code: ``` list = [2, 3, 5, 7, 11, 13] list2 = [range(list[-1], 2000000)] y =11 x = 1 v = list[-1]>= x while list[-1] ** 2 < 2000000: y= y + 2 prime = True while prime == True: for x in list: if x * 2 < y: if y % x == 0: prime = False...
`range()` already returns a list, but you put it into a new list: ``` list2 = [range(list[-1], 2000000)] ``` This results in a list containing a list, and `w` later on is set to the full range. Just remove the brackets there. ``` >>> [range(5)] [[0, 1, 2, 3, 4]] >>> range(5) [0, 1, 2, 3, 4] ```
how to print decimal values in python
12,411,778
4
2012-09-13T17:35:20Z
12,411,785
7
2012-09-13T17:36:21Z
[ "python", "decimal", "floating-accuracy" ]
``` print("enter start() to start the program") def start(): print("This script converts GBP into any currency based on the exchange rate...") print(" ") #enters a line exchangeRate = int(input("Enter the exchange rate (Eg: 0.80)")) print("how much would you like to convert???") ...
Use [`float()`](http://docs.python.org/library/functions.html#float) instead of [`int()`](http://docs.python.org/library/functions.html#int) with your `input()` call. I.e., ``` gpb = float(input()) ``` otherwise if the user enters `0.81`, [`int()`](http://docs.python.org/library/functions.html#int) will truncate ...
Python class returning value
12,412,324
2
2012-09-13T18:14:08Z
12,412,839
7
2012-09-13T18:49:31Z
[ "python", "class", "return" ]
I'm trying to create a class that returns a value, not self. I will show you an example comparing with a list: ``` >>> l = list() >>> print(l) [] >>> class MyClass: >>> pass >>> mc = MyClass() >>> print mc <__main__.MyClass instance at 0x02892508> ``` I need that MyClass returns a list, like `list()` does, not ...
I guess what you mean is a way to turn your class into kind of a list without subclassing `list` I so, just make a method that returns a list. ``` def MyClass(): def __init__(self): self.value1 = 1 self.value2 = 2 def get_list(self): return [self.value1, self.value2...] >>>print MyC...
Python class returning value
12,412,324
2
2012-09-13T18:14:08Z
12,413,139
14
2012-09-13T19:08:15Z
[ "python", "class", "return" ]
I'm trying to create a class that returns a value, not self. I will show you an example comparing with a list: ``` >>> l = list() >>> print(l) [] >>> class MyClass: >>> pass >>> mc = MyClass() >>> print mc <__main__.MyClass instance at 0x02892508> ``` I need that MyClass returns a list, like `list()` does, not ...
I think you are very confused about what is occurring. In Python, everything is an object: * `[]` (a list) is an object * `'abcde'` (a string) is an object * `1` (an integer) is an object * `MyClass()` (an instance) is an object * `MyClass` (a class) is also an object * `list` (a type--much like a class) is also an o...
split python source code into multiple files?
12,412,595
14
2012-09-13T18:33:10Z
12,412,670
10
2012-09-13T18:38:21Z
[ "python" ]
I have a code that I wish to split apart into multiple files. In matlab one can simply call a `.m` file, and as long as it is not defined as anything in particular it will just run as if it were part of the called code. Example (edited): **test.m** (matlab) ``` function [] = test() ... some code using variables ...
Python has importing and namespacing, which are good. In Python you can import into the current namespace, like: ``` >>> from test import disp >>> disp('World!') ``` Or with a namespace: ``` >>> import test >>> test.disp('World!') ```
split python source code into multiple files?
12,412,595
14
2012-09-13T18:33:10Z
12,412,672
18
2012-09-13T18:38:29Z
[ "python" ]
I have a code that I wish to split apart into multiple files. In matlab one can simply call a `.m` file, and as long as it is not defined as anything in particular it will just run as if it were part of the called code. Example (edited): **test.m** (matlab) ``` function [] = test() ... some code using variables ...
Sure! ``` #file -- test.py -- myvar = 42 def test_func(): print("Hello!") ``` Now, this file ("test.py") is in python terminology a "module". We can import it (as long as it can be found in our `PYTHONPATH`) Note that the current directory is always in `PYTHONPATH`, so if `use_test` is being run from the same di...
passing parameters to apscheduler handler function
12,412,708
8
2012-09-13T18:40:53Z
12,412,731
9
2012-09-13T18:42:29Z
[ "python" ]
I am using apscheduler and I am trying to pass in parameters to the handler function that gets called when the scheduled job is launched: ``` from apscheduler.scheduler import Scheduler import time def printit(sometext): print "this happens every 5 seconds" print sometext sched = Scheduler() sched.start() s...
`printit(sometext)` is not a callable, it is the result of the call. You can use: ``` lambda: printit(sometext) ``` Which is a callable to be called later which will probably do what you want.
Django custom admin dashboard error
12,412,786
3
2012-09-13T18:45:46Z
12,413,651
16
2012-09-13T19:44:38Z
[ "python", "django", "django-grappelli" ]
I tried to use django-grappelli dashboard, and the admin interface is giving error. ``` Django Version: 1.4.1 Exception Type: ImportError Exception Value: No module named dashboard In template /.../lib/python2.7/site-packages/grappelli/dashboard/templates/admin/index.html, error at line 32 31 {% block content %}...
Ok, it got working. dashboard.py needed to move to myproj/myproj
Calculate probability in normal distribution given mean, std in Python
12,412,895
27
2012-09-13T18:53:34Z
12,413,053
47
2012-09-13T19:03:15Z
[ "python", "statistics", "scipy", "probability" ]
How to calculate probability in normal distribution given mean, std in Python? I can always explicitly code my own function according to the definition like the OP in this question did: [Calculating Probability of a Random Variable in a Distribution in Python](http://stackoverflow.com/questions/9448246/calculating-prob...
There's one in [scipy.stats](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.norm.html): ``` >>> import scipy.stats >>> scipy.stats.norm(0, 1) <scipy.stats.distributions.rv_frozen object at 0x928352c> >>> scipy.stats.norm(0, 1).pdf(0) 0.3989422804014327 >>> scipy.stats.norm(0, 1).cdf(0) 0.5 >>> scipy.s...
Calculate probability in normal distribution given mean, std in Python
12,412,895
27
2012-09-13T18:53:34Z
12,413,491
12
2012-09-13T19:32:11Z
[ "python", "statistics", "scipy", "probability" ]
How to calculate probability in normal distribution given mean, std in Python? I can always explicitly code my own function according to the definition like the OP in this question did: [Calculating Probability of a Random Variable in a Distribution in Python](http://stackoverflow.com/questions/9448246/calculating-prob...
Scipy.stats is a great module. Just to offer another approach, you can calculate it directly using ``` import math def normpdf(x, mean, sd): var = float(sd)**2 pi = 3.1415926 denom = (2*pi*var)**.5 num = math.exp(-(float(x)-float(mean))**2/(2*var)) return num/denom ``` This uses the formula found ...
Complex syntax- Python
12,413,046
7
2012-09-13T19:02:56Z
12,413,085
14
2012-09-13T19:05:05Z
[ "python", "syntax" ]
I am quite new to programming and don't understand a lot of concepts. Can someone explain to me the syntax of line 2 and how it works? Is there no indentation required? And also, where I can learn all this from? ``` string = #extremely large number num = [int(c) for c in string if not c.isspace()] ```
That is a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions), a sort of shorthand for creating a new list. It is functionally equivalent to: ``` num = [] for c in string: if not c.isspace(): num.append(int(c)) ```
Map each list value to its corresponding percentile
12,414,043
13
2012-09-13T20:10:37Z
12,414,469
13
2012-09-13T20:42:07Z
[ "python", "numpy", "scipy", "median", "percentile" ]
I'd like to create a function that takes a (sorted) list as its argument and outputs a list containing each element's corresponding percentile. For example, `fn([1,2,3,4,17])` returns `[0.0, 0.25, 0.50, 0.75, 1.00]`. Can anyone please either: 1. Help me correct my code below? OR 2. Offer a better alternative than my...
I think you want [scipy.stats.percentileofscore](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.percentileofscore.html#scipy.stats.percentileofscore) Example: ``` percentileofscore([1, 2, 3, 4], 3) 75.0 percentiles = [percentileofscore(data, i) for i in data] ```
Map each list value to its corresponding percentile
12,414,043
13
2012-09-13T20:10:37Z
28,577,101
13
2015-02-18T06:08:44Z
[ "python", "numpy", "scipy", "median", "percentile" ]
I'd like to create a function that takes a (sorted) list as its argument and outputs a list containing each element's corresponding percentile. For example, `fn([1,2,3,4,17])` returns `[0.0, 0.25, 0.50, 0.75, 1.00]`. Can anyone please either: 1. Help me correct my code below? OR 2. Offer a better alternative than my...
I think your example input/output does not correspond to typical ways of calculating percentile. If you calculate the percentile as "proportion of data points strictly less than this value", then the top value should be 0.8 (since 4 of 5 values are less than the largest one). If you calculate it as "percent of data poi...
Suds ignoring proxy setting
12,414,600
5
2012-09-13T20:51:38Z
12,433,606
13
2012-09-15T00:40:46Z
[ "python", "salesforce", "suds" ]
I'm trying to use the salesforce-python-toolkit to make web services calls to the Salesforce API, however I'm having trouble getting the client to go through a proxy. Since the toolkit is based on top of suds, I tried going down to use just suds itself to see if I could get it to respect the proxy setting there, but it...
I went into #suds on freenode and Xelnor/rbarrois provided a great answer! Apparently the custom mapping in suds overrides urllib2's behavior for using the system configuration environment variables. This solution now relies on having the http\_proxy/https\_proxy/no\_proxy environment variables set accordingly. I hope...
Creating a 3D plot from a 3D numpy array
12,414,619
4
2012-09-13T20:53:10Z
12,414,814
10
2012-09-13T21:08:31Z
[ "python", "numpy", "matplotlib" ]
Ok, so I feel like there should be an easy way to create a 3-dimensional scatter plot using matplotlib. I have a 3D numpy array (`dset`) with 0's where I don't want a point and 1's where I do, basically to plot it now I have to step through three `for:` loops as such: ``` for i in range(30): for x in range(60): ...
If you have a `dset` like that, and you want to just get the `1` values, you could use `nonzero`, which "returns a tuple of arrays, one for each dimension of `a`, containing the indices of the non-zero elements in that dimension.". For example, we can make a simple 3d array: ``` >>> import numpy >>> numpy.random.seed...
Checking a Dictionary using a dot notation string
12,414,821
8
2012-09-13T21:09:15Z
12,414,913
15
2012-09-13T21:16:05Z
[ "python" ]
This one is blowing my mind. Given the following dictionary: ``` d = {"a":{"b":{"c":"winning!"}}} ``` I have this string (from an external source, and I can't change this metaphor). ``` k = "a.b.c" ``` I need to determine if the dictionary *has the key* 'c', so I can add it if it doesn't. This works swimmi...
You could use an infinite, nested [defaultdict](http://docs.python.org/library/collections.html#collections.defaultdict): ``` >>> from collections import defaultdict >>> infinitedict = lambda: defaultdict(infinitedict) >>> d = infinitedict() >>> d['key1']['key2']['key3']['key4']['key5'] = 'test' >>> d['key1']['key2'][...
Checking a Dictionary using a dot notation string
12,414,821
8
2012-09-13T21:09:15Z
12,415,273
7
2012-09-13T21:49:04Z
[ "python" ]
This one is blowing my mind. Given the following dictionary: ``` d = {"a":{"b":{"c":"winning!"}}} ``` I have this string (from an external source, and I can't change this metaphor). ``` k = "a.b.c" ``` I need to determine if the dictionary *has the key* 'c', so I can add it if it doesn't. This works swimmi...
... or using recursion: ``` def put(d, keys, item): if "." in keys: key, rest = keys.split(".", 1) if key not in d: d[key] = {} put(d[key], rest, item) else: d[keys] = item def get(d, keys): if "." in keys: key, rest = keys.split(".", 1) return g...
How to free memory after opening a file in Python
12,415,783
9
2012-09-13T22:39:06Z
12,416,475
9
2012-09-14T00:02:33Z
[ "python", "memory", "file-io", "large-files" ]
I'm opening a 3 GB file in Python to read strings. I then store this data in a dictionary. My next goal is to build a graph using this dictionary so I'm closely monitoring memory usage. It seems to me that Python loads the whole 3 GB file into memory and I can't get rid of it. My code looks like that : ``` with open(...
this really does make no sense to me either, and I wanted to figure out how/why this happens. ( i thought that's how this should work too! ) i replicated it on my machine - though with a smaller file. i saw two discrete problems here 1. why is Python reading the file into memory ( with lazy line reading, it shouldn't...
HTML not rendering in Django text field
12,416,253
4
2012-09-13T23:32:59Z
12,416,289
12
2012-09-13T23:36:53Z
[ "python", "django", "django-forms", "markdown" ]
I am attempting to use markdown to avoid having to type HTML within my wiki form, but for some reason the form is displaying HTML code instead of the intended formatting. My view function is as follows: ``` from django.shortcuts import render_to_response from mywiki.wiki.models import Page from django.http import Htt...
Use Django's [safe filter](https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#safe) so as for your Html not to be escaped. ``` {{ content|safe }} ```
print a string in python left justified with an offset
12,416,872
3
2012-09-14T01:07:36Z
12,416,881
8
2012-09-14T01:08:59Z
[ "python", "string-formatting" ]
I am using Python 2.4. I would like to print a string left justified but with an "offset". By that I mean, print a string with a set number of spaces before it. Example: Print string "Hello" in a space of width 20, left justified, but five spaces inserted before the string. ``` " Hello " #(The string ...
Not really. ``` >>> ' %-15s' % ('Hello',) ' Hello ' ```
how to release used memory immediately in python list?
12,417,498
12
2012-09-14T02:51:30Z
12,417,671
13
2012-09-14T03:19:02Z
[ "python" ]
in many cases ,you are sure you definitely won't use the list again,i hope the memory should be release right now ``` a = [11,22,34,567,9999] del a ``` i'm not sure if it really release the memory,you can use ``` del a[:] ``` that actually remove all elements in list a . so the best way to release is this? ``` de...
``` def release_list(a): del a[:] del a ``` Do not *ever* do this. Python automatically frees all objects that are not referenced any more, so a simple `del a` ensures that the list's memory will be released if the list isn't referenced anywhere else. If that's the case, then the individual list items will also ...
logarithmically spaced integers
12,418,234
16
2012-09-14T04:40:42Z
12,421,820
13
2012-09-14T09:35:25Z
[ "python", "numpy", "resampling" ]
Say I have a 10,000 pt vector that I want to take a slice of only 100 logarithmically spaced points. I want a function to give me integer values for the indices. Here's a simple solution that is simply using around + logspace, then getting rid of duplicates. ``` def genLogSpace( array_size, num ): lspace = around(...
This is a bit tricky. You can't always get logarithmically spaced numbers. As in your example, first part is rather linear. If you are OK with that, I have a solution. But for the solution, you should understand why you have duplicates. Logarithmic scale satisfies the condition: ``` s[n+1]/s[n] = constant ``` Let's ...
How to compile static library with -fPIC from boost.python
12,418,838
11
2012-09-14T05:51:36Z
12,420,419
15
2012-09-14T08:05:12Z
[ "c++", "python", "c", "boost", "boost-python" ]
By default, `libboostpython.a` is compiled without `-fPIC`. But I have to make a python extension and it is a dynamic library with `-fPIC` that links to static libraries. How can I compile a static library (`libboostpython.a`) with `-fPIC` from `boost.python`?
There are a couple options you could use: * Compile boost from source and pass extra compiler options to bjam. E.g. `bjam ... cxxflags='-fPIC'`. That would compile every boost source file as position independent code. * Use boost in the form of shared libraries. In this case you probably want to ship boost shared libr...
Python subprocess readlines() hangs
12,419,198
13
2012-09-14T06:29:21Z
12,471,855
21
2012-09-18T06:58:53Z
[ "python", "subprocess" ]
The task I try to accomplish is to stream a ruby file and print out the output. (***NOTE***: I don't want to print out everything at once) **main.py** ``` from subprocess import Popen, PIPE, STDOUT import pty import os file_path = '/Users/luciano/Desktop/ruby_sleep.rb' command = ' '.join(["ruby", file_path]) mast...
I assume you use `pty` due to reasons outlined in [Q: Why not just use a pipe (popen())?](http://pexpect.readthedocs.org/en/latest/FAQ.html#whynotpipe) (all other answers so far ignore your *"NOTE: I don't want to print out everything at once"*). `pty` is Linux only [as said in the docs](http://docs.python.org/dev/lib...
Assigning mulitple variables to a random item in list. Python
12,420,583
2
2012-09-14T08:18:19Z
12,420,602
7
2012-09-14T08:19:38Z
[ "python", "variables" ]
I want to have multiple variables that are set to random elements in the list. Right now I'm doing it somewhat like this: ``` from random import choice list = ["a", "b"] foo = choice(list) bar = choice(list) baz = choice(list) #etc. ``` I'm sure there is a better way to do this. I tried ``` foo = bar = baz = choic...
You can use [`random.sample()`](http://docs.python.org/library/random.html#random.sample) if you want to pluck out three *distinct* elements from the list (i.e. `foo` is never equal to `bar`, which might not be what you want): ``` foo, bar, baz = random.sample(l, 3) ``` I renamed your variable to `l` because `list` i...
Finding all divisors of a number optimization
12,421,969
3
2012-09-14T09:43:17Z
12,422,030
20
2012-09-14T09:47:10Z
[ "python", "math", "mathematical-optimization" ]
I have written the following function which finds all divisors of a given natural number and returns them as a list: ``` def FindAllDivisors(x): divList = [] y = 1 while y <= math.sqrt(x): if x % y == 0: divList.append(y) divList.append(int(x / y)) y += 1 return ...
You can find all the divisors of a number by calculating the *prime factorization*. Each divisor has to be a combination of the primes in the factorization. If you have a list of primes, this is a simple way to get the factorization: ``` def factorize(n, primes): factors = [] for p in primes: if p*p >...
render throws error AttributeError META - (Exception location: __getattr__ in urllib2)
12,423,581
4
2012-09-14T11:25:50Z
12,423,949
7
2012-09-14T11:50:22Z
[ "python", "django", "urllib2", "attributeerror" ]
I followed [this](http://www.chicagodjango.com/blog/magic-links/) article to try to load images from an external website. I am trying to pull all the images from an external link. I have used BeautifulSoup to parse the link and get all the required links. Before the view calls the render() function at the end of the c...
You've overwritten the `request` variable inside your function, because you reused it for the call to `urllib2.Request`. Use a different variable name there.
Python the simplest way to plot 3d surface
12,423,601
10
2012-09-14T11:27:37Z
12,424,252
11
2012-09-14T12:08:59Z
[ "python", "python-2.7", "plot", "geometry-surface" ]
I have a lot (289) of 3d points with xyz coordinates which looks like: ![3D points](http://i.stack.imgur.com/Ug1Rh.png) With plotting simply 3d space with points is OK, but I have trouble with surface There are some points: ``` for i in range(30): output.write(str(X[i])+' '+str(Y[i])+' '+str(Z[i])+'\n') -0....
Please have a look at [Axes3D.plot\_surface](http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html#surface-plots) or at the other `Axes3D` methods. You can find examples and inspirations [here](http://stackoverflow.com/questions/9170838/surface-plots-in-matplotlib), [here](http://stackoverflow.com/questions/4363857/...
Python the simplest way to plot 3d surface
12,423,601
10
2012-09-14T11:27:37Z
25,586,869
10
2014-08-30T21:23:13Z
[ "python", "python-2.7", "plot", "geometry-surface" ]
I have a lot (289) of 3d points with xyz coordinates which looks like: ![3D points](http://i.stack.imgur.com/Ug1Rh.png) With plotting simply 3d space with points is OK, but I have trouble with surface There are some points: ``` for i in range(30): output.write(str(X[i])+' '+str(Y[i])+' '+str(Z[i])+'\n') -0....
Solution with matplotlib: ``` #!/usr/bin/python3 import sys import matplotlib import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D import numpy from numpy.random import randn from scipy import array, newaxis # ====== ## data: ...
Local variables in Python nested functions
12,423,614
70
2012-09-14T11:28:10Z
12,423,750
79
2012-09-14T11:37:39Z
[ "python", "scope", "nested-function" ]
Okay, bear with me on this, I know it's going to look horribly convoluted, but please help me understand what's happening. ``` from functools import partial class Cage(object): def __init__(self, animal): self.animal = animal def gotimes(do_the_petting): do_the_petting() def get_petters(): for a...
The nested function looks up variables from the parent scope when executed, not when defined. The function body is compiled, and the 'free' variables (not defined in the function itself by assignment), are verified, then bound as closure cells to the function, with the code using an index to reference each cell. `pet_...
Local variables in Python nested functions
12,423,614
70
2012-09-14T11:28:10Z
12,423,782
10
2012-09-14T11:39:16Z
[ "python", "scope", "nested-function" ]
Okay, bear with me on this, I know it's going to look horribly convoluted, but please help me understand what's happening. ``` from functools import partial class Cage(object): def __init__(self, animal): self.animal = animal def gotimes(do_the_petting): do_the_petting() def get_petters(): for a...
My understanding is that cage is looked for in the parent function namespace when the yielded pet\_function is actually called, not before. So when you do ``` funs = list(get_petters()) ``` You generate 3 functions which will find the lastly created cage. If you replace your last loop with : ``` for name, f in get...
Why django doesn't save encrypted password?
12,423,796
2
2012-09-14T11:40:28Z
12,423,875
9
2012-09-14T11:45:27Z
[ "python", "django" ]
I've using django 1.4. When creating a new user, it saves plain password. Is there a setting for it so when saving a user, the password is saved encrypted? **EDIT** I'm simply using the built-in admin functionality to add a user. Nothing fancy - just the built in auth module and the user form that is automatically cr...
You should use the [`create_user`](https://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.models.UserManager.create_user) manager method when creating users. If you're creating custom forms, subclass one of the [`UserCreationForm`](https://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth....
How I can i conditionally change the values in a numpy array taking into account nan numbers?
12,424,824
2
2012-09-14T12:43:51Z
12,424,896
16
2012-09-14T12:47:49Z
[ "python", "open-source", "numpy", "statistics", "gdal" ]
My array is a 2D matrix and it has numpy.nan values besides negative and positive values: ``` >>> array array([[ nan, nan, nan, ..., -0.04891211, nan, nan], [ nan, nan, nan, ..., nan, nan, nan], [ nan, na...
The fact that you have `np.nan` in your array should not matter. Just use fancy indexing: ``` x[x>0] = new_value_for_pos x[x<0] = new_value_for_neg ``` If you want to replace your `np.nans`: ``` x[np.isnan(x)] = something_not_nan ``` More info on fancy indexing [a tutorial](http://www.scipy.org/Tentative_NumPy_Tuto...
Can I read and write file in one line with Python?
12,426,043
4
2012-09-14T13:56:11Z
12,426,076
15
2012-09-14T13:58:01Z
[ "python", "file-io" ]
with ruby I can ``` File.open('yyy.mp4', 'w') { |f| f.write(File.read('xxx.mp4')} ``` Can I do this using Python ?
Sure you can: ``` with open('yyy.mp4', 'wb') as f: f.write(open('xxx.mp4', 'rb').read()) ``` Note the binary mode flag there (`b`), since you are copying over `mp4` contents, you don't want python to reinterpret newlines for you. That'll take a lot of memory if `xxx.mp4` is large. Take a look at the [`shutil.cop...
commands vs subprocess
12,426,998
2
2012-09-14T14:56:26Z
12,427,019
7
2012-09-14T14:57:23Z
[ "python", "subprocess" ]
Just wondering if anybody could tell me why ``` import subprocess, commands p=subprocess.Popen(["ls", "*00080"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output=p.communicate()[0] print "o", output result=commands.getoutput("ls *00080") print "o", result ``` gives the outputs: ``` o ls: cannot access *0008...
`commands` spaws a shell which does the glob expansion. `subprocess` doesn't spawn a shell unless you pass `shell = True`. In other words: ``` p=subprocess.Popen("ls *00080",shell=True,stdout=subprocess.PIPE, stderr=subprocess.STDOUT) ``` should do the same thing that `commands` did.
combine two arrays and sort
12,427,146
10
2012-09-14T15:04:53Z
12,427,633
13
2012-09-14T15:30:34Z
[ "python", "numpy" ]
Given two sorted arrays like the following: ``` a = array([1,2,4,5,6,8,9]) b = array([3,4,7,10]) ``` I would like the output to be: ``` c = array([1,2,3,4,5,6,7,8,9,10]) ``` or: ``` c = array([1,2,3,4,4,5,6,7,8,9,10]) ``` I'm aware that I can do the following: ``` c = unique(concatenate((a,b)) ``` I'm just won...
Since you use numpy, I doubt that bisec helps you at all... So instead I would suggest two smaller things: 1. Do *not* use `np.sort`, use `c.sort()` method instead which sorts the array in place and avoids the copy. 2. `np.unique` must use `np.sort` which is not in place. So instead of using `np.unique` do the logic b...
combine two arrays and sort
12,427,146
10
2012-09-14T15:04:53Z
12,427,803
8
2012-09-14T15:41:47Z
[ "python", "numpy" ]
Given two sorted arrays like the following: ``` a = array([1,2,4,5,6,8,9]) b = array([3,4,7,10]) ``` I would like the output to be: ``` c = array([1,2,3,4,5,6,7,8,9,10]) ``` or: ``` c = array([1,2,3,4,4,5,6,7,8,9,10]) ``` I'm aware that I can do the following: ``` c = unique(concatenate((a,b)) ``` I'm just won...
Inserting elements into the middle of an `array` is a very inefficient operation as they're flat in memory, so you'll need to shift everything along whenever you insert another element. As a result, you probably don't want to use `bisect`. The complexity of doing so would be around `O(N^2)`. Your current approach is `...
How does Udacity web Python interpreter work?
12,427,361
8
2012-09-14T15:16:40Z
12,427,660
12
2012-09-14T15:32:43Z
[ "javascript", "python" ]
[Udacity](http://www.udacity.com/) gives students a web editor to enter Python programs. The editor recognizes Python keywords and built-in functions and allows to run a program. Do you know how this technology works? Are programs submitted to a backend and executed by the standard Python interpreter or is it a JavaScr...
While javascript python interpreters do exist: <http://syntensity.com/static/python.html> , they don't appear to be using one. It would be far too easy to cheat if they didn't at least run the programs once for verification on their own interpreter. After looking at the network activity on Udacity I can see that they ...
How do I improve scrapy's download speed?
12,427,451
4
2012-09-14T15:20:46Z
13,060,018
7
2012-10-25T00:43:27Z
[ "python", "scrapy" ]
I'm using scrapy to download pages from many different domains in parallel. I have hundreds of thousands of pages to download, so performance is important. Unfortunately, as I've profiled scrapy's speed, I'm only getting a couple pages per second. Really, about 2 pages per second on average. I've previously written my...
I had this problem in the past... And large part of it I solved with a 'Dirty' old tricky. [Do a local cache DNS](http://wiki.list.org/display/DOC/Improving+performance+by+local+DNS+caching). Mostly when you have this high cpu usage accessing simultaneous remote sites it is because scrapy is trying to resolve the url...
Why is Python faster than C when concatenating two strings?
12,429,061
14
2012-09-14T17:10:38Z
12,429,124
7
2012-09-14T17:15:27Z
[ "python", "c", "string", "performance" ]
Currently I want to compare the speed of Python and C when they're used to do string stuff. I think C should give better performance than Python will; however, I got a total contrary result. Here's the C program: ``` #include <unistd.h> #include <sys/time.h> #define L (100*1024) char s[L+1024]; char c[2*L+1024]; d...
I believe the reason for this is that Python strings are not null-terminated. in Python the string length is stored alongside the string, allowing it to skip the implicit strlen() used by strcat() when concatenating strings. Adding in the fact that string concatenation is implemented directly in C for Python is proba...
Why is Python faster than C when concatenating two strings?
12,429,061
14
2012-09-14T17:10:38Z
12,429,831
18
2012-09-14T18:14:37Z
[ "python", "c", "string", "performance" ]
Currently I want to compare the speed of Python and C when they're used to do string stuff. I think C should give better performance than Python will; however, I got a total contrary result. Here's the C program: ``` #include <unistd.h> #include <sys/time.h> #define L (100*1024) char s[L+1024]; char c[2*L+1024]; d...
Accumulated comments (mainly from me) converted into an answer: * What happens if you use your knowledge of the lengths of the strings and use `memmove()` or `memcpy()` instead of `strcpy()` and `strcat()`? (I note that the `strcat()` could be replaced with `strcpy()` with no difference in result — it might be inte...
in Python, How can I convert a string into a date object and get year, month and day separately?
12,430,287
5
2012-09-14T18:49:01Z
12,430,314
17
2012-09-14T18:50:49Z
[ "python", "string", "datetime" ]
If I have lets say this string "2008-12-12 19:21:10" how can I convert it into a date and get the year, month and day from that created object separately?
Use the [`datetime.datetime.strptime()` function](http://docs.python.org/library/datetime.html#datetime.datetime.strptime): ``` from datetime import datetime dt = datetime.strptime(datestring, '%Y-%m-%d %H:%M:%S') ``` Now you have a `datetime.datetime` object, and it has [`.year`](http://docs.python.org/library/datet...
Can we use regular expressions to check if there are an odd number of each type of character?
12,431,326
15
2012-09-14T20:10:19Z
12,431,651
7
2012-09-14T20:37:45Z
[ "python", "regex" ]
### The problem I'm trying to create a regex in which we can check if all letters present in some reference set are present in some other string, but only in odd numbers (1, 3, 5, ...). Here is a (very) crude image of the [DFA](http://en.wikipedia.org/wiki/Deterministic_finite_automaton "Deterministic Finite Automato...
Here's one way to do it, using lookaheads to assert each condition in turn. ``` ^(?=[^a]*a(?:[^a]*a[^a]*a)*[^a]*$)(?=[^b]*b(?:[^b]*b[^b]*b)*[^b]*$)(.*)$ ``` Here's [a demo](http://regexpal.com/?flags=gm&regex=%5E%28%3F%3D%5B%5Ea%5Cn%5D%2aa%28%3F%3A%5B%5Ea%5Cn%5D%2aa%5B%5Ea%5Cn%5D%2aa%29%2a%5B%5Ea%5Cn%5D%2a%24%29%28%3...
Can we use regular expressions to check if there are an odd number of each type of character?
12,431,326
15
2012-09-14T20:10:19Z
12,431,889
11
2012-09-14T21:00:18Z
[ "python", "regex" ]
### The problem I'm trying to create a regex in which we can check if all letters present in some reference set are present in some other string, but only in odd numbers (1, 3, 5, ...). Here is a (very) crude image of the [DFA](http://en.wikipedia.org/wiki/Deterministic_finite_automaton "Deterministic Finite Automato...
Regexes are not more limited than a [DFA](http://en.wikipedia.org/wiki/Deterministic_finite_automaton); in fact, they are equivalent. (Perl-style "regexes" with backreferences are strictly more powerful, so they are not "regular" at all.) We can easily write the regex if the string contains only `a`s: ``` a(aa)* ``` ...
Does creating functions inside functions have a recurring cost?
12,431,755
3
2012-09-14T20:46:47Z
12,431,824
8
2012-09-14T20:52:49Z
[ "python", "python-2.7" ]
I'm writing a function in Python that I'm planning to run for 10 000 or more times for each script execution. The function currently contains 3 sub-functions but will probably contain 20 or more when the script is complete. I'm just wondering; Will declaring those functions over and over (since the parent function will...
The performance impact of a function definition is negligible and comparable to defining a local variable. The body of the function is compiled only once, all that you end up with during execution of the code-block is loading the compiled block (`LOAD_CONST`), and the result of the `MAKE FUNCTION` byte code is then st...
Usage of pypy compiler
12,431,847
3
2012-09-14T20:55:56Z
12,432,159
7
2012-09-14T21:21:29Z
[ "python", "python-3.x", "python-2.7", "pypy" ]
Is there a difference in python programming while using just python and while using pypy compiler? I wanted to try using pypy so that my program execution time becomes faster. Does all the syntax that work in python works in pypy too? If there is no difference, can you tell me how can i install pypy on debian lunux and...
From the pypy [features page](http://pypy.org/features.html): > PyPy 1.9 implements Python 2.7.2 and runs on Intel x86 (IA-32) and > x86\_64 platforms, with ARM and PPC being underway. It supports all of > the core language, passing the Python test suite. This means that pretty much any code that you've written in Py...
PyQt4 set windows taskbar icon
12,432,637
13
2012-09-14T22:12:49Z
12,522,799
9
2012-09-21T00:31:30Z
[ "python", "qt4", "icons", "python-2.7", "pyqt4" ]
I'm working on an applcation in Python's PyQt4 and cannot find how to change the taskbar icon. I made my .ui files in Qt's Designer, where I can change the `windowIcon` properties. But that is not what I am looking for. I want to change the look of the application's icon in windows taskbar. For now it is Python logo in...
This problem is caused by some peculiarities in how taskbar icons are handled on the Windows platform. See [this answer](http://stackoverflow.com/a/1552105/984421) for details, along with a workaround using `ctypes`.
What is a clean way to convert a string percent to a float?
12,432,663
9
2012-09-14T22:15:41Z
12,432,693
30
2012-09-14T22:18:10Z
[ "python", "string", "python-2.7" ]
I have looked in the standard library and on StackOverflow, and have not found a similar question. So, is there a way to do the following without rolling my own function? Bonus points if someone writes a beautiful function if there is no built in way. ``` def stringPercentToFloat(stringPercent) # ??? return fl...
Use `strip('%')` , as: ``` In [9]: "99.5%".strip('%') Out[9]: '99.5' #convert this to float using float() and divide by 100 In [10]: def p2f(x): return float(x.strip('%'))/100 ....: In [12]: p2f("99%") Out[12]: 0.98999999999999999 In [13]: p2f("99.5%") Out[13]: 0.995 ```
What is a clean way to convert a string percent to a float?
12,432,663
9
2012-09-14T22:15:41Z
12,432,701
7
2012-09-14T22:18:47Z
[ "python", "string", "python-2.7" ]
I have looked in the standard library and on StackOverflow, and have not found a similar question. So, is there a way to do the following without rolling my own function? Bonus points if someone writes a beautiful function if there is no built in way. ``` def stringPercentToFloat(stringPercent) # ??? return fl...
``` float(stringPercent.strip('%')) / 100.0 ```
What is the difference between "datetime.timedelta" and "dateutil.relativedelta.relativedelta" when working only with days?
12,433,233
32
2012-09-14T23:29:11Z
12,433,328
34
2012-09-14T23:44:26Z
[ "python", "datetime", "timedelta" ]
What is the difference between [`datetime.timedelta`](http://docs.python.org/library/datetime.html#timedelta-objects) (from Python's standard library) and [`dateutil.relativedelta.relativedelta`](http://labix.org/python-dateutil) when working only with days? As far as I understand, `timedelta` only supports days (and ...
`dateutil` is an extension package to the python standard `datetime` module. As you say, it provides extra functionality, such as timedeltas that are expressed in units larger than a day. This is useful if you have to ask questions such as how many months can I save before my girlfriend's birthday comes up, or what's ...
Extract elements of list at odd positions
12,433,695
32
2012-09-15T01:05:25Z
12,433,705
70
2012-09-15T01:08:49Z
[ "python", "list", "slice" ]
So I want to create a list which is a sublist of some existing list. For example, `L = [1, 2, 3, 4, 5, 6, 7]`, I want to create a sublist `li` such that `li` contains all the elements in `L` at odd positions. While I can do it by ``` L = [1, 2, 3, 4, 5, 6, 7] li = [] count = 0 for i in L: if count % 2 == 1: ...
## Solution Yes, you can: ``` l = L[1::2] ``` And this is all. The result will contain the elements placed on the following positions (`0`-based, so first element is at position `0`, second at `1` etc.): ``` 1, 3, 5 ``` so the result (actual numbers) will be: ``` 2, 4, 6 ``` ## Explanation The `[1::2]` at the e...
How can I set the dash length in a matplotlib contour plot
12,434,426
4
2012-09-15T04:12:56Z
12,455,425
7
2012-09-17T08:16:38Z
[ "python", "matplotlib" ]
I'm making some contour plots in matplotlib and the length of the dashes are too long. The dotted line also doesn't look good. I'd like to manually set the length of the dash. I can set the exact dash length when I'm making a simple plot using plt.plot(), however I cannot figure out how to do the same thing with a cont...
Almost. It's: ``` for c in CS.collections: c.set_dashes([(0, (2.0, 2.0))]) ``` If you had put a `print c.get_dashes()` there, you would have found out (it's what I did). Perhaps the definition of the line style has changed a bit, and you were working from an older example. The [collections documentation](http:...
What does the "-U" option stand for in pip install -U
12,435,209
17
2012-09-15T06:48:54Z
12,435,220
26
2012-09-15T06:50:25Z
[ "python", "command-line", "pip" ]
Despite a ton of Googling, I can't find any docs for pip's command line options/arguments. What does pip install -U stand for? Does anyone have a link the a list of pip's options and arguments?
Type `pip install -h` to list help: > -U, --upgrade Upgrade all packages to the newest available version So, if you already *have* a package installed, it will upgrade the package for you. Without the -U switch it'll tell you the package is already installed and exit. Each `pip` subcommand has it's own help listing....
Python threading.timer - repeat function every 'n' seconds
12,435,211
38
2012-09-15T06:49:12Z
12,435,256
51
2012-09-15T06:56:41Z
[ "python", "python-3.x", "python-2.7" ]
I'm having difficulties with the python timer and would greatly appreciate some advice or help :D I'm not too knowledgeable of how threads work, but I just want to fire off a function every 0.5 seconds and be able to start and stop and reset the timer. However, I keep getting `RuntimeError: threads can only be starte...
The best way is to start the timer thread once. Inside your timer thread you'd code the following ``` class MyThread(Thread): def __init__(self, event): Thread.__init__(self) self.stopped = event def run(self): while not self.stopped.wait(0.5): print("my thread") ...
Python threading.timer - repeat function every 'n' seconds
12,435,211
38
2012-09-15T06:49:12Z
16,368,571
13
2013-05-03T22:40:03Z
[ "python", "python-3.x", "python-2.7" ]
I'm having difficulties with the python timer and would greatly appreciate some advice or help :D I'm not too knowledgeable of how threads work, but I just want to fire off a function every 0.5 seconds and be able to start and stop and reset the timer. However, I keep getting `RuntimeError: threads can only be starte...
From [Equivalent of setInterval in python](http://stackoverflow.com/q/5179467/4279): ``` import threading def setInterval(interval): def decorator(function): def wrapper(*args, **kwargs): stopped = threading.Event() def loop(): # executed in another thread while no...
Python threading.timer - repeat function every 'n' seconds
12,435,211
38
2012-09-15T06:49:12Z
24,488,061
15
2014-06-30T10:29:32Z
[ "python", "python-3.x", "python-2.7" ]
I'm having difficulties with the python timer and would greatly appreciate some advice or help :D I'm not too knowledgeable of how threads work, but I just want to fire off a function every 0.5 seconds and be able to start and stop and reset the timer. However, I keep getting `RuntimeError: threads can only be starte...
Using timer threads- ``` from threading import Timer,Thread,Event class perpetualTimer(): def __init__(self,t,hFunction): self.t=t self.hFunction = hFunction self.thread = Timer(self.t,self.handle_function) def handle_function(self): self.hFunction() self.thread = Timer(self.t,s...
Combine Related Resources With TastyPie
12,435,992
6
2012-09-15T09:01:16Z
12,436,124
10
2012-09-15T09:22:03Z
[ "python", "django", "tastypie" ]
How can I combine multiple Resources in TastyPie? I have 3 models I'd like to combine: users, profiles and posts. Ideally I'd like profiles nested within user. I'd like to expose both the user and all of the profile location from UserPostResource. I'm not sure where to go from here. ``` class UserResource(ModelResour...
Tastypie fields (when the resource is a `ModelResource`) allow passing in the `attribute` kwarg, which in turn accepts regular django nested lookup syntax. So, first of all this might be useful: ``` # in UserProfile model (adding related_name) user = models.OneToOneField(User, related_name="profile") ``` and given t...
Python: confused with classes, attributes and methods in OOP
12,436,223
2
2012-09-15T09:36:19Z
12,436,253
8
2012-09-15T09:41:09Z
[ "python", "oop", "methods" ]
I'm learning Python OOP now and confused with somethings in the code below. Questions: 1. `def __init__(self, radius=1):` What does the argument/attribute "radius = 1" mean exactly? Why isn't it just called "radius"? 2. The method area() has no argument/attribute "radius". Where does it get its "radius" from...
The `def method(self, argument=value):` syntax defines a *keyword argument*, with a default value. Using that argument is now optional, if you do not specify it, the default value is used instead. In your example, that means `radius` is set to `1`. Instances are referred to, within a method, with the `self` parameter....
How to fix Python Numpy/Pandas installation?
12,436,979
12
2012-09-15T11:30:35Z
12,975,518
31
2012-10-19T13:39:55Z
[ "python", "numpy", "pip", "pandas", "easy-install" ]
I would like to install Python Pandas library (0.8.1) on Mac OS X 10.6.8. This library needs Numpy>=1.6. I tried this ``` $ sudo easy_install pandas Searching for pandas Reading http://pypi.python.org/simple/pandas/ Reading http://pandas.pydata.org Reading http://pandas.sourceforge.net Best match: pandas 0.8.1 Downlo...
Don't know if you solved the problem but if anyone has this problem in future. ``` $python >>import numpy >>print(numpy) ``` Go to the location printed and delete the `numpy` installation found there. You can then use `pip` or `easy_install`
how to replace punctuation in a string python?
12,437,667
6
2012-09-15T13:12:49Z
12,437,721
8
2012-09-15T13:21:25Z
[ "python", "string", "replace" ]
I would like to REPLACE (and not REMOVE) all punctuation characters by " " in a string in python. Is there something efficient of this flavour: ``` text = text.translate(string.maketrans("",""), string.punctuation) ``` thanks register
Modified solution from [Best way to strip punctuation from a string in Python](http://stackoverflow.com/questions/265960/best-way-to-strip-punctuation-from-a-string-in-python) ``` import string import re regex = re.compile('[%s]' % re.escape(string.punctuation)) out = regex.sub(' ', "This is, fortunately. A Test! str...
how to replace punctuation in a string python?
12,437,667
6
2012-09-15T13:12:49Z
12,437,738
21
2012-09-15T13:23:49Z
[ "python", "string", "replace" ]
I would like to REPLACE (and not REMOVE) all punctuation characters by " " in a string in python. Is there something efficient of this flavour: ``` text = text.translate(string.maketrans("",""), string.punctuation) ``` thanks register
This answer is for Python 2 and will only work for ASCII strings: The string module contains two things that will help you: a list of punctuation characters and the "maketrans" function. Here is how you can use them: ``` import string replace_punctuation = string.maketrans(string.punctuation, ' '*len(string.punctuati...
how to query an element from a list in pymongo
12,437,849
2
2012-09-15T13:38:19Z
12,437,945
12
2012-09-15T13:52:12Z
[ "python", "search", "pymongo" ]
`pymongo` throws me an error when trying to query and element from `tags` ``` db.users.find({"pseudo":"alucaard"}).distinct("produit_up") Out[1]: [{u'abus': 0, u'avctype': u'image/jpeg', u'date': u'2012-09-15', u'description': u'le fameux portable solide', u'id': u'alucaard134766932677', u'namep': u'nokia 3...
Your query is wrong. Try something closer to: ``` list(db.users.find({"document_up.tags":{"$in":["solide"]}})) ```
Profanities in Django comments
12,439,320
4
2012-09-15T16:56:00Z
12,439,441
7
2012-09-15T17:12:02Z
[ "python", "django", "nlp" ]
Since Django doesn't handle filtering profanities - does anyone have any suggestions on an easy way to implement some sort of natural language processing / filtering of profanities in django?
Django does handle filtering profanities. From <https://docs.djangoproject.com/en/1.4/ref/settings/#profanities-list>: > PROFANITIES\_LIST > > Default: () (Empty tuple) > > A tuple of profanities, as strings, that will be forbidden in comments when > `COMMENTS_ALLOW_PROFANITIES` is `False`. That said you'll still ne...
How to maximize a plt.show() window using Python
12,439,588
25
2012-09-15T17:31:02Z
12,599,064
15
2012-09-26T09:53:02Z
[ "python", "matplotlib" ]
Just for curiosity I would like to know how to do this in the code below. I have been searching for an answer but is useless. ``` import numpy as np import matplotlib.pyplot as plt data=np.random.exponential(scale=180, size=10000) print ('el valor medio de la distribucion exponencial es: ') print np.average(data) plt....
I usually use ``` mng = plt.get_current_fig_manager() mng.frame.Maximize(True) ``` before the call to `plt.show()`, and I get a maximized window. This works for the 'wx' backend only. EDIT: for Qt4Agg backend, see kwerenda's answer.
How to maximize a plt.show() window using Python
12,439,588
25
2012-09-15T17:31:02Z
14,537,262
14
2013-01-26T13:10:43Z
[ "python", "matplotlib" ]
Just for curiosity I would like to know how to do this in the code below. I have been searching for an answer but is useless. ``` import numpy as np import matplotlib.pyplot as plt data=np.random.exponential(scale=180, size=10000) print ('el valor medio de la distribucion exponencial es: ') print np.average(data) plt....
This makes the window take up the full screen for me, under Ubuntu 12.04 with the TkAgg backend: ``` mng = plt.get_current_fig_manager() mng.resize(*mng.window.maxsize()) ```
How to maximize a plt.show() window using Python
12,439,588
25
2012-09-15T17:31:02Z
18,824,814
24
2013-09-16T09:39:03Z
[ "python", "matplotlib" ]
Just for curiosity I would like to know how to do this in the code below. I have been searching for an answer but is useless. ``` import numpy as np import matplotlib.pyplot as plt data=np.random.exponential(scale=180, size=10000) print ('el valor medio de la distribucion exponencial es: ') print np.average(data) plt....
With Qt backend (FigureManagerQT) proper command is: ``` figManager = plt.get_current_fig_manager() figManager.window.showMaximized() ```
How to maximize a plt.show() window using Python
12,439,588
25
2012-09-15T17:31:02Z
22,418,354
50
2014-03-15T01:12:12Z
[ "python", "matplotlib" ]
Just for curiosity I would like to know how to do this in the code below. I have been searching for an answer but is useless. ``` import numpy as np import matplotlib.pyplot as plt data=np.random.exponential(scale=180, size=10000) print ('el valor medio de la distribucion exponencial es: ') print np.average(data) plt....
since I am on zero reputation I can leave no other mark than a new answer I am on a Windows (WIN7), running Python 2.7.5 & Matplotlib 1.3.1 I was able to maximize Figure windows for TkAgg, QT4Agg, and wxAgg using the following lines: ``` from matplotlib import pyplot as plt ### for 'TkAgg' backend plt.figure(1) plt....
How to maximize a plt.show() window using Python
12,439,588
25
2012-09-15T17:31:02Z
23,755,272
12
2014-05-20T08:59:14Z
[ "python", "matplotlib" ]
Just for curiosity I would like to know how to do this in the code below. I have been searching for an answer but is useless. ``` import numpy as np import matplotlib.pyplot as plt data=np.random.exponential(scale=180, size=10000) print ('el valor medio de la distribucion exponencial es: ') print np.average(data) plt....
For me nothing of the above worked. I use the Tk backend on Ubuntu 14.04 which contains matplotlib 1.3.1. The following code creates a fullscreen plot window which is not the same as maximizing but it serves my purpose nicely: ``` from matplotlib import pyplot as plt mng = plt.get_current_fig_manager() mng.full_scree...
Best way to get the nth element of each tuple from a list of tuples in Python
12,440,342
9
2012-09-15T19:25:50Z
12,440,358
16
2012-09-15T19:27:17Z
[ "python" ]
I had some code that contained `zip(*G)[0]` (and elsewhere, `zip(*G)[1]`, with a different G). `G` is a list of tuples. What this does is return a list of the first (or generally, for `zip(*G)[n]`, the `n-1`th) element of each tuple in G as a tuple. For example, ``` >>> G = [(1, 2, 3), ('a', 'b', 'c'), ('you', 'and', ...
You can use a list comprehension ``` [x[0] for x in G] ``` or `operator.itemgetter()` ``` from operator import itemgetter map(itemgetter(0), G) ``` or sequence unpacking ``` [x for x, y, z in G] ``` **Edit**: Here is my take on timing the different options, also in Python 3.2: ``` from operator import itemgetter...
Best way to get the nth element of each tuple from a list of tuples in Python
12,440,342
9
2012-09-15T19:25:50Z
12,442,775
11
2012-09-15T21:45:06Z
[ "python" ]
I had some code that contained `zip(*G)[0]` (and elsewhere, `zip(*G)[1]`, with a different G). `G` is a list of tuples. What this does is return a list of the first (or generally, for `zip(*G)[n]`, the `n-1`th) element of each tuple in G as a tuple. For example, ``` >>> G = [(1, 2, 3), ('a', 'b', 'c'), ('you', 'and', ...
At least the *fastest* way in Python 2.7 is ``` t0,t1,t2=zip(*G) for SMALLER lists and [x[0] for x in G] in general ``` Here is the test: ``` from operator import itemgetter G = [(1, 2, 3), ('a', 'b', 'c'), ('you', 'and', 'me')] def f1(): return tuple(x[0] for x in G) def f2(): return tuple(map(itemgetter(0...
Mayavi doesn't run from within Spyder: complains about "ValueError: API 'QString' ..."
12,442,938
9
2012-09-15T22:23:09Z
12,454,872
7
2012-09-17T07:33:05Z
[ "python", "mayavi", "spyder" ]
I am unable to run/use Mayavi library from within Spyder IDE. I have described the problem below. Any help will be very useful. (Thank you very much in advance.) **Steps to reproduce the problem:** 1. Just importing the Mayavi library in a script (for example using "import mayavi.mlab as mlab") and executing the scri...
Thanks Avaris for your response. I have a solution for now (I am not sure of it as a "fix"). I modified the following setting in `Tools->Preferences->Console->External Modules->Enthought Tool Suite->ETS_TOOLKIT`: change from `Qt4` to `wx`. After changing this setting, I am able to execute code with Mayavi library and ...
Writing a Python extension in Go (Golang)
12,443,203
37
2012-09-15T23:19:31Z
12,443,815
10
2012-09-16T01:39:45Z
[ "python", "c", "go", "cython" ]
I currently use Cython to link C and Python, and get speedup in slow bits of python code. However, I'd like to use goroutines to implement a really slow (and very parallelizable) bit of code, but it must be callable from python. (I've already seen [this question](http://stackoverflow.com/questions/1743526/differences-b...
Unfortunately, this is not currently possible. Go can run C code (and that C code can then call back into Go), but the [`main` function has to be in Go](https://groups.google.com/d/msg/golang-nuts/nVw-Zgjt9Y8/PcegzOFp_pcJ), so the Go runtime can set things up.
Writing a Python extension in Go (Golang)
12,443,203
37
2012-09-15T23:19:31Z
32,813,045
25
2015-09-27T21:29:39Z
[ "python", "c", "go", "cython" ]
I currently use Cython to link C and Python, and get speedup in slow bits of python code. However, I'd like to use goroutines to implement a really slow (and very parallelizable) bit of code, but it must be callable from python. (I've already seen [this question](http://stackoverflow.com/questions/1743526/differences-b...
**Update 2015**: possible as of Go 1.5 <https://blog.filippo.io/building-python-modules-with-go-1-5/> > with Go 1.5 you can build .so objects and import them as Python modules, running Go code (instead of C) directly from Python.
Can I set IDLE to start Python 2.5 by default?
12,443,510
2
2012-09-16T00:25:35Z
12,443,813
9
2012-09-16T01:39:10Z
[ "python", "python-2.7", "python-idle", "python-2.5", "coexistence" ]
Ok, so I just installed Python 2.7, but I all ready had python 2.5. I realized that because I installed Python 2.7 last, IDLE automatically opens Python 2.7 IDLE, which I don't want. Is there any way to set the Python 2.5 IDLE to automatically open when I use the right click option on a python source file? Thanks.
You can easily create or edit the right-click properties for a file. To edit the right-click menu for a particular file extension: 1. Run `assoc .py` from the command line and note the name of the association: > C:>assoc .py > .py=Python.File 2. Run `regedit.exe`. 3. Browse to `HKEY_CLASSES_ROOT\Python.File\...
Calculating bounding box of numpy array
12,443,688
5
2012-09-16T01:10:01Z
12,443,736
8
2012-09-16T01:22:09Z
[ "python", "numpy" ]
I'm struggling with a simple question. I have a numpy array of the form: ``` [[[ 1152.07507324 430.84799194] [ 4107.82910156 413.95199585] [ 4127.64941406 2872.32006836] [ 1191.71643066 2906.11206055]]] ``` And I want to calculate the bounding box, meaning, I want to have the leftmost, topmost, rightmost ...
Use the `numpy.min` and `numpy.max` builtins: ``` def bounding_box(iterable): min_x, min_y = numpy.min(iterable[0], axis=0) max_x, max_y = numpy.max(iterable[0], axis=0) return numpy.array([(min_x, min_y), (max_x, min_y), (max_x, max_y), (min_x, max_y)]) ```
How long does my Python application take to run?
12,444,004
7
2012-09-16T02:31:11Z
12,444,018
8
2012-09-16T02:34:22Z
[ "python", "timer" ]
Basically, I want to be able to output the elapsed time that the application is running for. I think I need to use some sort of timeit function but I'm not sure which one. I'm looking for something like the following... ``` START MY TIMER code for application more code more code etc STOP MY TIMER ``` OUTPUT ELAPSED T...
The simplest way to do it is to put: ``` import time start_time = time.time() ``` at the start and ``` print "My program took", time.time() - start_time, "to run" ``` at the end.
Error 2006: "MySQL server has gone away" using Python, Bottle Microframework and Apache
12,444,272
2
2012-09-16T03:37:00Z
12,444,282
14
2012-09-16T03:40:12Z
[ "python", "mysql", "apache", "mod-wsgi", "bottle" ]
After accessing my web app using: - Python 2.7 - the Bottle micro framework v. 0.10.6 - Apache 2.2.22 - mod\_wsgi - on Ubuntu Server 12.04 64bit; I'm receiving this error after several hours: ``` OperationalError: (2006, 'MySQL server has gone away') ``` I'm using MySQL - the native one included in Pyt...
This is MySQL error, not Python's. The list of possible causes and possible solutions is here: [MySQL 5.5 Reference Manual: C.5.2.9. MySQL server has gone away](http://dev.mysql.com/doc/refman/5.5/en/gone-away.html). Possible causes include: > * You tried to run a query after closing the connection to the server. Th...
TypeError: only integer arrays with one element can be converted to an index
12,444,316
26
2012-09-16T03:50:00Z
12,460,988
31
2012-09-17T14:05:03Z
[ "python", "scikit-learn", "feature-selection" ]
I'm getting the following error when performing recursive feature selection with cross-validation: ``` Traceback (most recent call last): File "/Users/.../srl/main.py", line 32, in <module> argident_sys.train_classifier() File "/Users/.../srl/identification.py", line 194, in train_classifier feat_selector....
I finally got to solve the problem. Two things had to be done: 1. **train\_argcands\_target** is a list and it has to be a numpy array. I'm surprised it worked well before when I just used the estimator directly. 2. For some reason (I don't know why, yet), it doesn't work either if I use the sparse matrix created by t...
TypeError: only integer arrays with one element can be converted to an index
12,444,316
26
2012-09-16T03:50:00Z
19,286,703
7
2013-10-10T03:44:35Z
[ "python", "scikit-learn", "feature-selection" ]
I'm getting the following error when performing recursive feature selection with cross-validation: ``` Traceback (most recent call last): File "/Users/.../srl/main.py", line 32, in <module> argident_sys.train_classifier() File "/Users/.../srl/identification.py", line 194, in train_classifier feat_selector....
If anyone is still interested, I used the `CountVectorizer` on something very similar and it gave me the same error. I realized that the vectorizer gives me a COO sparse matrix which is basically a coordinate list. Elements in COO matrices can't be accessed through row indexes. It is best to convert it to a CSR matrix...
How do I set the figure title and axes labels font size in Matplotlib?
12,444,716
159
2012-09-16T05:54:36Z
12,444,777
232
2012-09-16T06:07:44Z
[ "python", "matplotlib" ]
I am creating a figure in Matplotlib like this: ``` from matplotlib import pyplot as plt fig = plt.figure() plt.plot(data) fig.suptitle('test title') plt.xlabel('xlabel') plt.ylabel('ylabel') fig.savefig('test.jpg') ``` I want to specify font sizes for the figure title and the axis labels. I need all three to be dif...
Functions dealing with text like `label`, `title`, etc. accept parameters same as [matplotlib.text.Text](http://matplotlib.org/users/text_props.html). For the font size you can use `size/fontsize`: ``` from matplotlib import pyplot as plt fig = plt.figure() plt.plot(data) fig.suptitle('test title', fontsize=20) p...
"Josephus-problm" using list in python
12,444,979
3
2012-09-16T06:53:02Z
12,445,063
8
2012-09-16T07:10:12Z
[ "python", "list", "josephus" ]
I wanted to know if it will be possible to solve the Josepheus problem using list in python. In simple terms Josephus problem is all about finding a position in a circular arrangement which would be safe if executions were handled out using a skip parameter which is known beforehand. For eg : given a circular arrange...
Quite simply, you can use `list.pop(i)` to delete each victim (and get his ID) in a loop. Then, we just have to worry about wrapping the indices, which you can do just by taking the skipped index mod the number of remaining prisoners. So then, the question solution becomes ``` def josephus(ls, skip): skip -= 1 # ...