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 |
|---|---|---|---|---|---|---|---|---|---|
Generator destruction when the break statement occurs | 9,026,065 | 3 | 2012-01-26T22:03:33Z | 9,026,138 | 9 | 2012-01-26T22:08:46Z | [
"python",
"generator"
] | I want to know when the Obj.**del()** method
is going to be called.
```
def my_integers():
Obj = ExitObj()
i = 0
while(1):
yield i
i += 1
def test_fun():
for i in my_integers():
if i > 3:
break
anything_function()
test_fun()
```
I did a test and Obj appeared to be ... | > I want to know when the `Obj.__del__()` method is going to be called.
You can't. It might never. Finalizers in Python (or in any environment with an automated garbage collector scheme, really) are not guaranteed to run at all, and should only be used for last-resort cleanup. If you want predictable lifetime manageme... |
Python lightweight database wrapper for SQLite | 9,026,069 | 23 | 2012-01-26T22:03:48Z | 9,026,145 | 12 | 2012-01-26T22:09:05Z | [
"python",
"sqlite"
] | Is there a lightweight database wrapper in Python that I can use for SQLite. I would like something like Django's ORM, but that I can just point to a database file and it'll make the required API for me (i.e handle all the CRUD). | SQLAlchemy may be what you are looking for.
<http://www.sqlalchemy.org/> |
Python lightweight database wrapper for SQLite | 9,026,069 | 23 | 2012-01-26T22:03:48Z | 9,027,726 | 30 | 2012-01-27T00:59:47Z | [
"python",
"sqlite"
] | Is there a lightweight database wrapper in Python that I can use for SQLite. I would like something like Django's ORM, but that I can just point to a database file and it'll make the required API for me (i.e handle all the CRUD). | Yeah, SQLAlchemy is great, but there are also other options. One of them is Peewee.
Very lightweight and it may fits perfectly with what you are looking for.
<https://github.com/coleifer/peewee> |
argparse argument order | 9,027,028 | 13 | 2012-01-26T23:28:31Z | 9,028,031 | 10 | 2012-01-27T01:50:01Z | [
"python",
"arguments",
"order",
"argparse",
"kwargs"
] | I have a little problem.
I use `argparse` to parse my arguments, and it's working very well.
To have the args, I do :
```
p_args = parser.parse_args(argv)
args = dict(p_args._get_kwargs())
```
But the problem with `p_args` is that I don't know how to get these arguments ordered by their position in the command line... | To keep arguments ordered, I use a custom action like this:
```
import argparse
class CustomAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
if not 'ordered_args' in namespace:
setattr(namespace, 'ordered_args', [])
previous = namespace.ordered... |
lxml.etree fromsting() and tostring() are not returning the same data | 9,027,081 | 2 | 2012-01-26T23:34:30Z | 9,045,141 | 8 | 2012-01-28T12:11:37Z | [
"python",
"lxml",
"tostring"
] | I'm learning lxml (after using ElementTree) and I'm baffled why .fromstring and .tostring do not appear to be reversible. Here's my example:
```
import lxml.etree as ET
f = open('somefile.xml','r')
data = f.read()
tree_in = ET.fromstring(data)
tree_out = ET.tostring(tree_in)
f2 = open('samefile.xml','w')
f2.write(tree... | The "missing the end of the file at some arbirtrary point" problem is hard to explain without a complete reproducible example.
But I suspect that what you refer to as "a bunch of crap" are [CDATA sections](http://en.wikipedia.org/wiki/CDATA#CDATA_sections_in_XML). You have several of those in your example (which is no... |
Plot 4D graph in python2.7 | 9,027,266 | 2 | 2012-01-26T23:55:06Z | 9,029,645 | 7 | 2012-01-27T06:15:02Z | [
"python",
"numpy",
"plot",
"matplotlib",
"scipy"
] | I want to plot red, blue and green colors on the three axis and an array which stores the value corresoding to each combination of color in python2.7....when i run my program either becomes unresponsive for 24 hours or it gives me memory error. Here is my code:
```
import pylab
import math
from itertools import produc... | First, your program is slow because you're doing a lot of unnecessary work building `N`. You're building a 70 MB list a few bytes at a time (256\*256\*256=16,777,216 appends!). A better (faster, memory efficient) way to build `p` is to use numpy's array broadcasting, and then reuse `p` to make `N`:
```
import numpy as... |
how to link multiple python scripts | 9,028,036 | 8 | 2012-01-27T01:50:39Z | 9,028,063 | 21 | 2012-01-27T01:54:34Z | [
"python",
"function"
] | i am new to python and i would like to seperate my functions into different files like i do with c++ (a driver file and a file for different categories of functions that i end up linking together upon compilation).
suppose i want to create a simple 'driver' file which launches the main program and a 'function' file wh... | You can `import` modules. Simply create different python files and import them at the start of your script.
For example I got this `function.py` file :
```
def func(a, b):
return a+b
```
And this `main.py` file:
```
import function
if __name__ == "__main__":
ans = function.func(2, 3)
print ans
```
And... |
Django add optional arguments to decorator | 9,030,255 | 2 | 2012-01-27T07:37:52Z | 9,030,358 | 7 | 2012-01-27T07:51:39Z | [
"python",
"django",
"decorator"
] | I have the following decorator and view which works fine.
**Decorator**
```
def event_admin_only(func):
"""
Checks if the current role for the user is an Event Admin or not
"""
def decorator(request, *args, **kwargs):
event = get_object_or_404(Event, slug=kwargs['event_slug'])
allowed... | You need to wrap the decorator function creation in another function:
```
def the_decorator(arg1, arg2):
def _method_wrapper(view_method):
def _arguments_wrapper(request, *args, **kwargs) :
"""
Wrapper with arguments to invoke the method
"""
#do something ... |
Hide all warnings in ipython | 9,031,783 | 54 | 2012-01-27T10:18:38Z | 9,031,848 | 103 | 2012-01-27T10:23:42Z | [
"python",
"warnings",
"ipython"
] | I need to produce a screencast of an ipython session, and to avoid confusing viewers, I want to disable all warnings emitted by `warnings.warn` calls from different packages. Is there a way to configure the ipythonrc file to automatically disable all such warnings? | I eventually figured it out. Place:
```
import warnings
warnings.filterwarnings('ignore')
```
inside `~/.ipython/profile_default/startup/disable-warnings.py`. I'm leaving this question and answer for the record in case anyone else comes across the same issue. |
Amazon Web Services: python or ruby? | 9,032,716 | 13 | 2012-01-27T11:36:16Z | 9,032,972 | 18 | 2012-01-27T12:00:02Z | [
"python",
"ruby",
"amazon-web-services"
] | I'm about to start a fairly complex project involving AWS, particularly EC2, S3 and Dynamo, and try to decide which language to use. I know python and ruby, no java/net/php.
<http://aws.amazon.com/ruby> | <http://aws.amazon.com/python>
From my understanding, there's no official SDK for python, is [boto](http://code.g... | > From my understanding, there's no official SDK for python, is boto an
> adequate replacement?
Absolutely, [boto](http://code.google.com/p/boto/) could have been considered the de facto Python SDK for AWS for quite some time already, and recently its author, Mitch Garnaat, has fortunately joined the AWS team as well,... |
Django Management Command ImportError | 9,032,858 | 3 | 2012-01-27T11:50:02Z | 9,033,140 | 8 | 2012-01-27T12:17:30Z | [
"python",
"django",
"importerror",
"pythonpath"
] | I have problem with imported module into my `qsl/management/commands/<customcommand>.py` file.
in fact, my app structure is :
```
qsl/management/commands/ : dir for my management commands
qsl/management/jobs/ : dir for my mangement jobs
```
jobs are python classes that contains the job i want to be done in the coresp... | Make sure that all the folders have a `__init__.py` in them so that they can be imported as modules.
The structure is described here: <https://docs.djangoproject.com/en/dev/howto/custom-management-commands/>
Something like this for your structure:
```
qsl/
__init__.py
models.py
management/
__init_... |
How to check task status in Celery? | 9,034,091 | 46 | 2012-01-27T13:42:19Z | 9,034,974 | 47 | 2012-01-27T14:41:36Z | [
"python",
"web-services",
"celery",
"django-celery"
] | How does one check whether a task is running in celery (specifically, I'm using celery-django)?
I've read the documentation, and I've googled, but I can't see a call like:
```
my_example_task.state() == RUNNING
```
My use-case is that I have an external (java) service for transcoding. When I send a document to be tr... | Return the task\_id (which is given from .delay()) and ask the celery instance afterwards about the state:
```
x = method.delay(1,2)
print x.task_id
```
When asking, get a new AsyncResult using this task\_id:
```
from celery.result import AsyncResult
res = AsyncResult("your-task-id")
res.ready()
``` |
How to check task status in Celery? | 9,034,091 | 46 | 2012-01-27T13:42:19Z | 9,046,208 | 38 | 2012-01-28T14:59:57Z | [
"python",
"web-services",
"celery",
"django-celery"
] | How does one check whether a task is running in celery (specifically, I'm using celery-django)?
I've read the documentation, and I've googled, but I can't see a call like:
```
my_example_task.state() == RUNNING
```
My use-case is that I have an external (java) service for transcoding. When I send a document to be tr... | Every `Task` object has a `.request` property, which contains it `AsyncRequest` object. Accordingly, the following line gives the state of a Task `task`:
```
task.AsyncResult(task.request.id).state
``` |
How to check task status in Celery? | 9,034,091 | 46 | 2012-01-27T13:42:19Z | 27,751,833 | 8 | 2015-01-03T04:47:54Z | [
"python",
"web-services",
"celery",
"django-celery"
] | How does one check whether a task is running in celery (specifically, I'm using celery-django)?
I've read the documentation, and I've googled, but I can't see a call like:
```
my_example_task.state() == RUNNING
```
My use-case is that I have an external (java) service for transcoding. When I send a document to be tr... | You can also create custom states and update it's value duting task execution.
This example is from docs:
```
@app.task(bind=True)
def upload_files(self, filenames):
for i, file in enumerate(filenames):
if not self.request.called_directly:
self.update_state(state='PROGRESS',
met... |
Initialize many string variables | 9,034,707 | 4 | 2012-01-27T14:25:17Z | 9,034,755 | 10 | 2012-01-27T14:28:09Z | [
"python",
"variable-assignment"
] | I'm initializing a lot of string variables as follows:
`a, b, c, d, e, f, g, h = "", "", "", "", "", "", "", ""`
You can see that this doesn't look very nice (morever the variables have longer names). Is there some more compact shortcut? | Definitely more compact:
```
a=b=c=d=e=f=g=h=""
``` |
Incorrect user for supervisor'd celeryd | 9,034,709 | 7 | 2012-01-27T14:25:20Z | 9,626,834 | 9 | 2012-03-08T23:42:16Z | [
"python",
"ubuntu",
"celery",
"supervisord"
] | I have some periodic tasks that I run with celery (daemonized by supervisord), but after trying to create a directory in the home dir for the user i setup for the supervisor'd process I got a "permission denied" error. After looking at the `os.environ` dict in a running celery task I noticed that the `USER` var is set ... | I believe this is caused by the fact that you didn't set the HOME and USER environment variables. This is necessary when using the "user=" option if your subprocess relies on those being set.
After supervisord documentation on [Subprocess Environment](http://supervisord.org/subprocess.html#subprocess-environment):
> ... |
Python - Access object attributes as in a dictionary | 9,035,479 | 4 | 2012-01-27T15:12:45Z | 9,035,508 | 16 | 2012-01-27T15:14:40Z | [
"python",
"object",
"dictionary"
] | ```
>>> my_object.name = 'stuff'
>>> my_str = 'name'
>>> my_object[my_str] # won't work because it's not a dictionary :)
```
How can I access to the fields of `my_object` defined on `my_str` ? | ```
getattr(my_object, my_str)
```
[More on getattr.](http://effbot.org/zone/python-getattr.htm) |
Library for gradient boosting tree | 9,035,754 | 15 | 2012-01-27T15:30:55Z | 10,566,620 | 12 | 2012-05-12T19:11:22Z | [
"python",
"c",
"machine-learning"
] | Do you know of a good library for gradient boosting tree machine learning?
preferably:
* with good algorithms such as AdaBoost, TreeBoost, AnyBoost, LogitBoost, etc
* with configurable weak classifiers
* capable of both classification and prediction (regression)
* with all kinds of allowed signals: numbers, categorie... | If you're looking for a python version, the latest release of [scikit-learn](http://scikit-learn.org/stable/) features gradient boosted regression trees for classification and regression ([docs](http://scikit-learn.org/stable/modules/ensemble.html#gradient-boosting)).
It is similar to R's gbm package - gbm is faster f... |
Is there a way to access an iteration-counter in Python's for loop? | 9,035,863 | 3 | 2012-01-27T15:37:32Z | 9,035,900 | 17 | 2012-01-27T15:39:20Z | [
"python",
"foreach"
] | Is there a way to access an iteration-counter in Python's for loop?
I usually use my own variable and increase it in any loop. Is there a more pythonic way? | Use [`enumerate`](http://docs.python.org/library/functions.html#enumerate):
```
sequence = [1, 45, 65, 7]
for i, val in enumerate(sequence):
print i, val
```
Output:
```
0 1
1 45
2 65
3 7
``` |
Python command line parameters | 9,036,013 | 25 | 2012-01-27T15:47:25Z | 9,036,042 | 8 | 2012-01-27T15:49:18Z | [
"python",
"command-line",
"command-line-arguments"
] | I am just starting with python so I am struggling with a quite simple example. Basically I want pass the name of an executable plus its input via the command line arguments, e.g.:
```
python myprogram refprogram.exe refinput.txt
```
That means when executing `myprogram`, it executes `refprogram.exe` and passes to it ... | `sys.argv` is a list, and is indexed using square brackets, e.g. `sys.argv[1]`. You may want to check `len(sys.argv)` before indexing it as well.
Also, if you wanted to pass parameters to `os.system()`, you might want something like `os.system(' '.join(sys.argv[1:]))`, but this won't work for arguments with spaces. Yo... |
Python command line parameters | 9,036,013 | 25 | 2012-01-27T15:47:25Z | 9,036,107 | 28 | 2012-01-27T15:52:55Z | [
"python",
"command-line",
"command-line-arguments"
] | I am just starting with python so I am struggling with a quite simple example. Basically I want pass the name of an executable plus its input via the command line arguments, e.g.:
```
python myprogram refprogram.exe refinput.txt
```
That means when executing `myprogram`, it executes `refprogram.exe` and passes to it ... | A far, far better way to do this is with the [argparse library](http://docs.python.org/dev/library/argparse.html). The [envoy wrapper](https://github.com/kennethreitz/envoy) library makes [subprocess](http://docs.python.org/library/subprocess.html) easier to work with as well.
A simple example:
```
import argparse
im... |
Python command line parameters | 9,036,013 | 25 | 2012-01-27T15:47:25Z | 9,036,113 | 60 | 2012-01-27T15:53:10Z | [
"python",
"command-line",
"command-line-arguments"
] | I am just starting with python so I am struggling with a quite simple example. Basically I want pass the name of an executable plus its input via the command line arguments, e.g.:
```
python myprogram refprogram.exe refinput.txt
```
That means when executing `myprogram`, it executes `refprogram.exe` and passes to it ... | This line
```
res = os.system(sys.argv(1)) sys.argv(2)
```
Is wrong in a couple of ways.
First, sys.argv is a list, so you use square brackets to access its contents:
```
sys.argv[1]
sys.argv[2]
```
Second, you close out your parentheses on `os.system` too soon, and `sys.argv(2)` is left hanging off of the end of ... |
Python: Histogram with area normalized to something other than 1 | 9,036,298 | 7 | 2012-01-27T16:02:55Z | 9,036,546 | 10 | 2012-01-27T16:19:53Z | [
"python",
"matplotlib",
"histogram",
"area"
] | Is there a way to tell matplotlib to "normalize" a histogram such that its area equals a specified value (other than 1)?
The option "normed = 0" in
```
n, bins, patches = plt.hist(x, 50, normed=0, histtype='stepfilled')
```
just brings it back to a frequency distribution. | Just calculate it and normalize it to any value you'd like, then use `bar` to plot the histogram.
On a side note, this will normalize things such that the *area* of all the bars is `normed_value`. The raw sum will *not* be `normed_value` (though it's easy to have that be the case, if you'd like).
E.g.
```
import num... |
Python: Histogram with area normalized to something other than 1 | 9,036,298 | 7 | 2012-01-27T16:02:55Z | 9,038,087 | 7 | 2012-01-27T18:17:00Z | [
"python",
"matplotlib",
"histogram",
"area"
] | Is there a way to tell matplotlib to "normalize" a histogram such that its area equals a specified value (other than 1)?
The option "normed = 0" in
```
n, bins, patches = plt.hist(x, 50, normed=0, histtype='stepfilled')
```
just brings it back to a frequency distribution. | You can pass a `weights` argument to `hist` instead of using `normed`. For example, if your bins cover the interval `[minval, maxval]`, you have `n` bins, and you want to normalize the area to `A`, then I think
```
weights = np.empty_like(x)
weights.fill(A * n / (maxval-minval) / x.size)
plt.hist(x, bins=n, range=(min... |
Get Monday and Sunday and last year's Monday and Sunday, same week | 9,036,885 | 3 | 2012-01-27T16:43:08Z | 9,036,993 | 7 | 2012-01-27T16:50:07Z | [
"python",
"date"
] | Given datetime.datetime.now(), how do I get this week's Monday - Sunday and then the same Monday - Sunday for last year, considering leap years?
One idea I had was to get the timedelta for -365 days and then find the nearest Monday or Sunday. I'm sure there is a better way.
Edit: I don't mind using datetuil, if there... | If using dateutil is not a problem, just use it :)
The [relativedelta](http://labix.org/python-dateutil#head-ba5ffd4df8111d1b83fc194b97ebecf837add454) is the object you need
Here you will be able to substract one year to the current date.
```
NOW = datetime.now()
last_monday = NOW+relativedelta(years=-1, weekday=MO)
... |
Making Python scripts run on Windows without specifying ".py" extension | 9,037,346 | 15 | 2012-01-27T17:17:39Z | 9,037,618 | 23 | 2012-01-27T17:40:59Z | [
"python",
"windows",
"windows-7"
] | I want to able to open a command prompt at the folder which contains a python script and just type in the script name without the .py and watch it run.
Following the various tips on google to do this, I do:
1. Add the python.exe to my path
2. Add .py to PATHEXT
3. Try to open the .py file in windows explored. When pr... | Add .PY to PATHEXT as noted before
Then do:
```
assoc .py=Python.File
ftype Python.File=c:\Python27\python.exe "%1" %*
```
Adding python to the path isn't necessary to execute the script in a command prompt or double clicking in Explorer, only if you want to start an interactive python session or running the script ... |
Python NameError: global name 'any' is not defined | 9,037,821 | 3 | 2012-01-27T17:57:19Z | 9,037,983 | 9 | 2012-01-27T18:09:59Z | [
"python",
"any"
] | I am getting the following error on my production server:
```
Traceback (most recent call last):
File "/usr/lib/python2.4/site-packages/django/core/handlers/base.py", line 89, in get_response
response = middleware_method(request)
File "myproject/middleware.py", line 31, in process_request
if not any(m.match(path) f... | You are actually running on Python 2.4, which doesn't have an `any` builtin.
If you need to define your own `any`, it's easy:
```
try:
any
except NameError:
def any(s):
for v in s:
if v:
return True
return False
``` |
Writing a help for python script | 9,037,828 | 9 | 2012-01-27T17:58:03Z | 9,037,852 | 16 | 2012-01-27T17:59:57Z | [
"python"
] | I am trying to make my python script very user friendly, so I like to write some sort of help for it. What is your advise for this? I could just put in some logic that if the user passed help as a paramater to the script, they get help. Is there a best practise or convention for this? | Use [argparse](http://docs.python.org/library/argparse.html#module-argparse).
For example, with **test.py**:
```
import argparse
parser=argparse.ArgumentParser(
description='''My Description. And what a lovely description it is. ''',
epilog="""All's well that ends well.""")
parser.add_argument('--foo', type=... |
python Pool with worker Processes | 9,038,711 | 22 | 2012-01-27T19:10:38Z | 9,039,979 | 38 | 2012-01-27T20:59:41Z | [
"python",
"multiprocessing"
] | I am trying to use a worker Pool in python using Process objects. Each worker (a Process) does some initialization (takes a non-trivial amount of time), gets passed a series of jobs (ideally using `map()`), and returns something. No communication is necessary beyond that. However, I can't seem to figure out how to use ... | I would suggest that you use a Queue for this.
```
class Worker(Process):
def __init__(self, queue):
super(Worker, self).__init__()
self.queue= queue
def run(self):
print 'Worker started'
# do some initialization here
print 'Computing things!'
for data in iter(... |
Name of a function returning a generator | 9,039,265 | 9 | 2012-01-27T19:56:29Z | 9,039,331 | 13 | 2012-01-27T20:01:13Z | [
"python",
"naming-conventions"
] | How do you name a function that returns a generator (that is, uses `yield foo` instead of `return foo`)?
* It's definitely not `getFoo()` because it does not return a value of Foo.
* It's probably not `foos()` because I'd rather have an easy-to-distinguish prefix.
* It's probably not exactly `listFoo()` because it doe... | I think `foo` or `foos` are possibilities. Or, to mimic Python2 dicts' `iteritems`, you could use `iterfoo`. |
getting arguments from command line python | 9,039,320 | 2 | 2012-01-27T20:00:26Z | 9,039,366 | 9 | 2012-01-27T20:04:40Z | [
"python"
] | I am trying to get three arguments from command line:
```
-o (for outputfile) -k (number of clusters) -l (data to be clustered)
```
So i wrote this.
```
def get_input():
print 'ARGV :', sys.argv[1:]
options, remainder = getopt.getopt(sys.argv[1:], 'o:v:k:l', ['output=',
... | `getopt` is a rather old module. If you have Python2.7, use [argparse](http://docs.python.org/library/argparse.html#module-argparse).
If you have a slightly older version of Python >= 2.3, you can still [install argparse](http://pypi.python.org/pypi/argparse):
With
```
import argparse
parser=argparse.ArgumentParser()... |
Why I can not split by space? | 9,039,335 | 2 | 2012-01-27T20:01:34Z | 9,039,493 | 7 | 2012-01-27T20:16:42Z | [
"python"
] | Here is the string:
```
u'\u041a\u0440\u0430\u0441\u0438\u043b\u044c\u043d\u0438\u043a\u043e\u0432 \u0421\u0435\u0440\u0433\u0435\u0439 \u0410\u043b\u0435\u043a\u0441\u0430\u043d\u0434\u0440\u043e\u0432\u0438\u0447'
```
if I try to `.split()` that, it doesn't work - just one part is returned. What can be wrong here?
... | Ah. See, the key was in information that you didn't post until requested. Your string isn't what it looks like:
```
[u'\u041a\u0440\u0430\u0441\u0438\u043b\u044c\u043d\u0438\u043a\u043e\u0432 \u0421\u0435\u0440\u0433\u0435\u0439 \u0410\u043b\u0435\u043a\u0441\u0430\u043d\u0434\u0440\u043e\u0432\u0438\u0447']... |
Finding the average of a list | 9,039,961 | 163 | 2012-01-27T20:58:18Z | 9,039,992 | 222 | 2012-01-27T21:00:36Z | [
"python",
"list",
"lambda",
"average",
"reduce"
] | I have to find the average of a list in Python. This is my code so far
```
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print reduce(lambda x, y: x + y, l)
```
I've got it so it adds together the values in the list, but I don't know how to make it divide into them? | If your reduce is already returning your sum, then all you have left to do is divide.
```
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print reduce(lambda x, y: x + y, l) / len(l)
```
though `sum(l)/len(l)` would be simpler, as you wouldn't need a lambda.
If you want a more exact float result instead of an int then just use... |
Finding the average of a list | 9,039,961 | 163 | 2012-01-27T20:58:18Z | 9,040,000 | 255 | 2012-01-27T21:01:18Z | [
"python",
"list",
"lambda",
"average",
"reduce"
] | I have to find the average of a list in Python. This is my code so far
```
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print reduce(lambda x, y: x + y, l)
```
I've got it so it adds together the values in the list, but I don't know how to make it divide into them? | ```
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
sum(l) / float(len(l))
``` |
Finding the average of a list | 9,039,961 | 163 | 2012-01-27T20:58:18Z | 9,040,008 | 33 | 2012-01-27T21:02:23Z | [
"python",
"list",
"lambda",
"average",
"reduce"
] | I have to find the average of a list in Python. This is my code so far
```
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print reduce(lambda x, y: x + y, l)
```
I've got it so it adds together the values in the list, but I don't know how to make it divide into them? | Why would you use `reduce()` for this when Python has a perfectly cromulent `sum()` function?
```
print sum(l) / float(len(l))
```
(The `float()` is necessary to force Python to do a floating-point division.) |
Finding the average of a list | 9,039,961 | 163 | 2012-01-27T20:58:18Z | 9,040,210 | 7 | 2012-01-27T21:17:32Z | [
"python",
"list",
"lambda",
"average",
"reduce"
] | I have to find the average of a list in Python. This is my code so far
```
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print reduce(lambda x, y: x + y, l)
```
I've got it so it adds together the values in the list, but I don't know how to make it divide into them? | `sum(l) / float(len(l))` is the right answer, but just for completeness you can compute an average with a single reduce:
```
>>> reduce(lambda x, y: x + y / float(len(l)), l, 0)
20.111111111111114
```
Note that this can result in a slight rounding error:
```
>>> sum(l) / float(len(l))
20.111111111111111
``` |
Finding the average of a list | 9,039,961 | 163 | 2012-01-27T20:58:18Z | 9,042,800 | 127 | 2012-01-28T03:59:51Z | [
"python",
"list",
"lambda",
"average",
"reduce"
] | I have to find the average of a list in Python. This is my code so far
```
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print reduce(lambda x, y: x + y, l)
```
I've got it so it adds together the values in the list, but I don't know how to make it divide into them? | Or you could use [numpy.mean](http://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html):
```
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
import numpy as np
print np.mean(l)
``` |
Finding the average of a list | 9,039,961 | 163 | 2012-01-27T20:58:18Z | 21,071,982 | 77 | 2014-01-12T06:34:01Z | [
"python",
"list",
"lambda",
"average",
"reduce"
] | I have to find the average of a list in Python. This is my code so far
```
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print reduce(lambda x, y: x + y, l)
```
I've got it so it adds together the values in the list, but I don't know how to make it divide into them? | A [statistics](http://docs.python.org/dev/library/statistics.html#module-statistics) module has been [added to python 3.4](http://docs.python.org/dev/whatsnew/3.4.html#statistics). It has a function to calculate the average called [mean](http://docs.python.org/dev/library/statistics.html#statistics.mean). An example wi... |
Finding the average of a list | 9,039,961 | 163 | 2012-01-27T20:58:18Z | 21,600,945 | 8 | 2014-02-06T10:58:22Z | [
"python",
"list",
"lambda",
"average",
"reduce"
] | I have to find the average of a list in Python. This is my code so far
```
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print reduce(lambda x, y: x + y, l)
```
I've got it so it adds together the values in the list, but I don't know how to make it divide into them? | Instead of casting to float, you can add 0.0 to the sum:
```
def avg(l):
return sum(l, 0.0) / len(l)
``` |
How can I implement a C++ class in Python, to be called by C++? | 9,040,669 | 32 | 2012-01-27T22:03:02Z | 9,040,943 | 10 | 2012-01-27T22:32:26Z | [
"c++",
"python",
"swig",
"boost-python"
] | I have a class interface written in C++. I have a few classes that implement this interface also written in C++. These are called in the context of a larger C++ program, which essentially implements "main". I want to be able to write implementations of this interface in Python, and allow them to be used in the context ... | Quoting <http://wiki.python.org/moin/boost.python/Inheritance>
"Boost.Python also allows us to represent C++ inheritance relationships so that wrapped derived classes may be passed where values, pointers, or references to a base class are expected as arguments."
There are examples of virtual functions so that solves ... |
How can I implement a C++ class in Python, to be called by C++? | 9,040,669 | 32 | 2012-01-27T22:03:02Z | 9,042,139 | 34 | 2012-01-28T01:18:18Z | [
"c++",
"python",
"swig",
"boost-python"
] | I have a class interface written in C++. I have a few classes that implement this interface also written in C++. These are called in the context of a larger C++ program, which essentially implements "main". I want to be able to write implementations of this interface in Python, and allow them to be used in the context ... | There's two parts to this answer. First you need to expose your interface in Python in a way which allows Python implementations to override parts of it at will. Then you need to show your C++ program (in `main` how to call Python.
---
# Exposing the existing interface to Python:
The first part is pretty easy to do ... |
How can I implement a C++ class in Python, to be called by C++? | 9,040,669 | 32 | 2012-01-27T22:03:02Z | 9,078,135 | 10 | 2012-01-31T10:40:18Z | [
"c++",
"python",
"swig",
"boost-python"
] | I have a class interface written in C++. I have a few classes that implement this interface also written in C++. These are called in the context of a larger C++ program, which essentially implements "main". I want to be able to write implementations of this interface in Python, and allow them to be used in the context ... | Minimal example; note that it is complicated by the fact that `Base` is not pure virtual. There we go:
1. baz.cpp:
```
#include<string>
#include<boost/python.hpp>
using std::string;
namespace py=boost::python;
struct Base{
virtual string foo() const { return "Base.foo"; }
// fooBase is no... |
How can I implement a C++ class in Python, to be called by C++? | 9,040,669 | 32 | 2012-01-27T22:03:02Z | 9,100,991 | 7 | 2012-02-01T18:13:00Z | [
"c++",
"python",
"swig",
"boost-python"
] | I have a class interface written in C++. I have a few classes that implement this interface also written in C++. These are called in the context of a larger C++ program, which essentially implements "main". I want to be able to write implementations of this interface in Python, and allow them to be used in the context ... | Based upon [the (very helpful) answer by Eudoxos](http://stackoverflow.com/a/9078135/168175) I've taken his code and extended it such that there is now an embedded interpreter, with a built-in module.
This answer is the Boost.Python equivalent of [my SWIG based answer](http://stackoverflow.com/a/9042139/168175).
The ... |
How to find all possible sequences of elements in a list? | 9,040,939 | 6 | 2012-01-27T22:32:07Z | 9,040,952 | 21 | 2012-01-27T22:33:33Z | [
"python"
] | I have a list [2,3,4]. How do I find all possible sequence of elements in the list?
So the output should be:
[2,3,4]
[2,4,3]
[3,2,4]
[3,4,2]
[4,2,3]
[4,3,2] | You can do this easily using [`itertools.permutations()`](http://docs.python.org/library/itertools.html#itertools.permutations):
```
>>> from itertools import permutations
>>> list(permutations([2, 3, 4]))
[(2, 3, 4), (2, 4, 3), (3, 2, 4), (3, 4, 2), (4, 2, 3), (4, 3, 2)]
```
And if for some reason you need lists ins... |
Get a return value using subprocess | 9,041,141 | 9 | 2012-01-27T22:52:39Z | 9,041,165 | 14 | 2012-01-27T22:55:05Z | [
"python",
"subprocess"
] | I want to be able to define a variable by the return value of a script. This is what I currently have:
```
sum_total_earnings_usd = subprocess.call([SCRIPT, "-d", date])
```
I have checked the return value of SCRIPT, however, when I try and set this variable, it always returns 0 ( <http://docs.python.org/library/subp... | Use `subprocess.check_output()` instead of `subprocess.call()` |
How do "binary" numbers relate to my everyday programming? | 9,041,185 | 6 | 2012-01-27T22:57:11Z | 9,041,227 | 11 | 2012-01-27T23:02:56Z | [
"php",
"python",
"binary",
"binary-data"
] | I am trying very hard to develop a much deeper understanding of programming as a whole. I understand the textbook definition of "binary", but what I don't understand is exactly how it applies to my day to day programming?
The concept of "binary numbers" vs .. well... "regular" numbers, is completely lost on me despite... | Binary trees (one of your tags), particularly [binary search trees](http://en.wikipedia.org/wiki/Binary_search_tree), are practical for some everyday programming scenarios (e.g. sorting).
Binary numbers are essential to computing fundamentals but more rarely used in higher-level languages.
Binary numbers are useful i... |
How does SWIG wrap a map<string,string> in Python? | 9,041,192 | 7 | 2012-01-27T22:58:11Z | 9,041,629 | 12 | 2012-01-27T23:52:32Z | [
"c++",
"python",
"stl",
"swig"
] | I'm using SWIG 2.0 to create a Python wrapper for a C++ library. One method has an argument of type "const std::map&". SWIG happily generates a wrapper for it, but I can't figure out how to invoke the method. If I pass, for example, {"a":"b"} for that argument, I get a "NotImplementedError: Wrong number or type of argu... | When you're using a C++ template (e.g. a `std::map<string, string>`) you need to create an alias for it in your `.i` file so you can use it in python:
```
namespace std {
%template(map_string_string) map<string, string>;
}
```
Now let's say you want to wrap a function that looks like this:
```
void foo(const std::ma... |
OpenCV Python rotate image by X degrees around specific point | 9,041,681 | 11 | 2012-01-27T23:59:01Z | 9,042,907 | 15 | 2012-01-28T04:28:24Z | [
"python",
"opencv",
"rotation"
] | I'm having a hard time finding examples for rotating an image around a specific point by a specific (often very small) angle in Python using OpenCV.
This is what I have so far, but it produces a very strange resulting image, but it is rotated somewhat:
```
def rotateImage( image, angle ):
if image != None:
... | ```
import numpy as np
def rotateImage(image, angle):
image_center = tuple(np.array(image.shape)/2)
rot_mat = cv2.getRotationMatrix2D(image_center,angle,1.0)
result = cv2.warpAffine(image, rot_mat, image.shape,flags=cv2.INTER_LINEAR)
return result
```
Assuming you're using the cv2 version, that code finds the... |
OpenCV Python rotate image by X degrees around specific point | 9,041,681 | 11 | 2012-01-27T23:59:01Z | 18,683,594 | 7 | 2013-09-08T12:18:10Z | [
"python",
"opencv",
"rotation"
] | I'm having a hard time finding examples for rotating an image around a specific point by a specific (often very small) angle in Python using OpenCV.
This is what I have so far, but it produces a very strange resulting image, but it is rotated somewhat:
```
def rotateImage( image, angle ):
if image != None:
... | Or much easier use
[SciPy](http://sourceforge.net/projects/scipy/)
```
from scipy import ndimage
#rotation angle in degree
rotated = ndimage.rotate(image_to_rotate, 45)
```
see
[here](http://scipy-lectures.github.io/advanced/image_processing/#id5)
for more usage info. |
Higher Order Functions vs loops - running time & memory efficiency? | 9,042,174 | 7 | 2012-01-28T01:27:18Z | 9,042,305 | 7 | 2012-01-28T01:52:24Z | [
"python",
"higher-order-functions"
] | Does using Higher Order Functions & Lambdas make running time & memory efficiency better or worse?
For example, to multiply all numbers in a list :
```
nums = [1,2,3,4,5]
prod = 1
for n in nums:
prod*=n
```
vs
```
prod2 = reduce(lambda x,y:x*y , nums)
```
Does the HOF version have any advantage over the loop ve... | Higher-order functions can be very fast.
For example, `map(ord, somebigstring)` is *much* faster than the equivalent list comprehension `[ord(c) for c in somebigstring]`. The former wins for three reasons:
* map() pre-sizes the result string to the length of *somebigstring*. In contrast, the list-comprehension must m... |
Normalizing unicode text to filenames, etc. in Python | 9,042,515 | 18 | 2012-01-28T02:46:27Z | 9,042,633 | 31 | 2012-01-28T03:11:58Z | [
"python",
"unicode",
"plone",
"normalization",
"unicode-normalization"
] | Are there any standalonenish solutions for normalizing international unicode text to safe ids and filenames in Python?
E.g. turn `My International Text: åäö` to `my-international-text-aao`
[plone.i18n](https://github.com/plone/plone.i18n) does really good job, but unfortunately it depends on `zope.security` and `z... | What you want to do is also known as "slugify" a string. Here's a possible solution:
```
import re
from unicodedata import normalize
_punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.:]+')
def slugify(text, delim=u'-'):
"""Generates an slightly worse ASCII-only slug."""
result = []
for word i... |
Python logging - Is there something below DEBUG? | 9,042,919 | 10 | 2012-01-28T04:31:58Z | 9,042,936 | 12 | 2012-01-28T04:36:32Z | [
"python",
"logging"
] | In some other technologies we occasionally used a log level below DEBUG that I believe was called "verbose". I realize that the need for such a level is very subjective. But in my mind "just" having INFO and DEBUG isn't really enough. We had times where something very spammy (more spammy than debug) needed to be logged... | *DEBUG* is the lowest level out of the ones provided by the logging module: `('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL')`. Their numeric values are here: <http://docs.python.org/howto/logging.html#logging-levels>
You can create [custom levels](http://docs.python.org/howto/logging.html#custom-levels) (though the ... |
Hash a Range of Values | 9,043,172 | 9 | 2012-01-28T05:28:06Z | 9,043,414 | 7 | 2012-01-28T06:21:16Z | [
"python",
"hash",
"universal-hashing"
] | I know that I can hash singular values as keys in a `dict`. For example, I can hash `5` as one of the keys in a `dict`.
I am currently facing a problem that requires me to hash a range of values.
Basically, I need a faster way to to do this:
```
if 0 <= x <= 0.1:
# f(A)
elif 0.1 <= x <= 0.2:
# f(B)
elif 0.2 ... | As others have noted, the best algorithm you're going to get for this is something that's O(log N), not O(1), with something along the lines of a bisection search through a sorted list.
The easiest way to do this in Python is with the `bisect` standard module, <http://docs.python.org/library/bisect.html>. Note, in par... |
How to detect if change in time series data is no longer significant? | 9,043,399 | 4 | 2012-01-28T06:19:13Z | 9,117,089 | 7 | 2012-02-02T17:37:34Z | [
"python",
"statistics",
"time-series",
"data-analysis",
"significance"
] | I have a set of news articles for which there are stats, eg.: number of twitter posts mentioning the article for range of days. Natural behavior of stats values is that the number of new posts grows fast and then decreases as the news ages.
I would like to know how to calculate the number of days after which the chang... | This question is really about **time-series analysis**. Since you are interested in determining the cut-off point, a good place to start would be by reading up on **[Control Charts](http://en.wikipedia.org/wiki/Control_chart)**.
If you want to delve deeper into the statistics (beyond control charts), then look into [Ch... |
Efficient date range overlap calculation in python? | 9,044,084 | 29 | 2012-01-28T09:01:23Z | 9,044,111 | 58 | 2012-01-28T09:07:35Z | [
"python",
"date",
"date-range"
] | I have two date ranges where each range is determined by a start and end date (obviously, datetime.date() instances). The two ranges can overlap or not. I need the number of days of the overlap. Of course I can pre-fill two sets with all dates within both ranges and the perform a set intersection but this is possibly i... | * Determine the latest of the two start dates and the earliest of the two end dates.
* Compute the timedelta by subtracting them.
* If the delta is positive, that is the number of days of overlap.
Here is an example calculation:
```
>>> from datetime import datetime
>>> from collections import namedtuple
>>> Range = ... |
Python: Merging Two Lists | 9,044,296 | 2 | 2012-01-28T09:43:32Z | 9,044,343 | 7 | 2012-01-28T09:50:39Z | [
"python"
] | I have two lists
```
list1= [6, 1, 8, 1, 2]
list2= ["Mail Opened", "Mail Not Opened", "Mail Opened", "Mail Not Opened", "Mail Not Opened"]
```
I was to trying results like
```
(14,"mailopened") (4,"mailnotopened")
```
First i tried to convert them Dict but it does not accept duplicate values.
is it Possible ... | Use a `defaultdict` and simply add the values from `list1`.
```
from collections import defaultdict
list1 = [6, 1, 8, 1, 2]
list2 = ["Mail Opened", "Mail Not Opened", "Mail Opened", "Mail Not Opened", "Mail Not Opened"]
added = defaultdict(int)
for i, k in enumerate(list2):
added[k] += list1[i]
```
This works ... |
Python iterator behaviour | 9,044,870 | 2 | 2012-01-28T11:21:15Z | 9,044,902 | 9 | 2012-01-28T11:27:46Z | [
"python",
"iterator",
"generator"
] | Given an arbitrary input string I'm meant to find the sum of all numbers in that string.
This obviously requires that i know the NEXT element in string while iterating through it...and make the decision whether its an integer. if the previous element was an integer also, the two elements form a new integer, all other c... | Python strings are already iterable, no need to create you own iterator.
What you want is thus simply achieved without iterators:
```
s = "acdre2345ty2390"
total = 0
num = 0
for c in s:
if c.isdigit():
num = num * 10 + int(c)
else:
total += num
num = 0
total += num
```
Which result... |
Why is a[:]=1 fundamentally different to a[:]='1'? | 9,045,169 | 37 | 2012-01-28T12:17:02Z | 9,045,181 | 79 | 2012-01-28T12:18:41Z | [
"python"
] | Please consider the two snippets of code (notice the distinction between string and integer):
```
a = []
a[:] = '1'
```
and
```
a = []
a[:] = 1
```
In the first case `a` is `['1']`. In the second, I get the error `TypeError: can only assign an iterable`. Why would using `'1'` over `1` be fundamentally different her... | **Assigning to a slice requires an iterable on the right-hand side.**
`'1'` is iterable, while `1` is not. Consider the following:
```
In [7]: a=[]
In [8]: a[:]='abc'
```
The result is:
```
In [9]: a
Out[9]: ['a', 'b', 'c']
```
As you can see, the list gets *each character* of the string as a separate item. This ... |
Getting the download link for a public Google Docs file | 9,045,392 | 5 | 2012-01-28T12:57:35Z | 9,045,572 | 15 | 2012-01-28T13:23:38Z | [
"python",
"api",
"google-docs"
] | Reading the [Google Docs API](http://code.google.com/apis/documents/docs/3.0/developers_guide_protocol.html#DownloadingFiles) I find this:
> ## Downloading
>
> Files cannot be downloaded in a format other than
> the one in which they were originally uploaded. The download URL for
> files looks something like this:
>
>... | Hi nightcracker try this:
```
https://docs.google.com/uc?export=download&id=DOCIDGOESHERE
```
I've only tried it with one pdf and it worked ok so maybe having a play with that will help....
All the best,
Dave |
Windows Python Version and VC++ Redistributable Version | 9,047,072 | 7 | 2012-01-28T17:01:01Z | 9,047,700 | 14 | 2012-01-28T18:28:35Z | [
"python",
"windows",
"visual-c++"
] | Can someone help fill out this table, or link to a reference, that identifies which version of VC++ Redistributable each Python version is built against on Windows.
---
1. Windows Python Version
2. DLL Name
3. VC++ Redistributable
4. Link to installer
---
1. 2.4
2. msvcr71.dll
3. Microsoft Visual C++ 2003 (7.1), in... | 1. Windows Python Version
2. DLL Name
3. VC++ Redistributable
4. Link to installer
---
1. 2.4, 2.5 [32 bit]
2. msvcr71.dll, msvcp72.dll
3. Microsoft Visual C++ 2003 (7.1), included with .net 1.1
4. <http://msdn.microsoft.com/en-us/netframework/aa569264>
---
1. 2.6, 2.7, 3.0, 3.1, 3.2 [32 bit]
2. msvcr90.dll, msvcp9... |
- vs -= operators with numpy | 9,047,111 | 11 | 2012-01-28T17:06:47Z | 9,047,154 | 9 | 2012-01-28T17:11:38Z | [
"python",
"numpy"
] | I'm having some strange behavior in my python code related to `-` and `-=`. I'm writing a QR decomposition using numpy, and have the following line of code in a double loop:
```
v = v - r[i,j] * q[:,i]
```
where `q` and `r` are both `numpy.array`, and `v` is a slice of another `numpy.array` taken as `v = x[:,j]`.
Th... | You could get different results from `x - y` and `x -= y` if the data types of `x` and `y` differ.
For example:
```
import numpy as np
x = np.array(range(0,6))
y = np.array(np.arange(0,3,0.5))
print x - y
x -= y
print x
```
This prints out:
```
[ 0. 0.5 1. 1.5 2. 2.5]
[0 0 1 1 2 2]
```
It may be worth ma... |
- vs -= operators with numpy | 9,047,111 | 11 | 2012-01-28T17:06:47Z | 9,047,211 | 14 | 2012-01-28T17:18:40Z | [
"python",
"numpy"
] | I'm having some strange behavior in my python code related to `-` and `-=`. I'm writing a QR decomposition using numpy, and have the following line of code in a double loop:
```
v = v - r[i,j] * q[:,i]
```
where `q` and `r` are both `numpy.array`, and `v` is a slice of another `numpy.array` taken as `v = x[:,j]`.
Th... | When `v` is a slice, then `v -= X` and `v = v - X` produce very different results. Consider
```
>>> x = np.arange(6)
>>> v = x[1:4]
>>> v -= 1
>>> v
array([0, 1, 2])
>>> x
array([0, 0, 1, 2, 4, 5])
```
where `v -= 1` updates the slice, and therefore the array that it views, in-place, vs.
```
>>> x = np.arange(6)
>>>... |
Python raw_input ignore newline | 9,047,349 | 5 | 2012-01-28T17:34:39Z | 9,047,589 | 7 | 2012-01-28T18:09:40Z | [
"python",
"raw-input"
] | Is there a way to ignore newline characters in data entered through raw\_input? I am trying to use raw\_input to input a list of strings that are copied and pasted from a spreadsheet. the problem is that it appears that the new line characters cause the data to be entered prematurely. All the empty spaces will be strip... | Because `raw_input` only takes one line from input you need to create a loop:
```
names = []
print('Shoot me some names partner: ')
while True:
try:
name = raw_input()
except KeyboardInterrupt:
break
names.append(name)
print('What do you want to do?')
print('1 - format names for program 1'... |
How to check for a key in a defaultdict without updating the dictionary (Python)? | 9,047,364 | 6 | 2012-01-28T17:36:30Z | 9,047,395 | 12 | 2012-01-28T17:39:50Z | [
"python",
"dictionary",
"defaultdict"
] | I usually use the following idiom when working with a Python dictionary:
```
try:
val = dct[key]
except KeyError:
print key, " is not valid"
```
since for large dictionaries, the statement
```
if key in dct:
# do something
```
is not very efficient (so I remember reading, but I've noticed it in practice... | > How can I perform a lookup without updating the defaultdict?
With `key in dct`, i.e. explicitly.
If this is *really* too expensive for you (measure and you'll be sure), there are workarounds for specific situations. E.g., if your default value is `'ham'` and in some situations you don't want to store `(key, 'ham')`... |
How to check for a key in a defaultdict without updating the dictionary (Python)? | 9,047,364 | 6 | 2012-01-28T17:36:30Z | 9,047,511 | 8 | 2012-01-28T17:55:22Z | [
"python",
"dictionary",
"defaultdict"
] | I usually use the following idiom when working with a Python dictionary:
```
try:
val = dct[key]
except KeyError:
print key, " is not valid"
```
since for large dictionaries, the statement
```
if key in dct:
# do something
```
is not very efficient (so I remember reading, but I've noticed it in practice... | `key in dct` *has* to be fast, saying that is slow would be like saying that `dct[key]` is slow, and that must never be the case. Retrieving an element from a dictionary given its key and testing membership of a key have to be O(1) operations in any decent dictionary implementation, and it's easy to see how the members... |
Where is the __builtin__ module in Python3? Why was it renamed? | 9,047,745 | 32 | 2012-01-28T19:07:01Z | 9,047,762 | 45 | 2012-01-28T19:09:11Z | [
"python"
] | I was curious about the `__builtin__` module and how it's used, but I can't find it in Python3! Why was it moved?
Python 2.7
```
>>> import __builtin__
>>>
```
Python 3.2
```
>>> import __builtin__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named __builtin__
>>>
... | The `__builtin__` module was renamed to `builtins` in Python3.
This change solves 2 sources of confusion for the average Python developer.
* Is it `'__builtins__'` or `'__builtin__'` that is in the global namespace?
Darn s!
* Is `__builtin__` a [special method name](http://docs.python.org/reference/datamodel.html#s... |
Swap the elements of two sequences, such that the difference of the element-sums gets minimal. | 9,047,908 | 5 | 2012-01-28T19:29:00Z | 9,048,164 | 8 | 2012-01-28T20:05:02Z | [
"c++",
"python",
"algorithm",
"data-structures"
] | An interview question:
> Given two non-ordered integer sequences `a` and `b`, their size is n, all
> numbers are randomly chosen: Exchange the elements of `a` and `b`, such that the sum of the elements of `a` minus the sum of the elements of `b` is minimal.
Given the example:
```
a = [ 5 1 3 ]
b = [ 2 4 9 ]
```
The... | Revised solution:
1. Merge both lists x = merge(a,b).
2. Calculate median of x (complexity O(n) See <http://en.wikipedia.org/wiki/Selection_algorithm> )
3. Using this median swap elements between a and b. That is, find an element in a that is less than median, find one in b that is more than median and swap them
Fina... |
How do I call a function twice or more times consecutively in python? | 9,047,985 | 12 | 2012-01-28T19:40:36Z | 9,048,006 | 30 | 2012-01-28T19:43:32Z | [
"python",
"function",
"shortcut",
"sequential"
] | Is there a short way to call a function twice or more consecutively in python? For example:
```
do()
do()
do()
```
maybe like :
```
3*do()
``` | I would:
```
for _ in range(3):
do()
```
The `_` is convention for a variable whose value you don't care about.
You might also see some people write:
```
[do() for _ in range(3)]
```
however that is slightly more expensive because it creates a list containing the return values of each invocation of `do()` (eve... |
How do I call a function twice or more times consecutively in python? | 9,047,985 | 12 | 2012-01-28T19:40:36Z | 9,048,049 | 9 | 2012-01-28T19:50:10Z | [
"python",
"function",
"shortcut",
"sequential"
] | Is there a short way to call a function twice or more consecutively in python? For example:
```
do()
do()
do()
```
maybe like :
```
3*do()
``` | You could define a function that repeats the passed function N times.
```
def repeat_fun(times, f):
for i in range(times): f()
```
If you want to make it even more flexible, you can even pass arguments to the function being repeated:
```
def repeat_fun(times, f, *args):
for i in range(times): f(*args)
```
U... |
Create random number within an annulus | 9,048,095 | 5 | 2012-01-28T19:56:23Z | 9,048,443 | 17 | 2012-01-28T20:43:29Z | [
"python",
"random"
] | I am trying generate a random number that is within an annulus, i.e. we have a max and min radius. I tried doing:
```
while True:
x=random.uniform(-maxR, maxR)
y=random.uniform(-maxR, maxR)
R=math.sqrt(x**2 + y**2)
if R <= maxRadius and R >= minRadius:
if x>= -maxRadius and x <= maxRadius and x... | In general you can either draw the correct distribution directly or use rejection.
## To draw directly use
* draw theta uniformly on [0,2pi): `theta = random.uniform(0,2*pi)`
* draw r from [the power-law distribution r^1](http://stackoverflow.com/q/918736/2509).
The only complexity compared to doing this for a cir... |
Is there a more pythonic way of storing parameters so they can be used in a function call? | 9,048,099 | 5 | 2012-01-28T19:56:47Z | 9,048,112 | 12 | 2012-01-28T19:58:15Z | [
"python"
] | I'm currently writing a small script using pygame, but I don't believe this question to be related strictly to pygame.
I have a class that holds a dictionary of function parameters contained in tuples:
```
self.stim = {1:(firstParam, secondparam, thirdparam),
2:(firstParam2, secondparam2, thirdparam2),
... | Sure, it is called [argument list unpacking](http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists) (thanks Björn Pollex for the link):
```
def action(self, stimType):
pygame.draw.rect(*self.stim[stimType])
```
And if you are not using a dict for any particular reason, then a tuple for the co... |
Django Overriding Model Clean() vs Save() | 9,048,108 | 19 | 2012-01-28T19:57:53Z | 9,048,338 | 22 | 2012-01-28T20:28:37Z | [
"python",
"django",
"django-models",
"django-admin"
] | I have a couple of actions to perform when saving a models, especially from the admin. I capitalize a couple of fields and check to make sure that either one field or the other is filled. I also create the field slug. RIght now these are split between overriding the clean and the save functions. It works now, but I am ... | You should use clean to do validation-related work, and to parse/change/otherwise clean the input. Capitalizing fields and generating a slug can happen here. I also use clean to force a field like `post_type` to a specific value in proxy models. If you raise `django.core.exceptions.ValidationError('error text')` inside... |
Importing packages in Python | 9,048,518 | 35 | 2012-01-28T20:53:18Z | 9,048,561 | 22 | 2012-01-28T20:58:08Z | [
"python",
"python-import"
] | I am probably missing something obvious but anyway:
When you import a package like `os` in python, you can use any submodules/subpackages off the bet. For example this works:
```
>>> import os
>>> os.path.abspath(...)
```
However I have my own package which is structured as follows:
```
FooPackage/
__init__.py
... | You need to import the submodule:
```
import FooPackage.foo
```
---
What you're doing is looking for `foo` in `FooPackage/__init__.py`. You could solve it by putting `import FooPackage.foo as foo` (or `from . import foo`) in `FooPackage/__init__.py`, then Python will be able to find `foo` there. But I recommend usin... |
Importing packages in Python | 9,048,518 | 35 | 2012-01-28T20:53:18Z | 9,049,246 | 44 | 2012-01-28T22:38:30Z | [
"python",
"python-import"
] | I am probably missing something obvious but anyway:
When you import a package like `os` in python, you can use any submodules/subpackages off the bet. For example this works:
```
>>> import os
>>> os.path.abspath(...)
```
However I have my own package which is structured as follows:
```
FooPackage/
__init__.py
... | When you import `FooPackage`, Python searches the directories on PYTHONPATH until it finds a file called `FooPackage.py` or a directory called `FooPackage` containing a file called `__init__.py`. However, having found the package directory, it does *not* then scan that directory and automatically import all .py files.
... |
Importing packages in Python | 9,048,518 | 35 | 2012-01-28T20:53:18Z | 18,202,890 | 7 | 2013-08-13T07:17:09Z | [
"python",
"python-import"
] | I am probably missing something obvious but anyway:
When you import a package like `os` in python, you can use any submodules/subpackages off the bet. For example this works:
```
>>> import os
>>> os.path.abspath(...)
```
However I have my own package which is structured as follows:
```
FooPackage/
__init__.py
... | You need to add `from . import foo` to the `__init__.py` file in your package. |
How to group a regular expression in re.split() function? | 9,048,530 | 2 | 2012-01-28T20:55:11Z | 9,048,552 | 7 | 2012-01-28T20:57:08Z | [
"python",
"regex",
"split"
] | See two examples how re.split() works:
```
>>> re.split(',', 'a,b')
['a', 'b']
```
but
```
>>> re.split('(,)', 'a,b')
['a', ',', 'b']
```
Why I get ',' in the list? How to avoid it?
I am asking, because I would like to make a split using an expression similar to 'xy(a|b)cd'. | Use a non-capturing group, like:
```
re.split('(?:,)', 'a,b')
``` |
What are the differences amongst Python's "__get*__" and "_del*__" methods? | 9,048,826 | 13 | 2012-01-28T20:22:49Z | 9,049,984 | 21 | 2012-01-29T00:50:54Z | [
"python",
"getter-setter",
"standard-library",
"accessor"
] | I just started learning Python a few months ago, and I'm trying to understand the differences between the different `__get*__` methods:
```
__get__
__getattr__
__getattribute__
__getitem___
```
And their `__del*__` equivalents:
```
__del__
__delattr__
__delete__
__delitem__
```
What are the differences between thes... | The documentation for every method that you listed is easly reachable from the [documentation index](http://docs.python.org/py3k/genindex-_.html) .
Anyway this may be a little extended reference:
### `__get__`, `__set__` and `__del__` are descriptors
*"In a nutshell, a descriptor is a way to customize what happens w... |
How to unpack only some arguments from zip, not all? | 9,049,005 | 7 | 2012-01-28T22:00:30Z | 9,049,058 | 11 | 2012-01-28T22:08:12Z | [
"python"
] | My sql query:
```
select id,value,zvalue from axis
```
gives me result like this:
```
ans=(1,23,34)(12,34,35)(31,67,45)(231,3412,234)
```
now if i want all these 3 variables as 3 different lists
```
id,value,zvalue=zip(*ans)
```
it will give me 3 separate lists.
but if i only want id and value as separate lis... | The number of arguments must match, this is a rule in Python 2. For Python 3, you can use \* to capture into a list.
The common pythonic (2.x) workaround is to use `_` to denote variables you won't use, i.e.:
```
id,value,_ = zip(*ans) # only works for exactly three values
```
As DSM commented, for Python 3, you can... |
Would optional static typing benefit Python API-design or be a disadvantage? (type checking decorator example included) | 9,049,319 | 3 | 2012-01-28T22:49:38Z | 9,049,604 | 7 | 2012-01-28T23:42:38Z | [
"python",
"static-typing"
] | I'm a long time Python developer and I really love the dynamic nature of the language, but I wonder if Python would benefit from optional static typing.
**Would it be beneficial to be able to apply static typing to the API of a library, and what would the disadvantages of this be?**
I quickly sketched up a decorator i... | Personally, I don't find this idea attractive for Python. This is all just my opinion, of course, but for context I'll tell you that Python and Haskell are probably my two favourite programming languages - I like languages at both extreme ends of the static vs dynamic typing spectrum.
I see the main benefits of static... |
App Engine appending items to ListProperty | 9,049,382 | 4 | 2012-01-28T23:02:21Z | 9,049,476 | 7 | 2012-01-28T23:17:58Z | [
"python",
"google-app-engine",
"gae-datastore"
] | I think I'm loosing my mind, why doens't the following work?
```
class Parent(db.Model):
childrenKeys = db.ListProperty(str,indexed=False,default=None)
p = Parent.get_or_insert(key_name='somekey')
p.childrenKeys = p.childrenKeys.append('newchildkey')
p.put()
```
I get this error:
```
BadValueError: Property chi... | You should remove the `p.childrenKeys` assignment:
```
class Parent(db.Model):
childrenKeys = db.ListProperty(str,indexed=False,default=[])
p = Parent.get_or_insert('somekey')
p.childrenKeys.append('newchkey')
p.put()
``` |
What does it mean in linux scripts? #!/usr/bin/python -tt | 9,050,331 | 16 | 2012-01-29T02:08:23Z | 9,050,352 | 15 | 2012-01-29T02:13:49Z | [
"python",
"linux",
"bash",
"interpreter"
] | I know that in the begining of .sh bash scripts is
```
#!/bin/bash
```
which points to the command interpeter executable.
But during watching Google Python Class <http://www.youtube.com/watch?v=tKTZoB2Vjuk> I noticed that for python they use
```
#!/usr/bin/python -tt
```
. Surfing the Internet I also have found su... | Question #1) The line is called a shebang, and there's no right form that works universally. e.g.
```
#!python
#!/usr/bin/python
#!/usr/local/bin/python
#!/usr/bin/python -t
```
are all valid/acceptable forms, but may not work on all systems:
`#!python` will work only if the python executable is somewhere in your sh... |
Python - Using quotation marks inside quotation marks | 9,050,355 | 25 | 2012-01-29T02:14:14Z | 9,050,384 | 85 | 2012-01-29T02:19:17Z | [
"python"
] | Well... When I want to do a command "print" in python and I need to use quotation marks, I don't know how to do it without closing the sentence. For instance:
> print " "a word that needs quotation marks" "
But when I try to do what I did above, I end up closing the sentence and I can't put the word I need between qu... | You could do this in one of three ways:
1) Use single and double quotes together:
```
>>> print '"A word that needs quotation marks"'
"A word that needs quotation marks"
```
2) Escape the double quotes within the string:
```
>>> print "\"A word that needs quotation marks\""
"A word that needs quotation marks"
```
... |
customizing just one side of tick marks in matplotlib using spines | 9,051,494 | 7 | 2012-01-29T06:52:01Z | 9,051,679 | 14 | 2012-01-29T07:36:19Z | [
"python",
"numpy",
"scipy",
"matplotlib"
] | I have a matplotlib horizontal bar drawn as follows:
```
import matplotlib.pyplot as plt
from numpy import *
from scipy import *
bars = arange(5) + 0.1
vals = rand(5)
print bars, vals
plt.figure(figsize=(5,5), dpi=100)
spines = ["bottom"]
ax = plt.subplot(1, 1, 1)
for loc, spine in ax.spines.iteritems():
if loc not ... | you could simply use:
```
ax.tick_params(axis='y', direction='out')
```
this will orientate the ticks as you want. And:
```
ax.yaxis.tick_left()
```
this will not plot the right ticks |
customizing just one side of tick marks in matplotlib using spines | 9,051,494 | 7 | 2012-01-29T06:52:01Z | 24,124,345 | 7 | 2014-06-09T16:14:58Z | [
"python",
"numpy",
"scipy",
"matplotlib"
] | I have a matplotlib horizontal bar drawn as follows:
```
import matplotlib.pyplot as plt
from numpy import *
from scipy import *
bars = arange(5) + 0.1
vals = rand(5)
print bars, vals
plt.figure(figsize=(5,5), dpi=100)
spines = ["bottom"]
ax = plt.subplot(1, 1, 1)
for loc, spine in ax.spines.iteritems():
if loc not ... | You can use:
```
ax.tick_params(top="off")
ax.tick_params(bottom="off")
ax.tick_params(right="off")
ax.tick_params(left="off")
``` |
Removing one list from another | 9,053,260 | 6 | 2012-01-29T12:47:59Z | 9,053,286 | 11 | 2012-01-29T12:52:44Z | [
"python"
] | In python (2.7) we can do:
```
>>> a = [1, 2, 3]
>>> b = [4 , 5]
>>> a + b
[1, 2, 3, 4, 5]
```
However we can't do a - b.
Since python seems to have something cool for nearly everything, what is the most python-esque to do a - b, in your opinion?
Similar question for dictionaries, which can neither do a + b, or a -... | You can do this with sets:
```
>>> s = set([1,2,3] + [4,5])
>>> s - set([4, 5])
{1, 2, 3}
```
The main difference of course being a set cannot contain duplicate elements. |
Finding the sum of even valued terms in fibonacci sequence | 9,053,545 | 3 | 2012-01-29T13:32:40Z | 9,053,585 | 13 | 2012-01-29T13:38:39Z | [
"python",
"sum",
"fibonacci"
] | ```
#!/usr/bin/python2
"""
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the ... | Basically what you're doing here is adding every second element of the fibonacci sequence while the question asks to only sum the even elements.
What you should do instead is just iterate over all the fibonacci values below 4000000 and do a `if value % 2 == 0: total += value`. The `%` is the remainder on division oper... |
Comparing lists of dictionaries | 9,054,365 | 5 | 2012-01-29T15:36:34Z | 9,054,505 | 8 | 2012-01-29T15:57:30Z | [
"python",
"list",
"dictionary"
] | I have two lists of test results. The test results are represented as dictionaries:
```
list1 = [{testclass='classname', testname='testname', testtime='...},...]
list2 = [{testclass='classname', testname='testname', ...},...]
```
The dictionary representation is slightly different in both lists, because for one list ... | Try this:
```
def get_new_failures(list1, list2):
check = set([(d['classname'], d['testname']) for d in list2])
return [d for d in list1 if (d['classname'], d['testname']) not in check]
``` |
How do I raise a window that is minimized or covered with PyGObject? | 9,054,462 | 5 | 2012-01-29T15:50:25Z | 9,054,712 | 7 | 2012-01-29T16:29:43Z | [
"python",
"gtk",
"pygtk",
"gtk3",
"pygobject"
] | I'd been using the answer provided in the [PyGTK FAQ](http://faq.pygtk.org/index.py?req=all#10.25), but that doesn't seem to work with PyGObject. For your convenience, here is a test case that works with PyGTK, and then a translated version that doesn't work with PyGObject.
PyGTK Version:
```
import gtk
def raise_wi... | As explained in this [post](http://python.6.n6.nabble.com/raise-gtk-Window-to-top-tp1941878p1941879.html), there are two options:
Raise the window temporarily (probably what you're looking for):
```
def raise_window(widget, w2):
w2.present()
```
Raise the window permanently (or until explicitly changed by config... |
Matplotlib doesn't display graph in virtualenv | 9,054,718 | 15 | 2012-01-29T16:30:36Z | 9,098,604 | 9 | 2012-02-01T15:35:50Z | [
"python",
"virtualenv",
"matplotlib"
] | I have pip installed matplotlib in my virtualenv and I am trying to plot a simple graph. I use Eclipse and PyDev. When I run the script from Eclipse it doesn't display any graph at all. I have tried the suggestions proposed in other questions such as adding plt.ion() but that doesn't work either. I have also tried the ... | Your code works inside my virtualenv on OSX 10.7 with Python 2.7:

What version of Python are you using inside your virtualenv? My guess is that either you have not installed a matplotlib dependency or your installation of an installed dependency was ... |
Matplotlib doesn't display graph in virtualenv | 9,054,718 | 15 | 2012-01-29T16:30:36Z | 16,856,545 | 9 | 2013-05-31T11:46:30Z | [
"python",
"virtualenv",
"matplotlib"
] | I have pip installed matplotlib in my virtualenv and I am trying to plot a simple graph. I use Eclipse and PyDev. When I run the script from Eclipse it doesn't display any graph at all. I have tried the suggestions proposed in other questions such as adding plt.ion() but that doesn't work either. I have also tried the ... | I had the same issue, and installing `matplotlib` using `easy_install` instead of `pip` did not solve it. In the end, I found out that the problem was simply that matplotlib could not find any backend for plotting.
I solved it by doing the following (I am using Debian wheezy):
```
pip uninstall matplotlib
sudo apt-ge... |
Python requests exception handling | 9,054,820 | 21 | 2012-01-29T16:46:54Z | 9,054,856 | 43 | 2012-01-29T16:52:23Z | [
"python",
"exception",
"http-request",
"python-requests"
] | How to handle exceptions with python library requests?
For example how to check is PC connected to internet?
When I try
```
try:
requests.get('http://www.google.com')
except ConnectionError:
# handle the exception
```
it gives me error name `ConnectionError` is not defined | Assuming you did `import requests`, you want `requests.ConnectionError`. `ConnectionError` is an exception defined by `requests`. See the [API documentation](http://docs.python-requests.org/en/latest/api/) here. |
Python: How to append a value in a dict to a list if the value is found in another list | 9,055,079 | 2 | 2012-01-29T17:19:54Z | 9,055,097 | 10 | 2012-01-29T17:22:04Z | [
"python",
"list",
"dictionary"
] | Example:
```
list1 =['a','b','c','d']
new_list = []
dict = {'a':24, 'b':53 ,'c':26, 'd':9}
```
How would I take list1 and append the associated values of dict into new\_list, so as to produce this:
```
new_list = [24,53,26,9]
``` | Don't use 'dict' as a variable name, it will shadow the builtin dict() function.
```
list1 =['a','b','c','d']
d = {'a':24, 'b':53 ,'c':26, 'd':9}
new_list = [d[k] for k in list1]
assert new_list == [24, 53, 26, 9]
``` |
Python and PYAML - yaml.scanner.ScannerError: mapping values are not allowed here | 9,055,371 | 5 | 2012-01-29T17:57:49Z | 9,055,411 | 16 | 2012-01-29T18:03:21Z | [
"python",
"yaml",
"pyyaml"
] | I am on ubunty 64 with python 2.7 and using PyYAML-3.10
Below is my yaml file:
```
host:localhost
username:root
password:test
database:test
operations_database:operations
treeroot:
branch1:
name: Node 1
branch1-1:
name: Node 1-1
branch2:
name: Node 2
branch2-1:
... | Try putting spaces after the colons. |
Random List choices in python | 9,055,968 | 3 | 2012-01-29T19:18:29Z | 9,056,007 | 13 | 2012-01-29T19:22:47Z | [
"python",
"list",
"variables",
"random"
] | Is there a way to pass a variable to the `choice()` function for a list. I have a bunch of lists and I want to randomly select from one list and then use the string that is returned to select from a list that has that string name.
```
A = ['1','2','3']
print choice (A) - this gets me a random choice from the list
```... | In Python, you can do this using *references*.
```
A = [1, 2, 3]
B = [4, 5, 6]
C = [7, 8, 9]
MasterList = [A, B, C]
whichList = choice(MasterList)
print choice(whichList)
```
Note that `A, B, C` are names of previously assigned variables, instead of quoted strings. If you ever find yourself using quoted names to ref... |
Python OpenCV - Find black areas in a binary image | 9,056,646 | 11 | 2012-01-29T20:51:34Z | 9,059,648 | 23 | 2012-01-30T05:14:26Z | [
"python",
"opencv",
"colors",
"detection",
"threshold"
] | There is any method/function in the python wrapper of Opencv that finds black areas in a binary image? (like **regionprops** in Matlab)
Up to now I load my source image, transform it into a binary image via threshold and then invert it to highlight the black areas (that now are white).
I can't use third party librarie... | Basically, you use the [`findContours`](http://opencv.itseez.com/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=findcontours#cv.FindContours) function, in combination with many other functions OpenCV provides for especially this purpose.
Useful functions used (surprise, surprise, they *al... |
Python remove set from set | 9,056,833 | 24 | 2012-01-29T21:10:35Z | 9,056,935 | 7 | 2012-01-29T21:23:55Z | [
"python",
"set"
] | According to my interpretation of Python 2.7.2 documentation for [Built-In Types 5.7 Set Types](http://docs.python.org/library/stdtypes.html#set-types-set-frozenset), it should be possible to remove the elements of set A from set B by passing A to `set.remove(elem)` or `set.discard(elem)`
From the documentation for 2.... | You can't have `set`s of `set`s in Python as a `set` is mutable. Instead, you can have `set`s of `frozenset`s. On the other hand, you can call `__contains__()`, `remove()`, and `discard()` with a `set`. See this example:
```
a = set([frozenset([2])])
set([2]) in a # you get True
a.remove(set([2])) # a is now em... |
Python remove set from set | 9,056,833 | 24 | 2012-01-29T21:10:35Z | 9,056,964 | 9 | 2012-01-29T21:27:13Z | [
"python",
"set"
] | According to my interpretation of Python 2.7.2 documentation for [Built-In Types 5.7 Set Types](http://docs.python.org/library/stdtypes.html#set-types-set-frozenset), it should be possible to remove the elements of set A from set B by passing A to `set.remove(elem)` or `set.discard(elem)`
From the documentation for 2.... | You already answered the question. It refers to sets of sets (actually sets containing frozensets).
[The paragraph you are referring to](http://docs.python.org/library/stdtypes.html#set-types-set-frozenset) begins with:
> Note, the elem argument to the \_\_contains\_\_(), remove(), and discard() methods may be a set.... |
Any alternative way to check if there is any attribute in python? | 9,057,309 | 3 | 2012-01-29T22:21:07Z | 9,057,338 | 8 | 2012-01-29T22:24:03Z | [
"python",
"attributes"
] | ```
a = SomeClass()
if hasattr(a, 'property'):
a.property
```
Is this the only way to check if there is a property or not? Is there any other way to do the same thing? | You could just use the property and catch the `AttributeError` exception if it doesn't exist. But using `hasattr` is also a reasonable approach.
A potential issue with catching the exception is that you can't easily distinguish between the attribute not existing, and it existing but when you call it some code is run a... |
How can I intercept calls to python's "magic" methods in new style classes? | 9,057,669 | 21 | 2012-01-29T23:14:22Z | 9,059,858 | 21 | 2012-01-30T05:43:51Z | [
"python",
"python-3.x"
] | I'm trying to intercept calls to python's double underscore magic methods in new style classes. This is a trivial example but it show's the intent:
```
class ShowMeList(object):
def __init__(self, it):
self._data = list(it)
def __getattr__(self, name):
attr = object.__getattribute__(self._data... | For performance reasons, Python always looks in the class (and parent classes') `__dict__` for magic methods and does not use the normal attribute lookup mechanism. A workaround is to use a metaclass to automatically add proxies for magic methods at the time of class creation; I've used this technique to avoid having t... |
Unwanted RST TCP packet with Scapy | 9,058,052 | 16 | 2012-01-30T00:15:17Z | 9,154,940 | 17 | 2012-02-06T02:17:08Z | [
"python",
"networking",
"tcp",
"scapy"
] | In order to understand how TCP works, I tried to forge my own TCP SYN/SYN-ACK/ACK (based on the tutorial: <http://www.thice.nl/creating-ack-get-packets-with-scapy/> ).
The problem is that whenever my computer recieve the SYN-ACK from the server, it generates a RST packet that stops the connection process.
I tried on ... | The article you cited makes this pretty clear...
> Since you are not completing the full TCP handshake your operating system might try to take control and can start sending RST (reset) packets, to avoid this we can use iptables:
```
iptables -A OUTPUT -p tcp --tcp-flags RST RST -s 192.168.1.20 -j DROP
```
Essentiall... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.