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 get the closest single row after a specific datetime index using Python Pandas | 9,877,391 | 10 | 2012-03-26T18:11:04Z | 9,918,868 | 21 | 2012-03-29T03:54:52Z | [
"python",
"pandas"
] | DataFrame I have:
```
A B C
2012-01-01 1 2 3
2012-01-05 4 5 6
2012-01-10 7 8 9
2012-01-15 10 11 12
```
What I am using now:
```
date_after = dt.datetime( 2012, 1, 7 )
frame.ix[date_after:].ix[0:1]
Out[1]:
A B C
2012-01-10 7 8 9
```
Is there any better way of d... | You might want to go directly do the index:
```
i = frame.index.searchsorted(date)
frame.ix[frame.index[i]]
```
A touch verbose but you could put it in a function. About as good as you'll get (`O(log n)`) |
Is there a Python equivalent to the 'which' command | 9,877,462 | 9 | 2012-03-26T18:16:29Z | 9,877,856 | 7 | 2012-03-26T18:45:24Z | [
"python",
"shell",
"operating-system"
] | Put another way, is there a cross-platform way of knowing which file will be executed by `subprocess.Popen(file)` without first executing it? | I believe there is none in the python libraries
```
>>> def which(pgm):
path=os.getenv('PATH')
for p in path.split(os.path.pathsep):
p=os.path.join(p,pgm)
if os.path.exists(p) and os.access(p,os.X_OK):
return p
>>> os.which=which
>>> os.which('ls.exe')
'C:\\GNUwin32\\bin\\ls.exe'
... |
Is there a Python equivalent to the 'which' command | 9,877,462 | 9 | 2012-03-26T18:16:29Z | 17,025,295 | 18 | 2013-06-10T13:39:35Z | [
"python",
"shell",
"operating-system"
] | Put another way, is there a cross-platform way of knowing which file will be executed by `subprocess.Popen(file)` without first executing it? | Python 3.3 added `shutil.which()` to provide a cross-platform means of discovering executables:
<http://docs.python.org/3.3/library/shutil.html#shutil.which>
> Return the path to an executable which would be run if the given cmd was called. If no cmd would be called, return None.
Sample calls:
```
>>> shutil.which(... |
What is the best way to get a semi long unique id (non sequential) key for Database objects | 9,877,524 | 16 | 2012-03-26T18:21:00Z | 9,878,781 | 18 | 2012-03-26T19:53:35Z | [
"python",
"django",
"flask"
] | Iam building a web app and I would like my URL scheme to look something like this:
```
someurl.com/object/FJ1341lj
```
Currently I just use the primary key from my SQL Alchemy objects, but the problem is that I dont want the Urls to be sequential or low numbers. For instance my URLs look like this:
```
someurl.com/o... | ### Encoding the integers
You could use a reversible encoding for your integers:
```
def int_str(val, keyspace):
""" Turn a positive integer into a string. """
assert val >= 0
out = ""
while val > 0:
val, digit = divmod(val, len(keyspace))
out += keyspace[digit]
return out[::-1]
d... |
How do I get the user agent with Flask? | 9,878,020 | 66 | 2012-03-26T18:57:01Z | 9,878,384 | 18 | 2012-03-26T19:24:02Z | [
"python",
"flask"
] | I'm trying to get access to the user agent with Flask, but I either can't find the documentation on it, or it doesn't tell me. | ```
flask.request.user_agent.string
``` |
How do I get the user agent with Flask? | 9,878,020 | 66 | 2012-03-26T18:57:01Z | 9,878,404 | 110 | 2012-03-26T19:25:48Z | [
"python",
"flask"
] | I'm trying to get access to the user agent with Flask, but I either can't find the documentation on it, or it doesn't tell me. | ```
from flask import request
request.headers.get('User-Agent')
```
You can also use the [`request.user_agent`](http://werkzeug.pocoo.org/docs/utils/#module-werkzeug.useragents) object which contains the following attributes which are created based on the useragent string:
* platform (windows, linux, macos, etc.)
* b... |
scipy.optimize.leastsq with bound constraints | 9,878,558 | 18 | 2012-03-26T19:38:35Z | 9,879,899 | 9 | 2012-03-26T21:07:46Z | [
"python",
"optimization",
"scipy",
"mathematical-optimization"
] | I am looking for an optimisation routine within scipy/numpy which could solve a non-linear least-squares type problem (e.g., fitting a parametric function to a large dataset) but including bounds and constraints (e.g. minima and maxima for the parameters to be optimised). At the moment I am using the python version of ... | scipy has several [constrained optimization routines](http://docs.scipy.org/doc/scipy/reference/optimize.html#constrained-multivariate) in scipy.optimize. The constrained least squares variant is [scipy.optimize.fmin\_slsqp](http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.fmin_slsqp.html#scipy.optimi... |
scipy.optimize.leastsq with bound constraints | 9,878,558 | 18 | 2012-03-26T19:38:35Z | 9,886,759 | 17 | 2012-03-27T09:29:50Z | [
"python",
"optimization",
"scipy",
"mathematical-optimization"
] | I am looking for an optimisation routine within scipy/numpy which could solve a non-linear least-squares type problem (e.g., fitting a parametric function to a large dataset) but including bounds and constraints (e.g. minima and maxima for the parameters to be optimised). At the moment I am using the python version of ... | [scipy.optimize.least\_squares](http://scipy.github.io/devdocs/generated/scipy.optimize.least_squares.html) in scipy 0.17 (January 2016)
handles bounds; use that, not this hack.
---
Bound constraints can easily be made quadratic,
and minimized by leastsq along with the rest.
Say you want to minimize a sum of 10 squ... |
Adding a ManyToManyWidget to the reverse of a ManyToManyField in the Django Admin | 9,879,687 | 13 | 2012-03-26T20:53:48Z | 21,480,139 | 14 | 2014-01-31T12:30:19Z | [
"python",
"django",
"django-models",
"django-admin"
] | Let's say I have a simple blog app in Django 1.4:
```
class Post(models.Model):
title = â¦
published_on = â¦
tags = models.ManyToManyField('Tag')
class Tag(models.Model):
name = â¦
```
i.e. a post has many tags. On the Django admin, I get a nice little `<select multi>` if I include `tags` in the `... | This is possible to do with a custom form.
```
from django.contrib import admin
from django import forms
from models import Post, Tag
class PostAdminForm(forms.ModelForm):
tags = forms.ModelMultipleChoiceField(
Tag.objects.all(),
widget=admin.widgets.FilteredSelectMultiple('Tags', False),
... |
How to decode encodeURIComponent in GAE (python)? | 9,880,173 | 8 | 2012-03-26T21:30:56Z | 9,880,400 | 8 | 2012-03-26T21:51:20Z | [
"python",
"google-app-engine",
"unicode",
"character-encoding",
"uri"
] | I have a unicode string that was encoded on the client side using JS encodeURIComponent.
If I use the following in Python locally, I get the expected result:
```
>>> urllib.unquote("Foo%E2%84%A2%20Bar").decode("utf-8")
>>> u'Foo\u2122 Bar'
```
But when I run this in Google App Engine, I get:
```
Traceback (most rec... | My guess is that `h.path` is a unicode object. Then `urllib.unquote` would return a unicode object. When `decode` is called on a unicode object at first it is converted to `str` using default encoding (which is ascii) and here you get the `'ascii' codec can't encode` exception.
Here is a proof:
```
>>> urllib.unquote... |
python list vs. tuple for on-the-fly key iteration | 9,880,553 | 3 | 2012-03-26T22:03:27Z | 9,880,567 | 7 | 2012-03-26T22:05:12Z | [
"python"
] | Say I have components that I need to iterate through, for example "From" and "To." As a convenience, I can iterate through these strings, but I don't need them stored for any extended period since I only have to do this once. Would it be better to use a list or tuple in this instance?
```
info = {}
for type in ('from'... | If you're not going to do changes to it, I think a tuple applies better. I only use lists when I need to do dynamic operations to the collection such as append, subtract etc.
Plus, in most situations accessing a tuple is faster. That being said you should always test your specific use case before deciding. |
Broken Pipe Error causes streaming Elastic MapReduce job on AWS to fail | 9,881,269 | 7 | 2012-03-26T23:15:07Z | 9,920,198 | 9 | 2012-03-29T06:32:54Z | [
"python",
"hadoop",
"amazon-web-services",
"mapreduce",
"elastic-map-reduce"
] | Everything works fine locally when I do as follows:
```
cat input | python mapper.py | sort | python reducer.py
```
However, when I run the streaming MapReduce job on AWS Elastic Mapreduce, the job does not complete successfully. The `mapper.py` runs part way through (I know this because of writing to `stderr` along ... | Your streaming process (your Python script) is terminating prematurely. This may be do to it thinking input is complete (e.g. interpreting an EOF) or a swallowed exception. Either way, Hadoop is trying to feed into via STDIN to your script, but since the application has terminated (and thus STDIN is no longer a valid F... |
OS starts killing processes when multi-threaded python process runs | 9,881,440 | 6 | 2012-03-26T23:41:17Z | 9,881,705 | 7 | 2012-03-27T00:18:15Z | [
"python",
"kill",
"pycurl",
"python-multithreading"
] | This is the strangest thing!
I have a multi-threaded client application written in Python. I'm using threading to concurrently download and process pages. I would use the cURL multi-handle except that the bottleneck is definitely the processor (not the bandwidth) in this application so it is more efficient to use a th... | You've triggered the kernel's Out Of Memory (OOM) handler; it selects which processes to kill in a complicated fashion that *tries* hard to kill as few processes as possible to make the most impact. Chrome apparently makes the most inviting process to kill under the criteria the kernel uses.
You can see a summary of t... |
Anonymous functions referencing local variables in python | 9,881,962 | 6 | 2012-03-27T00:56:28Z | 9,881,984 | 7 | 2012-03-27T00:59:45Z | [
"python",
"variables",
"callback",
"scope"
] | How can I define anonymous functions in python, where the bahaviour should depend on the value of a local variable at definiton-time, and also accept arguments
Example:
```
def callback(val1, val2):
print "{0} {1}".format(val1, val2)
i = 0
f0 = lambda x: callback(i, x)
i = 1
f1 = lambda x: callback(i, x)
f0(8) #... | ## Closures in python using [functools.partial](http://docs.python.org/library/functools.html#functools.partial)
```
from functools import partial
i = 0
f0 = partial(callback, i)
i = 1
f1 = partial(callback, i)
f0()
# 0
f1()
# 1
```
`partial` is like a lambda but wraps the value at that moment into the arg. Not eva... |
Find Out If a Function has been Called | 9,882,280 | 7 | 2012-03-27T01:42:37Z | 9,882,439 | 12 | 2012-03-27T02:06:48Z | [
"python",
"python-3.x"
] | I am programming in Python, and I am wondering if i can test if a function has been called in my code
```
def example():
pass
example()
#Pseudocode:
if example.has_been_called:
print("foo bar")
```
How would I do this? | If it's OK for the function to know its own name, you can use a function attribute:
```
def example():
example.has_been_called = True
pass
example.has_been_called = False
example()
#Actual Code!:
if example.has_been_called:
print("foo bar")
```
You could also use a decorator to set the attribute:
```
i... |
How to delete rows from a table using an SQLAlchemy query without ORM? | 9,882,358 | 7 | 2012-03-27T01:52:00Z | 9,882,897 | 19 | 2012-03-27T03:14:34Z | [
"python",
"orm",
"sqlalchemy"
] | I'm writing a quick and dirty maintenace script to delete some rows and would like to avoid having to bring my ORM classes/mappings over from the main project. I have a query that looks similar to:
```
address_table = Table('address',metadata,autoload=True)
addresses = session.query(addresses_table).filter(addresses_t... | Looking through some code where I did something similar, I believe this will do what you want.
```
d = addresses_table.delete(addresses_table.c.retired == 1)
d.execute()
```
Calling delete() on a table object gives you a sql.expression (if memory serves), that you then execute. I've assumed above that the table is bo... |
simple json dumps function with unicode | 9,883,464 | 2 | 2012-03-27T04:39:50Z | 9,883,470 | 11 | 2012-03-27T04:40:53Z | [
"python",
"unicode",
"simplejson"
] | Here is a sample run of simple json using python2.4 version
```
>>>
>>> orig='{"key1":"Val", "key2":"val2"}'
>>> origDict = simplejson.loads(orig)
>>> origDict
{'key2': 'val2', 'key1': 'Val'}
>>> origDict['key2'] = '\xe4\xbd\xa0\xe5\xa5\xbd'
>>> simplejson.dumps(origDict)
'{"key2": "\\u4f60\\u597d", "key1": "Val"}'
`... | Pass `ensure_ascii=False` and encode manually after. |
RESTful Authentication with Tornado | 9,883,833 | 5 | 2012-03-27T05:30:29Z | 9,885,111 | 9 | 2012-03-27T07:31:09Z | [
"python",
"backbone.js",
"tornado"
] | I'm trying to create a RESTful backend for a Backbone.js app in Tornado - creating the resources has been no problem and everything works as I intend. However, I've spent hours scouring the web trying to find some sort of guidance on how to properly handle authentication and session management using this setup. Note th... | Looking at the Tornado docs, it looks like you'll just need to populate the [current\_user property of the RequestHandler](http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler.get_current_user) after you've authenticated him. Then you'll be able to decorate your protected URLs with the [@authenticate... |
What exactly are Python's iterator, iterable, and iteration protocols? | 9,884,132 | 149 | 2012-03-27T06:03:37Z | 9,884,245 | 9 | 2012-03-27T06:14:51Z | [
"python",
"iterator",
"iteration"
] | What are the most basic definitions of "iterable", "iterator" and "iteration" in Python?
I've read multiple definitions but their exact meaning still won't sink in.
Can someone please help me with the basic idea? | An iterable is a object which has a `__iter__()` method. It can possibly iterated over several times, such as `list()`s and `tuple()`s.
An iterator is the object which iterates. It is returned by an `__iter__()` method, returns itself via its own `__iter__()` method and has a `next()` method (`__next__()` in 3.x).
It... |
What exactly are Python's iterator, iterable, and iteration protocols? | 9,884,132 | 149 | 2012-03-27T06:03:37Z | 9,884,259 | 193 | 2012-03-27T06:15:50Z | [
"python",
"iterator",
"iteration"
] | What are the most basic definitions of "iterable", "iterator" and "iteration" in Python?
I've read multiple definitions but their exact meaning still won't sink in.
Can someone please help me with the basic idea? | **Iteration** is a general term for taking each item of something, one after another. Any time you use a loop, explicit or implicit, to go over a group of items, that is iteration.
In Python, **iterable** and **iterator** have specific meanings.
An **iterable** is an object that has an `__iter__` method which returns... |
What exactly are Python's iterator, iterable, and iteration protocols? | 9,884,132 | 149 | 2012-03-27T06:03:37Z | 9,884,501 | 169 | 2012-03-27T06:39:31Z | [
"python",
"iterator",
"iteration"
] | What are the most basic definitions of "iterable", "iterator" and "iteration" in Python?
I've read multiple definitions but their exact meaning still won't sink in.
Can someone please help me with the basic idea? | Here's the explanation I use in teaching Python classes:
An ITERABLE is:
* anything that can be looped over (i.e. you can loop over a string or file)
* anything that can appear on the right-side of a for-loop: `for x in iterable: ...`
* anything you can call with `iter()` that will return an ITERATOR: `iter(obj)`
* a... |
What exactly are Python's iterator, iterable, and iteration protocols? | 9,884,132 | 149 | 2012-03-27T06:03:37Z | 18,744,706 | 41 | 2013-09-11T14:59:39Z | [
"python",
"iterator",
"iteration"
] | What are the most basic definitions of "iterable", "iterator" and "iteration" in Python?
I've read multiple definitions but their exact meaning still won't sink in.
Can someone please help me with the basic idea? | The above answers are great, but as most of what I've seen, don't stress the *distinction* enough for people like me.
Also, people tend to get "too Pythonic" by putting definitions like "X is an object that has `__foo__()` method" before. Such definitions are correct--they are based on duck-typing philosophy, but the ... |
Looping from 1 to infinity in Python | 9,884,213 | 18 | 2012-03-27T06:12:15Z | 9,884,244 | 43 | 2012-03-27T06:14:49Z | [
"python",
"loops"
] | In C, I would do this:
```
int i;
for (i = 0;; i++)
if (thereIsAReasonToBreak(i))
break;
```
How can I achieve something similar in Python? | Using [`count`](http://docs.python.org/library/itertools.html#itertools.count) from `itertools`
```
import itertools
for i in itertools.count():
if thereIsAReasonToBreak(i):
break
```
In Python2 `xrange()` is limited to sys.maxint, which may be enough for most practical purposes
```
import sys
for i in range(s... |
xls to csv converter | 9,884,353 | 27 | 2012-03-27T06:25:09Z | 9,884,551 | 36 | 2012-03-27T06:43:58Z | [
"python",
"excel",
"csv",
"xls",
"export-to-csv"
] | I am using win32.client in python for converting my .xlsx and .xls file into a .csv. When I execute this code it's giving an error. My code is:
```
def convertXLS2CSV(aFile):
'''converts a MS Excel file to csv w/ the same name in the same directory'''
print "------ beginning to convert XLS to CSV ------"
... | I would use xlrd - it's faster, cross platform and works directly with the file. One thing to note - it doesn't work on xlsx files - so you'd have to save your Excel file as xls. *Edit: As of version 0.8.0, `xlrd` reads both XLS and XLSX files.*
```
import xlrd
import csv
def csv_from_excel():
wb = xlrd.open_... |
xls to csv converter | 9,884,353 | 27 | 2012-03-27T06:25:09Z | 9,886,039 | 14 | 2012-03-27T08:42:30Z | [
"python",
"excel",
"csv",
"xls",
"export-to-csv"
] | I am using win32.client in python for converting my .xlsx and .xls file into a .csv. When I execute this code it's giving an error. My code is:
```
def convertXLS2CSV(aFile):
'''converts a MS Excel file to csv w/ the same name in the same directory'''
print "------ beginning to convert XLS to CSV ------"
... | I'd use [csvkit](https://github.com/onyxfish/csvkit), which uses xlrd (for xls) and openpyxl (for xlsx) to convert just about any tabular data to csv.
Once installed, with its dependencies, it's a matter of:
```
python in2csv myfile > myoutput.csv
```
It takes care of all the format detection issues, so you can pass... |
xls to csv converter | 9,884,353 | 27 | 2012-03-27T06:25:09Z | 18,837,202 | 20 | 2013-09-16T20:57:58Z | [
"python",
"excel",
"csv",
"xls",
"export-to-csv"
] | I am using win32.client in python for converting my .xlsx and .xls file into a .csv. When I execute this code it's giving an error. My code is:
```
def convertXLS2CSV(aFile):
'''converts a MS Excel file to csv w/ the same name in the same directory'''
print "------ beginning to convert XLS to CSV ------"
... | Maybe someone find this ready-to-use piece of code useful. It allows to create CSVs from all spreadsheets in Excel's workbook.

```
# -*- coding: utf-8 -*-
import xlrd
import csv
from os import sys
def csv_from_excel(excel_file):
workbook = xlrd.... |
xls to csv converter | 9,884,353 | 27 | 2012-03-27T06:25:09Z | 26,146,618 | 17 | 2014-10-01T17:01:30Z | [
"python",
"excel",
"csv",
"xls",
"export-to-csv"
] | I am using win32.client in python for converting my .xlsx and .xls file into a .csv. When I execute this code it's giving an error. My code is:
```
def convertXLS2CSV(aFile):
'''converts a MS Excel file to csv w/ the same name in the same directory'''
print "------ beginning to convert XLS to CSV ------"
... | I would use `pandas`. The computationally heavy parts are written in cython or c-extensions to speed up the process and the syntax is very clean. For example, if you want to turn "Sheet1" from the file "your\_workbook.xls" into the file "your\_csv.csv", you just use the top-level function `read_excel` and the method `t... |
In Python, if I return inside a "with" block, will the file still close? | 9,885,217 | 89 | 2012-03-27T07:37:30Z | 9,885,287 | 85 | 2012-03-27T07:42:50Z | [
"python",
"return",
"with-statement"
] | Consider the following:
```
with open(path, mode) as f:
return [line for line in f if condition]
```
Will the file be closed properly, or does using `return` somehow bypass the [context manager](https://docs.python.org/library/contextlib.html)? | Yes, it acts like the `finally` block after a `try` block, i.e. it always executes (unless the python process terminates in an unusual way of course).
It is also mentioned in one of the examples of [PEP-343](http://www.python.org/dev/peps/pep-0343/) which is the specification for the `with` statement:
```
with locked... |
In Python, if I return inside a "with" block, will the file still close? | 9,885,217 | 89 | 2012-03-27T07:37:30Z | 9,885,550 | 10 | 2012-03-27T08:05:19Z | [
"python",
"return",
"with-statement"
] | Consider the following:
```
with open(path, mode) as f:
return [line for line in f if condition]
```
Will the file be closed properly, or does using `return` somehow bypass the [context manager](https://docs.python.org/library/contextlib.html)? | Yes.
```
def example(path, mode):
with open(path, mode) as f:
return [line for line in f if condition]
```
..is pretty much equivalent to:
```
def example(path, mode):
f = open(path, mode)
try:
return [line for line in f if condition]
finally:
f.close()
```
More accurately, ... |
Indexing NumPy 2D array with another 2D array | 9,885,529 | 3 | 2012-03-27T08:03:39Z | 12,100,648 | 8 | 2012-08-23T22:04:09Z | [
"python",
"numpy",
"indexing",
"scipy"
] | I have something like
```
m = array([[1, 2],
[4, 5],
[7, 8],
[6, 2]])
```
and
```
select = array([0,1,0,0])
```
My target is
```
result = array([1, 5, 7, 6])
```
I tried [\_ix](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ix_.html) as I read at [Simplfy row AND col... | The *numpy* way to do this is by using `np.choose` or fancy indexing/take (see below):
```
m = array([[1, 2],
[4, 5],
[7, 8],
[6, 2]])
select = array([0,1,0,0])
result = np.choose(select, m.T)
```
So there is no need for python loops, or anything, with all the speed advantages numpy ... |
How I do to update data on many-to-many with WTForms and SQLAlchemy? | 9,885,693 | 6 | 2012-03-27T08:17:47Z | 13,401,070 | 11 | 2012-11-15T15:46:12Z | [
"python",
"sqlalchemy",
"flask",
"wtforms",
"flask-sqlalchemy"
] | I've a small problem on my App build with Flask Framework.
I'm trying to create a simple User + Permissions module. To archive it, I've a many-to-many relation between Users and Permissions table.
Here is my model, form and route
**Model**
```
user_perm = db.Table('user_perm',
db.Column('user_id', db.Integer, d... | ## The cause of the problem
The crux of your problem is that **SQL Alchemy is expecting the `permissions` relationship to be populated with sqlalchemy `permission` objects, not the `int`s you are passing it**.
In your view:
```
form = EditUser(request.form, obj=user)
form.permissions.choices = [(p.id, p.perm) for p... |
Python os.getenv on OSX (Django 1.4) | 9,886,178 | 6 | 2012-03-27T08:52:20Z | 9,886,343 | 13 | 2012-03-27T09:03:11Z | [
"python",
"django",
"linux",
"osx"
] | I just updated an environment to Django 1.4. On syncdb's first run I get the following error:
```
TypeError: decode() argument 1 must be string, not None
```
This error is triggered by `django/contrib/auth/management/init`:
```
try:
return getpass.getuser().decode(locale.getdefaultlocale()[1])
except (ImportErro... | The immediate resolution for this, assuming you are using bash as your shell:
`$ export LC_ALL=en_US.UTF-8`
`$ export LANG=en_US.UTF-8`
This will set your locale for that session, and syncdb will work. You can add this to your profile and make it permanent for your shells.
You can use the `locale` command to see th... |
How can I convert canvas content to an image? | 9,886,274 | 7 | 2012-03-27T08:59:02Z | 10,432,892 | 9 | 2012-05-03T13:55:26Z | [
"python",
"bitmap",
"tkinter"
] | ```
from Tkinter import *
root = Tk()
cv = Canvas(root)
cv.create_rectangle(10,10,50,50)
cv.pack()
root.mainloop()
```
I want to convert canvas content to a bitmap or other image, and then do other operations, such as rotating or scaling the image, or changing its coordinates.
Bitmaps can improve efficiency to show i... | You can either generate a postscript document (to feed into some other tool: ImageMagick, Ghostscript, etc):
```
from Tkinter import *
root = Tk()
cv = Canvas(root)
cv.create_rectangle(10,10,50,50)
cv.pack()
root.mainloop()
cv.update()
cv.postscript(file="file_name.ps", colormode='color')
root.mainloop()
```
or dra... |
Adding different sized/shaped displaced NumPy matrices | 9,886,303 | 5 | 2012-03-27T09:00:38Z | 9,886,733 | 8 | 2012-03-27T09:27:39Z | [
"python",
"numpy"
] | In short: I have two matrices (or arrays):
```
import numpy
block_1 = numpy.matrix([[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0]])
block_2 = numpy.matrix([[ 1, 1, 1],
[ 1, 1, 1],
... | An easy solution that looks like MATLAB solution is:
```
import numpy as np
block_1 = np.zeros((5,4)) #sample data 1
block_2 = np.ones((4,3)) #sample data 2
block_1[1:5,1:4] = block_1[1:5,1:4] + block_2
print(block_1)
```
---
So package it as a reusable function:
```
import numpy as np
#Usage:
# addAtPos(xycoo... |
Python: Convert unicode string to MM/DD/YYYY | 9,887,471 | 4 | 2012-03-27T10:10:46Z | 9,887,532 | 11 | 2012-03-27T10:15:08Z | [
"python",
"datetime",
"converter"
] | I have a unicode string for example **u'Mar232012'**. I want to convert it to the format MM/DD/YYYY using python in the post efficient and reliable manner. | ```
import datetime
datetime.datetime.strptime(u'Mar232012', '%b%d%Y').strftime('%m/%d/%Y')
```
prints `'03/23/2012'` |
How to change Tor identity in Python? | 9,887,505 | 15 | 2012-03-27T10:13:07Z | 9,928,803 | 16 | 2012-03-29T15:41:46Z | [
"python",
"tor"
] | I have the following script:
```
import socks
import socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
socket.socket = socks.socksocket
import urllib2
print(urllib2.urlopen("http://www.ifconfig.me/ip").read())
```
which uses tor and [SocksiPy](http://sourceforge.net/projects/socksipy/)
Now I ... | Today, I have searched a lot about this question, and finally managed to answer myself. But before I need to say that pirvoxy and tor should be configured correctly. First script, then a little bit about configuration:
```
import urllib2
from TorCtl import TorCtl
proxy_support = urllib2.ProxyHandler({"http" : "127.0.... |
How to change Tor identity in Python? | 9,887,505 | 15 | 2012-03-27T10:13:07Z | 17,111,084 | 10 | 2013-06-14T14:41:35Z | [
"python",
"tor"
] | I have the following script:
```
import socks
import socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
socket.socket = socks.socksocket
import urllib2
print(urllib2.urlopen("http://www.ifconfig.me/ip").read())
```
which uses tor and [SocksiPy](http://sourceforge.net/projects/socksipy/)
Now I ... | Another simple solution, no external libraries required, works for both IPv4 and IPv6:
```
import socket
try:
tor_c = socket.create_connection((TOR_CTRL_HOST, TOR_CTRL_PORT))
tor_c.send('AUTHENTICATE "{}"\r\nSIGNAL NEWNYM\r\n'.format(TOR_CTRL_PWD))
response = tor_c.recv(1024)
if response != '250 OK\r\... |
How to change Tor identity in Python? | 9,887,505 | 15 | 2012-03-27T10:13:07Z | 19,809,147 | 18 | 2013-11-06T10:06:49Z | [
"python",
"tor"
] | I have the following script:
```
import socks
import socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
socket.socket = socks.socksocket
import urllib2
print(urllib2.urlopen("http://www.ifconfig.me/ip").read())
```
which uses tor and [SocksiPy](http://sourceforge.net/projects/socksipy/)
Now I ... | Tor wrote a new TOR control library in Python, [stem](https://stem.torproject.org/index.html). It can be found on [PyPI](https://pypi.python.org/pypi/stem/1.1.0). They provide some nice tutorials how to work with it, [one](https://stem.torproject.org/faq.html#how-do-i-request-a-new-identity-from-tor) of them explains h... |
How does operator binding work in this Python example? | 9,889,260 | 8 | 2012-03-27T12:08:41Z | 9,889,345 | 9 | 2012-03-27T12:14:28Z | [
"python",
"operator-keyword",
"operator-precedence"
] | I've recently stumbled over this expression:
```
True == False in (False,)
```
It evaluates to `False`, but I don't understand why.
`True == False` is `False` and `False in (False,)` is `True`, so both (to me) plausible possibilities
```
True == (False in (False,))
```
and
```
(True == False) in (False,)
```
eval... | I believe this is a corner case of Python's comparison-operator chaining. It gets expanded to
```
(True == False) and (False in (False,))
```
which evaluates to `False`.
This behavior was intended to match conventional math notation (e.g. `x == y == z` meaning that all three are equal, or `0 <= x < 10` meaning `x` ... |
Regular expression to return all characters between two special characters | 9,889,635 | 11 | 2012-03-27T12:36:38Z | 9,889,668 | 10 | 2012-03-27T12:38:26Z | [
"python",
"regex",
"parsing"
] | How would I go about using regx to return all characters between two brackets.
Here is an example:
```
foobar['infoNeededHere']ddd
needs to return infoNeededHere
```
I found a regex to do it between curly brackets but all attempts at making it work with square brackets have failed. Here is that regex: `(?<={)[^}]*(?=... | [`^.*\['(.*)'\].*$`](http://rubular.com/r/bgixv2J6yF) will match a line and capture what you want in a group.
You have to escape the `[` and `]` with `\`
The documentation at the rubular.com [proof](http://rubular.com/r/bgixv2J6yF) link will explain how the expression is formed. |
Regular expression to return all characters between two special characters | 9,889,635 | 11 | 2012-03-27T12:36:38Z | 9,891,784 | 13 | 2012-03-27T14:41:12Z | [
"python",
"regex",
"parsing"
] | How would I go about using regx to return all characters between two brackets.
Here is an example:
```
foobar['infoNeededHere']ddd
needs to return infoNeededHere
```
I found a regex to do it between curly brackets but all attempts at making it work with square brackets have failed. Here is that regex: `(?<={)[^}]*(?=... | If you're new to **REG**(gular) **EX**(pressions) you learn about them at [Python Docs](http://docs.python.org/library/re.html). Or, if you want a gentler introduction, you can check out the [HOWTO](http://docs.python.org/howto/regex.html). They use Perl-style syntax.
## Regex
The expression that you need is `.*?\[(.... |
How to use regex with optional characters in python? | 9,891,814 | 14 | 2012-03-27T14:43:19Z | 9,891,850 | 24 | 2012-03-27T14:45:13Z | [
"python",
"regex"
] | Say I have a string
```
"3434.35353"
```
and another string
```
"3593"
```
How do I make a single regular expression that is able to match both without me having to set the pattern to something else if the other fails? I know `\d+` would match the `3593`, but it would not do anything for the `3434.35353`, but (`\d+... | You can put a `?` after a group of characters to make it optional.
You want a dot followed by any number of digits `\.\d+`, grouped together `(\.\d+)`, optionally `(\.\d+)?`. Stick that in your pattern:
```
import re
print re.match("(\d+(\.\d+)?)", "3434.35353").group(1)
```
```
3434.35353
```
```
print re.match("(... |
Association_proxy with 0-n relations | 9,892,046 | 4 | 2012-03-27T14:54:53Z | 9,904,511 | 7 | 2012-03-28T09:20:29Z | [
"python",
"sqlalchemy"
] | I got an error trying to use an association\_proxy.
I got mapped class A, with 0-n relation to B. B has 0-n relation to C. The association\_proxy is to access A from C.
```
class C(base):
a = association_proxy('b', 'a')
```
It works without problem if it *really* has a relation to B. But if this relation is `nul... | I believe from reading <http://docs.sqlalchemy.org/en/latest/orm/extensions/associationproxy.html#querying-with-association-proxies> that the case is handled when you are issuing a query (ie the SQL uses an EXISTS clause to catch the non existing B issue).
In order to get the accessor shortcut to work, you need to use... |
How to get Python m2Crypto to work with virtualenv? | 9,892,606 | 6 | 2012-03-27T15:25:39Z | 10,389,472 | 12 | 2012-04-30T19:33:46Z | [
"python",
"virtualenv",
"m2crypto"
] | I'm trying to install M2Crypto so that I can generate pkey in my web app. My hosting requirements dictate that I must use pip to install any dependencies. Installing m2crypto at the system level is not an option for me. I'm using Mint 12 in development and will be deploying to heroku.
**error: command 'swig' failed wi... | Your problem has nothing to do with virtualenv. You just don't have swig installed.
Install swig using your distribution's package manager and try reinstalling M2Crypto in the virtualenv. |
Is it possible to use bpython as a full debugger? | 9,892,751 | 16 | 2012-03-27T15:33:26Z | 9,951,954 | 20 | 2012-03-31T00:29:38Z | [
"python",
"debugging",
"bpython"
] | I would like to use the [bpython](http://bpython-interpreter.org/) interpreter for debugging.
My question is similar to "[Is it possible to go into ipython from code?](http://stackoverflow.com/questions/1126930/is-it-possible-to-go-into-ipython-from-code)", which asks about ipython.
If you use `ipdb.set_trace()` you g... | **Yes,** using [this wrapper](https://hg.bpython-interpreter.org/bpython/src/5c1f2b5cf054/bpdb/debugger.py), which you can also access by adding the statement `import bpdb` to your code. Add `bpdb.set_trace()` wherever you want to break, and from the `pdb` interpreter enter "B" to jump into a `bpython` session with eve... |
Is it possible to use bpython as a full debugger? | 9,892,751 | 16 | 2012-03-27T15:33:26Z | 9,970,154 | 9 | 2012-04-02T02:12:51Z | [
"python",
"debugging",
"bpython"
] | I would like to use the [bpython](http://bpython-interpreter.org/) interpreter for debugging.
My question is similar to "[Is it possible to go into ipython from code?](http://stackoverflow.com/questions/1126930/is-it-possible-to-go-into-ipython-from-code)", which asks about ipython.
If you use `ipdb.set_trace()` you g... | If you are looking for a cooler looking debugger that does completion and syntax highlighting you might want to take a look at pdb++. <http://pypi.python.org/pypi/pdbpp/>

It's a drop in replacement for pdb. So you can continue to use
```
import pdb... |
How to use PyPy on Windows? | 9,893,317 | 3 | 2012-03-27T16:04:05Z | 9,895,099 | 7 | 2012-03-27T18:07:21Z | [
"python",
"pypy"
] | I was wondering how to use PyPy 1.8 on Windows XP 32-bit. I downloaded the zip file off the website and installed it into a My Documents file. Initially, I thought it was similar to psyco in that I had to "import psyco," but I found that PyPy.exe acted like the Python command line instead.
I tried dragging my scripts ... | Maybe I'm not following what you're trying to do, but isn't it just a question of opening a command prompt and running pypy myscriptname ? Assuming you've got all the paths for PyPy and your script straight, anyway (e.g. your script's in PyPy's folder). |
Python Matplotlib Colormap | 9,893,440 | 4 | 2012-03-27T16:10:38Z | 9,905,922 | 9 | 2012-03-28T10:48:24Z | [
"python",
"matplotlib"
] | I use the colormap "jet" to plot my graphics. But, I would like to have the lower values in white color and this colormap goes from blue to red colors. I also don't want to use another colormap because I need this range of colors...
I tried to make my colormap to get the same as "jet" with a range of values in white, b... | Probably there should be an easiest solution, but the way I figured out is by creating your own matplotlib.colors.LinearSegmentedColormap, based on the "jet" one.
(The lowest level of your colormap is defined in the first line of each tuple of red, green, and blue, so that's where you start editting. I add one extra t... |
Python Matplotlib Colormap | 9,893,440 | 4 | 2012-03-27T16:10:38Z | 20,524,448 | 7 | 2013-12-11T16:22:00Z | [
"python",
"matplotlib"
] | I use the colormap "jet" to plot my graphics. But, I would like to have the lower values in white color and this colormap goes from blue to red colors. I also don't want to use another colormap because I need this range of colors...
I tried to make my colormap to get the same as "jet" with a range of values in white, b... | There is another way to do the same without defining a new colobar.
You can use the cmap.set\_under method that defines the color to be used for all values below a given threshold. The threshold is defined during the pcolormesh :
```
from matplotlib.pyplot import *
import numpy as np
mycmap = cm.get_cmap('jet')
mycma... |
How do I use cx_freeze? | 9,895,636 | 22 | 2012-03-27T18:44:33Z | 9,920,229 | 9 | 2012-03-29T06:35:53Z | [
"python",
"cx-freeze"
] | I've created my setup.py file as instructed but I don't actually.. understand what to do next. Typing "python setup.py build" into the command line just gets a syntax error.
So, what do I do?
setup.py:
```
from cx_Freeze import setup, Executable
setup(
name = "On Dijkstra's Algorithm",
version = "3.1",
... | I'm really not sure what you're doing to get that error, it looks like you're trying to run cx\_Freeze on its own, without arguments. So here is a short step-by-step guide on how to do it in windows (Your screenshot looks rather like the windows command line, so I'm assuming that's your platform)
1. Write your setup.p... |
How do I use cx_freeze? | 9,895,636 | 22 | 2012-03-27T18:44:33Z | 10,036,845 | 7 | 2012-04-05T22:24:01Z | [
"python",
"cx-freeze"
] | I've created my setup.py file as instructed but I don't actually.. understand what to do next. Typing "python setup.py build" into the command line just gets a syntax error.
So, what do I do?
setup.py:
```
from cx_Freeze import setup, Executable
setup(
name = "On Dijkstra's Algorithm",
version = "3.1",
... | I ran into a similar issue. I solved it by setting the Executable options in a variable and then simply calling the variable. Below is a sample setup.py that I use:
```
from cx_Freeze import setup, Executable
import sys
productName = "ProductName"
if 'bdist_msi' in sys.argv:
sys.argv += ['--initial-target-dir', '... |
How do I use cx_freeze? | 9,895,636 | 22 | 2012-03-27T18:44:33Z | 13,570,653 | 19 | 2012-11-26T18:11:55Z | [
"python",
"cx-freeze"
] | I've created my setup.py file as instructed but I don't actually.. understand what to do next. Typing "python setup.py build" into the command line just gets a syntax error.
So, what do I do?
setup.py:
```
from cx_Freeze import setup, Executable
setup(
name = "On Dijkstra's Algorithm",
version = "3.1",
... | * Add `import sys` as the new topline
* You misspelled "executables" on the last line.
* Remove `script =` on last line.
The code should now look like:
```
import sys
from cx_Freeze import setup, Executable
setup(
name = "On Dijkstra's Algorithm",
version = "3.1",
description = "A Dijkstra's Algorithm he... |
Why does naming a file 'con.txt' in windows make Python write to console, not file? | 9,895,686 | 7 | 2012-03-27T18:48:03Z | 9,895,737 | 10 | 2012-03-27T18:50:55Z | [
"python"
] | I need help debugging some odd file behavior in Python. Take the following script (`write_con.py`):
```
f=open('con.txt','w')
f.write('hi')
```
In Linux, this creates a file called `con.txt` with the contents `hi`. In Windows this writes `hi` to the console and does not create a file. I've tried this with Python 2.5.... | [Legacy](http://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words). In DOS, writing to a file called "CON" writes it to the console instead; Windows continues this tradition. |
Why does naming a file 'con.txt' in windows make Python write to console, not file? | 9,895,686 | 7 | 2012-03-27T18:48:03Z | 9,895,837 | 7 | 2012-03-27T18:56:09Z | [
"python"
] | I need help debugging some odd file behavior in Python. Take the following script (`write_con.py`):
```
f=open('con.txt','w')
f.write('hi')
```
In Linux, this creates a file called `con.txt` with the contents `hi`. In Windows this writes `hi` to the console and does not create a file. I've tried this with Python 2.5.... | You have to check the [Wikipedia Filename page](http://en.wikipedia.org/wiki/Filename). It has a table containing the reserved characters for quite a lot of file systems.
*In Windows and DOS utilities, some words might also be reserved and can not be used as filenames. For example, DOS Device file:*
***CON**, PRN, AU... |
Getting FFProbe Information With Python | 9,896,644 | 2 | 2012-03-27T19:49:22Z | 9,896,732 | 7 | 2012-03-27T19:56:39Z | [
"python",
"ffmpeg",
"ffprobe"
] | I've been attempting to figure this out for forever now (I'm new to programming) and I can't figure it out.
I'm attempting to build a script that will test the file, and give me output from which I can get information like "Audio Format" that I can then put into the filename. However, I can't even get the script to re... | Few problems in your code
1. args list to Popen has last argument as `-i filename` which is a syntax error use `'-i '+filename` instead
2. `shell=True` is usually not needed and is unnecessary burden.
Other than that it seems to be working, are you not seeing output after fixing #1 ?
Edit: Looks like you are having ... |
Recursive functions and lists appending/extending | 9,896,951 | 3 | 2012-03-27T20:13:41Z | 9,897,033 | 15 | 2012-03-27T20:18:31Z | [
"python",
"list",
"function",
"recursion",
"extend"
] | This is a very simple code in place of a bigger problem, but I'm hoping I can tackle it in chunks. I'll start with my first problem.
```
def testrecurse(z,target):
x=[]
if z<target:
z*=2
x.append(z)
x.extend(testrecurse(z,target))
return x
```
This is a test function to help my bra... | How about this?
```
def testrecurse(z, target):
if z >= target:
return []
return [z] + testrecurse(2 * z, target)
```
Example:
```
>>> testrecurse(1, 1000)
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
```
Note that it does not include `1024` any more. If you want this, change the third line to
```
... |
Why can't I add a tuple to a list with the '+' operator in Python? | 9,897,070 | 3 | 2012-03-27T20:20:35Z | 9,897,113 | 9 | 2012-03-27T20:23:22Z | [
"python",
"operator-overloading",
"language-design",
"internals"
] | Python not support adding a tuple to a list:
```
>>> [1,2,3] + (4,5,6)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "tuple") to list
```
What are the disadvantages for providing such a support in the language? Note that I would expect this to be sy... | This is not supported because the `+` operator is supposed to be symmetric. What return type would you expect? The Python Zen includes the rule
```
In the face of ambiguity, refuse the temptation to guess.
```
The following works, though:
```
a = [1, 2, 3]
a += (4, 5, 6)
```
There is no ambiguity what type to use h... |
Pickle alternatives | 9,897,345 | 8 | 2012-03-27T20:38:41Z | 12,095,050 | 8 | 2012-08-23T15:23:57Z | [
"python",
"serialization"
] | I am trying to serialize a large (~10\*\*6 rows, each with ~20 values) list, to be used later by myself (so pickle's lack of safety isn't a concern).
Each row of the list is a tuple of values, derived from some SQL database. So far, I have seen datetime.datetime, strings, integers, and NoneType, but I might eventually... | Pickle is actually quite fast so long as you aren't using the (default) ASCII protocol. Just make sure to dump using `protocol=pickle.HIGHEST_PROTOCOL`. |
How do you change the code example font size in LaTeX PDF output with sphinx? | 9,899,283 | 7 | 2012-03-27T23:43:19Z | 9,960,329 | 7 | 2012-03-31T22:40:24Z | [
"python",
"documentation",
"latex",
"python-sphinx"
] | I find the default code example font in the PDF generated by sphinx to be far too large.
I've tried getting my hands dirty in the generated .tex file inserting font size commands like `\tiny` above the code blocks, but it just makes the line above the code block tiny, not the code block itself.
I'm not sure what else... | I worked it out. Pygments uses a `\begin{Verbatim}` block to denote code snippets, which uses the `fancyvrb` package. The [documentation I found (warning: PDF)](ftp://tug.ctan.org/ctan/macros/latex/contrib/fancyvrb/fancyvrb.pdf) mentions a `formatcom` option for the verbatim block.
Pygments' [latex writer source](http... |
Going from a for loop to a list comprehension | 9,899,395 | 4 | 2012-03-28T00:00:38Z | 9,899,415 | 7 | 2012-03-28T00:03:44Z | [
"python",
"nested-lists"
] | I have a program that displays and inventory report and i was just wondering how I could put the following into a list comprehension instead of a for-loop...I'm kind of a noob at all this python jargon but from what i know is that anything that is in the form of a for-loop can also be expressed as a list comprehension.... | Your code is essentially equivalent to
```
TotSize[:] = map(sum, data)
```
This will sum over all of `data`, not only the first `row` rows and the firs `col` cols. It will also resize `TotSize` to match the number of rows `data` has (assuming `TotSize` is a list).
I wonder why you are passing in the list that should... |
PySide: Removing a widget from a layout | 9,899,409 | 15 | 2012-03-28T00:02:49Z | 9,899,475 | 25 | 2012-03-28T00:11:53Z | [
"python",
"qt",
"pyside",
"qlayout"
] | I'm trying to remove a Qt widget from a layout in a PySide application.
Here is a minimal example. It is a widget with 5 buttons in it, and the middle one is supposed to remove itself when clicked:
```
import sys
from PySide import QtGui
app = QtGui.QApplication(sys.argv)
widget = QtGui.QWidget()
layout = QtGui.QVBo... | Super simple fix:
```
def deleteButton():
b = layout.takeAt(2)
buttons.pop(2)
b.widget().deleteLater()
```
You first have to make sure you are addressing the actual button and not the QWidgetItem that is returned from the layout, and then call deleteLater() which will tell Qt to destroy the widget after t... |
re.findall regex hangs or very slow | 9,899,554 | 3 | 2012-03-28T00:25:46Z | 9,899,607 | 9 | 2012-03-28T00:33:26Z | [
"python",
"regex"
] | My input file is a large txt file with concatenated texts I got from an open text library. I am now trying to extract only the content of the book itself and filter out other stuff such as disclaimers etc. So I have around 100 documents in my large text file (around 50 mb).
I then have identified the start and end mar... | You are correct in thinking that using the sequence `.*`, which appears more than once, is causing problems. The issue is that the solver is trying many possible combinations of `.*`, leading to a result known as [catastrophic backtracking](http://www.regular-expressions.info/catastrophic.html).
The usual solution is ... |
Python - What's the use of if True:? | 9,902,350 | 2 | 2012-03-28T06:40:36Z | 9,902,397 | 8 | 2012-03-28T06:43:51Z | [
"python"
] | I just came accross the following code in an existent project, which I'm working on:
```
if True:
x = 5
y = 6
return x+y
else:
return 'Something
```
Inside the if True are lots of conditions and some will also return the function already.
Why would somebody write in that way? The code contained some o... | It might be a remnant of debugging or refactoring. It may be that instead of `True`, there was orginally a condition or variable there but it has now been replaced by `True`. The developer perhaps left it there without refactoring or cleaning it up all the way.
If you're free to edit the code as you wish and you're su... |
How to sum column values with python | 9,903,772 | 3 | 2012-03-28T08:29:45Z | 9,903,940 | 7 | 2012-03-28T08:42:03Z | [
"python",
"sum"
] | I have a rowset that looks like this:
```
defaultdict(<type 'dict'>,
{
u'row1': {u'column1': 33, u'column2': 55, u'column3': 23},
u'row2': {u'column1': 32, u'column2': 32, u'column3': 17},
u'row3': {u'column1': 31, u'column2': 87, u'column3': 18}
})
```
I want to be able to easily get the sum of column1, ... | ```
>>> from collections import defaultdict
>>> x = defaultdict(dict,
{
u'row1': {u'column1': 33, u'column2': 55, u'column3': 23},
u'row2': {u'column1': 32, u'column2': 32, u'column3': 17},
u'row3': {u'column1': 31, u'column2': 87, u'column3': 18}
})
>>> sums = defaultdict(int)
>>> ... |
Python variable value in quotes | 9,905,241 | 2 | 2012-03-28T10:04:05Z | 9,905,294 | 7 | 2012-03-28T10:07:54Z | [
"python",
"string",
"variables",
"variable-assignment",
"quotes"
] | I am editing a script, which authenticates to openstack keystone to get a token. The API-Call works but I want to use variables instead of the direct values to make it more readable und reusable. But the problem is that it is necessary for the values to be in quotes (") and I can't figure out how to do that. I found so... | The easiest solution for this particular case is to define a Python dictionary first, and then use `json.dumps()` to convert it to JSON:
```
osuser = "nodermatt"
ospassword = "feelfree"
ostenant = "4"
d = {"auth":
{"passwordCredentials": {"username": osuser, "password": ospassword},
"tenantId": oste... |
string to list conversion in python | 9,905,471 | 4 | 2012-03-28T10:19:00Z | 9,905,575 | 8 | 2012-03-28T10:25:24Z | [
"python",
"string",
"list"
] | I have a string.
```
s = '1989, 1990'
```
I want to convert that to list using python & i want output as,
```
s = ['1989', '1990']
```
Is there any fastest one liner way for the same? | Use **list comprehensions**:
```
s = '1989, 1990'
[x.strip() for x in s.split(',')]
```
Short and easy.
*Additionally, this has been [asked](http://stackoverflow.com/a/4071407/589206) many times!* |
Confusion about __get__ and __call__ in python | 9,905,720 | 10 | 2012-03-28T10:34:43Z | 9,905,864 | 8 | 2012-03-28T10:44:46Z | [
"python"
] | See the simple example below:
```
class Celsius(object):
def __init__(self, value=0.0):
self.value = float(value)
def __get__(self, instance, owner):
return self.value
def __set__(self, instance, value):
self.value = float(value)
def __call__(self):
print('__call__ ... | The differences lie in the fact the the first attribute is a *class* attribute while the second is an *instance* attribute.
As per [the documentation](http://docs.python.org/reference/datamodel.html#implementing-descriptors), If an object that implements at least the first of the `Descriptor` methods (`__get__`, `__se... |
Python Does Not Read Entire Text File | 9,905,874 | 8 | 2012-03-28T10:45:17Z | 9,906,259 | 17 | 2012-03-28T11:09:16Z | [
"python",
"text",
"filesize",
"file-io"
] | I'm running into a problem that I haven't seen anyone on StackOverflow encounter or even google for that matter.
My main goal is to be able to replace occurences of a string in the file with another string. Is there a way there a way to be able to acess all of the lines in the file.
The problem is that when I try to ... | Try:
```
f = open("filename.txt", "rb")
```
On Windows, `rb` means open file in binary mode. According to the docs, text mode vs. binary mode only has an impact on end-of-line characters. But (if I remember correctly) I believe opening files in text mode on Windows also does something with EOF (hex 1A).
You can also... |
python: decorate a class by defining the decorator as a class | 9,906,144 | 13 | 2012-03-28T11:02:10Z | 9,910,180 | 12 | 2012-03-28T14:56:21Z | [
"python",
"decorator"
] | Could someone please show a simple example of this? I'm trying to achieve what has been implemented in Python 2.6 using [PEP 3129](http://www.python.org/dev/peps/pep-3129/) except using classes not functions as Bruce Eckel explains [here](http://www.artima.com/weblogs/viewpost.jsp?thread=240845)
The following works:
... | If you want to overwrite `new_method()`, just do it:
```
class Decorator(object):
def __init__(self, arg):
self.arg = arg
def __call__(self, cls):
class Wrapped(cls):
classattr = self.arg
def new_method(self, value):
return value * 2
return Wrappe... |
Change Jupyter QtConsole settings | 9,906,938 | 24 | 2012-03-28T11:52:44Z | 18,904,744 | 24 | 2013-09-19T20:55:47Z | [
"python",
"jupyter"
] | It is possible to make persistent changes to settings for default settings on Windows 7?
I would like to change font-size and shell size. | Instructions on configuring the ipython command line application are [here](http://ipython.org/ipython-doc/dev/config/ipython.html) on IPython's web site. Step-by-step instructions for configuring the font size in particular:
First, create the IPython profile. Simply running IPython or IPython's QtConsole should do th... |
python: find only common key-value pairs of several dicts: dict intersection | 9,906,944 | 9 | 2012-03-28T11:53:11Z | 9,907,020 | 18 | 2012-03-28T11:58:43Z | [
"python"
] | I have 0 or more dicts in a list:
```
>>> dicts = [dict(a=3, b=89, d=2), dict(a=3, b=89, c=99), dict(a=3, b=42, c=33)]
```
I want to create a new dict that contains only keys that are in **all** the above dicts, and only if the values are all the same:
```
>>> dict_intersection(*dicts)
{"a": 3}
```
I feel that ther... | ```
>>> dict(set.intersection(*(set(d.iteritems()) for d in dicts)))
{'a': 3}
```
Note: This solution requires the dictionary values to be hashable, in addition to the keys. |
Locking sqlite file on NFS filesystem possible? | 9,907,429 | 8 | 2012-03-28T12:24:41Z | 9,962,003 | 18 | 2012-04-01T04:56:52Z | [
"python",
"sqlite",
"sqlite3",
"locking",
"nfs"
] | Let's say there are two python scripts that want to write data to the same table which is stored in an SQLite file using the `sqlite3` module. The SQLite-file is stored on an NFS filesystem. In the [SQLite-FAQ](http://www.sqlite.org/faq.html#q5) I read:
> SQLite uses reader/writer locks to control access to the databa... | Do not use SQLite with NFS. It is as simple as that. NFS semantics are different than regular filesystems and are looser. You will eventually get corruption. Every now and then someone on the SQLite-users mailing list posts with their "workarounds". They never work although they appear to in the short term. |
Python fcntl does not lock as expected | 9,907,616 | 13 | 2012-03-28T12:36:27Z | 9,909,028 | 7 | 2012-03-28T13:56:56Z | [
"python",
"fcntl"
] | On a Debian-based OS (Ubuntu, Debian Squeeze), I'm using Python (2.7, 3.2) fcntl to lock a file. As I understand from what I read, fnctl.flock locks a file in a way, that an exception will be thrown if another client wants to lock the same file.
I built a little example, which I would expect to throw an excepiton, sin... | Got it. The error in my script is that I create a new file descriptor on each call:
```
fcntl.flock(open('/tmp/locktest', 'r'), fcntl.LOCK_EX | fcntl.LOCK_NB)
(...)
fcntl.flock(open('/tmp/locktest', 'r'), fcntl.LOCK_EX | fcntl.LOCK_NB)
```
Instead, I have to assign the file object to a variable and than try to lock:
... |
Python fcntl does not lock as expected | 9,907,616 | 13 | 2012-03-28T12:36:27Z | 15,922,532 | 9 | 2013-04-10T09:52:38Z | [
"python",
"fcntl"
] | On a Debian-based OS (Ubuntu, Debian Squeeze), I'm using Python (2.7, 3.2) fcntl to lock a file. As I understand from what I read, fnctl.flock locks a file in a way, that an exception will be thrown if another client wants to lock the same file.
I built a little example, which I would expect to throw an excepiton, sin... | Old post, but if anyone else finds it, I get this behaviour:
```
>>> fcntl.flock(open('test.flock', 'w'), fcntl.LOCK_EX)
>>> fcntl.flock(open('test.flock', 'w'), fcntl.LOCK_EX | fcntl.LOCK_NB)
# That didn't throw an exception
>>> f = open('test.flock', 'w')
>>> fcntl.flock(f, fcntl.LOCK_EX)
>>> fcntl.flock(open('test... |
Python fcntl does not lock as expected | 9,907,616 | 13 | 2012-03-28T12:36:27Z | 17,375,816 | 9 | 2013-06-29T01:30:05Z | [
"python",
"fcntl"
] | On a Debian-based OS (Ubuntu, Debian Squeeze), I'm using Python (2.7, 3.2) fcntl to lock a file. As I understand from what I read, fnctl.flock locks a file in a way, that an exception will be thrown if another client wants to lock the same file.
I built a little example, which I would expect to throw an excepiton, sin... | I hade the same problem... I've solved it holding the opened file in a separate variable:
Won't work:
```
fcntl.lockf(open('/tmp/locktest', 'w'), fcntl.LOCK_EX | fcntl.LOCK_NB)
```
Works:
```
lockfile = open('/tmp/locktest', 'w')
fcntl.lockf(lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
```
I think that the first doesn... |
How to sort list of date object? | 9,907,670 | 3 | 2012-03-28T12:39:17Z | 9,907,876 | 9 | 2012-03-28T12:50:25Z | [
"python"
] | How to sort list of date object ?
For example I have unsorted list of date objects. How to get max/min value from this list ? | Use the list [sort method](http://docs.python.org/tutorial/datastructures.html#more-on-lists):
```
In [1]: from datetime import date, timedelta
In [2]: a=[date.today(), date.today() + timedelta(days=1), date.today() - timedelta(days=1)]
In [3]: a
Out[3]:
[datetime.date(2012, 3, 28),
datetime.date(2012, 3, 29),
da... |
Weak References in python | 9,908,013 | 20 | 2012-03-28T12:57:47Z | 9,908,142 | 7 | 2012-03-28T13:05:36Z | [
"python",
"python-2.7"
] | I have been trying to understand how python weak reference list's/dictionary's work and have been reading the documentation for it as well, however i cannot seem to figure out how they work and what they can be used for. Could anyone give me a basic example of what they do/explanation of how they work? It would be very... | The point is that they allow references to be retained to objects without preventing them from being garbage collected.
The two main reasons why you would want this are where you do your own periodic resource management, e.g. closing files, but because the time between such passes may be long, the garbage collector ma... |
Weak References in python | 9,908,013 | 20 | 2012-03-28T12:57:47Z | 9,908,216 | 32 | 2012-03-28T13:09:56Z | [
"python",
"python-2.7"
] | I have been trying to understand how python weak reference list's/dictionary's work and have been reading the documentation for it as well, however i cannot seem to figure out how they work and what they can be used for. Could anyone give me a basic example of what they do/explanation of how they work? It would be very... | # Theory
The reference count usually works as such: each time you create a reference to an object, it is increased by one, and whenever you delete a reference, it is decreased by one.
Weak references allow you to create references to an object that will not increase the reference count.
The reference count is used b... |
Django django-extensions commands unavailable ( graph_models ) | 9,908,270 | 11 | 2012-03-28T13:12:47Z | 9,908,599 | 21 | 2012-03-28T13:31:35Z | [
"python",
"django",
"graphviz",
"pygraphviz"
] | I'm trying to install django-extensions + graphviz + pygraph but i can't.
I have done the following steps ( under Ubuntu ):
```
sudo apt-get install graphviz libgraphviz-dev graphviz-dev python-pygraphviz
```
in the project virtualenv (running python 2.7.2+):
```
source <path to virtualenv>/bin/activate
pip install ... | Run this in `manage.py shell`:
```
from django.conf import settings; 'django_extensions' in settings.INSTALLED_APPS
```
If it doesn't return True, then it means that you didn't add 'django\_extensions' properly in INSTALLED\_APPS, and that would be the only reason why Django doesn't find the command. |
Sharing a result queue among several processes | 9,908,781 | 32 | 2012-03-28T13:42:59Z | 9,928,191 | 48 | 2012-03-29T15:08:42Z | [
"python",
"multiprocessing"
] | The documentation for the `multiprocessing` module shows how to pass a queue to a process started with `multiprocessing.Process`. But how can I share a queue with asynchronous worker processes started with `apply_async`? I don't need dynamic joining or anything else, just a way for the workers to (repeatedly) report th... | Try using [multiprocessing.Manager](http://docs.python.org/library/multiprocessing.html#sharing-state-between-processes) to manage your queue and to also make it accessible to different workers.
```
import multiprocessing
def worker(name, que):
que.put("%d is done" % name)
if __name__ == '__main__':
pool = mu... |
Django - Form not valid but no error | 9,909,513 | 7 | 2012-03-28T14:22:08Z | 9,909,564 | 12 | 2012-03-28T14:25:07Z | [
"python",
"django",
"django-forms"
] | Model:
```
class Session(models.Model):
tutor = models.ForeignKey(User)
start_time = models.DateTimeField()
end_time = models.DateTimeField()
def __unicode__(self):
return u'%s - %s' % (self.tutor, self.start_time)
```
Form:
```
class SessionForm(forms.ModelForm):
class Meta:
mode... | You have not passed any data to the form, so it is not valid. The instance argument is not used to set the form data, just the initial data. |
What is a reference cycle in python? | 9,910,774 | 15 | 2012-03-28T15:26:46Z | 9,910,838 | 9 | 2012-03-28T15:29:56Z | [
"python",
"garbage-collection",
"reference-counting",
"cyclic-reference"
] | I have looked in the official documentation for python, but i cannot seem to find what a reference cycle is. Could anyone please clarify what it is for me, as i am trying to understand the GC module. Thank you in advance for your replies. | This is a reference cycle:
```
l = []
l.append(l)
```
The first element of `l`, i.e. `l[0]`, is now a cyclic reference to `l` itself. |
What is a reference cycle in python? | 9,910,774 | 15 | 2012-03-28T15:26:46Z | 9,910,848 | 13 | 2012-03-28T15:30:27Z | [
"python",
"garbage-collection",
"reference-counting",
"cyclic-reference"
] | I have looked in the official documentation for python, but i cannot seem to find what a reference cycle is. Could anyone please clarify what it is for me, as i am trying to understand the GC module. Thank you in advance for your replies. | A reference cycle simply means one or more objects referencing each other, such that if you drew it out on paper with arrows representing the dependencies you would see a cycle.
The (almost) simplest reference cycle is having two objects `a` and `b` that refer to each other:
```
a.other = b
b.some_attr = a
```
Naive... |
Python - number of digits in exponent | 9,910,972 | 12 | 2012-03-28T15:37:30Z | 9,911,741 | 13 | 2012-03-28T16:22:07Z | [
"python",
"floating-point",
"exponent"
] | Is it possible to set the number of digits to be used for printing the exponent of a floating-point number? I want to set it to 3.
Currently,
```
f = 0.0000870927939438012
>>> "%.14e"%f
'8.70927939438012e-05'
>>> "%0.14e"%f
'8.709279e-005'
```
What I want to print is:
`'8.70927939438012e-005'` | There is a no way to control that, best way is to write a function for this e.g.
```
def eformat(f, prec, exp_digits):
s = "%.*e"%(prec, f)
mantissa, exp = s.split('e')
# add 1 to digits as 1 is taken by sign +/-
return "%se%+0*d"%(mantissa, exp_digits+1, int(exp))
print eformat(0.0000870927939438012,... |
App Engine NDB alternative for db.StringListProperty | 9,911,006 | 4 | 2012-03-28T15:39:09Z | 9,911,514 | 15 | 2012-03-28T16:07:08Z | [
"python",
"google-app-engine",
"gae-datastore"
] | I have a need to store an ordered list of strings and am trying to start using ndb. Previously I used a db.StringListProperty. That's not available in ndb though, so what's the recommended alternative? Looking at the [ndb types](https://developers.google.com/appengine/docs/python/ndb/properties#types), I'm thinking I n... | ```
ndb.StringProperty(repeated=True)
``` |
libmysqlclient.18.dylib image not found when using MySQL from Django on OS X | 9,911,195 | 17 | 2012-03-28T15:49:14Z | 9,913,418 | 34 | 2012-03-28T18:20:47Z | [
"python",
"mysql",
"django"
] | I'm starting down the path of learning Python/Django and have hit my first snag. When attempting to set my database in `settings.py`, the internal server fails with:
```
File "/Library/Python/2.7/site-packages/django/db/backends/mysql/base.py", line 16, in <module>
raise ImproperlyConfigured("Error loading MySQLdb mod... | From your comments, it appears that the `libmysqlclient` dylib was installed with a non-absolute library name path. That's contrary to standard practice on OS X which is different from most other Unix-y systems in this respect. You should be able to *permanently* fix the problem (at least until your next upgrade) by mo... |
python parallel map (multiprocessing.Pool.map) with global data | 9,911,819 | 9 | 2012-03-28T16:27:32Z | 9,912,396 | 15 | 2012-03-28T17:07:15Z | [
"python",
"parallel-processing"
] | I'm trying to call a function on multiple processes. The obvious solution is python's `multiprocessing` module. The problem is that the function has side effects. It creates a temporary file and registers that file to be deleted on exit using the `atexit.register` and a global list. The following should demonstrate the... | You need that list (glob\_data) to be backed by shared memory, Multiprocessing's Manager gives you just that:
```
import multiprocessing as multi
from multiprocessing import Manager
manager = Manager()
glob_data= manager.list([])
def func(a):
glob_data.append(a)
map(func,range(10))
print glob_data #[0,1,2,3,4... |
How do I let my matplotlib plot go beyond the axes? | 9,912,206 | 7 | 2012-03-28T16:53:49Z | 9,914,119 | 19 | 2012-03-28T19:10:43Z | [
"python",
"matplotlib",
"z-order",
"axes"
] | I have to translate an image plotting script from matlab to matplotlib/pylab, and I'm trying to achieve the same effect as the matlab image below:

As you can see, the z order of the plots seem to be higher than the z order of the grid, so the markers... | To get the marker to show beyond the axes you can turn the clipping off. This can be done using the keyword argument in the `plot` command `clip_on=False`.
For example:
```
import matplotlib.pyplot as plt
plt.plot(range(5), range(5), 'ro', markersize=20, clip_on=False, zorder=100)
plt.show()
```
![enter image descri... |
Is it possible to import a compiled python file? | 9,913,193 | 4 | 2012-03-28T18:02:32Z | 9,913,278 | 7 | 2012-03-28T18:09:16Z | [
"python",
"import",
"module",
"compiled"
] | I can't seem to figure out how to import a compiled .pyc module into my code so I can use it within my main script. Is this even possible? | If there is foo.pyc, import foo will automatically use foo.pyc whether foo.py exists or not
(If foo.py is newer, it will be used)
<http://docs.python.org/tutorial/modules.html> |
Convert NumPy array to cvMat cv2 | 9,913,392 | 6 | 2012-03-28T18:17:47Z | 9,913,733 | 10 | 2012-03-28T18:41:58Z | [
"python",
"opencv",
"numpy",
"matplotlib"
] | With [OpenCV](http://en.wikipedia.org/wiki/OpenCV) 2, [IPython](http://en.wikipedia.org/wiki/IPython) now uses NumPy arrays by default.
```
cvimage = cv2.imread("image.png") #using OpenCV 2
type(cvimage)
Out: numpy.ndarray #dtype is uint8
pltimage = plt.imread("image.png") #using Matplotlib
type(pltimage)
Out: nump... | The function has the following docstring: `imshow(winname, mat) -> None`.
You can see the doc string by typing `cv2.imshow.__doc__` in the interpreter.
Try `cv2.imshow('Image', cvimage)`. |
Convert NumPy array to cvMat cv2 | 9,913,392 | 6 | 2012-03-28T18:17:47Z | 19,341,140 | 9 | 2013-10-13T02:13:34Z | [
"python",
"opencv",
"numpy",
"matplotlib"
] | With [OpenCV](http://en.wikipedia.org/wiki/OpenCV) 2, [IPython](http://en.wikipedia.org/wiki/IPython) now uses NumPy arrays by default.
```
cvimage = cv2.imread("image.png") #using OpenCV 2
type(cvimage)
Out: numpy.ndarray #dtype is uint8
pltimage = plt.imread("image.png") #using Matplotlib
type(pltimage)
Out: nump... | The question technically asks how to convert a NumPy Array (analogous to CV2 array) into a Mat object (CV). For anyone who is interested, this can be done by:
```
mat_array = cv.fromarray(numpy_array)
```
where mat\_array is a Mat object, and numpy\_array is a NumPy array or image.
I would suggest staying away from o... |
Given a list of Tuples, return a new list of the first values of the tuples | 9,913,790 | 3 | 2012-03-28T18:46:09Z | 9,913,809 | 7 | 2012-03-28T18:47:41Z | [
"python"
] | I have a list of tuples and I want a new list consisting of the first values of the tuples.
I.e. if the list is:
[(1,5),(4,10),(100,3),(4,8)]
I want to create the following list:
[1,4,100,4]
The following code works:
```
a = [(1,5),(4,10),(100,3),(4,8)]
l = []
for i in range(len(a)):
l.append(a[i][0])
```
Bu... | I'd usually use a list comprehension:
```
>>> a = [(1,5),(4,10),(100,3),(4,8)]
>>> [x for x, y in a]
[1, 4, 100, 4]
``` |
How do I check if a user left the 'input' or 'raw_input' prompt empty? | 9,914,061 | 4 | 2012-03-28T19:06:45Z | 9,914,098 | 10 | 2012-03-28T19:09:43Z | [
"python",
"python-2.x"
] | How do I check if input has been entered?
For example:
```
x = str(raw_input('Message>> '))
```
or
```
y = input('Number>> ')
``` | You know if nothing was entered for the second one because it will raise a `SyntaxError`. You can catch the error like this:
```
try:
y=input('Number>> ')
except SyntaxError:
y = None
```
then test
```
# not just 'if y:' because 0 evaluates to False!
if y is None:
```
or, preferably, use `raw_input`:
```
t... |
Pythonic and efficient way of defining multiple regexes for use over many iterations | 9,914,552 | 5 | 2012-03-28T19:43:47Z | 9,914,817 | 7 | 2012-03-28T20:04:02Z | [
"python",
"regex",
"performance"
] | I am presently writing a Python script to process some 10,000 or so input documents. Based on the script's progress output I notice that the first 400+ documents get processed really fast and then the script slows down although the input documents all are approximately the same size.
I am assuming this may have to do ... | The re module caches compiled regex patterns. The cache is cleared when it reaches a size of re.\_MAXCACHE which by default is 100. (Since you have 10 functions with 10-20 regexes each (i.e. 100-200 regexes), your observed slow-down makes sense with the clearing of the cache.)
If you are okay with changing private var... |
How can I ignore ValueError when I try to remove an element from a list? | 9,915,339 | 14 | 2012-03-28T20:42:54Z | 9,915,349 | 13 | 2012-03-28T20:43:39Z | [
"python",
"list",
"error-handling",
"elements"
] | How can I ignore the "not in list" error message if I call `a.remove(x)` when `x` is not present in list `a`?
This is my situation:
```
>>> a = range(10)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a.remove(10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in ... | A good and thread-safe way to do this is to just try it and ignore the exception:
```
try:
a.remove(10)
except ValueError:
pass # do nothing!
``` |
How can I ignore ValueError when I try to remove an element from a list? | 9,915,339 | 14 | 2012-03-28T20:42:54Z | 9,915,560 | 10 | 2012-03-28T20:59:43Z | [
"python",
"list",
"error-handling",
"elements"
] | How can I ignore the "not in list" error message if I call `a.remove(x)` when `x` is not present in list `a`?
This is my situation:
```
>>> a = range(10)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a.remove(10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in ... | I'd personally consider using a `set` instead of a `list` as long as the order of your elements isn't necessarily important. Then you can use the discard method:
```
>>> S = set(range(10))
>>> S
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> S.remove(10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module... |
Can I access specific key values in dictionary from django template? | 9,915,370 | 3 | 2012-03-28T20:45:25Z | 9,915,404 | 8 | 2012-03-28T20:47:52Z | [
"python",
"django",
"django-templates"
] | Is there any get() function for this instead?
```
{% for key, value in choices.items %}
<li>{{key}} - {{value}}</li>
{% endfor %}
```
From python I have the get() function to get values from a specific key. But I couldn't find a corresponding way to do that with django template tags. So I wonder is it possible?
I ... | You can use `{{ choices.items.key }}` to access a specific dict element.
There is no reason to care about whitespace in the HTML code though; the typical end-user has no real business in reading it and if he's curious he an always use a DOM viewer or run it through a HTML beautifier. |
What is a frozen Python module? | 9,916,432 | 10 | 2012-03-28T22:14:40Z | 9,916,610 | 7 | 2012-03-28T22:31:49Z | [
"python",
"module",
"imp"
] | The Python help of the module `imp` is talking about a frozen module. What is it?
<http://docs.python.org/library/imp.html#imp.PY_FROZEN> | This link explains what the Python Freeze utility is in detail:
<http://wiki.python.org/moin/Freeze>
In a nutshell, it creates a portable version of a python script that carries its own built in interpreter (basically like a binary executable), so that you can run it on machines without python. |
A "round"ed number multiplied by 0.01 results in x.y00000000000001 and not x.y? | 9,916,613 | 3 | 2012-03-28T22:32:06Z | 9,916,640 | 7 | 2012-03-28T22:34:21Z | [
"python",
"openerp"
] | The reason I'm asking this is because there is a validation in [OpenERP](http://www.openerp.com/) that it's driving me crazy:
```
>>> round(1.2 / 0.01) * 0.01
1.2
>>> round(12.2 / 0.01) * 0.01
12.200000000000001
>>> round(122.2 / 0.01) * 0.01
122.2
>>> round(1222.2 / 0.01) * 0.01
1222.2
```
As you can see, the second... | This has in fact nothing to with `round`, you can witness the exact same problem if you just do `1220 * 0.01`:
```
>>> 1220*0.01
12.200000000000001
```
What you see here is a standard floating point issue.
You might want to read what Wikipedia has to say about [floating point accuracy problems](http://en.wikipedia.o... |
Importing modules in Python - best practice | 9,916,878 | 33 | 2012-03-28T22:58:43Z | 9,916,900 | 27 | 2012-03-28T23:02:02Z | [
"python",
"coding-style",
"workflow"
] | I am new to Python as I want to expand skills that I learned using R.
In R I tend to load a bunch of libraries, sometimes resulting in function name conflicts.
What is best practice in Python. I have seen some specific variations that I do not see a difference between
`import pandas`, `from pandas import *`, and `fro... | `import pandas` imports the pandas module under the pandas namespace, so you would need to call objects within pandas using `pandas.foo`.
`from pandas import *` imports all objects from the pandas module into your current namespace, so you would call objects within pandas using only `foo`. Keep in mind this could have... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.