title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
Python re.findall() is not working as expected | 12,999,419 | 7 | 2012-10-21T15:50:25Z | 12,999,616 | 7 | 2012-10-21T16:12:44Z | [
"python",
"regex"
] | I have the code:
```
import re
sequence="aabbaa"
rexp=re.compile("(aa|bb)+")
rexp.findall(sequence)
```
This returns `['aa']`
If we have
```
import re
sequence="aabbaa"
rexp=re.compile("(aa|cc)+")
rexp.findall(sequence)
```
we get `['aa','aa']`
Why is there a difference and why (for the first) do we not get `['aa... | The unwanted behaviour comes down to the way you formulate regualar expression:
```
rexp=re.compile("(aa|bb)+")
```
Parentheses `(aa|bb)` forms a group.
And if we look at the [docs of findall](http://docs.python.org/library/re.html#re.findall) we will see this:
> Return all non-overlapping matches of pattern in str... |
String contains all the elements of a list | 12,999,930 | 2 | 2012-10-21T16:46:49Z | 12,999,951 | 8 | 2012-10-21T16:49:34Z | [
"python",
"regex",
"list"
] | I am shifting to Python, and am still relatively new to the pythonic approach. I want to write a function that takes a string and a list and returns true if all the elements in the list occur in the string.
---
This seemed fairly simple. However, I am facing some difficulties with it. The code goes something like thi... | ```
>>> all(x in 'tomato' for x in ['t','o','m','a'])
True
>>> all(x in 'potato' for x in ['t','o','m','a'])
False
``` |
Openpyxl - object has no attribute 'load_workbook' | 13,000,128 | 5 | 2012-10-21T17:10:51Z | 15,493,400 | 7 | 2013-03-19T07:03:29Z | [
"python",
"openpyxl"
] | I'm trying to load an existing workbook using openpyxl.
But when I'm trying to run [this code](http://packages.python.org/openpyxl/usage.html#read-an-existing-workbook) - I'm getting following error:
```
AttributeError: 'module' object has no attribute 'load_workbook'
```
`import openpyxl` works fine, what I'm doing ... | The examples are for a later version of `openpyxl`. In 1.1.4 the main `__init__.py` did not provide a shortcut to `load_workbook` in the form of
```
from openpyxl.reader.excel import load_workbook
```
so you will have to do that instead of:
```
from openpyxl import load_workbook
```
what is shown in the example. |
Reshape Long Format Multivalue Dataframes with Pandas | 13,000,427 | 2 | 2012-10-21T17:42:17Z | 13,003,683 | 7 | 2012-10-22T00:42:23Z | [
"python",
"pivot",
"pandas",
"reshape"
] | I would like to turn:
```
DateTime ColumnName Min Avg Max
2012-10-14 11:29:23.810000 Percent_Used 24 24 24
2012-10-14 11:29:23.810000 Current_Count 254503 254503 254503
... | There is a `melt` in `pandas.core.reshape`:
```
In [52]: melted = reshape.melt(df, id_vars=['DateTime', 'ColumnName'])
In [53]: melted.set_index(['DateTime', 'ColumnName', 'variable']).value.unstack([1, 2])
Out[53]:
ColumnName Percent_Used Current_Count Max Percent_Used Current_Count Ma... |
What happens when you call `if key in dict` | 13,001,913 | 5 | 2012-10-21T20:32:03Z | 13,001,957 | 7 | 2012-10-21T20:38:06Z | [
"python",
"hash",
"dictionary",
"equality"
] | I have a class (let's call it `myClass`) that implements both `__hash__` and `__eq__`. I also have a `dict` that maps `myClass` objects to some value, computing which takes some time.
Over the course of my program, many (in the order of millions) `myClass` objects are instantiated. This is why I use the `dict` to keep... | `__hash__` will always be called; `__eq__` will be called if the object is indeed in the dictionary, or if another object with the same hash is in the dictionary. The hash value is used to narrow down the choice of possible keys. The keys are grouped into "buckets" by hash value, but for lookup Python still has to chec... |
What happens when you call `if key in dict` | 13,001,913 | 5 | 2012-10-21T20:32:03Z | 13,001,967 | 7 | 2012-10-21T20:38:58Z | [
"python",
"hash",
"dictionary",
"equality"
] | I have a class (let's call it `myClass`) that implements both `__hash__` and `__eq__`. I also have a `dict` that maps `myClass` objects to some value, computing which takes some time.
Over the course of my program, many (in the order of millions) `myClass` objects are instantiated. This is why I use the `dict` to keep... | First, `__hash__(myNewMyClassObj)` gets called. If no object with the same hash is found in the dictionary, Python assumes `myNewMyClassObj` is not in the dictionary. (Note that Python requires that whenever `__eq__` evaluates as equal for two objects, their `__hash__` must be identical.)
If some objects with the same... |
Printing a list down and then across | 13,002,059 | 2 | 2012-10-21T20:48:16Z | 13,002,165 | 7 | 2012-10-21T20:59:35Z | [
"python",
"list-comprehension"
] | How do you print a list down and then across in Python?
```
l = [v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14]
v1 v4 v7 v10 v13
v2 v5 v8 v11 v14
v3 v6 v9 v12
```
The length of the list can vary but for now I would like to print in a 5 column format. | Something like this should work:
```
>>> def print_list_matrix(lst, row_num):
... for i in range(row_num):
... print ' '.join(lst[i::row_num])
...
>>> print_list_matrix(lst, 3)
v1 v4 v7 v10 v13
v2 v5 v8 v11 v14
v3 v6 v9 v12
>>> print_list_matrix(lst, 4)
v1 v5 v9 v13
v2 v6 v10 v14
v3 v7 v11
v4 v8 v12
``` |
How do I convert an array to string using the jinja template engine? | 13,002,848 | 5 | 2012-10-21T22:31:40Z | 13,003,841 | 13 | 2012-10-22T01:13:10Z | [
"python",
"flask",
"jinja2"
] | I have a array element called tags and would like to convert the array of tags to string separated by a blank space. But how do you do that in Jinga?
I have tried:
```
{{ tags|join }}
``` | Actually you are almost there, for join with space, just put it like this:
```
{{ tags|join(' ') }}
```
see the [jinja docs](http://jinja.pocoo.org/docs/templates/#join) for more details |
Faster way to loop through every pixel of an image in Python? | 13,003,949 | 8 | 2012-10-22T01:30:15Z | 13,003,956 | 12 | 2012-10-22T01:31:53Z | [
"python",
"image",
"loops",
"time",
"numpy"
] | I need to loop through each pixel of a 2560x2160 2D numpy array (image). A simplified version of my problem is as follows:
```
import time
import numpy as np
t = time.clock()
limit = 9000
for (x,y), pixel in np.ndenumerate(image):
if( pixel > limit )
pass
tt = time.clock()
print tt-t
```
This is taking a... | Use a boolean matrix:
```
x, y = (image > limit).nonzero()
vals = image[x, y]
``` |
If Google App Engine cron jobs have a 10 minute limit, then why do I get a DeadlineExceededError after the normal 30 seconds? | 13,004,038 | 3 | 2012-10-22T01:43:59Z | 13,004,204 | 8 | 2012-10-22T02:12:37Z | [
"python",
"google-app-engine",
"cron",
"timeout"
] | According to <https://developers.google.com/appengine/docs/python/config/cron> cron jobs can run for 10 minutes. However, when I try and test it by going to the url for the cron job when signed in as an admin, it times out with a DeadlineExceededError. Best I can tell this happens about 30 seconds in, which is the non-... | The way GAE executes a cron job allows it to run for 10 min. This is probably done (i'm just guessing here) through checking the user-agent, IP address, or some other method. Just because you setup a cron job to hit a URL in your application doesn't mean a standard HTTP request from your browser will allow it to run fo... |
Why does this function return the wrong results? | 13,005,173 | 2 | 2012-10-22T05:00:49Z | 13,005,201 | 11 | 2012-10-22T05:03:42Z | [
"python"
] | Can someone tell me why when I try out this function with this particular example: **is\_valid\_sequence('ABCDEFG')**, it comes up "True" instead of "False"? I am completely new to programming in general. This is for an online course I'm taking. Thanks.
```
def is_valid_sequence(dna_sequence):
''' (str) -> bool
... | You are returning too early. Try this
```
for char in dna_sequence:
if char not in 'ACTG':
return False
return True
```
or more simply
```
return all(char in 'ACTG' for char in dna_sequence)
``` |
How can I defer the execution of Celery tasks? | 13,006,151 | 7 | 2012-10-22T06:42:18Z | 13,017,010 | 7 | 2012-10-22T17:58:29Z | [
"python",
"django",
"celery",
"django-celery"
] | I have a small script that enqueues tasks for processing. This script makes a whole lot of database queries to get the items that should be enqueued. The issue I'm facing is that the celery workers begin picking up the tasks as soon as it is enqueued by the script. This is correct and it is the way celery is supposed t... | eta/countdown options enable to delay the task execution:
<http://docs.celeryproject.org/en/master/userguide/calling.html#eta-and-countdown> |
python data and non-data descriptors | 13,007,179 | 7 | 2012-10-22T07:59:56Z | 13,007,296 | 7 | 2012-10-22T08:09:51Z | [
"python",
"descriptor"
] | According to [Python's documentation](http://docs.python.org/reference/datamodel.html#invoking-descriptors),
> Data descriptors with `__set__()` and `__get__()` defined always override a redefinition in an instance dictionary.
I have no problem understanding this sentence, but can someone clarify for me why such a ru... | The override applies to descriptors that are part of the *class* `__dict__`.
Python will always look up `type(instance).__dict__[attributename].__get__(instance, type(instance))`, and will *not* use `instance.__dict__` to search for a instance-override.
Here is an example using a contrived `Descriptor` class and a pr... |
Find all the occurrences of a character in a string | 13,009,675 | 11 | 2012-10-22T10:39:21Z | 13,009,866 | 23 | 2012-10-22T10:50:28Z | [
"python",
"string"
] | I am trying to find all the occurences of "|" in a string.
```
def findSectionOffsets(text):
startingPos = 0
endPos = len(text)
for position in text.find("|",startingPos, endPos):
print position
endPos = position
```
But I get an error:
```
for position in text.find("|",startingPos, ... | The function
```
def findOccurences(s, ch):
return [i for i, letter in enumerate(s) if letter == ch]
findOccurrences(yourString, "|")
```
will return a list of the indexes of yourString in which the | occur |
Can you create traditional fixed length and type arrays in Python? | 13,010,474 | 4 | 2012-10-22T11:26:11Z | 13,010,595 | 8 | 2012-10-22T11:33:49Z | [
"python"
] | I am teaching the A level syllabus by the Cambridge exam board. One typical question on the practical paper is this:
> In a programming language of your choice, declare an array of ten integers and then initializes it.
I have this:
```
myArray = [] #create the array
for i in range(10): # initializes to 0
... | You could try to use the [`array` module](http://docs.python.org/library/array.html) to specify the type of your array:
```
import array
a = array.array('i') # Define an integer array.
```
You can then add the elements you want to the array. I'm not sure whether you can predefine the size your array should have, thou... |
Sum lists with different lengths | 13,011,394 | 11 | 2012-10-22T12:22:34Z | 13,011,467 | 17 | 2012-10-22T12:27:07Z | [
"python",
"algorithm",
"list",
"sum"
] | What's the best way to sum two or more lists even if they have different lengths?
For example I have:
```
lists = [[1, 2], [0, 3, 4], [5]]
```
and the result should be:
```
result = [6, 5, 4]
``` | You can use [`itertools.izip_longest()`](http://docs.python.org/library/itertools.html?highlight=itertools#itertools.izip_longest), and use a `fillvalue` equal to `0`
```
In [6]: [sum(x) for x in itertools.izip_longest(*lists, fillvalue=0)]
Out[6]: [6, 5, 4]
```
for Python < 2.6:
```
In [27]: ml = max(map(len, lists... |
Is De Morgan's Law Pythonic? | 13,012,459 | 24 | 2012-10-22T13:25:53Z | 13,012,492 | 15 | 2012-10-22T13:28:14Z | [
"python",
"pep8",
"demorgans-law"
] | Which of the following if statements is more Pythonic?
```
if not a and not b:
do_something
```
OR
```
if not ( a or b ):
do something
```
Its not predicate logic so I should use the Python key words because its more readable right?
In the later solution more optimal than the other? (I don't believe so.)
... | I'd say whichever is easier for you to read, depending on what a and b are. |
Is De Morgan's Law Pythonic? | 13,012,459 | 24 | 2012-10-22T13:25:53Z | 13,012,903 | 15 | 2012-10-22T13:51:54Z | [
"python",
"pep8",
"demorgans-law"
] | Which of the following if statements is more Pythonic?
```
if not a and not b:
do_something
```
OR
```
if not ( a or b ):
do something
```
Its not predicate logic so I should use the Python key words because its more readable right?
In the later solution more optimal than the other? (I don't believe so.)
... | I think both your examples are equally readable, however if I wanted to "push the boat out" on readability I would go with:
```
not any((a, b))
```
*Since to me this reads much more like English, and hence is the most Pythonic.* |
pydot: is it possible to plot two different nodes with the same string in them? | 13,012,621 | 6 | 2012-10-22T13:36:02Z | 13,012,983 | 12 | 2012-10-22T13:55:34Z | [
"python",
"decision-tree",
"pydot"
] | I'm using pydot in order to draw graphs in python.
I'd like to represent a decision tree, say something like (a1,a2,a3 are attributes and two classes are 0 and 1:
```
a1>3
/ \
a2>10 a3>-7
/ \ / \
1 0 1 0
```
However, using pydot, only two leaves are created and the tree looks l... | Your nodes always need a unique names, otherwise you cannot name them uniquely to attach edges between them. However, you can give each node a label, which is what is displayed when rendered.
So you'll need to add nodes with unique ids:
```
graph = pydot.Dot(graph_type='graph')
graph.add_node(pydot.Node('literal_0_0'... |
Flask + WTForms + SelectMultipleField and Dynamic Choices | 13,013,419 | 9 | 2012-10-22T14:21:23Z | 13,020,558 | 8 | 2012-10-22T22:01:03Z | [
"python",
"flask",
"wtforms"
] | I am trying to use WTForms.SelectMultipleField to manage some dynamic choices on a form but I'm running into some difficulty with it being modified client-side before being submitted for validation.
Basically I have two SelectMultipleField options:
```
class MyForm(Form):
assigned = SelectMultipleField('Assigned'... | Update `choices` in the `POST` request:
```
AVAILABLE_CHOICES = [('1','1'),('2','2')]
DEFAULT_CHOICES = []
class MyForm(Form):
assigned = SelectMultipleField('Assigned', choices=DEFAULT_CHOICES)
available = SelectMultipleField('Available', choices=AVAILABLE_CHOICES)
@app.view("/myview", methods=['GET','POST'... |
Python cannot handle numbers string starting with 0. Why? | 13,013,638 | 11 | 2012-10-22T14:31:29Z | 13,013,678 | 19 | 2012-10-22T14:33:39Z | [
"python",
"python-3.x",
"syntax-error"
] | I just executed the following program on my python interpreter:
```
>>> def mylife(x):
... if x>0:
... print(x)
... else:
... print(-x)
...
>>> mylife(01)
File "<stdin>", line 1
mylife(01)
^
SyntaxError: invalid token
>>> mylife(1)
1
>>> mylife(-1)
1
>>> mylife(0)
0
```
Now, I... | My guess is that since `012` is no longer an octal literal constant in python3.x, they disallowed the `012` syntax to avoid strange backward compatibility bugs. Consider your python2.x script which using octal literal constants:
```
a = 012 + 013
```
Then you port it to python 3 and it still works -- It just gives yo... |
String.strip() in Python | 13,013,734 | 14 | 2012-10-22T14:37:21Z | 13,013,812 | 23 | 2012-10-22T14:40:31Z | [
"python",
"string",
"strip"
] | While learning about python, I came upon this code, which takes a text file, splits each line into an array, and inserts it into a custom dictionary, where the array[0] is the key and array[1] is the value:
```
my_dict = {}
infile = open("file.txt")
for line in infile:
#line = line.strip()
#parts = [p.strip(... | If you can comment out code and your program still works, then yes, that code was optional.
`.strip()` removes *all* whitespace at the start and end, including spaces, tabs, newlines and carriage returns. Leaving it in doesn't do any harm, and allows your program to deal with unexpected extra whitespace inserted into ... |
How to draw a rectangle over a specific region in a matplotlib graph | 13,013,781 | 26 | 2012-10-22T14:39:00Z | 13,014,729 | 32 | 2012-10-22T15:32:12Z | [
"python",
"matplotlib"
] | I have a graph, computed from some data, drawn in matplotlib. I want to draw a rectangular region around the global maximum of this graph. I tried `plt.axhspan,` but the rectangle doesn't seem to appear when I call `plt.show()`
So, how can a rectangular region be drawn onto a matplotlib graph? Thanks! | The most likely reason is that you used data units for the x arguments when calling axhspan. From [the function's docs](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.axhspan) (my emphasis):
> y coords are in data units and *x coords are in axes (relative 0-1)
> units*.
So any rectangle stretching left o... |
threads vs. processes in Python | 13,014,007 | 3 | 2012-10-22T14:50:53Z | 13,014,040 | 9 | 2012-10-22T14:52:59Z | [
"python",
"multithreading",
"serial-port",
"multiprocessing"
] | I'm about to start a program using Python which is mostly doing polling, it will constantly read from the serial port (via `PySerial`) and read from a file descriptor which will be changing from time to time. I started looking into the `threading` module but then I kept finding [more](http://stackoverflow.com/questions... | `multiprocessing` is mainly used in Python to avoid the GIL (Global Interpreter Lock), which stops threads being useful for trying to compute in parallel - for resource access, threads are perfect, and the better option for ease of implementation.
The GIL means that only one thread can operate on any Python object at ... |
Django post_save() signal implementation | 13,014,411 | 23 | 2012-10-22T15:14:11Z | 13,016,385 | 7 | 2012-10-22T17:14:13Z | [
"python",
"django",
"django-models",
"django-signals"
] | I have a question about django.
I have ManyToMany Models here
```
class Product(models.Model):
name = models.CharField(max_length=255)
price = models.DecimalField(default=0.0, max_digits=9, decimal_places=2)
stock = models.IntegerField(default=0)
def __unicode__(self):
return self.name
... | Personally I would override the TransactionDetail's save() method and in there save the new TransactionDetail and then run
```
self.product.stock -= self.amount
self.product.save()
``` |
Django post_save() signal implementation | 13,014,411 | 23 | 2012-10-22T15:14:11Z | 13,016,982 | 69 | 2012-10-22T17:56:24Z | [
"python",
"django",
"django-models",
"django-signals"
] | I have a question about django.
I have ManyToMany Models here
```
class Product(models.Model):
name = models.CharField(max_length=255)
price = models.DecimalField(default=0.0, max_digits=9, decimal_places=2)
stock = models.IntegerField(default=0)
def __unicode__(self):
return self.name
... | If you really want to use signals to achieve this, here's briefly how,
```
from django.db.models.signals import post_save
from django.dispatch import receiver
class TransactionDetail(models.Model):
# ... fields here
# method for updating
@receiver(post_save, sender=TransactionDetail, dispatch_uid="update_stock_c... |
Pythonic iteration over sliding window pairs in list? | 13,014,595 | 6 | 2012-10-22T15:24:29Z | 13,014,661 | 8 | 2012-10-22T15:28:04Z | [
"python",
"list",
"iteration",
"itertools",
"list-manipulation"
] | What's the most Pythonic efficient way to iterate over a list in sliding pairs? Here's a related example:
```
>>> l
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> for x, y in itertools.izip(l, l[1::2]): print x, y
...
a b
b d
c f
```
this is iteration in pairs, but how can we get iteration over a sliding pair? Meaning iter... | You can go even simpler. Just zip the list and the list offset by one.
```
In [4]: zip(l, l[1:])
Out[4]: [('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e'), ('e', 'f'), ('f', 'g')]
``` |
Regex - match returns None. Where am I wrong? | 13,014,623 | 4 | 2012-10-22T15:25:59Z | 13,014,658 | 12 | 2012-10-22T15:27:54Z | [
"python",
"regex"
] | ```
>>> import re
>>> s = 'this is a test'
>>> reg1 = re.compile('test$')
>>> match1 = reg1.match(s)
>>> print match1
None
```
in Kiki that matches the test at the end of the s. What do I miss? (I tried `re.compile(r'test$')` as well) | Use
```
match1 = reg1.search(s)
```
instead. The `match` function *only* matches at the start of the string ... see the documentation [here](http://docs.python.org/library/re.html#search-vs-match). |
Warnings and errors after trying to install Flask 0.9 | 13,014,984 | 9 | 2012-10-22T15:46:20Z | 13,015,078 | 15 | 2012-10-22T15:52:09Z | [
"python",
"install",
"flask"
] | I'm trying ot install [Flask](http://flask.pocoo.org/), but I'm betting all these warnings and errors:
```
alex@alex-K43U:~/flask$ pip install Flask
Downloading/unpacking Flask
Downloading Flask-0.9.tar.gz (481Kb): 481Kb downloaded
Running setup.py egg_info for package Flask
warning: no files found matching '... | The warnings you can safely ignore; however this error:
`error: could not create '/usr/local/lib/python2.7/dist-packages/flask': Permission denied`
Tells me that you are trying to install this in to your global system Python. Nothing wrong with that, but if you want to do that you need to run the command with elevate... |
Uploading files using requests and send extra data | 13,015,166 | 4 | 2012-10-22T15:57:30Z | 13,015,529 | 8 | 2012-10-22T16:18:44Z | [
"python",
"python-2.7",
"python-requests"
] | I am trying to upload a file using [requests](http://requests.readthedocs.org/en/latest/). I need to upload a PDF file and at the same time send some other data to the form like the author's name.
I tried this:
```
requests.get(url, files = {"file":open("file.txt"), "author" : "me" })
```
But it doesn't send data to... | So I understand that you want to upload to a URL, a pdf file along with some extra parameters.
First error that you have is you are using `.get()` and not `.post()`.
I am using samples from the [documentation](http://requests.readthedocs.org/en/latest/user/quickstart/), which you should go through. This should get yo... |
Ensuring files are closed in Python | 13,015,207 | 2 | 2012-10-22T16:00:12Z | 13,015,268 | 9 | 2012-10-22T16:03:14Z | [
"python",
"file-io"
] | I have classes that can take a file as an argument, for example:
```
ParserClass(file('/some/file', 'rb'))
```
If I understand Python correctly, the file will be closed automatically once the object is garbage collected. What I don't understand is exactly when that happens. In a function like:
```
def parse_stuff(fi... | You can use the `with` statement to open the file, which will ensure that the file is closed.
```
with open('/some/file', 'rb') as f:
parser = ParserClasss(f)
return list(parser.info())
```
See <http://www.python.org/dev/peps/pep-0343/> for more details. |
Python: Parse list of 'key:value' elements to dictionary of 'key': value pairs | 13,015,304 | 2 | 2012-10-22T16:05:00Z | 13,015,337 | 10 | 2012-10-22T16:07:01Z | [
"python",
"list",
"dictionary"
] | I have the following list:
```
['a:1', 'b:2', 'c:3', 'd:4']
```
I would like to convert to a ordered dict (using `collections`):
```
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
```
I have seen solutions using regex [here](http://stackoverflow.com/questions/10380992/get-python-dictionary-from-string-containing-key-value-pairs)... | ```
d = collections.OrderedDict(el.split(':') for el in your_list)
```
Or, converting the values to integers:
```
OrderedDict( (k, int(v)) for k, v in (el.split(':') for el in your_list))
``` |
Python - Flatten a dict of lists into unique values? | 13,016,129 | 6 | 2012-10-22T16:58:50Z | 13,016,177 | 8 | 2012-10-22T17:02:28Z | [
"python"
] | I have a dict of lists in python:
```
content = {88962: [80, 130], 87484: [64], 53662: [58,80]}
```
I want to turn it into a list of the unique values
```
[58,64,80,130]
```
I wrote a manual solution, but it's a manual solution. I know there are more concise and more elegant way to do this with list comprehensions,... | ```
from itertools import chain
sorted(set(chain.from_iterable(content.itervalues())))
# [58, 64, 80, 130]
```
Or another option is `itertools.groupby`:
```
[k for k, g in groupby(sorted(chain.from_iterable(content.itervalues())))]
``` |
Python - Flatten a dict of lists into unique values? | 13,016,129 | 6 | 2012-10-22T16:58:50Z | 13,016,200 | 12 | 2012-10-22T17:03:45Z | [
"python"
] | I have a dict of lists in python:
```
content = {88962: [80, 130], 87484: [64], 53662: [58,80]}
```
I want to turn it into a list of the unique values
```
[58,64,80,130]
```
I wrote a manual solution, but it's a manual solution. I know there are more concise and more elegant way to do this with list comprehensions,... | Double set comprehension:
```
sorted({x for v in content.itervalues() for x in v})
``` |
Making some detail explanations in python string | 13,016,598 | 2 | 2012-10-22T17:28:25Z | 13,016,613 | 8 | 2012-10-22T17:29:30Z | [
"python",
"regex",
"comments"
] | With Java, I can split the string and give some detailed explanations
```
String x = "a" + // First
"b" + // Second
"c"; // Third
// x = "abc"
```
How can I make the equivalence in python?
I could split the string, but I can't make a comment on this like I do with Java.
```
x = "a" \
"b" \
"c"
`... | This
```
x = ( "a" #foo
"b" #bar
)
```
will work.
The magic is done here by the parenthesis -- python automatically continues lines inside of any unterminated brakets (`([{`). Note that python also automatically concatenates strings when they're placed next to each other (We don't even need the `+` operato... |
sort numbers in one line | 13,016,918 | 9 | 2012-10-22T17:51:27Z | 13,016,933 | 28 | 2012-10-22T17:52:27Z | [
"python",
"string",
"sorting"
] | We have numbers in a string like this:
```
numbers = "1534423543"
```
We want to sort this and return:
```
"1,2,3,4,5"
```
(only unique numbers!)
How to do it in ONE line? | use `set()` to get unique items, then sort them using `sorted()` and finally join them using `",".join()`
```
In [109]: strs="1534423543"
In [110]: ",".join(sorted(set(strs)))
Out[110]: '1,2,3,4,5'
``` |
Weird Extra Looping | 13,017,027 | 5 | 2012-10-22T18:00:01Z | 13,017,090 | 8 | 2012-10-22T18:05:05Z | [
"python",
"python-3.x"
] | I'm still a bit new to Python, but, I feel *really* stupid right now 'cause I've just spent an hour trying to figure out why this for loop isn't doing what I want. I shouldn't be spending an hour on a for loop. Anyway, I'm trying to generate a list of dictionaries, and give them each a unique number, so I do this...
`... | What's happening is that you're appending a reference to the same dictionary to the list each time.
```
print list(map(id, initiate(4)))
# [42283920, 42283920, 42283920, 42283920]
```
Your function is correctly written as:
```
def initiate(n):
return [ {'num': i, 'blah': 0, 'doubleblah': 0} for i in range(n) ]
`... |
Using PySerial is it possble to wait for data? | 13,017,840 | 10 | 2012-10-22T18:53:15Z | 13,018,084 | 7 | 2012-10-22T19:08:52Z | [
"python",
"serial-port",
"pyserial"
] | I've got a python program which is reading data from a serial port via the `PySerial` module. The two conditions I need to keep in mind are: I don't know how much data will arive, and I don't know when to expect data.
Based on this I have came up with the follow code snipets:
```
#Code from main loop, spawning thread... | You can set `timeout = None`, then the `read` call will block until the requested number of bytes are there. If you want to wait until data arrives, just do a `read(1)` with timeout `None`. If you want to check data without blocking, do a `read(1)` with timeout zero, and check if it returns any data.
(see documentatio... |
Using PySerial is it possble to wait for data? | 13,017,840 | 10 | 2012-10-22T18:53:15Z | 13,018,267 | 13 | 2012-10-22T19:19:48Z | [
"python",
"serial-port",
"pyserial"
] | I've got a python program which is reading data from a serial port via the `PySerial` module. The two conditions I need to keep in mind are: I don't know how much data will arive, and I don't know when to expect data.
Based on this I have came up with the follow code snipets:
```
#Code from main loop, spawning thread... | Ok, I actually got something together that I like for this. Using a combination of `read()` with no timeout and the `inWaiting()` method:
```
#Modified code from main loop:
s = serial.Serial(5)
#Modified code from thread reading the serial port
while 1:
tdata = s.read() # Wait forever for anything
time... |
matplotlib savefig image size with bbox_inches='tight' | 13,018,115 | 8 | 2012-10-22T19:11:20Z | 13,018,800 | 10 | 2012-10-22T19:54:38Z | [
"python",
"matplotlib"
] | I have to make a vector plot and I want to just see the vectors without the axes, titles etc so here is how I try to do it:
```
pyplot.figure(None, figsize=(10, 16), dpi=100)
pyplot.quiver(data['x'], data['y'], data['u'], data['v'],
pivot='tail',
units='dots',
scale=0.2,
... | ```
import matplotlib.pyplot as plt
import numpy as np
sin, cos = np.sin, np.cos
fig = plt.figure(frameon = False)
fig.set_size_inches(5, 8)
ax = plt.Axes(fig, [0., 0., 1., 1.], )
ax.set_axis_off()
fig.add_axes(ax)
x = np.linspace(-4, 4, 20)
y = np.linspace(-4, 4, 20)
X, Y = np.meshgrid(x, y)
deg = np.arctan(Y**3-3*Y... |
AuthAlreadyAssociated Exception in Django Social Auth | 13,018,147 | 6 | 2012-10-22T19:12:59Z | 13,032,929 | 8 | 2012-10-23T14:36:39Z | [
"python",
"django",
"django-socialauth"
] | After I create a user using say Facebook(let's say fbuser) or Google(googleuser). If I create another user through the normal django admin(normaluser), and try logging again using Facebook or Google while third user(normaluser) is logged in, it throws an error exception AuthAlreadyAssociated.
1. Ideally it should thro... | DSA doesn't logout accounts (or flush sessions) at the moment. `AuthAlreadyAssociated` highlights the scenario where the current user is not associated to the current social account trying to be used. There are a couple solutions that might suite your project:
1. Define a sub-class of `social_auth.middleware.SocialAut... |
Python HMAC-SHA1 vs Java HMAC-SHA1 different results | 13,019,598 | 5 | 2012-10-22T20:47:17Z | 13,019,685 | 8 | 2012-10-22T20:53:41Z | [
"java",
"python",
"sha1",
"hmac"
] | I borrowed the HMAC-SHA1 Java code from <http://tools.ietf.org/html/rfc6238> and adapted slightly to hardcode it to use one known key/message pair with known output.
I then tried to write the same code in Python to verify the results, however I'm getting different values in Python and Java.
The Java values are known ... | I think the problem is that in Java, you're using the raw bytes as the key (only converting them to a hex string for output):
```
System.out.println("Key is..." + bytesToHex(keyBytes) + "\n");
// ...
SecretKeySpec macKey = new SecretKeySpec(keyBytes, "RAW");
```
But in Python, you're using the hex string:
```
k = "3... |
Converting YAML file to python dict | 13,019,653 | 3 | 2012-10-22T20:51:28Z | 13,020,322 | 8 | 2012-10-22T21:40:30Z | [
"python",
"data-structures",
"dictionary",
"yaml"
] | I am having the following problem of mapping documents within a YAML file to a `dict` and properly mapping them.
I have the following YAML file, which represents a server (`db.yml`):
```
instanceId: i-aaaaaaaa
environment:us-east
serverId:someServer
awsHostname:ip-someip
serverName:somewebsite.com... | I think your yaml file should look like (or at least something like, so it's structured correctly anyway):
```
instance:
Id: i-aaaaaaaa
environment: us-east
serverId: someServer
awsHostname: ip-someip
serverName: somewebsite.com
ipAddr: 192.168.0.1
roles: [webserver,php]
```
Then, `... |
Get business days between start and end date using pandas | 13,019,719 | 7 | 2012-10-22T20:56:13Z | 13,020,027 | 9 | 2012-10-22T21:16:33Z | [
"python",
"pandas"
] | I'm using pandas and I'm wondering what's the easiest way to get the business days between a start and end date using pandas?
There are a lot of posts out there regarding doing this in Python (for [example](http://stackoverflow.com/questions/2224742/business-days-in-python)), but I would be interested to use directly ... | Use `BDay()` to get the business days in range.
```
from pandas.tseries.offsets import *
In [185]: s
Out[185]:
2011-01-01 -0.011629
2011-01-02 -0.089666
2011-01-03 -1.314430
2011-01-04 -1.867307
2011-01-05 0.779609
2011-01-06 0.588950
2011-01-07 -2.505803
2011-01-08 0.800262
2011-01-09 0.376406... |
Why can't I get `pip install lxml` to work within a virtualenv? | 13,019,942 | 48 | 2012-10-22T21:11:10Z | 13,020,013 | 95 | 2012-10-22T21:14:46Z | [
"python",
"virtualenv",
"virtualenvwrapper"
] | Note: I'm using virtualenvwrapper.
Before activating the virtual environment:
```
$ pip install lxml
Requirement already satisfied (use --upgrade to upgrade): lxml in /usr/lib/python2.7/dist-packages
Cleaning up...
```
After activating the virtual environment:
```
(test-env)$ pip install lxml
force/build/lxml/src... | You probably already have lxml installed on your system, perhaps installed due to a system package. Thus, the first attempt (`pip install lxml` without an active virtualenv) doesn't fail, but it also doesn't install it; it really doesn't do anything.
In a virtualenv, by default, the system packages are ignored. Theref... |
Why can't I get `pip install lxml` to work within a virtualenv? | 13,019,942 | 48 | 2012-10-22T21:11:10Z | 21,110,025 | 13 | 2014-01-14T09:32:53Z | [
"python",
"virtualenv",
"virtualenvwrapper"
] | Note: I'm using virtualenvwrapper.
Before activating the virtual environment:
```
$ pip install lxml
Requirement already satisfied (use --upgrade to upgrade): lxml in /usr/lib/python2.7/dist-packages
Cleaning up...
```
After activating the virtual environment:
```
(test-env)$ pip install lxml
force/build/lxml/src... | **for centos users:**
when getting:
> error: command 'gcc' failed with exit status 1
DO:
```
sudo yum install libxslt-devel libxml2-devel
``` |
SQL multiple inserts with Python | 13,020,908 | 2 | 2012-10-22T22:33:49Z | 13,020,926 | 15 | 2012-10-22T22:35:55Z | [
"python",
"mysql",
"mysql-python"
] | **UPDATE**
After passing execute() a list of rows as per Nathan's suggestion, below, the code executes further but still gets stuck on the execute function. The error message reads:
```
query = query % db.literal(args)
TypeError: not all arguments converted during string formatting
```
So it still isn't working... | You need to give [`executemany()`](http://www.python.org/dev/peps/pep-0249/#executemany) a list of rows. You don't need break the name and email out into separate lists, just create one list with both of the values in it.
```
rows = []
for row in range(sheet.nrows):
"""name is in the 0th col. email is the 4th col... |
Retrieving column index from column name in python pandas | 13,021,654 | 29 | 2012-10-22T23:48:58Z | 13,021,797 | 49 | 2012-10-23T00:06:36Z | [
"python",
"dataframe",
"pandas"
] | In R when you need to retrieve a column index based on the name of the column you could do
```
idx <- which(names(my_data)==my_colum_name)
```
Is there a way to do the same with pandas dataframes? | Sure, you can use `.get_loc()`:
```
In [45]: df = DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]})
In [46]: df.columns
Out[46]: Index([apple, orange, pear], dtype=object)
In [47]: df.columns.get_loc("pear")
Out[47]: 2
```
although to be honest I don't often need this myself. Usually access by name ... |
How to properly quit a program in python | 13,022,385 | 8 | 2012-10-23T01:33:45Z | 13,022,426 | 9 | 2012-10-23T01:39:33Z | [
"python",
"string",
"python-3.x",
"quit"
] | Im a middle school student, and im starting to learn coding in python. I have been watching video tutorials, but i cant seem to figure out how to make the game quit if you type q. here what i have..
```
print('How old do you thing Fred the Chicken is?')
number = 17
Quit = q
run = 17
while run:
guess = int(input('Ent... | ## Getting `Q` as input
```
Quit = int(input('Press Q to Quit')
```
You're asking for `Q` as the input, but only accepting an `int`. So take off the `int` part:
```
Quit = input('Press Q to Quit')
```
Now `Quit` will be whatever the user typed in, so let's check for "Q" instead of `True`:
```
if Quit == "Q":
```
... |
How come unpacking is faster than accessing by index? | 13,024,416 | 28 | 2012-10-23T06:08:10Z | 13,024,454 | 15 | 2012-10-23T06:11:52Z | [
"python"
] | I'm referring to this question, and especially the comments to the first answer from @David Robinson and @mgilson:
[Sum the second value of each tuple in a list](http://stackoverflow.com/q/12218112/341971)
The original question was to sum the second value of each tuble:
```
structure = [('a', 1), ('b', 3), ('c', 2)]
... | Indexing goes through the `__getitem__` special method, which thus has to do function lookup and execution for each item. That means that for a list of `n` items, you wind up doing `n` lookups/calls.
Unpacking doesn't have to deal with that when working with native lists/tuples; it just goes through `__iter__` which i... |
How come unpacking is faster than accessing by index? | 13,024,416 | 28 | 2012-10-23T06:08:10Z | 13,024,551 | 29 | 2012-10-23T06:19:28Z | [
"python"
] | I'm referring to this question, and especially the comments to the first answer from @David Robinson and @mgilson:
[Sum the second value of each tuple in a list](http://stackoverflow.com/q/12218112/341971)
The original question was to sum the second value of each tuble:
```
structure = [('a', 1), ('b', 3), ('c', 2)]
... | If you take a look at the python bytecode, it becomes quite obvious very quickly why unpacking is faster:
```
>>> import dis
>>> def unpack_or_index(t=(0, 1)):
... _, x = t
... x = t[1]
...
>>> dis.dis(unpack_or_index)
2 0 LOAD_FAST 0 (t)
3 UNPACK_SEQUENCE 2
... |
How to test DateTimeProperty in App Engine NDB? | 13,025,011 | 5 | 2012-10-23T06:55:10Z | 13,025,967 | 8 | 2012-10-23T08:05:06Z | [
"python",
"google-app-engine",
"app-engine-ndb"
] | I'm trying to test a filter for the DateTimeProperty with App Engine's NDB but I have it set to auto\_now?
Is there a way to get around this for unit testing?
Example:
```
class MyModel(ndb.Model)
timestamp = ndb.DateTimeProperty(auto_now)
name = ndb.StringProperty()
def testMyModelFilter(self):
test1 = MyMo... | So one thing you can try (as alluded to by @mjibson) is overriding your model during the test. Since `MyModel` itself is an object, you can modify the `_auto_now` property of `timestamp` to False for your test. For example:
```
def testMyModelFilter(self):
# Change the auto_now parameter to False
MyModel.timestamp... |
split string by arbitrary number of white spaces | 13,028,120 | 2 | 2012-10-23T10:09:47Z | 13,028,140 | 10 | 2012-10-23T10:11:10Z | [
"python",
"split"
] | I'm trying to find the most pythonic way to split a string like
"some words in a string"
into single words. `string.split(' ')` works ok but it returns a bunch of white space entries in the list. Of course i could iterate the list and remove the white spaces but I was wondering if there was a better way? | Just use [`my_str.split()`](http://docs.python.org/library/stdtypes.html#str.split) without `' '`.
---
More, you can also indicate how many splits to perform by specifying the second parameter:
```
>>> ' 1 2 3 4 '.split(None, 2)
['1', '2', '3 4 ']
>>> ' 1 2 3 4 '.split(None, 1)
['1', '2 3 4 ']
``` |
getting only values fullfilling condition in a numpy array | 13,029,029 | 8 | 2012-10-23T11:03:26Z | 13,029,098 | 8 | 2012-10-23T11:06:38Z | [
"python",
"arrays",
"numpy"
] | There must a be a (very) quick and efficient way to get only elements from a numpy array, or even more interestingly from a slice of it.
Suppose I have a numpy array:
```
import numpy as np
a = np.arange(-10,10)
```
Now if I have a list:
```
s = [9, 12, 13, 14]
```
I can select elements from a:
```
a[s] #array([-... | How about:
```
In [19]: b = a[s]
In [20]: b[b > 0]
Out[20]: array([2, 3, 4])
``` |
Python property callable | 13,029,254 | 8 | 2012-10-23T11:16:17Z | 13,029,425 | 8 | 2012-10-23T11:27:09Z | [
"python",
"properties",
"callable"
] | Is there any way to have a property and a method with the same name?
I mean a property that can be used the usual way **and** to be callable at the same time?
Like this:
```
>>> b = Book()
>>> b.pages
123
>>> b.pages()
123
>>> b.pages(including_toc=False)
123
>>> b.pages(including_toc=True)
127
``` | No, you can't.
`()` always calls an *object* from the expression on its left-hand side.
What this means is, that `b.pages()` can be read as follows:
```
_tmp = b.pages
_tmp()
```
As you can see, methods *are* attributes.
What you *could* (but shouldn't) do is wrap integers in some custom class and provide a `__cal... |
How to save requests (python) cookies to a file? | 13,030,095 | 17 | 2012-10-23T12:09:07Z | 13,031,628 | 28 | 2012-10-23T13:33:01Z | [
"python",
"cookies",
"python-2.7",
"python-requests"
] | How to use the library `requests` (in python) after a request
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
bot = requests.session()
bot.get('http://google.com')
```
to keep all the cookies in a file and then restore the cookies from a file. | There is no immediate way to do so, but it's not hard to do.
You can get a `CookieJar` object from the session as `session.cookies`. You can use [`requests.utils.dict_from_cookiejar`](http://docs.python-requests.org/en/latest/api/#requests.utils.dict_from_cookiejar) to transform it into a dict. Then, you can use [`pic... |
How to save requests (python) cookies to a file? | 13,030,095 | 17 | 2012-10-23T12:09:07Z | 16,859,266 | 12 | 2013-05-31T14:07:11Z | [
"python",
"cookies",
"python-2.7",
"python-requests"
] | How to use the library `requests` (in python) after a request
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
bot = requests.session()
bot.get('http://google.com')
```
to keep all the cookies in a file and then restore the cookies from a file. | After a call such as `r = requests.get()`, `r.cookies` will return a `RequestsCookieJar` which you can directly [`pickle`](http://docs.python.org/2/library/pickle.html), i.e.
```
import pickle
def save_cookies(requests_cookiejar, filename):
with open(filename, 'wb') as f:
pickle.dump(requests_cookiejar, f)... |
How to save requests (python) cookies to a file? | 13,030,095 | 17 | 2012-10-23T12:09:07Z | 25,858,635 | 11 | 2014-09-15T23:50:49Z | [
"python",
"cookies",
"python-2.7",
"python-requests"
] | How to use the library `requests` (in python) after a request
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
bot = requests.session()
bot.get('http://google.com')
```
to keep all the cookies in a file and then restore the cookies from a file. | Expanding on @miracle2k's answer, requests `Session`s are [documented](http://docs.python-requests.org/en/latest/api/#sessionapi) to work with any [cookielib](https://docs.python.org/2/library/cookielib.html#cookielib.CookieJar) `CookieJar`. The `LWPCookieJar` (and `MozillaCookieJar`) can save and load their cookies to... |
Can flask framework send real-time data from server to client browser? | 13,030,235 | 11 | 2012-10-23T12:17:16Z | 13,030,462 | 16 | 2012-10-23T12:30:43Z | [
"python",
"web-applications",
"comet",
"flask",
"juggernaut"
] | I was wondering how (if at all) flask performs long polling, so the server can send data over a connection to the client. For example if the server receives a twitter feed via the streaming api how will that be passed to the client browser?
I gather that you cannot use flask.flash for such a situation.
Thanks
Thanks... | You can do so with the help of [`gevent`](http://www.gevent.org)+[`socketio`](http://socket.io).
* [an example app using Flask with `gevent`+`socketio`](https://github.com/kcarnold/flask-gevent-socketio-chat).
* [a socket.io route in Flask](https://gist.github.com/858806)
* [gevent-socketio](https://github.com/abourge... |
How to serialize to JSON a list of model objects in django/python | 13,031,058 | 11 | 2012-10-23T13:03:53Z | 13,031,216 | 22 | 2012-10-23T13:11:29Z | [
"python",
"json",
"django",
"django-models"
] | I am trying to serialize a list of model object defined as:
```
class AnalysisInput(models.Model):
input_user = models.CharField(max_length=45)
input_title = models.CharField(max_length=45)
input_date = models.DateTimeField()
input_link = models.CharField(max_length=100)
```
I wrote a custom serialize... | A custom encoder is not called recursively. You are actually better off *not* using a custom encoder, and instead convert your objects to simple python types before serializing.
You could add a `as_json` or similarly named method to your model and calling that every time you need a JSON result:
```
class AnalysisInpu... |
How to serialize to JSON a list of model objects in django/python | 13,031,058 | 11 | 2012-10-23T13:03:53Z | 16,616,386 | 12 | 2013-05-17T19:19:11Z | [
"python",
"json",
"django",
"django-models"
] | I am trying to serialize a list of model object defined as:
```
class AnalysisInput(models.Model):
input_user = models.CharField(max_length=45)
input_title = models.CharField(max_length=45)
input_date = models.DateTimeField()
input_link = models.CharField(max_length=100)
```
I wrote a custom serialize... | The best way I found to serialize your Django models is by using `django.core.serializers` to serialize your model list into JSON, XML, or YAML. No custom serialization code required! Documentation is here: <https://docs.djangoproject.com/en/dev/topics/serialization/>
Here is my implementation:
lead/models.py:
```
f... |
How can I "change" a python struct_time object? | 13,031,559 | 8 | 2012-10-23T13:29:46Z | 13,031,653 | 15 | 2012-10-23T13:34:22Z | [
"python",
"time"
] | When dealing with times and dates in python, you will stumble across the time.struct\_time object:
```
st = time.strptime("23.10.2012", "%d.%m.%Y")
print st
time.struct_time(tm_year=2012, tm_mon=10, tm_mday=23, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=297, tm_isdst=-1)
```
Now as this struct does not support... | Use the [`datetime` module](http://docs.python.org/library/datetime.html) instead, which has a far richer set of objects to handle date(time) arithmetic:
```
import datetime
adate = datetime.datetime.strptime("23.10.2012", "%d.%m.%Y").date()
adate + datetime.timedelta(days=30)
```
You can use the excellent [`python-d... |
regular expression using in glob.glob of python | 13,031,989 | 9 | 2012-10-23T13:49:50Z | 13,032,338 | 18 | 2012-10-23T14:07:36Z | [
"python",
"glob"
] | ```
import glob
list = glob.glob(r'*abc*.txt') + glob.glob(r'*123*.txt') + glob.glob(r'*a1b*.txt')
for i in list:
print i
```
This code is working to list files in current folder which have 'abc' '123' or 'a1b' in their names.
How to use one glob to made this function,thanks | The easiest way would be to filter the glob results yourself. Here is how to do it using a simple loop comprehension:
```
import glob
res = [f for f in glob.glob("*.txt") if "abc" in f or "123" in f or "a1b" in f]
for f in res:
print f
```
You could also use a regexp and no `glob`:
```
import os
import re
res = ... |
regular expression using in glob.glob of python | 13,031,989 | 9 | 2012-10-23T13:49:50Z | 17,197,678 | 8 | 2013-06-19T17:35:14Z | [
"python",
"glob"
] | ```
import glob
list = glob.glob(r'*abc*.txt') + glob.glob(r'*123*.txt') + glob.glob(r'*a1b*.txt')
for i in list:
print i
```
This code is working to list files in current folder which have 'abc' '123' or 'a1b' in their names.
How to use one glob to made this function,thanks | Here is a ready to use way of doing this, based on the other answers. It's not the most performance critical, but it works as described;
```
def reglob(path, exp, invert=False):
"""glob.glob() style searching which uses regex
:param exp: Regex expression for filename
:param invert: Invert match to non mat... |
Remove all specific value from array | 13,032,448 | 5 | 2012-10-23T14:13:13Z | 13,032,474 | 8 | 2012-10-23T14:14:36Z | [
"python"
] | I have to remove all specific values from array (if any), so i write:
```
while value_to_remove in my_array:
my_array.remove(value_to_remove)
```
Is there more pythonic way to do this, by one command? | You can try:
`filter (lambda a: a != value_to_remove, my_array)`
Example:
```
>>> my_array = ["abc", "def", "xyz", "abc", "pop", "abc"]
>>> filter (lambda a: a != "abc", my_array)
['def', 'xyz', 'pop']
``` |
Django MPTT : Filter by depth? | 13,032,629 | 2 | 2012-10-23T14:22:59Z | 13,032,698 | 7 | 2012-10-23T14:26:16Z | [
"python",
"django",
"django-models",
"django-mptt",
"mptt"
] | I would like to know a thing about django-mptt, as I'm considering using it for a engineering coordination project.
I would have a Model class (say, 'Interface'), with a ForeignKey to the Model (say, 'Location') in the Tree.
Will I be able to filter Interfaces by the depth of the Location they refer to ? The depth be... | Found my answer finally : [django-mptt dev documentation](http://django-mptt.readthedocs.org/en/latest/technical_details.html#level)
> Level The level (or âdepthâ) at which a node sits in the tree.
>
> Root nodes are level 0, their immediate children are level 1, their
> immediate children are level 2 and so on...... |
Image size (Python, OpenCV) | 13,033,278 | 8 | 2012-10-23T14:54:34Z | 23,207,185 | 24 | 2014-04-21T22:34:08Z | [
"python",
"opencv",
"size"
] | I would like to get the Image size in python,as I do it with c++.
```
int w = src->width;
printf("%d", 'w');
``` | Using opneCV and numpy it is as easy as this:
```
import numpy as np
import cv2
img = cv2.imread('your_image.jpg',0)
height, width = img.shape[:2]
``` |
Caching or prefetching Django's inverse relationships | 13,033,716 | 2 | 2012-10-23T15:16:06Z | 13,033,791 | 7 | 2012-10-23T15:19:15Z | [
"python",
"django",
"prefetch"
] | Consider a shema with a Publishers table and a Books table so that
```
def Publisher(models.Model):
city = models.CharField()
...
def Book(models.Model):
title = models.CharField()
publisher = models.ForeignKey(Publisher)
```
In my template I wish to display a list of certain publishers with all its books. I... | In Django 1.4+, use [`prefetch_related`](https://docs.djangoproject.com/en/dev/ref/models/querysets/#prefetch-related)
```
Publisher.objects.filter(city='NY').prefetch_related('book_set')
```
In Django <1.4, use [django-batch-select](https://github.com/lilspikey/django-batch-select). |
Using global variables between files? | 13,034,496 | 46 | 2012-10-23T15:54:30Z | 13,034,908 | 87 | 2012-10-23T16:16:48Z | [
"python",
"share",
"globals"
] | I'm bit confused about how the global variables work. I have a large project, with around 50 files, and I need to define global variables for all those files.
What I did was define them in my projects `main.py` file, as following:
```
# ../myproject/main.py
# Define global myList
global myList
myList = []
# Imports... | The problem is you defined `myList` from main.py, but subfile.py needs to use it. Here is a clean way to solve this problem: move all globals to a file, I call this file `settings.py`. This file is responsible for defining globals and initializing them:
```
# settings.py
def init():
global myList
myList = []
... |
Does the Python 3 interpreter have a JIT feature? | 13,034,991 | 30 | 2012-10-23T16:21:56Z | 13,035,213 | 11 | 2012-10-23T16:35:21Z | [
"python",
"python-3.x",
"jit"
] | I found that when I ask something more to Python, python doesn't use my machine resource at 100% and it's not really fast, it's fast if compared to many other interpreted languages, but when compared to compiled languages i think that the difference is really remarkable.
It's possible to speedup things with a JIT comp... | The only Python implementation that has a JIT is [PyPy](http://pypy.org/). Byt - PyPy is a Python 2 implementation, not a Python 3 implementation. You could [support the Python 3 port](http://pypy.org/py3donate.html). |
Does the Python 3 interpreter have a JIT feature? | 13,034,991 | 30 | 2012-10-23T16:21:56Z | 13,035,238 | 36 | 2012-10-23T16:36:56Z | [
"python",
"python-3.x",
"jit"
] | I found that when I ask something more to Python, python doesn't use my machine resource at 100% and it's not really fast, it's fast if compared to many other interpreted languages, but when compared to compiled languages i think that the difference is really remarkable.
It's possible to speedup things with a JIT comp... | First off, Python 3(.x) is a language, for which there can be any number of implementations. Okay, to this day no implementation except CPython actually implements those versions of the language. But that will change (PyPy is catching up).
To answer the question you meant to ask: CPython, 3.x or otherwise, does not, n... |
Does the Python 3 interpreter have a JIT feature? | 13,034,991 | 30 | 2012-10-23T16:21:56Z | 13,035,563 | 7 | 2012-10-23T16:57:38Z | [
"python",
"python-3.x",
"jit"
] | I found that when I ask something more to Python, python doesn't use my machine resource at 100% and it's not really fast, it's fast if compared to many other interpreted languages, but when compared to compiled languages i think that the difference is really remarkable.
It's possible to speedup things with a JIT comp... | The Numba project should work on Python 3. Although it is not exactly what you asked, you may want to give it a try:
<https://github.com/numba/numba/blob/master/docs/source/doc/userguide.rst>.
It does not support all Python syntax at this time. |
Error When calling stored procedure in python - Using MySQLdb | 13,035,379 | 3 | 2012-10-23T16:45:09Z | 13,035,397 | 7 | 2012-10-23T16:45:52Z | [
"python",
"mysql",
"python-2.7",
"mysql-python"
] | I have a MySQL stored procedure called test which accepts one argument.
I can execute the stored procedure from python 2.7x using below code
```
data='Teststr'
cur = db.cursor()
cur.execute("CALL test('{0}')".format(data))
```
But when I use
```
data='Teststr'
cur = db.cursor()
cur.callproc('test',data)
```
I am en... | You want `cur.callproc('test', (data,))` to pass a tuple of 1 element
eg:
```
>>> a = 'hello'
>>> len(a) # just a
5
>>> len( (a) ) # still just a
5
>>> len( (a,) ) # single element tuple containing a
1
``` |
Remove rows with duplicate indices (Pandas DataFrame and TimeSeries) | 13,035,764 | 56 | 2012-10-23T17:11:04Z | 13,036,848 | 46 | 2012-10-23T18:27:46Z | [
"python",
"pandas"
] | I'm reading some automated weather data from the web. The observations occur every 5 minutes and are compiled into monthly files for each weather station. Once I'm done parsing a file, the DataFrame looks something like this:
```
Sta Precip1hr Precip5min Temp DewPnt WindSpd WindDir AtmPres... | Oh my. This is actually so simple!
```
grouped = df3.groupby(level=0)
df4 = grouped.last()
df4
A B rownum
2001-01-01 00:00:00 0 0 6
2001-01-01 01:00:00 1 1 7
2001-01-01 02:00:00 2 2 8
2001-01-01 03:00:00 3 3 3
2001-01-01 04:00:00 4 4 4
2001-01... |
Remove rows with duplicate indices (Pandas DataFrame and TimeSeries) | 13,035,764 | 56 | 2012-10-23T17:11:04Z | 14,900,065 | 57 | 2013-02-15T17:27:14Z | [
"python",
"pandas"
] | I'm reading some automated weather data from the web. The observations occur every 5 minutes and are compiled into monthly files for each weather station. Once I'm done parsing a file, the DataFrame looks something like this:
```
Sta Precip1hr Precip5min Temp DewPnt WindSpd WindDir AtmPres... | A simple solution is to use `drop_duplicates`
```
df4 = df3.drop_duplicates(subset='rownum', keep='last')
```
For me, this operated quickly on large data sets.
This requires that 'rownum' be the column with duplicates. In the modified example, 'rownum' has no duplicates, therefore nothing gets eliminated. What we re... |
Remove rows with duplicate indices (Pandas DataFrame and TimeSeries) | 13,035,764 | 56 | 2012-10-23T17:11:04Z | 34,297,689 | 36 | 2015-12-15T19:25:20Z | [
"python",
"pandas"
] | I'm reading some automated weather data from the web. The observations occur every 5 minutes and are compiled into monthly files for each weather station. Once I'm done parsing a file, the DataFrame looks something like this:
```
Sta Precip1hr Precip5min Temp DewPnt WindSpd WindDir AtmPres... | I would suggest using the [duplicated](http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.Index.duplicated.html) method on the Pandas Index itself:
```
df3 = df3[~df3.index.duplicated(keep='first')]
```
While all the methods suggested above work, the currently accepted answer is by far the least per... |
Getting output with IPython Notebook | 13,036,197 | 14 | 2012-10-23T17:42:13Z | 13,075,334 | 22 | 2012-10-25T18:56:27Z | [
"python",
"ipython",
"ipython-notebook"
] | When I launch [IPython Notebook](https://en.wikipedia.org/wiki/IPython#Notebook) I can navigate to it and enter code. However, nothing is ever echo'd back to the IPython Notebook interface.
I know the server is getting the queries (from `--debug output`) and responding to them it's just never giving me output in my IP... | The return output to the notebook was being blocked by Sophos Endpoint Security and Control.
Disabling "Sophos Web Intelligence Service" in services.msc worked, but it was not ideal since it turns off my web intelligence or whatever ... I don't really want to make myself more susceptible to bad stuff...
So the soluti... |
Getting output with IPython Notebook | 13,036,197 | 14 | 2012-10-23T17:42:13Z | 19,381,372 | 15 | 2013-10-15T12:33:57Z | [
"python",
"ipython",
"ipython-notebook"
] | When I launch [IPython Notebook](https://en.wikipedia.org/wiki/IPython#Notebook) I can navigate to it and enter code. However, nothing is ever echo'd back to the IPython Notebook interface.
I know the server is getting the queries (from `--debug output`) and responding to them it's just never giving me output in my IP... | I am in the same situation as the OP and just found out that the IPython notebook works (without disablying Sophos) when it is started with
```
ipython notebook --ip=localhost
``` |
Python calendar: day/month names in specific locale | 13,037,370 | 6 | 2012-10-23T19:02:28Z | 13,037,425 | 8 | 2012-10-23T19:05:37Z | [
"python",
"calendar"
] | I am playing with Python's [calendar](http://docs.python.org/library/calendar.html) module that's in the standard library. Basically I need a list of all days of a month, like so:
```
>>> import calendar
>>> calobject = calendar.monthcalendar(2012, 10)
>>> print calobject
[[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13,... | This is from the source code of the `calendar` module:
```
def formatmonthname(self, theyear, themonth, width, withyear=True):
with TimeEncoding(self.locale) as encoding:
s = month_name[themonth]
if encoding is not None:
s = s.decode(encoding)
if withyear:
s = "%s %r... |
Python calendar: day/month names in specific locale | 13,037,370 | 6 | 2012-10-23T19:02:28Z | 13,037,803 | 12 | 2012-10-23T19:31:07Z | [
"python",
"calendar"
] | I am playing with Python's [calendar](http://docs.python.org/library/calendar.html) module that's in the standard library. Basically I need a list of all days of a month, like so:
```
>>> import calendar
>>> calobject = calendar.monthcalendar(2012, 10)
>>> print calobject
[[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13,... | Ha! Found an easy way to get localized day/month names:
```
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'de_DE')
'de_DE'
>>> import calendar
>>> calendar.month_name[10]
'Oktober'
>>> calendar.day_name[1]
'Dienstag'
``` |
Get keys from template | 13,037,401 | 6 | 2012-10-23T19:04:33Z | 13,037,514 | 10 | 2012-10-23T19:12:27Z | [
"python",
"string-formatting"
] | I would like to get a list of all possible keyword arguments a string template might use in a substitution.
**Is there a way to do this other than re?**
I want to do something like this:
```
text="$one is a $lonely $number."
keys = get_keys(text)
# keys = ('one', 'lonely', 'number')
```
I'm writing a simple Mad-li... | If it's okay to use `string.format`, consider using built-in class `string.Formatter` which has a `parse()` method:
```
>>> from string import Formatter
>>> [i[1] for i in Formatter().parse('Hello {1} {foo}')]
['1', 'foo']
```
See [here](http://docs.python.org/library/string.html#string.Formatter.parse) for more deta... |
How to access class-scope variables without self? | 13,037,426 | 5 | 2012-10-23T19:05:36Z | 13,037,450 | 9 | 2012-10-23T19:07:43Z | [
"python",
"class",
"static",
"scope"
] | So I have a class, which I'm using as a local namespace. I have some static functions in the class, but they can't access the class scope variables. Why is this?
```
class Foo:
foo_string = "I am a foo"
@staticmethod
def foo():
print foo_string
```
---
```
>>> Foo.foo()
[Stack Trace]
NameErr... | Python doesn't let class variables fall into scope this way, there are two ways to do this, the first is to use a class method:
```
@classmethod
def foo(cls):
print(cls.foo_string)
```
Which I would argue is the best solution.
The second is to access by name:
```
@staticmethod
def foo():
print(Foo.foo_strin... |
Decimal precision in python without decimal module | 13,037,500 | 4 | 2012-10-23T19:11:17Z | 13,037,913 | 7 | 2012-10-23T19:37:54Z | [
"python",
"python-3.x"
] | I'm fairly new to Python, and was wondering how would I be able to control the decimal precision of any given number without using any the decimal module or floating points (eg: " %4f" %n).
Examples (edit):
input(2/7)
> 0.28571428571....
input(1/3)
> 0.33333333333333....
and I wanted them to thousand decimal poin... | We can use a `long` to store a decimal with high precision, and do arithmetic on it. Here's how you'd print it out:
```
def print_decimal(val, prec):
intp, fracp = divmod(val, 10**prec)
print str(intp) + '.' + str(fracp).zfill(prec)
```
Usage:
```
>>> prec = 1000
>>> a = 2 * 10**prec
>>> b = a//7
>>> print_d... |
Proper use of `isinstance(obj, class)` | 13,039,060 | 3 | 2012-10-23T20:53:09Z | 13,039,182 | 10 | 2012-10-23T21:02:20Z | [
"python",
"class",
"isinstance"
] | As I write it, it seems almost surreal to me that I'm actually experiencing this problem.
I have a list of objects. Each of these objects are of instances of an `Individual` class that I wrote.
Thus, conventional wisdom says that `isinstance(myObj, Individual)` should return `True`. However, this was not the case. So... | This error indicates that the `Individual` class somehow got created twice. You created `pop[0]` with one version of `Instance`, and are checking for instance with the other one. Although they are pretty much identical, Python doesn't know that, and `isinstance` fails. To verify this, check whether `pop[0].__class__ is... |
How to retrive GET vars in python bottle app | 13,039,411 | 9 | 2012-10-23T21:18:54Z | 13,039,456 | 12 | 2012-10-23T21:21:39Z | [
"python",
"bottle",
"query-parameters"
] | I'm trying to make a simple REST api using the Python bottle app.
I'm facing a problem in retrieving the GET variables from the request global object.
Any suggestions how to retrieve this from the GET request? | They are stored in the `request.query` object.
<http://bottlepy.org/docs/dev/tutorial.html#query-variables>
It looks like you can also access them by treating the `request.query` attribute like a dictionary:
```
request.query['city']
```
So `dict(request.query)` would create a dictionary of all the query parameters... |
unable to call firefox from selenium in python on AWS machine | 13,039,530 | 25 | 2012-10-23T21:26:33Z | 13,055,412 | 45 | 2012-10-24T18:27:06Z | [
"python",
"selenium",
"amazon-web-services",
"screen-scraping",
"web-scraping"
] | I am trying to use selenium from python to scrape some dynamics pages with javascript. However, I cannot call firefox after I followed the instruction of selenium on the pypi page(http://pypi.python.org/pypi/selenium). I installed firefox on AWS ubuntu 12.04. The error message I got is:
```
In [1]: from selenium impor... | The problem is Firefox requires a display. I've used [pyvirtualdisplay](http://pypi.python.org/pypi/PyVirtualDisplay) in my example to simulate a display. The solution is:
```
from pyvirtualdisplay import Display
from selenium import webdriver
display = Display(visible=0, size=(1024, 768))
display.start()
driver= we... |
Networkx: Differences between pagerank, pagerank_numpy, and pagerank_scipy? | 13,040,548 | 8 | 2012-10-23T22:52:31Z | 13,041,155 | 16 | 2012-10-24T00:06:46Z | [
"python",
"numpy",
"scipy",
"networkx",
"pagerank"
] | Does anyone know about the differences in accuracy between the three different pagerank functions in Networkx?
I have a graph of 1000 nodes and 139732 edges, and the "plain" `pagerank` function didn't seem to work at all -- all but two of the nodes had the same PG, so I'm assuming this function doesn't work quite as w... | Each of the three functions uses a different approach to solving the same problem:
`networkx.pagerank()` is a pure-Python implementation of the power-method to compute the largest eigenvalue/eigenvector or the Google matrix. It has two parameters that control the accuracy - `tol` and `max_iter`.
`networkx.pagerank_sc... |
How do I create documentation with Pydoc? | 13,040,646 | 28 | 2012-10-23T23:02:16Z | 13,043,765 | 15 | 2012-10-24T06:04:38Z | [
"python",
"documentation",
"python-3.x",
"documentation-generation",
"pydoc"
] | I'm trying to create a document out of my module. I used `pydoc` from the command-line in Windows 7 using Python 3.2.3:
```
python "<path_to_pydoc_>\pydoc.py" -w myModule
```
This led to my shell being filled with text, one line for each file in my module, saying:
```
no Python documentation found for '<file_name>'
... | As RocketDonkey suggested, your module itself needs to have some docstrings.
For example, in `myModule/__init__.py`:
```
"""
The mod module
"""
```
You'd also want to generate documentation for each file in `myModule/*.py` using
```
pydoc myModule.thefilename
```
to make sure the generated files match the ones tha... |
How do I create documentation with Pydoc? | 13,040,646 | 28 | 2012-10-23T23:02:16Z | 13,050,049 | 35 | 2012-10-24T13:17:18Z | [
"python",
"documentation",
"python-3.x",
"documentation-generation",
"pydoc"
] | I'm trying to create a document out of my module. I used `pydoc` from the command-line in Windows 7 using Python 3.2.3:
```
python "<path_to_pydoc_>\pydoc.py" -w myModule
```
This led to my shell being filled with text, one line for each file in my module, saying:
```
no Python documentation found for '<file_name>'
... | pydoc is fantastic for generating documentation, but the documentation has to be written in the first place. You must have docstrings in your source code as was mentioned by RocketDonkey in the comments:
```
"""
This example module shows various types of documentation available for use
with pydoc. To generate HTML do... |
How do I create documentation with Pydoc? | 13,040,646 | 28 | 2012-10-23T23:02:16Z | 27,890,642 | 34 | 2015-01-11T18:36:48Z | [
"python",
"documentation",
"python-3.x",
"documentation-generation",
"pydoc"
] | I'm trying to create a document out of my module. I used `pydoc` from the command-line in Windows 7 using Python 3.2.3:
```
python "<path_to_pydoc_>\pydoc.py" -w myModule
```
This led to my shell being filled with text, one line for each file in my module, saying:
```
no Python documentation found for '<file_name>'
... | Another thing that people may find useful...make sure to leave off ".py" from your module name. For example, if you are trying to generate documentation for **'original'** in '**original.py**':
> ```
> yourcode_dir$ pydoc -w original.py
> no Python documentation found for 'original.py'
>
> yourcode_dir$ pydoc -w origi... |
Will python class __init__ method implicitly return None? | 13,043,359 | 5 | 2012-10-24T05:11:15Z | 13,043,389 | 7 | 2012-10-24T05:15:37Z | [
"python"
] | I tried to return a value in a class constructor (**init**):
```
class A:
def __init__(self):
return 1
```
but there is a run-time error saying **init** should return None. If this is the case, how to understand:
```
a=A()
```
where "a" is assigned as the class instance? | It works like this:
You do:
```
a = A()
```
`A.__new__()` is called, and returns an instance of the class `A`.
Equivalently:
```
a = A.__new__(A)
```
Python then calls
```
a.__init__()
```
Which, as the error message says, should not return a value. |
Will python class __init__ method implicitly return None? | 13,043,359 | 5 | 2012-10-24T05:11:15Z | 13,043,507 | 23 | 2012-10-24T05:30:40Z | [
"python"
] | I tried to return a value in a class constructor (**init**):
```
class A:
def __init__(self):
return 1
```
but there is a run-time error saying **init** should return None. If this is the case, how to understand:
```
a=A()
```
where "a" is assigned as the class instance? | Strictly speaking, it's not `A.__new__()` that's creating the the instance `a`.
When you define `class A(object):` (or `class A:` as well if you are using Python3, `class A:` is the [*old-style* class that has been deprecated](http://stackoverflow.com/questions/54867/old-style-and-new-style-classes-in-python)), it is ... |
Install mysql-python return error in CentOs | 13,044,201 | 10 | 2012-10-24T06:52:12Z | 13,044,295 | 31 | 2012-10-24T07:01:30Z | [
"python",
"mysql",
"django",
"mysql-python"
] | I want to run a django project on CentOs. I tried to install mysql-python by easy\_install and pip but I got error with both of them. I Googled the problem and found some suggestions, but none of them helped me.
errors are:
```
_mysql.c:29:20: error: Python.h: No such file or directory
_mysql.c:40:26: error: structme... | I think you need to install the python development libraries first:
```
yum install python-devel
``` |
Install mysql-python return error in CentOs | 13,044,201 | 10 | 2012-10-24T06:52:12Z | 14,585,503 | 31 | 2013-01-29T14:42:32Z | [
"python",
"mysql",
"django",
"mysql-python"
] | I want to run a django project on CentOs. I tried to install mysql-python by easy\_install and pip but I got error with both of them. I Googled the problem and found some suggestions, but none of them helped me.
errors are:
```
_mysql.c:29:20: error: Python.h: No such file or directory
_mysql.c:40:26: error: structme... | Just to mention for the others that might end up here too,
After installing python-devel, I had the very same error but with **mysql\_config.h** missing
I solved this error in installing mysql-devel
```
$ yum install mysql-devel.x86_64
```
Hope this helps |
Cython code 3-4 times slower than Python / Numpy code? | 13,044,515 | 6 | 2012-10-24T07:19:51Z | 13,045,311 | 10 | 2012-10-24T08:18:53Z | [
"python",
"performance",
"numpy",
"scipy",
"cython"
] | I am trying to convert my Python / Numpy code to Cython code for speedup purposes. However, Cython is MUCH slower (3-4 times) than the Python / Numpy code. Am I using Cython correctly? Am I passing arguments correctly to myc\_rb\_etc() in my Cython code? What about when I call the integrate function? Thank you in advan... | Change the function definition to include the types of the parameters:
```
def myc_rb_e2f(np.ndarray[double,ndim=1]y, double t, np.ndarray[double, ndim=1] k, np.ndarray[double, ndim=1] d):
```
This will improve the running time about 3 times over the numpy implementation and 6 - 7 times over your initial cython imple... |
Python - mechanism to identify compressed file type and uncompress | 13,044,562 | 10 | 2012-10-24T07:24:35Z | 13,044,946 | 16 | 2012-10-24T07:53:38Z | [
"python",
"compression",
"zip",
"tar",
"rar"
] | A compressed file can be classified into below logical groups
a. The operating system which you are working on (\*ix, Win) etc.
b. Different types of compression algorithm (i.e .zip,.Z,.bz2,.rar,.gzip). Atleast from a standard list of mostly used compressed files.
c. Then we have tar ball mechanism - where I supp... | [This page](http://www.garykessler.net/library/file_sigs.html) has a list of "magic" file signatures. Grab the ones you need and put them in a dict like below. Then we need a function that matches the dict keys with the start of the file. I've written a suggestion, though it can be optimized by preprocessing the `magic... |
Python - mechanism to identify compressed file type and uncompress | 13,044,562 | 10 | 2012-10-24T07:24:35Z | 13,045,892 | 8 | 2012-10-24T08:57:42Z | [
"python",
"compression",
"zip",
"tar",
"rar"
] | A compressed file can be classified into below logical groups
a. The operating system which you are working on (\*ix, Win) etc.
b. Different types of compression algorithm (i.e .zip,.Z,.bz2,.rar,.gzip). Atleast from a standard list of mostly used compressed files.
c. Then we have tar ball mechanism - where I supp... | Based on lazyr's answer and my comment, here is what I mean:
```
class CompressedFile (object):
magic = None
file_type = None
mime_type = None
proper_extension = None
def __init__(self, f):
# f is an open file or file like object
self.f = f
self.accessor = self.open()
... |
Using sudo with Python script | 13,045,593 | 11 | 2012-10-24T08:37:20Z | 13,045,700 | 14 | 2012-10-24T08:45:14Z | [
"python",
"shell",
"subprocess"
] | I'm trying to write a small script to mount a VirtualBox shared folder each time I execute the script. I want to do it with Python, because I'm trying to learn it for scripting.
The problem is that I need privileges to launch mount command. I could run the script as sudo, but I prefer it to make sudo by its own.
I al... | ```
sudoPassword = 'mypass'
command = 'mount -t vboxsf myfolder /home/myuser/myfolder'
p = os.system('echo %s|sudo -S %s' % (sudoPassword, command))
```
Try this and let me know if it works. :-)
And this one:
`os.popen("sudo -S %s"%(command), 'w').write('mypass')` |
Using sudo with Python script | 13,045,593 | 11 | 2012-10-24T08:37:20Z | 24,257,940 | 24 | 2014-06-17T07:23:03Z | [
"python",
"shell",
"subprocess"
] | I'm trying to write a small script to mount a VirtualBox shared folder each time I execute the script. I want to do it with Python, because I'm trying to learn it for scripting.
The problem is that I need privileges to launch mount command. I could run the script as sudo, but I prefer it to make sudo by its own.
I al... | Many answers focus on how to make your solution work, while very few suggest that *your solution is a **very bad** approach*. If you really want to "practice to learn", why not practice using good solutions? Hardcoding your password is learning the *wrong* approach!
If what you really want is a password-less `mount` f... |
matplotlib very slow. Is it normal? | 13,046,127 | 9 | 2012-10-24T09:10:50Z | 13,060,980 | 12 | 2012-10-25T03:11:04Z | [
"python",
"performance",
"matplotlib"
] | I am creating a couple of pdf plots with matplotlib which is composed of 400 subplots. Each one has only 5 data points. It takes 420 s on a good computer to save 5 pdf picture. Is there any way to optimize the code or it is just normal for matplotlib?
Portion of code for plotting:
```
plot_cnt = 1
for k in np.arange(... | Building off of what @rowman said, you can do this all in one axes (as you turn off all the ticks etc). Something like:
```
K_max = 20
K_min = 0
L_max = 20
L_min = 0
ax = plt.subplot(111)
x_offset = 7 # tune these
y_offset = 7 # tune these
plt.setp(ax, 'frame_on', False)
ax.set_ylim([0, (K_max-K_min +1)*y_offset ])
ax... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.