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 sqlalchemy length of a string column | 1,777,814 | 12 | 2009-11-22T04:32:17Z | 1,778,993 | 14 | 2009-11-22T15:17:33Z | [
"python",
"sqlalchemy"
] | Consider this simple table definition (using SQLAlchemy-0.5.6)
```
from sqlalchemy import *
db = create_engine('sqlite:///tutorial.db')
db.echo = False # Try changing this to True and see what happens
metadata = MetaData(db)
user = Table('user', metadata,
Column('user_id', Integer, primary_key=True),
Colu... | ```
User.name.property.columns[0].type.length
```
Note, that SQLAlchemy supports composite properties, that's why `columns` is a list. It has single item for simple column properties. |
Python float - str - float weirdness | 1,778,368 | 6 | 2009-11-22T10:28:18Z | 1,778,381 | 14 | 2009-11-22T10:35:48Z | [
"python",
"string",
"floating-point",
"floating-accuracy"
] | ```
>>> float(str(0.65000000000000002))
0.65000000000000002
>>> float(str(0.47000000000000003))
0.46999999999999997 ???
```
What is going on here?
How do I convert `0.47000000000000003` to string and the resultant value back to float?
I am using Python 2.5.4 on Windows. | `str(0.47000000000000003)` give `'0.47'` and `float('0.47')` can be `0.46999999999999997`.
This is due to the way floating point number are represented (see this [wikipedia](http://en.wikipedia.org/wiki/IEEE%5F754) article)
Note: `float(repr(0.47000000000000003))` or `eval(repr(0.47000000000000003))` will give you the... |
What is wrong with the pearson algorithm from âProgramming Collective Intelligenceâ? | 1,778,411 | 5 | 2009-11-22T10:52:58Z | 1,778,429 | 11 | 2009-11-22T11:01:58Z | [
"python",
"algorithm",
"pearson"
] | This function is from the book "Programming Collective Intelligenceâ, and is supposed to calculate the Pearson correlation coefficient for p1 and p2, which is supposed to be a number between -1 and 1.
If two critics rate items very similarly the function should return 1, or close to 1.
With real user data I sometim... | There is nothing wrong in your result. You are trying to plot a line through 3 points. In second case you have all three points with the same coordinates, i.e. effectively one point. You can't say do these points correlate or anti-correlate, because you can draw infinite number of lines through one point (`den` in your... |
Why does Python allow comparison of a callable and a number? | 1,778,521 | 2 | 2009-11-22T12:07:06Z | 1,778,611 | 9 | 2009-11-22T12:46:18Z | [
"python"
] | I used python to write an assignment last week, here is a code snippet
```
def departTime():
'''
Calculate the time to depart a packet.
'''
if(random.random < 0.8):
t = random.expovariate(1.0 / 2.5)
else:
t = random.expovariate(1.0 / 10.5)
return t
```
Can you see the problem? ... | **This isn't always a mistake**
Firstly, just to make things clear, this isn't **always** a mistake.
In this particular case, it's pretty clear the comparison is an error.
However, because of the dynamic nature of Python, consider the following (perfectly valid, if terrible) code:
```
import random
random.random = ... |
Why does Python allow comparison of a callable and a number? | 1,778,521 | 2 | 2009-11-22T12:07:06Z | 1,778,613 | 7 | 2009-11-22T12:47:08Z | [
"python"
] | I used python to write an assignment last week, here is a code snippet
```
def departTime():
'''
Calculate the time to depart a packet.
'''
if(random.random < 0.8):
t = random.expovariate(1.0 / 2.5)
else:
t = random.expovariate(1.0 / 10.5)
return t
```
Can you see the problem? ... | This is âfixedâ in Python 3 <http://docs.python.org/3.1/whatsnew/3.0.html#ordering-comparisons>. |
When should I drop support for python2.4 on my public python library? | 1,778,670 | 8 | 2009-11-22T13:17:31Z | 1,778,686 | 7 | 2009-11-22T13:24:11Z | [
"python"
] | I maintain an open source python project. Right now it supports python 2.4, 2.5, 2.6. I am looking for to add support for python 3. I guess it will be easier if I drop 2.4 support.
I know it is possible to support all but it is very annoying if I have to install 4 or 5 python versions on my machine and run the tests o... | I'd say it depends on your target audience. For enterprise stuff I think RedHat (certainly CentOS 5) are still on 2.4 - so if you want typical RedHat/CentOS using people to able to install without resorting to third party python installations then I think you need to keep 2.4 for a while. If most of your users are more... |
Swapping 1 with 0 and 0 with 1 in a pythonic way? | 1,779,286 | 12 | 2009-11-22T17:10:35Z | 1,779,303 | 59 | 2009-11-22T17:13:07Z | [
"python"
] | In some part of my Python program I have a val variable that can be 1 or 0. If it's 1 I must change to 0, if it's 0 I must change to 1.
How do you do it in a Pythonic way?
```
if val == 1:
val = 0
elif val == 0:
val = 1
```
it's too long!
I did:
```
swap = {0: 1, 1:0}
```
So I can use it:
```
swap[val]
`... | This isn't pythonic, but it is language neutral. Often `val = 1 - val` is simplest. |
Swapping 1 with 0 and 0 with 1 in a pythonic way? | 1,779,286 | 12 | 2009-11-22T17:10:35Z | 1,779,305 | 16 | 2009-11-22T17:13:20Z | [
"python"
] | In some part of my Python program I have a val variable that can be 1 or 0. If it's 1 I must change to 0, if it's 0 I must change to 1.
How do you do it in a Pythonic way?
```
if val == 1:
val = 0
elif val == 0:
val = 1
```
it's too long!
I did:
```
swap = {0: 1, 1:0}
```
So I can use it:
```
swap[val]
`... | Since `True == 1` and `False == 0` in python,
you could just use `var = not var`
It will just swap it. |
Swapping 1 with 0 and 0 with 1 in a pythonic way? | 1,779,286 | 12 | 2009-11-22T17:10:35Z | 1,779,501 | 9 | 2009-11-22T18:23:02Z | [
"python"
] | In some part of my Python program I have a val variable that can be 1 or 0. If it's 1 I must change to 0, if it's 0 I must change to 1.
How do you do it in a Pythonic way?
```
if val == 1:
val = 0
elif val == 0:
val = 1
```
it's too long!
I did:
```
swap = {0: 1, 1:0}
```
So I can use it:
```
swap[val]
`... | Just another possibility:
```
i = (1,0)[i]
```
This works well as long as i is positive, as [dbr](http://stackoverflow.com/users/745/) pointed out in the comments it doesn't work fail for i < 0.
Are you sure you don't want to use `False` and `True`? It sounds almost like it. |
Swapping 1 with 0 and 0 with 1 in a pythonic way? | 1,779,286 | 12 | 2009-11-22T17:10:35Z | 1,871,430 | 10 | 2009-12-09T03:35:04Z | [
"python"
] | In some part of my Python program I have a val variable that can be 1 or 0. If it's 1 I must change to 0, if it's 0 I must change to 1.
How do you do it in a Pythonic way?
```
if val == 1:
val = 0
elif val == 0:
val = 1
```
it's too long!
I did:
```
swap = {0: 1, 1:0}
```
So I can use it:
```
swap[val]
`... | The shortest approach is using the bitwise operator XOR.
If you want `val` to be reassigned:
```
val ^= 1
```
If you do not want `val` to be reassigned:
```
val ^ 1
``` |
How do I use Python to convert a string to a number if it has commas in it as thousands separators? | 1,779,288 | 43 | 2009-11-22T17:10:48Z | 1,779,324 | 58 | 2009-11-22T17:20:11Z | [
"python"
] | I have a string that represents a number which uses commas to separate thousands. How can I convert this to a number in python?
```
>>> int("1,000,000")
```
Generates a `ValueError`.
I could replace the commas with empty strings before I try to convert it, but that feels wrong somehow. Is there a better way? | ```
import locale
locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' )
locale.atoi('1,000,000')
# 1000000
locale.atof('1,000,000.53')
# 1000000.53
``` |
How do I use Python to convert a string to a number if it has commas in it as thousands separators? | 1,779,288 | 43 | 2009-11-22T17:10:48Z | 1,781,958 | 23 | 2009-11-23T09:18:32Z | [
"python"
] | I have a string that represents a number which uses commas to separate thousands. How can I convert this to a number in python?
```
>>> int("1,000,000")
```
Generates a `ValueError`.
I could replace the commas with empty strings before I try to convert it, but that feels wrong somehow. Is there a better way? | There are several ways to parse numbers with thousands separators. And I doubt that the way described by ~ubuntu is the best in all cases. That's why I list other ways too.
1. The proper place to call `setlocale()` is in `__main__` module. It's global setting and will affect the whole program and even C extensions (al... |
What does abstract mean in this context? | 1,779,365 | 2 | 2009-11-22T17:36:53Z | 1,779,393 | 8 | 2009-11-22T17:46:03Z | [
"python",
"abstract"
] | I need some help in understanding a python concept.
```
class TilePuzzleProblem(search.Problem):
""" This class is the class for the NxN - blanks tile puzzle problem """
def __init__(self, N, blanks, initial, goal):
""" Initialize """
search.Problem.__init__(self, initial, goal)
self.N = N... | This is a trick described [here](http://norvig.com/python-iaq.html). There's not keyword `abstract` in Python, so, if you won't override this method in some subclass, it'll cause `NotImplementedError`. |
Python metaclasses vs class decorators | 1,779,372 | 26 | 2009-11-22T17:39:39Z | 1,779,404 | 31 | 2009-11-22T17:49:49Z | [
"python",
"decorator",
"metaclass"
] | What are the main differences between Python metaclasses and class decorators? Is there something I can do with one but not with the other? | Decorators are much, much simpler and more limited -- and therefore should be preferred whenever the desired effect can be achieved with either a metaclass or a class decorator.
Anything you can do with a class decorator, you can of course do with a custom metaclass (just apply the functionality of the "decorator func... |
Python programs coexisting on Windows | 1,779,630 | 3 | 2009-11-22T19:02:39Z | 1,779,818 | 7 | 2009-11-22T20:08:42Z | [
"python",
"windows"
] | I'm looking for a way to let multiple Python programs coexist on the same Windows machine.
Here's the problem: suppose program A needs Python 2.5, B needs 2.6, C needs 3, and each of them needs its own version of Qt, Wx or whatever other modules or whatever.
Trying to install all these dependencies on the same machin... | [VirtualEnv](http://pypi.python.org/pypi/virtualenv).
> virtualenv is a tool to create
> isolated Python environments.
>
> The basic problem being addressed is
> one of dependencies and versions, and
> indirectly permissions. Imagine you
> have an application that needs version
> 1 of LibFoo, but another application
>... |
Import Error on boost python hello program | 1,780,003 | 12 | 2009-11-22T21:06:59Z | 3,524,865 | 11 | 2010-08-19T18:12:42Z | [
"python",
"boost"
] | ```
#include <boost/python.hpp>
using namespace boost::python;
struct World{
void set(std::string msg) { this->msg = msg; }
std::string greet() { return msg; }
std::string msg;
};
BOOST_PYTHON_MODULE(hello)
{
class_<World>("World")
.def("greet", &World::greet)
.def("set", &World::set)
... | Solved this via <http://stackoverflow.com/questions/1771063/help-needed-with-boost-python>
```
g++ -c -fPIC hello.cpp -o hello.o
g++ -shared -Wl,-soname,hello.so -o hello.so hello.o -lpython2.6 -lboost_python
```
did the trick for me. I hope this is as clear as possible as i was struggling with this for about half a... |
Split dictionary of lists into list of dictionaries | 1,780,174 | 8 | 2009-11-22T22:11:55Z | 1,780,295 | 11 | 2009-11-22T22:41:55Z | [
"python"
] | What i need to do is to convert something like this
```
{'key1': [1, 2, 3], 'key2': [4, 5, 6]}
```
into
```
[{'key1':1, 'key2':4}, {'key1':2, 'key2':5}, {'key1':3, 'key2':6}]
```
The length of the value lists can vary!
What's the quickest way to do this (preferably without for loops)? | **Works for any number of keys**
```
>>> map(dict, zip(*[[(k, v) for v in value] for k, value in d.items()]))
[{'key2': 4, 'key1': 1}, {'key2': 5, 'key1': 2}, {'key2': 6, 'key1': 3}]
```
For example:
```
d = {'key3': [7, 8, 9], 'key2': [4, 5, 6], 'key1': [1, 2, 3]}
>>> map(dict, zip(*[[(k, v) for v in value] for k,... |
Tornado and Python 3.x | 1,780,303 | 11 | 2009-11-22T22:45:06Z | 1,780,348 | 13 | 2009-11-22T23:01:01Z | [
"python",
"asynchronous",
"python-3.x",
"wsgi",
"tornado"
] | I really like [Tornado](http://www.tornadoweb.org/) and I would like to use it with Python 3, though it is written for Python versions 2.5 and 2.6.
Unfortunately it seems like the project's source doesn't come with a test suite. If I understand correctly the WSGI part of it wouldn't be that easy to port as it's spec i... | Software without a decent test suite is [legacy software](http://rads.stackoverflow.com/amzn/click/0131177052) -- even if it has been released yesterday!-) -- so the first important step is to start building a test suite; I recommend Feathers' book in the URL, but you can start with [this PDF](http://www.objectmentor.c... |
Tornado and Python 3.x | 1,780,303 | 11 | 2009-11-22T22:45:06Z | 6,326,762 | 24 | 2011-06-13T04:45:53Z | [
"python",
"asynchronous",
"python-3.x",
"wsgi",
"tornado"
] | I really like [Tornado](http://www.tornadoweb.org/) and I would like to use it with Python 3, though it is written for Python versions 2.5 and 2.6.
Unfortunately it seems like the project's source doesn't come with a test suite. If I understand correctly the WSGI part of it wouldn't be that easy to port as it's spec i... | first of all, I want to apologize for an answer to an outdated topic,
but once I found this topic through Google, I want to update important information!
In the Tornado 2.0 adds support for Python 3.2!
<https://github.com/facebook/tornado/blob/master/setup.py>
<http://groups.google.com/group/python-tornado/browse_th... |
How do I update an already existing row when using ModelForms? | 1,780,499 | 7 | 2009-11-23T00:07:25Z | 1,780,566 | 9 | 2009-11-23T00:34:04Z | [
"python",
"django",
"modelform",
"piston"
] | Greetings,
I have a question on how to update an existing row in my database when one of the fields is my primary key. I am using ModelForm and Django-Piston - my main goal here is to have RESTful Post send to my webservice. I am able to have initial Posts be sent correctly (i.e. that Primary key value doesn't exist y... | The [django docs](http://docs.djangoproject.com/en/dev/topics/forms/modelforms/) give a simple example of how to create "a form to change an existing [[entity]]":
```
>>> article = Article.objects.get(pk=1)
>>> form = ArticleForm(instance=article)
```
If as it seems you want to use the same flow both for inserting ne... |
How do I use __getitem__ and __iter__ and return values from a dictionary? | 1,780,571 | 9 | 2009-11-23T00:35:14Z | 1,780,590 | 19 | 2009-11-23T00:41:10Z | [
"python",
"iterator"
] | I have an object with a dictionary that I want to access via `__getitem__` as well as iterate over (values only, keys don't matter) but am not sure how to do it.
For example:
```
Python 2.5.2 (r252:60911, Jul 22 2009, 15:33:10)
>>> class Library(object):
... def __init__(self):
... self.books = { 'title' : obj... | ```
def __iter__(self): return self.books.itervalues()
``` |
Getting every odd variable in a list? | 1,780,763 | 3 | 2009-11-23T02:03:21Z | 1,780,770 | 13 | 2009-11-23T02:06:41Z | [
"python"
] | If I make a list in Python and want to write a function that would return only odd numbers from a range 1 to x how would I do that?
For example, if I have list [1, 2, 3, 4] from 1 to 4 (4 ix my x), I want to return [1, 3]. | If you want to start with an arbitrary list:
```
[item for item in yourlist if item % 2]
```
but if you're always starting with `range`, `range(1, x, 2)` is better!-)
For example:
```
$ python -mtimeit -s'x=99' 'filter(lambda(t): t % 2 == 1, range(1, x))'
10000 loops, best of 3: 38.5 usec per loop
$ python -mtimeit... |
How do I encode a 4-byte string as a single 32-bit integer? | 1,780,922 | 2 | 2009-11-23T03:09:30Z | 1,780,937 | 8 | 2009-11-23T03:15:27Z | [
"c#",
"python",
"algorithm",
"powershell"
] | First, a disclaimer. I'm not a CS grad nor a math major, so simplicity is important.
I have a four-character string (e.g. "isoy") that I need to pass as a single 32-bit integer field. Of course at the other end, I need to decode it back to a string. The string will only contain A-Z, and case is not important, if that ... | For Python, [struct.unpack](http://docs.python.org/library/struct.html?highlight=struct.pack#struct.pack) does the job (to make a 4-byte string into an int -- `struct.pack` goes the other way):
```
>>> import struct
>>> struct.unpack('i', 'isoy')[0]
2037347177
>>> struct.pack('i', 2037347177)
'isoy'
>>>
```
(you can ... |
How do I encode a 4-byte string as a single 32-bit integer? | 1,780,922 | 2 | 2009-11-23T03:09:30Z | 1,780,959 | 10 | 2009-11-23T03:22:16Z | [
"c#",
"python",
"algorithm",
"powershell"
] | First, a disclaimer. I'm not a CS grad nor a math major, so simplicity is important.
I have a four-character string (e.g. "isoy") that I need to pass as a single 32-bit integer field. Of course at the other end, I need to decode it back to a string. The string will only contain A-Z, and case is not important, if that ... | To 32-bit unsigned integer:
```
uint x = BitConverter.ToUInt32(Encoding.ASCII.GetBytes("isoy"), 0); // 2037347177
```
To string:
```
string s = Encoding.ASCII.GetString(BitConverter.GetBytes(x)); // "isoy"
```
[BitConverter](http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx) uses the native endi... |
regular expression matching everything except a given regular expression | 1,781,554 | 5 | 2009-11-23T07:17:03Z | 1,781,605 | 19 | 2009-11-23T07:31:56Z | [
"python",
"regex"
] | I am trying to figure out a regular expression which matches any string which doesn't start with mpeg. A generalization of this is matching any string which doesn't start with a given regular expression.
I tried something like as follows:
```
[^m][^p][^e][^g].*
```
The problem with this is that it requires at least ... | ```
^(?!mpeg).*
```
This uses a negative lookahead to only match a string where the beginning doesn't match `mpeg`. Essentially, it requires that "the position at the beginning of the string cannot be a position where if we started matching the regex `mpeg`, we could successfully match" - thus matching anything which ... |
regular expression matching everything except a given regular expression | 1,781,554 | 5 | 2009-11-23T07:17:03Z | 1,781,620 | 8 | 2009-11-23T07:35:27Z | [
"python",
"regex"
] | I am trying to figure out a regular expression which matches any string which doesn't start with mpeg. A generalization of this is matching any string which doesn't start with a given regular expression.
I tried something like as follows:
```
[^m][^p][^e][^g].*
```
The problem with this is that it requires at least ... | don't lose your mind with regex.
```
if len(mystring) >=4 and mystring[:4]=="mpeg":
print "do something"
```
or use startswith() with "not" keyword
```
if len(mystring)>=4 and not mystring.startswith("mpeg")
``` |
To understand: From PHP Array to Python? | 1,781,617 | 7 | 2009-11-23T07:34:21Z | 1,781,649 | 21 | 2009-11-23T07:44:59Z | [
"php",
"python",
"arrays",
"loops"
] | This is Common task In PHP and other programming languages.I moved from PHP developer.
I want to make sure with this collections.
Anyone have who good in python please help me to understand clearly .
This is my collections from PHP code.
```
<?php
$php = array(1,2,3,4,5,6,7,8,9,10);
for ($i = 0; $i < 10 ; $i ++)
echo ... | All of these are quite obvious really. I'm only listing the *Pythonic* ways to do these things
### Example 1
PHP
```
$php = array(1,2,3,4,5,6,7,8,9,10);
for ($i = 0; $i < 10 ; $i ++)
echo $php[$i]."<br>";
```
Python (generally you *iterate* over lists in Python, instead of accessing by index):
```
lst = [1,2,3,4,5... |
To understand: From PHP Array to Python? | 1,781,617 | 7 | 2009-11-23T07:34:21Z | 1,781,694 | 10 | 2009-11-23T08:00:12Z | [
"php",
"python",
"arrays",
"loops"
] | This is Common task In PHP and other programming languages.I moved from PHP developer.
I want to make sure with this collections.
Anyone have who good in python please help me to understand clearly .
This is my collections from PHP code.
```
<?php
$php = array(1,2,3,4,5,6,7,8,9,10);
for ($i = 0; $i < 10 ; $i ++)
echo ... | "What is in Python?", quite a philosophical question, always a great way to start a day. I think what *is in* Python can best be answered by the Zen of Python (type `import this` in an interactive shell):
* Beautiful is better than ugly.
* Explicit is better than implicit.
* Simple is better than complex.
* Complex is... |
Multiplying a tuple by a scalar | 1,781,970 | 18 | 2009-11-23T09:19:40Z | 1,781,987 | 20 | 2009-11-23T09:22:41Z | [
"python",
"python-imaging-library"
] | I have the following code:
```
print img.size
print 10 * img.size
```
this will print
```
(70, 70)
(70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70)
```
while I'd like it to print
```
(700, 700)
```
Is any way there to do this without having to write
```
print (10 * img.size[0], 10... | Might be a nicer way, but this should work
```
tuple([10*x for x in img.size])
``` |
Multiplying a tuple by a scalar | 1,781,970 | 18 | 2009-11-23T09:19:40Z | 1,781,995 | 10 | 2009-11-23T09:24:29Z | [
"python",
"python-imaging-library"
] | I have the following code:
```
print img.size
print 10 * img.size
```
this will print
```
(70, 70)
(70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70)
```
while I'd like it to print
```
(700, 700)
```
Is any way there to do this without having to write
```
print (10 * img.size[0], 10... | The **pythonic** way would be using a list comprehension:
```
y = tuple([z * 10 for z in img.size])
```
Another way could be:
```
y = tuple(map((10).__mul__, img.size))
``` |
Multiplying a tuple by a scalar | 1,781,970 | 18 | 2009-11-23T09:19:40Z | 1,782,003 | 18 | 2009-11-23T09:25:30Z | [
"python",
"python-imaging-library"
] | I have the following code:
```
print img.size
print 10 * img.size
```
this will print
```
(70, 70)
(70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70)
```
while I'd like it to print
```
(700, 700)
```
Is any way there to do this without having to write
```
print (10 * img.size[0], 10... | ```
img.size = tuple(i * 10 for i in img.size)
``` |
app engine: string to datetime? | 1,782,255 | 6 | 2009-11-23T10:24:45Z | 1,782,287 | 11 | 2009-11-23T10:34:56Z | [
"python",
"datetime"
] | i have string
```
date = "11/28/2009"
hour = "23"
minutes = "59"
seconds = "00"
```
how can i convert to datetime object and store it in datastore? | I apologize if this isn't what you want, but at least for the first part of the question you could probably do it like so?
```
>>> import datetime
>>> datetime.datetime.strptime(date + ' ' + hour + ':' + minutes + ':' + seconds, '%m/%d/%Y %H:%M:%S')
datetime.datetime(2009, 11, 28, 23, 59)
``` |
Is it possible to hook up a more robust HTML parser to Python mechanize? | 1,782,368 | 9 | 2009-11-23T10:50:44Z | 5,039,584 | 10 | 2011-02-18T09:27:11Z | [
"python",
"mechanize"
] | I am trying to parse and submit a form on a website using mechanize, but it appears that the built-in form parser cannot detect the form and its elements. I suspect that it is choking on poorly formed HTML, and I'd like to try pre-parsing it with a parser better designed to handle bad HTML (say lxml or BeautifulSoup) a... | I had a problem where a form field was missing from a form, I couldn't find any malformed html but I figured that was the cause so I used BeautifulSoup's prettify function to parse it and it worked.
```
resp = br.open(url)
soup = BeautifulSoup(resp.get_data())
resp.set_data(soup.prettify())
br.set_response(resp)
```
... |
Python decorator handling docstrings | 1,782,843 | 34 | 2009-11-23T12:24:39Z | 1,782,881 | 12 | 2009-11-23T12:31:32Z | [
"python",
"decorator",
"docstring"
] | I have a problem using docstrings with decorators. Given the following example:
```
def decorator(f):
def _decorator():
print 'decorator active'
f()
return _decorator
@decorator
def foo():
'''the magic foo function'''
print 'this is function foo'
help(foo)
```
Now the help doesn't sh... | I found a solution, but don't know if it's really nice:
```
def decorator(f):
def _decorator():
print 'decorator active'
f()
_decorator.__name__=f.__name__
_decorator.__doc__=f.__doc__
return _decorator
```
The part with `_decorator.__name__=f.__name__` seems a little bit hideous... Wh... |
Python decorator handling docstrings | 1,782,843 | 34 | 2009-11-23T12:24:39Z | 1,782,888 | 48 | 2009-11-23T12:33:04Z | [
"python",
"decorator",
"docstring"
] | I have a problem using docstrings with decorators. Given the following example:
```
def decorator(f):
def _decorator():
print 'decorator active'
f()
return _decorator
@decorator
def foo():
'''the magic foo function'''
print 'this is function foo'
help(foo)
```
Now the help doesn't sh... | Use `functools.wraps()` to update the attributes of the decorator:
```
from functools import wraps
def decorator(f):
@wraps(f)
def _decorator():
print 'decorator active'
f()
return _decorator
@decorator
def foo():
'''the magic foo function'''
print 'this is function foo'
help(foo... |
Where in a virtualenv does *my* code go? | 1,783,146 | 64 | 2009-11-23T13:31:01Z | 1,783,482 | 38 | 2009-11-23T14:33:35Z | [
"python",
"project",
"virtualenv"
] | What sort of directory structure should one follow when using `virtualenv`? For instance, if I were building a WSGI application and created a virtualenv called `foobar` I would start with a directory structure like:
```
/foobar
/bin
{activate, activate.py, easy_install, python}
/include
{python2.6/...}
/... | If you only have a few projects every so often, nothing stops you from creating a new virtualenv for each one, and putting your packages right inside:
```
/foobar
/bin
{activate, activate.py, easy_install, python}
/include
{python2.6/...}
/lib
{python2.6/...}
/mypackage1
__init__.py
/mypackag... |
Where in a virtualenv does *my* code go? | 1,783,146 | 64 | 2009-11-23T13:31:01Z | 1,785,127 | 51 | 2009-11-23T18:44:16Z | [
"python",
"project",
"virtualenv"
] | What sort of directory structure should one follow when using `virtualenv`? For instance, if I were building a WSGI application and created a virtualenv called `foobar` I would start with a directory structure like:
```
/foobar
/bin
{activate, activate.py, easy_install, python}
/include
{python2.6/...}
/... | `virtualenv` provides a python interpreter instance, not an application instance. You wouldn't normally create your application files within the directories containing a system's default python, likewise there's no requirement to locate your application within a virtualenv directory. For example, you might have a proje... |
Where in a virtualenv does *my* code go? | 1,783,146 | 64 | 2009-11-23T13:31:01Z | 1,785,770 | 17 | 2009-11-23T20:35:28Z | [
"python",
"project",
"virtualenv"
] | What sort of directory structure should one follow when using `virtualenv`? For instance, if I were building a WSGI application and created a virtualenv called `foobar` I would start with a directory structure like:
```
/foobar
/bin
{activate, activate.py, easy_install, python}
/include
{python2.6/...}
/... | Because virtualenvs are not relocatable, in my opinion it is bad practice to place your project files inside a virtualenv directory. The virtualenv itself is a generated development/deployment artifact (sort of like a .pyc file), not part of the project; it should be easy to blow it away and recreate it anytime, or cre... |
Growing matrices columnwise in NumPy | 1,783,251 | 15 | 2009-11-23T13:54:00Z | 1,790,187 | 18 | 2009-11-24T13:50:48Z | [
"python",
"arrays",
"numpy"
] | In pure Python you can grow matrices column by column pretty easily:
```
data = []
for i in something:
newColumn = getColumnDataAsList(i)
data.append(newColumn)
```
[NumPy](http://en.wikipedia.org/wiki/NumPy)'s array doesn't have the append function. The `hstack` function doesn't work on zero sized arrays, th... | NumPy actually does have an *append* function, which it seems might do what you want, e.g.,
```
import numpy as NP
my_data = NP.random.random_integers(0, 9, 9).reshape(3, 3)
new_col = NP.array((5, 5, 5)).reshape(3, 1)
res = NP.append(my_data, new_col, axis=1)
```
your second snippet (hstack) will work if you add anot... |
How do I copy wsgi.input if I want to process POST data more than once? | 1,783,383 | 7 | 2009-11-23T14:18:41Z | 1,783,469 | 10 | 2009-11-23T14:32:05Z | [
"python",
"wsgi"
] | In WSGI, post data is consumed by reading the file-like object `environ['wsgi.input']`. If a second element in the stack also wants to read post data it may hang the program by reading when there's nothing more to read.
How should I copy the POST data so it can be processed multiple times? | You could try putting a file-like replica of the stream back in the environment:
```
from cStringIO import StringIO
length = int(environ.get('CONTENT_LENGTH', '0'))
body = StringIO(environ['wsgi.input'].read(length))
environ['wsgi.input'] = body
```
Needing to do this is a bit of a smell, though. Ideally only one pi... |
How do I copy wsgi.input if I want to process POST data more than once? | 1,783,383 | 7 | 2009-11-23T14:18:41Z | 1,786,453 | 7 | 2009-11-23T22:18:43Z | [
"python",
"wsgi"
] | In WSGI, post data is consumed by reading the file-like object `environ['wsgi.input']`. If a second element in the stack also wants to read post data it may hang the program by reading when there's nothing more to read.
How should I copy the POST data so it can be processed multiple times? | Go have a look at [WebOb](http://pythonpaste.org/webob/) package. It provides functionality that allows one to designate that wsgi.input should be made seekable. This has the effect of allowing you to rewind the input stream such that content can be replayed through different handler. Even if you don't use WebOb, the w... |
Any python Support Vector Machine library around that allows online learning? | 1,783,669 | 10 | 2009-11-23T15:03:29Z | 1,784,156 | 8 | 2009-11-23T16:09:44Z | [
"python",
"artificial-intelligence",
"machine-learning",
"svm"
] | I do know there are some libraries that allow to use Support vector Machines from python code, but I am looking specifically for libraries that allow one to teach it online (this is, without having to give it all the data at once).
Are there any? | [LibSVM](http://www.csie.ntu.edu.tw/~cjlin/libsvm/) includes a python wrapper that works via SWIG.
Example svm-test.py from their distribution:
```
#!/usr/bin/env python
from svm import *
# a three-class problem
labels = [0, 1, 1, 2]
samples = [[0, 0], [0, 1], [1, 0], [1, 1]]
problem = svm_problem(labels, samples);... |
term by term division in python (division termino a termino en python ) | 1,785,005 | 3 | 2009-11-23T18:18:48Z | 1,785,047 | 7 | 2009-11-23T18:26:30Z | [
"python"
] | **hello all,** need to define a function that can be divided term by term matrix or in the worst cases, between arrays of lists so you get the result in a third matrix,
thanks for any response | Unless I'm misunderstanding, this is where [`numpy`](http://numpy.scipy.org/) can be put to good use:
```
>>> from numpy import *
>>> a = array([[1,2,3],[4,5,6],[7,8,9]])
>>> b = array([[0.5] * 3, [0.5] * 3, [0.5] * 3])
>>> a / b
array([[ 2., 4., 6.],
[ 8., 10., 12.],
[ 14., 16., 18.]])
```
Th... |
Convert \r text to \n so readlines() works as intended | 1,785,233 | 11 | 2009-11-23T18:58:13Z | 1,785,275 | 31 | 2009-11-23T19:04:42Z | [
"python",
"readline"
] | In Python, you can read a file and load its lines into a list by using
```
f = open('file.txt','r')
lines = f.readlines()
```
Each individual line is delimited by `\n` but if the contents of a line have `\r` then it is not treated as a new line. I need to convert all `\r` to `\n` and get the correct list `lines`.
If... | ```
f = open('file.txt','rU')
```
This opens the file with Python's [universal newline support](http://docs.python.org/library/functions.html#open) and `\r` is treated as an end-of-line. |
When should I use uuid.uuid1() vs. uuid.uuid4() in python? | 1,785,503 | 121 | 2009-11-23T19:48:24Z | 1,785,592 | 150 | 2009-11-23T20:05:41Z | [
"python",
"uuid"
] | I understand the differences between the two from the [docs.](http://docs.python.org/2/library/uuid.html)
`uuid1()`:
Generate a UUID from a host ID, sequence number, and the current time
`uuid4()`:
Generate a random UUID.
So `uuid1` uses machine/sequence/time info to generate a UUID. What are the pros and cons o... | `uuid1()` is guaranteed to not produce any collisions (under the assumption you do not create too many of them at the same time). I wouldn't use it if it's important that there's no connection between the `uuid` and the computer, as the mac address gets used to make it unique across computers.
You can create duplicate... |
When should I use uuid.uuid1() vs. uuid.uuid4() in python? | 1,785,503 | 121 | 2009-11-23T19:48:24Z | 1,785,670 | 21 | 2009-11-23T20:18:20Z | [
"python",
"uuid"
] | I understand the differences between the two from the [docs.](http://docs.python.org/2/library/uuid.html)
`uuid1()`:
Generate a UUID from a host ID, sequence number, and the current time
`uuid4()`:
Generate a random UUID.
So `uuid1` uses machine/sequence/time info to generate a UUID. What are the pros and cons o... | One instance when you may consider `uuid1()` rather than `uuid4()` is **when UUIDs are produced on separate machines**, for example when multiple online transactions are process on several machines for scaling purposes.
In such a situation, the risks of having collisions due to poor choices in the way the pseudo-rando... |
When should I use uuid.uuid1() vs. uuid.uuid4() in python? | 1,785,503 | 121 | 2009-11-23T19:48:24Z | 34,391,851 | 7 | 2015-12-21T08:51:22Z | [
"python",
"uuid"
] | I understand the differences between the two from the [docs.](http://docs.python.org/2/library/uuid.html)
`uuid1()`:
Generate a UUID from a host ID, sequence number, and the current time
`uuid4()`:
Generate a random UUID.
So `uuid1` uses machine/sequence/time info to generate a UUID. What are the pros and cons o... | My team just ran into trouble using UUID1 for a database upgrade script where we generated ~120k UUIDs within a couple of minutes. The UUID collision led to violation of a primary key constraint.
We've upgraded 100s of servers but on our Amazon EC2 instances we ran into this issue a few times. I suspect poor clock res... |
is there a Java equivalent of Python's defaultdict? | 1,786,206 | 25 | 2009-11-23T21:42:18Z | 1,786,345 | 7 | 2009-11-23T22:00:23Z | [
"java",
"python",
"hashmap"
] | In Python, the defaultdict class provides a convenient way to create a mapping from key -> [list of values], in the following example,
```
from collections import defaultdict
d = defaultdict(list)
d[1].append(2)
d[1].append(3)
# d is now {1: [2, 3]}
```
Is there an equivalent to this in Java?
## Why I chose Tendayi ... | in addition to apache collections, check also [google collections](http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Multimap.html):
> A collection similar to a Map, but which may associate multiple values with a single key. If you call put(K, V) twice, with the same key but differen... |
is there a Java equivalent of Python's defaultdict? | 1,786,206 | 25 | 2009-11-23T21:42:18Z | 1,812,263 | 15 | 2009-11-28T11:08:10Z | [
"java",
"python",
"hashmap"
] | In Python, the defaultdict class provides a convenient way to create a mapping from key -> [list of values], in the following example,
```
from collections import defaultdict
d = defaultdict(list)
d[1].append(2)
d[1].append(3)
# d is now {1: [2, 3]}
```
Is there an equivalent to this in Java?
## Why I chose Tendayi ... | There is nothing that gives the behaviour of default dict out of the box. However creating your own default dict in Java would not be that difficult.
```
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class DefaultDict<K, V> extends HashMap<K, V> {
Class<V> klass;
public ... |
Parsing XML in Python using ElementTree example | 1,786,476 | 48 | 2009-11-23T22:24:01Z | 1,786,583 | 34 | 2009-11-23T22:42:34Z | [
"python",
"xml",
"elementtree"
] | I'm having a hard time finding a good, basic example of how to parse XML in python using Element Tree. From what I can find, this appears to be the easiest library to use for parsing XML. Here is a sample of the XML I'm working with:
```
<timeSeriesResponse>
<queryInfo>
<locationParam>01474500</locationPar... | So I have ElementTree 1.2.6 on my box now, and ran the following code against the XML chunk you posted:
```
import elementtree.ElementTree as ET
tree = ET.parse("test.xml")
doc = tree.getroot()
thingy = doc.find('timeSeries')
print thingy.attrib
```
and got the following back:
```
{'name': 'NWIS Time Series Instan... |
Parsing XML in Python using ElementTree example | 1,786,476 | 48 | 2009-11-23T22:24:01Z | 1,786,786 | 14 | 2009-11-23T23:27:32Z | [
"python",
"xml",
"elementtree"
] | I'm having a hard time finding a good, basic example of how to parse XML in python using Element Tree. From what I can find, this appears to be the easiest library to use for parsing XML. Here is a sample of the XML I'm working with:
```
<timeSeriesResponse>
<queryInfo>
<locationParam>01474500</locationPar... | If I understand your question correctly:
```
for elem in doc.findall('timeSeries/values/value'):
print elem.get('dateTime'), elem.text
```
or if you prefer (and if there is only one occurrence of `timeSeries/values`:
```
values = doc.find('timeSeries/values')
for value in values:
print value.get('dateTime'),... |
Python - Simple algorithmic task on lists (standard question for a job-interview) | 1,786,504 | 3 | 2009-11-23T22:28:31Z | 1,786,534 | 9 | 2009-11-23T22:33:44Z | [
"python",
"algorithm"
] | There are 2 input lists L and M, for example:
```
L = ['a', 'ab', 'bba']
M = ['baa', 'aa', 'bb']
```
How to obtain 2 non-empty output lists U and V such that:
`''.join(U) == ''.join(V)) is True`,
and every element of U is in L, and every element of V is in M?
For example, one possible solution for the two inp... | What are you looking for -- all (the countable infinity of) possible solutions? The "shortest" (by some measure) **non-empty** solution, or the set of equal-shortest ones, or...?
Because, if **any** solution will do, setting U and V both to [] meets all the stated conditions, and is O(1) to boot;-).
**Edit**: ok, so,... |
How different are the semantics between Python and JavaScript? | 1,786,522 | 12 | 2009-11-23T22:30:41Z | 1,786,584 | 19 | 2009-11-23T22:42:43Z | [
"javascript",
"python",
"semantics"
] | Both these languages seem extremely similar to me. Although Python supports actual classes instead of being prototype-based, in Python classes are not all that different from functions that generate objects containing values and functions, just as you'd do in JavaScript. On the other hand, JavaScript only supports floa... | 1. Classical inheritance in Python, Prototypal inheritance in ECMAScript
2. ECMAScript is a braces and semicolons language while Python is white-space and indent/block based
3. No `var` keyword in Python, implicit globals in ECMAScript, both are lexically scoped
4. Closures in Python 2.5 and lower ( re: Alex Martelli's... |
what is the true difference between lemmatization vs stemming? | 1,787,110 | 30 | 2009-11-24T00:48:11Z | 1,787,121 | 44 | 2009-11-24T00:52:12Z | [
"python",
"nlp",
"nltk",
"lemmatization"
] | When do I use each ?
Also...is the NLTK lemmatization dependent upon Parts of Speech?
Wouldn't it be more accurate if it was? | Short and dense: <http://nlp.stanford.edu/IR-book/html/htmledition/stemming-and-lemmatization-1.html>
> The goal of both stemming and lemmatization is to reduce inflectional forms and sometimes derivationally related forms of a word to a common base form.
>
> However, the two words differ in their flavor. Stemming usu... |
what is the true difference between lemmatization vs stemming? | 1,787,110 | 30 | 2009-11-24T00:48:11Z | 1,787,709 | 8 | 2009-11-24T04:07:18Z | [
"python",
"nlp",
"nltk",
"lemmatization"
] | When do I use each ?
Also...is the NLTK lemmatization dependent upon Parts of Speech?
Wouldn't it be more accurate if it was? | As MYYN pointed out, stemming is the process of removing inflectional and sometimes derivational affixes to a base form that all of the original words are probably related to. Lemmatization is concerned with obtaining the single word that allows you to group together a bunch of inflected forms. This is harder than stem... |
what is the true difference between lemmatization vs stemming? | 1,787,110 | 30 | 2009-11-24T00:48:11Z | 5,605,064 | 8 | 2011-04-09T12:37:15Z | [
"python",
"nlp",
"nltk",
"lemmatization"
] | When do I use each ?
Also...is the NLTK lemmatization dependent upon Parts of Speech?
Wouldn't it be more accurate if it was? | The purpose of both stemming and lemmatization is to reduce morphological variation. This is in contrast to the the more general "term conflation" procedures, which may also address lexico-semantic, syntactic, or orthographic variations.
The real difference between stemming and lemmatization is threefold:
1. Stemming... |
what is the true difference between lemmatization vs stemming? | 1,787,110 | 30 | 2009-11-24T00:48:11Z | 31,247,216 | 7 | 2015-07-06T13:31:35Z | [
"python",
"nlp",
"nltk",
"lemmatization"
] | When do I use each ?
Also...is the NLTK lemmatization dependent upon Parts of Speech?
Wouldn't it be more accurate if it was? | > **Lemmatisation** is closely related to **stemming**. The difference is that a
> stemmer operates on a single word without knowledge of the context,
> and therefore cannot discriminate between words which have different
> meanings depending on part of speech. However, stemmers are typically
> easier to implement and ... |
How to call ssh by subprocess module so that it uses SSH_ASKPASS variable | 1,787,288 | 8 | 2009-11-24T01:45:36Z | 1,793,567 | 15 | 2009-11-24T23:05:30Z | [
"python",
"ssh",
"subprocess"
] | I am writing a GUI which uses SSH commands. I tried to use the subprocess module to call ssh and set the SSH\_ASKPASS environment variable so that my application can pop up a window asking for the SSH password. However I cannot make ssh read the password using the given SSH\_ASKPASS command: it always prompts it in the... | SSH uses the SSH\_ASKPASS variable only if the process is really detached from TTY (stdin redirecting and setting environment variables is not enough). To detach a process from console it should fork and call os.setsid(). So the first solution I found was:
```
# Detach process
pid = os.fork()
if pid == 0:
# Ensure... |
How do I limit the number of active threads in python? | 1,787,397 | 7 | 2009-11-24T02:24:12Z | 5,991,741 | 26 | 2011-05-13T12:22:13Z | [
"python",
"multithreading"
] | Am new to python and making some headway with `threading` - am doing some music file conversion and want to be able to utilize the multiple cores on my machine (one active conversion thread per core).
```
class EncodeThread(threading.Thread):
# this is hacked together a bit, but should give you an idea
def run... | If you want to limit the number of parallel threads, use a [semaphore](http://docs.python.org/library/threading.html#semaphore-objects):
```
threadLimiter = threading.BoundedSemaphore(maximumNumberOfThreads)
class EncodeThread(threading.Thread):
def run(self):
threadLimiter.acquire()
try:
... |
Python and .NET integration | 1,787,755 | 7 | 2009-11-24T04:21:28Z | 1,788,172 | 7 | 2009-11-24T06:18:44Z | [
"python",
".net",
"nlp",
"nltk",
"python.net"
] | I'm currently looking at python because I really like the text parsing capabilities and the nltk library, but traditionally I am a .Net/C# programmer. I don't think IronPython is an integration point for me because I am using NLTK and presumably would need a port of that library to the CLR. I've looked a little at [Pyt... | NLTK is pure-python and thus can be made to run on IronPython easily. A search turned up [this ticket](http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=24357) - all one has to do is install a couple of extra Python libraries that don't come by default with IronPython.
This is probably the easiest way for y... |
Using contexts in rdflib | 1,788,063 | 5 | 2009-11-24T05:45:43Z | 1,788,129 | 9 | 2009-11-24T06:06:22Z | [
"python",
"rdf",
"rdflib"
] | I am having trouble finding a clear, sensible example of usage of context with rdflib.
ConjunctiveGraph does not accept contexts, and Graph is deprecated. How am I supposed to create and operate on different contexts within the same global ConjunctiveGraph ? | Yes. This is the code
```
import rdflib
from rdflib.Graph import Graph
conj=rdflib.ConjunctiveGraph()
NS=rdflib.Namespace("http://example.com/#")
NS_CTX=rdflib.Namespace("http://example.com/context/#")
alice=NS.alice
bob=NS.bob
charlie=NS.charlie
pizza=NS.pizza
meat=NS.meat
chocolate=NS.chocolate
loves=NS.loves
h... |
How do I remove something form a list, plus string matching? | 1,788,710 | 2 | 2009-11-24T08:39:34Z | 1,788,728 | 10 | 2009-11-24T08:43:48Z | [
"python",
"regex",
"list"
] | ```
[(',', 52),
('news', 15),
('.', 11),
('bbc', 8),
('and', 8),
('the', 8),
(':', 6),
('music', 5),
('-', 5),
('blog', 4),
('world', 4),
('asia', 4),
('international', 4),
('on', 4),
('itunes', 4),
('online', 4),
('digital', 3)]
```
Suppose I have this list, with tuples inside.
How do I go through th... | ```
the_list = [(a, b) for a, b in the_list if a.isalpha()]
``` |
How to get the next token (int, float or string) from a file in Python? | 1,789,114 | 6 | 2009-11-24T10:11:15Z | 1,789,203 | 10 | 2009-11-24T10:29:50Z | [
"python"
] | Is there some way to just get the next token from a file in Python, as for example the Scanner class does in Java?
```
File file = new File("something");
Scanner myinput = new Scanner(file);
double a = myinput.nextDouble();
String s = myinput.next();
```
I'd like to ignore whitespaces, tabs, newlines and just get the... | Check out the shlex-module in the standard library: <http://docs.python.org/library/shlex.html>
```
import shlex
import StringIO # use in place of files
list(shlex.shlex(StringIO.StringIO('Some tokens. 123, 45.67 "A string with whitespace"')))
```
It does not handle floats the way you seem to want. Maybe you can ext... |
Clustering text in Python | 1,789,254 | 22 | 2009-11-24T10:43:39Z | 1,791,009 | 43 | 2009-11-24T15:58:35Z | [
"python",
"cluster-analysis",
"nlp"
] | I need to cluster some text documents and have been researching various options. It looks like LingPipe can cluster plain text without prior conversion (to vector space etc), but it's the only tool I've seen that explicitly claims to work on strings.
Are there any Python tools that can cluster text directly? If not, w... | The quality of text-clustering depends mainly on two factors:
1. Some notion of similarity between the documents you want to cluster. For example, it's easy to distinguish between newsarticles about sports and politics in vector space via tfidf-cosine-distance. It's a lot harder to cluster product-reviews in "good" or... |
How to parse *.py file with python? | 1,789,301 | 2 | 2009-11-24T10:54:06Z | 1,789,342 | 13 | 2009-11-24T11:01:07Z | [
"python",
"go",
"code-conversion"
] | I'd like to parse Python source in order to try making a basic source code converter from Python to Go.
* What module should I use?
* Should I proceed or not?
* If I should proceed, how? | Have a look at the [language services](http://docs.python.org/library/language.html) packages, particularly the [ast](http://docs.python.org/library/ast.html).
My guess is that if you don't already have a solid grasp of both parsing as well as code generation techniques, this is going to be a difficult project to unde... |
How to find number of bytes taken by python variable | 1,789,543 | 11 | 2009-11-24T11:41:47Z | 1,789,567 | 23 | 2009-11-24T11:47:20Z | [
"python"
] | Is there anyway i can know how much bytes taken by particular variable in python. E.g; lets say i have
```
int = 12
print (type(int))
```
it will print
```
<class 'int'>
```
But i wanted to know how many bytes it has taken on memory? is it possible? | You can find the functionality you are looking for [here](http://docs.python.org/library/sys.html#sys.getsizeof) (in `sys.getsizeof` - Python 2.6 and up).
Also: don't shadow the `int` builtin!
```
import sys
myint = 12
print sys.getsizeof(myint)
``` |
How to apply a logical operator to all elements in a python list | 1,790,520 | 29 | 2009-11-24T14:44:40Z | 1,790,532 | 69 | 2009-11-24T14:46:24Z | [
"python"
] | I have a list of booleans in python. I want to AND (or OR or NOT) them and get the result. The following code works but is not very pythonic.
```
def apply_and(alist):
if len(alist) > 1:
return alist[0] and apply_and(alist[1:])
else:
return alist[0]
```
Any suggestions on how to make it more pythonic appr... | Logical `and` across all elements in `a_list`:
```
all(a_list)
```
Logical `or` across all elements in `a_list`:
```
any(a_list)
```
---
If you feel creative, you can also do:
```
import operator
def my_all(a_list):
return reduce(operator.and_, a_list, True)
def my_any(a_list):
return reduce(operator.or_, a_... |
How to apply a logical operator to all elements in a python list | 1,790,520 | 29 | 2009-11-24T14:44:40Z | 1,790,558 | 9 | 2009-11-24T14:49:39Z | [
"python"
] | I have a list of booleans in python. I want to AND (or OR or NOT) them and get the result. The following code works but is not very pythonic.
```
def apply_and(alist):
if len(alist) > 1:
return alist[0] and apply_and(alist[1:])
else:
return alist[0]
```
Any suggestions on how to make it more pythonic appr... | [Reduce](http://docs.python.org/library/functions.html) can do this:
```
reduce(lambda a,b: a and b, alist, True)
```
As fortran mentioned, all is the most succinct way to do it. But reduce answers the more general question "How to apply a logical operator to all elements in a python list?" |
How to apply a logical operator to all elements in a python list | 1,790,520 | 29 | 2009-11-24T14:44:40Z | 1,790,576 | 28 | 2009-11-24T14:52:37Z | [
"python"
] | I have a list of booleans in python. I want to AND (or OR or NOT) them and get the result. The following code works but is not very pythonic.
```
def apply_and(alist):
if len(alist) > 1:
return alist[0] and apply_and(alist[1:])
else:
return alist[0]
```
Any suggestions on how to make it more pythonic appr... | ANDing and ORing is easy:
```
>>> some_list = [True] * 100
# OR
>>> any(some_list)
True
#AND
>>> all(some_list)
True
>>> some_list[0] = False
>>> any(some_list)
True
>>> all(some_list)
False
```
NOTing is also fairly easy:
```
>>> [not x for x in some_list]
[True, False, False, False, False, False, False, False, Fal... |
Running average in Python | 1,790,550 | 13 | 2009-11-24T14:48:41Z | 1,790,600 | 14 | 2009-11-24T14:55:39Z | [
"python",
"list-comprehension",
"moving-average"
] | Is there a pythonic way to **build up a list that contains a running average** of some function?
After reading a fun little piece about [Martians, black boxes, and the Cauchy distribution](http://www.johndcook.com/Cauchy%5Festimation.html), I thought it would be fun to calculate a running average of the Cauchy distrib... | You could write a generator:
```
def running_average():
sum = 0
count = 0
while True:
sum += cauchy(3,1)
count += 1
yield sum/count
```
Or, given a generator for Cauchy numbers and a utility function for a running sum generator, you can have a neat generator expression:
```
# Cauchy numbers generat... |
Parsing date with timezone from an email? | 1,790,795 | 21 | 2009-11-24T15:27:45Z | 1,790,885 | 21 | 2009-11-24T15:42:23Z | [
"python",
"datetime",
"timezone",
"format",
"rfc5322"
] | I am trying to retrieve date from an email. At first it's easy:
```
message = email.parser.Parser().parse(file)
date = message['Date']
print date
```
and I receive:
```
'Mon, 16 Nov 2009 13:32:02 +0100'
```
But I need a nice datetime object, so I use:
```
datetime.strptime('Mon, 16 Nov 2009 13:32:02 +0100', '%a, %... | `email.utils` has a `parsedate()` function for the RFC 2822 format, which as far as I know is not deprecated.
```
>>> import email.utils
>>> import time
>>> import datetime
>>> email.utils.parsedate('Mon, 16 Nov 2009 13:32:02 +0100')
(2009, 11, 16, 13, 32, 2, 0, 1, -1)
>>> time.mktime((2009, 11, 16, 13, 32, 2, 0, 1, -... |
Parsing date with timezone from an email? | 1,790,795 | 21 | 2009-11-24T15:27:45Z | 8,339,750 | 20 | 2011-12-01T10:22:20Z | [
"python",
"datetime",
"timezone",
"format",
"rfc5322"
] | I am trying to retrieve date from an email. At first it's easy:
```
message = email.parser.Parser().parse(file)
date = message['Date']
print date
```
and I receive:
```
'Mon, 16 Nov 2009 13:32:02 +0100'
```
But I need a nice datetime object, so I use:
```
datetime.strptime('Mon, 16 Nov 2009 13:32:02 +0100', '%a, %... | Use [`email.utils.parsedate_tz(date)`](https://docs.python.org/2/library/email.util.html#email.utils.parsedate_tz):
```
msg=email.message_from_file(open(file_name))
date=None
date_str=msg.get('date')
if date_str:
date_tuple=email.utils.parsedate_tz(date_str)
if date_tuple:
date=datetime.datetime.fromti... |
Looping through files in a folder | 1,792,312 | 32 | 2009-11-24T19:19:07Z | 1,792,350 | 34 | 2009-11-24T19:24:28Z | [
"python",
"file",
"loops"
] | I'm fairly new when it comes to programming, and have started out learning python.
What I want to do is to recolour sprites for a game, and I am given the original colours,
followed by what they are to be turned into. Each sprite has between 20 and 60 angles, so
looping through each one in the folder for each colour i... | [os.listdir()](http://docs.python.org/library/os.html) returns a list of file names. Thus, `filename` is a string. You need to open the file before iterating on it, I guess.
Also, be careful with backslashes in strings. They are mostly used for special escape sequences, so you need to escape them by doubling them. You... |
Looping through files in a folder | 1,792,312 | 32 | 2009-11-24T19:19:07Z | 1,792,374 | 10 | 2009-11-24T19:28:48Z | [
"python",
"file",
"loops"
] | I'm fairly new when it comes to programming, and have started out learning python.
What I want to do is to recolour sprites for a game, and I am given the original colours,
followed by what they are to be turned into. Each sprite has between 20 and 60 angles, so
looping through each one in the folder for each colour i... | ```
for pix in filename:
```
iterates over the letters of the filename. So that's certainly not what you want. You'll probably want to replace that line by:
```
with open(filename) as current_file:
for pix in current_file:
```
(assuming Python 2.6) and indent the rest of the loop accordingly.
However, I'm not s... |
What are the limits of Python? | 1,792,360 | 6 | 2009-11-24T19:26:02Z | 1,792,402 | 9 | 2009-11-24T19:32:56Z | [
"c++",
"python"
] | I spent a few days reading about C++ and Python and I found that Python is so much simpler and easy to learn.
So I wonder does it really worth spending time learning it? Or should I invest that time learning C++ instead?
What can C++ do and Python can't ? | Why don't you ask the converse question? Unlike C++, Python can give you [antigravity](http://xkcd.com/353/) and summon [souls](http://xkcd.com/413/) via its `import` command. On the other hand, C++'s 'equivalent' -- `#include` -- only allows you to get some boring I/O and math libraries.
Seriously though.. C++ allows... |
What are the limits of Python? | 1,792,360 | 6 | 2009-11-24T19:26:02Z | 1,793,767 | 31 | 2009-11-24T23:45:23Z | [
"c++",
"python"
] | I spent a few days reading about C++ and Python and I found that Python is so much simpler and easy to learn.
So I wonder does it really worth spending time learning it? Or should I invest that time learning C++ instead?
What can C++ do and Python can't ? | Some Python limits :
**- Python is slow.** It can be improved in many ways (see other answers) but the bare bone cPython is 100 times slower that C/C++.
*This problem is getter more and more mitigated. With Numpy, Pypy and asyncio, most performance problems are not covered, and only very specific use cases are a bott... |
What are the limits of Python? | 1,792,360 | 6 | 2009-11-24T19:26:02Z | 1,794,560 | 25 | 2009-11-25T04:10:50Z | [
"c++",
"python"
] | I spent a few days reading about C++ and Python and I found that Python is so much simpler and easy to learn.
So I wonder does it really worth spending time learning it? Or should I invest that time learning C++ instead?
What can C++ do and Python can't ? | Here's why it's worth learning Python:
A comparatively small number of problems are constrained by the speed of the algorithm. A comparatively large number of problems are bounded by the speed of the developer. |
Weird MySQL Python mod_wsgi Can't connect to MySQL server on 'localhost' (49) problem | 1,792,918 | 5 | 2009-11-24T21:05:57Z | 5,552,089 | 9 | 2011-04-05T12:50:24Z | [
"python",
"mysql",
"django",
"mod-wsgi",
"mysql-error-2003"
] | There have been similar questions on StackOverflow about this, but I haven't found quite the same situation. This is on a OS X Leopard machine using MySQL
Some starting information:
```
MySQL Server version 5.1.30
Apache/2.2.13 (Unix)
Python 2.5.1
mod_wsgi 3
```
mysqladmin also has skip-networking listed as OFF
... | I came across this error and it was due to an SELinux denial. /usr/bin/httpd didn't have permission to connect to port 3306. I corrected the issue with:
```
setsebool httpd_can_network_connect_db on
```
Seems to work great and should be more secure than just disabling SELinux. As Avinash Meetoo points out below, you ... |
How to join components of a path when you are constructing a URL in Python | 1,793,261 | 44 | 2009-11-24T22:06:07Z | 1,793,282 | 67 | 2009-11-24T22:10:12Z | [
"python",
"url"
] | For example, I want to join a prefix path to resource paths like /js/foo.js.
I want the resulting path to be relative to the root of the server. In the above example if the prefix was "media" I would want the result to be /media/js/foo.js.
os.path.join does this really well, but how it joins paths is OS dependent. In... | ```
>>> import urlparse
>>> urlparse.urljoin('/media/', 'js/foo.js')
'/media/js/foo.js'
```
Note that you will get different results from `/js/foo.js` and `js/foo.js` because the former begins with a slash which signifies that it already begins at the website root. |
How to join components of a path when you are constructing a URL in Python | 1,793,261 | 44 | 2009-11-24T22:06:07Z | 1,794,540 | 21 | 2009-11-25T04:05:12Z | [
"python",
"url"
] | For example, I want to join a prefix path to resource paths like /js/foo.js.
I want the resulting path to be relative to the root of the server. In the above example if the prefix was "media" I would want the result to be /media/js/foo.js.
os.path.join does this really well, but how it joins paths is OS dependent. In... | Since, from the comments the OP posted, it seems he **doesn't** want to preserve "absolute URLs" in the join (which is one of the key jobs of `urlparse.urljoin`;-), I'd recommend avoiding that. `os.path.join` would also be bad, for exactly the same reason.
So, I'd use something like `'/'.join(s.strip('/') for s in pie... |
How to join components of a path when you are constructing a URL in Python | 1,793,261 | 44 | 2009-11-24T22:06:07Z | 15,279,799 | 19 | 2013-03-07T19:15:45Z | [
"python",
"url"
] | For example, I want to join a prefix path to resource paths like /js/foo.js.
I want the resulting path to be relative to the root of the server. In the above example if the prefix was "media" I would want the result to be /media/js/foo.js.
os.path.join does this really well, but how it joins paths is OS dependent. In... | Like you say, `os.path.join` joins paths based on the current os. `posixpath.join` is the underlying module that is used on posix systems:
```
>>> os.path.join is posixpath.join
True
>>> posixpath.join('/media/', 'js/foo.js')
'/media/js/foo.js'
```
So you can just import and use `posixpath.join` instead for urls, whi... |
Python HTML scraping | 1,793,663 | 3 | 2009-11-24T23:23:25Z | 1,793,682 | 9 | 2009-11-24T23:27:31Z | [
"python",
"html",
"regex",
"screen-scraping",
"html-content-extraction"
] | It's not really scraping, I'm just trying to find the URLs in a web page where the class has a specific value. For example:
```
<a class="myClass" href="/url/7df028f508c4685ddf65987a0bd6f22e">
```
I want to get the href value. Any ideas on how to do this? Maybe regex? Could you post some example code?
I'm guessing ht... | Aargh, not [regex for parsing HTML](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454)!
Luckily in Python we have [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) or [lxml](http://codespeak.net/lxml/) to do that job for us. |
Python HTML scraping | 1,793,663 | 3 | 2009-11-24T23:23:25Z | 1,793,686 | 16 | 2009-11-24T23:28:17Z | [
"python",
"html",
"regex",
"screen-scraping",
"html-content-extraction"
] | It's not really scraping, I'm just trying to find the URLs in a web page where the class has a specific value. For example:
```
<a class="myClass" href="/url/7df028f508c4685ddf65987a0bd6f22e">
```
I want to get the href value. Any ideas on how to do this? Maybe regex? Could you post some example code?
I'm guessing ht... | Regex is usally a bad idea, try using [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/)
Quick example:
```
html = #get html
soup = BeautifulSoup(html)
links = soup.findAll('a', attrs={'class': 'myclass'})
for link in links:
#process link
``` |
How to make uniques in Django Models? And also index a column in Django | 1,793,957 | 8 | 2009-11-25T00:40:54Z | 1,794,072 | 11 | 2009-11-25T01:18:17Z | [
"python",
"mysql",
"django",
"django-models"
] | This is my simple Django database model. It's for a 5-star rating system.
```
class Rating(models.Model):
content = models.OneToOneField(Content, primary_key=True)
ip = models.CharField(max_length=200, blank=True)
rating = models.IntegerField(default=0)
```
As you can see, it is linked to "Content", whic... | Regarding your first question:
You should look at [unique\_together](http://docs.djangoproject.com/en/dev/ref/models/options/#unique-together), since this could solve your issue.
```
class Rating(models.Model):
content = models.OneToOneField(Content, primary_key=True)
ip = models.CharField(max_length=200, bla... |
How to make uniques in Django Models? And also index a column in Django | 1,793,957 | 8 | 2009-11-25T00:40:54Z | 1,794,461 | 7 | 2009-11-25T03:36:55Z | [
"python",
"mysql",
"django",
"django-models"
] | This is my simple Django database model. It's for a 5-star rating system.
```
class Rating(models.Model):
content = models.OneToOneField(Content, primary_key=True)
ip = models.CharField(max_length=200, blank=True)
rating = models.IntegerField(default=0)
```
As you can see, it is linked to "Content", whic... | BTW, if, as it appears from your terminology, you're using IP addresses as standing for users' identities, **please don't** -- it's a seriously horrible idea. Users coming in through their ISP will get their IPs changed at random times, so they might vote twice; users on a laptop connecting at various coffee shops, lib... |
Passing SQLite variables in Python | 1,793,970 | 4 | 2009-11-25T00:44:23Z | 1,793,987 | 9 | 2009-11-25T00:47:59Z | [
"python",
"sqlite"
] | I am writing a app in python and utilzing sqlite. I have a list of strings which I would like to add too the database, where each element represents some data which coincides with the column it will be put.
currently I have something like this
```
cursor.execute("""insert into credit
values ('Citi... | Use parameters to `.execute()`:
```
query = """
INSERT INTO credit
(bank, number, card, int1, value, type, int2)
VALUES
(?, ?, ?, ?, ?, ?, ?)
"""
data = ['Citi', '5567', 'visa', 6000, 9.99, '23', 9000]
cursor.execute(query, data)
```
According to [PEP249](http://www.python.org/d... |
Python on Rails? | 1,794,179 | 16 | 2009-11-25T01:56:10Z | 1,794,205 | 13 | 2009-11-25T02:02:14Z | [
"python",
"ruby-on-rails",
"metaprogramming",
"code-translation"
] | Would it be possible to translate the Ruby on Rails code base to Python?
I think many people like Python more than Ruby, but find Ruby on Rails features better (as a whole) than the ones in Python web frameworks.
So that, would it be possible? Or does Ruby on Rails utilize language-specific features that would be dif... | I think one of the things that people like about RoR is the domain-specific language (DSL) style of programming. This is something that Ruby is much better at than Python. |
Python on Rails? | 1,794,179 | 16 | 2009-11-25T01:56:10Z | 1,794,250 | 16 | 2009-11-25T02:14:22Z | [
"python",
"ruby-on-rails",
"metaprogramming",
"code-translation"
] | Would it be possible to translate the Ruby on Rails code base to Python?
I think many people like Python more than Ruby, but find Ruby on Rails features better (as a whole) than the ones in Python web frameworks.
So that, would it be possible? Or does Ruby on Rails utilize language-specific features that would be dif... | Many of the methodology used in Rails has been translated into Django. Have you tried it?
<http://www.djangoproject.com/> |
Python on Rails? | 1,794,179 | 16 | 2009-11-25T01:56:10Z | 1,794,268 | 11 | 2009-11-25T02:21:22Z | [
"python",
"ruby-on-rails",
"metaprogramming",
"code-translation"
] | Would it be possible to translate the Ruby on Rails code base to Python?
I think many people like Python more than Ruby, but find Ruby on Rails features better (as a whole) than the ones in Python web frameworks.
So that, would it be possible? Or does Ruby on Rails utilize language-specific features that would be dif... | [This is a great blog post](http://blog.ianbicking.org/what-really-makes-rails-work.html). Rails developers chose a framework, and coding in Ruby is the afterthought.
Python developers chose the language for the language, not the framework. On the other hand, that made a lot lower bar to entry for frameworks. |
How can I read the memory of another process in Python in Windows? | 1,794,579 | 8 | 2009-11-25T04:15:40Z | 1,794,686 | 10 | 2009-11-25T04:44:59Z | [
"python"
] | I'm trying to write a Python script that reads a series of memory locations of a particular process.
How can I do this in Python?
I'll be using Windows if it matters. I have the processes PID that I'm attempting to read/edit.
Am I going to have to revert to calling ReadProcessMemory() and using ctypes? | I didn't see anything in the standard python libraries but I found an example using ctypes like you suggested on another site:
```
from ctypes import *
from ctypes.wintypes import *
OpenProcess = windll.kernel32.OpenProcess
ReadProcessMemory = windll.kernel32.ReadProcessMemory
CloseHandle = windll.kernel32.CloseHandl... |
Is there a cross-platform way to open a file browser in Python? | 1,795,111 | 10 | 2009-11-25T06:56:36Z | 1,795,849 | 15 | 2009-11-25T09:56:24Z | [
"python",
"cross-platform",
"operating-system"
] | I'm thinking something along the lines of the [webbrowser](http://docs.python.org/library/webbrowser.html) module, but for file browsers. In Windows I'd like to open explorer, in GNOME on Linux I want to open nautilus, Konqueror on KDE, etc. I'd prefer not to kludge it up if I can avoid it. ;-) | > I'd prefer not to kludge it up if I can avoid it.
Weeell I think you are going to need a little bit of platform-sniffing kludge, but hopefully not as much as the ghastly command-sniffing `webbrowser` module. Here's a first stab at it:
```
if sys.platform=='win32':
subprocess.Popen(['start', d], shell= True)
el... |
How can I get a list of all classes within current module in Python? | 1,796,180 | 170 | 2009-11-25T10:59:46Z | 1,796,234 | 7 | 2009-11-25T11:09:18Z | [
"python",
"reflection",
"inspect"
] | I've seen plenty of examples of people extracting all of the classes from a module, usually something like:
```
# foo.py
class Foo:
pass
# test.py
import inspect
import foo
for name, obj in inspect.getmembers(foo):
if inspect.isclass(obj):
print obj
```
Awesome.
But I can't find out how to get all ... | I don't know if there's a 'proper' way to do it, but your snippet is on the right track: just add `import foo` to foo.py, do `inspect.getmembers(foo)`, and it should work fine. |
How can I get a list of all classes within current module in Python? | 1,796,180 | 170 | 2009-11-25T10:59:46Z | 1,796,247 | 215 | 2009-11-25T11:12:22Z | [
"python",
"reflection",
"inspect"
] | I've seen plenty of examples of people extracting all of the classes from a module, usually something like:
```
# foo.py
class Foo:
pass
# test.py
import inspect
import foo
for name, obj in inspect.getmembers(foo):
if inspect.isclass(obj):
print obj
```
Awesome.
But I can't find out how to get all ... | Try this:
```
import sys
current_module = sys.modules[__name__]
```
In your context:
```
import sys, inspect
def print_classes():
for name, obj in inspect.getmembers(sys.modules[__name__]):
if inspect.isclass(obj):
print(obj)
```
And even better:
```
clsmembers = inspect.getmembers(sys.modu... |
How can I get a list of all classes within current module in Python? | 1,796,180 | 170 | 2009-11-25T10:59:46Z | 1,796,252 | 12 | 2009-11-25T11:13:14Z | [
"python",
"reflection",
"inspect"
] | I've seen plenty of examples of people extracting all of the classes from a module, usually something like:
```
# foo.py
class Foo:
pass
# test.py
import inspect
import foo
for name, obj in inspect.getmembers(foo):
if inspect.isclass(obj):
print obj
```
Awesome.
But I can't find out how to get all ... | What about
```
g = globals().copy()
for name, obj in g.iteritems():
```
? |
Accessing a Python traceback from the C API | 1,796,510 | 17 | 2009-11-25T12:05:44Z | 1,796,569 | 7 | 2009-11-25T12:21:48Z | [
"python"
] | I'm having some trouble figuring out the proper way to walk a Python traceback using the C API. I'm writing an application that embeds the Python interpreter. I want to be able to execute arbitrary Python code, and if it raises an exception, to translate it to my own application-specific C++ exception. For now, it is s... | I've discovered that `_frame` is actually defined in the `frameobject.h` header included with Python. Armed with this plus looking at `traceback.c` in the Python C implementation, we have:
```
#include <Python.h>
#include <frameobject.h>
PyTracebackObject* traceback = get_the_traceback();
int line = traceback->tb_li... |
Accessing a Python traceback from the C API | 1,796,510 | 17 | 2009-11-25T12:05:44Z | 15,907,460 | 7 | 2013-04-09T16:30:29Z | [
"python"
] | I'm having some trouble figuring out the proper way to walk a Python traceback using the C API. I'm writing an application that embeds the Python interpreter. I want to be able to execute arbitrary Python code, and if it raises an exception, to translate it to my own application-specific C++ exception. For now, it is s... | I prefer calling into python from C:
```
err = PyErr_Occurred();
if (err != NULL) {
PyObject *ptype, *pvalue, *ptraceback;
PyObject *pystr, *module_name, *pyth_module, *pyth_func;
char *str;
PyErr_Fetch(&ptype, &pvalue, &ptraceback);
pystr = PyObject_Str(pvalue);
str = PyString_AsString(pystr)... |
Python, thread and gobject | 1,796,588 | 5 | 2009-11-25T12:25:21Z | 1,796,638 | 7 | 2009-11-25T12:34:35Z | [
"python",
"multithreading",
"pygtk"
] | I am writing a program by a framework using pygtk. The main program doing the following things:
1. Create a watchdog thread to monitor some resource
2. Create a client to receive data from socket
3. call `gobject.Mainloop()`
but it seems after my program enter the Mainloop, the watchdog thread also won't run.
My wor... | Can you post some code? It could be that you have problems with the [Global Interpreter Lock](http://docs.python.org/glossary.html#term-global-interpreter-lock).
[Your problem solved by someone else :)](http://www.jejik.com/articles/2007/01/python-gstreamer%5Fthreading%5Fand%5Fthe%5Fmain%5Floop/). I could copy-paste t... |
import an array in python | 1,796,597 | 9 | 2009-11-25T12:26:18Z | 1,796,610 | 17 | 2009-11-25T12:29:03Z | [
"python",
"numpy"
] | How can I import an array to python (numpy.arry) from a file and that way the file must be written if it doesn't already exist.
For example, save out a matrix to a file then load it back. | Checkout the entry on the [numpy example list](http://scipy.org/Numpy%5FExample%5FList#head-e20ed4935bc0f3edcb23420fe9d2617dbcd6b1ea). Here is the entry on .loadtxt()
```
>>> from numpy import *
>>>
>>> data = loadtxt("myfile.txt") # myfile.txt contains 4 columns of numbers
>>> t,z = data[:,0], d... |
Is there something like for i in range(length) in PHP? | 1,797,322 | 6 | 2009-11-25T14:38:49Z | 1,797,342 | 9 | 2009-11-25T14:41:25Z | [
"php",
"python",
"range"
] | In python we have:
```
for i in range(length)
```
What about in PHP? | Straight from the [docs:](http://php.net/manual/en/function.range.php)
```
foreach (range(0, 12) as $number) {
echo $number;
}
``` |
Recognising tone of the audio | 1,797,631 | 14 | 2009-11-25T15:19:55Z | 1,797,674 | 16 | 2009-11-25T15:27:20Z | [
"python",
"audio"
] | I have a guitar and I need my pc to be able to tell what note is being played, recognizing the tone. Is it possible to do it in python, also is it possible with pygame? Being able of doing it in pygame would be very helpful. | To recognize the frequency of an audio signal, you would use the FFT ([fast Fourier transform](http://en.wikipedia.org/wiki/Fast%5FFourier%5Ftransform)) algorithm. As far as I can tell, PyGame has no means to record audio, nor does it support the FFT transform.
First, you need to capture the raw sampled data from the ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.