title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
python: iterate over dictionary sorted by key | 16,710,112 | 20 | 2013-05-23T09:23:12Z | 16,710,216 | 36 | 2013-05-23T09:27:47Z | [
"python",
"sorting",
"dictionary"
] | I have a Python dictionary
```
steps = {1:"value1", 5:"value2", 2:"value3"}
```
I need to iterate over this is sorted order by the key.
I tried this:
```
x = sorted(steps, key=lambda key: steps[key])
```
but the values are gone from x. | > I need to iterate over this is sorted order by the key.
I think `lambdas` is overkill here, try this:
```
>>> steps = {1:"val1", 5:"val2", 2:"val3"}
>>>
>>> for key in sorted(steps):
... print steps[key]
...
val1
val3
val2
``` |
Group HITs into batches in amazon mechanical turk with boto? | 16,716,029 | 8 | 2013-05-23T14:03:23Z | 16,716,484 | 8 | 2013-05-23T14:23:12Z | [
"python",
"amazon-web-services",
"boto",
"mechanicalturk"
] | I followed [this tutorial](http://www.toforge.com/2011/04/boto-mturk-tutorial-create-hits/) to create HITs on amazon Mturk. I notice, however, that all my HITs are listed as individual tasks---I have to click on "manage HITs individually" in the [upper right, here](http://content.screencast.com/users/harryf/folders/Jin... | You can't create batches through the API. Lots of discussion of this on the AWS forums and there is no way to do it. |
How do I fit a sine curve to my data with pylab and numpy? | 16,716,302 | 8 | 2013-05-23T14:15:10Z | 16,716,964 | 19 | 2013-05-23T14:42:44Z | [
"python",
"sine",
"economics"
] | For a school project I am trying to show that economies follow a relatively sinusoidal growth pattern. Beyond the economics of it, which are admittedly dodgy, I am building a python simulation to show that even when we let some degree of randomness take hold, we can still produce something relatively sinusoidal. I am h... | You can use the [least-square optimization](http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.leastsq.html) function in scipy to fit any arbitrary function to another. In case of fitting a sin function, the 3 parameters to fit are the offset ('a'), amplitude ('b') and the phase ('c').
As long as you p... |
Django South migration history causing an integrity error | 16,718,583 | 4 | 2013-05-23T15:56:28Z | 20,351,753 | 8 | 2013-12-03T12:52:22Z | [
"python",
"django",
"django-models",
"migration",
"django-south"
] | My south migration history table is causing integrity errors every time I try to run a new migration. Here is the error:
```
django.db.utils.IntegrityError: duplicate key value violates unique constraint "south_migrationhistory_pkey"
DETAIL: Key (id)=(40) already exists.
```
So far, this is only happening locally. I... | How about
`SELECT setval('south_migrationhistory_id_seq', (SELECT MAX(id) FROM south_migrationhistory));`
That worked for me.
You probably should do a `pg_dump` beforehand, just in case it all goes wrong.
I'm using postgres, you might need to use a slightly different command to update your database sequence for oth... |
Convert a number enclosed in parentheses (string) to a negative integer (or float) using Python? | 16,718,648 | 8 | 2013-05-23T15:59:33Z | 16,718,742 | 12 | 2013-05-23T16:04:01Z | [
"python"
] | In Python, what is the simplest way to convert a number enclosed in parentheses (string) to a negative integer (or float)?
For example, '(4,301)' to -4301, as commonly encountered in accounting applications. | The simplest way is:
```
my_str = "(4,301)"
num = -int(my_str.translate(None,"(),"))
``` |
Convert a number enclosed in parentheses (string) to a negative integer (or float) using Python? | 16,718,648 | 8 | 2013-05-23T15:59:33Z | 16,718,893 | 7 | 2013-05-23T16:11:14Z | [
"python"
] | In Python, what is the simplest way to convert a number enclosed in parentheses (string) to a negative integer (or float)?
For example, '(4,301)' to -4301, as commonly encountered in accounting applications. | Since you are reading from a system that put in thousands separators, it's worth mentioning that we are not using them the same way all around the world, which is why you should consider using a locale system. Consider:
```
import locale
locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' )
my_str = "(4,301)"
result = -loc... |
Is convolution slower in Numpy than in Matlab? | 16,719,720 | 4 | 2013-05-23T16:57:22Z | 16,721,374 | 7 | 2013-05-23T18:31:51Z | [
"python",
"performance",
"matlab",
"numpy",
"convolution"
] | Convolution in Matlab appears to be twice as fast as convolution in Numpy.
Python code (takes 19 seconds on my machine):
```
import numpy as np
from scipy import ndimage
import time
img = np.ones((512,512,512))
kernel = np.ones((5,5,5))/125
start_time = time.time()
ndimage.convolve(img,kernel,mode='constant')
print... | What exact operation are you doing? There are a number of optimizations that `ndimage` provides if you don't need general N-d convolution.
For example, your current operation:
```
img = np.ones((512,512,512))
kernel = np.ones((5,5,5))/125
result = ndimage.convolve(img, kernel)
```
is equivalent to:
```
img = np.one... |
Python string.replace regular expression | 16,720,541 | 89 | 2013-05-23T17:44:27Z | 16,720,705 | 153 | 2013-05-23T17:53:28Z | [
"python",
"regex"
] | I have a parameter file of the form
```
parameter-name parameter-value
```
where the parameters may be in any order but there is only one parameter per line. I want to replace one parameter's parameter-value with a new value.
I am using a line replace function posted previously ([Search and replace a line in a file ... | [`str.replace()`](http://docs.python.org/2/library/stdtypes.html#str.replace) does not recognize regular expressions, to perform a substitution using regular expressions use [`re.sub()`](http://docs.python.org/2/library/re.html#re.sub).
For example:
```
import re
line = re.sub(r"(?i)^.*interfaceOpDataFile.*$", "inter... |
Python string.replace regular expression | 16,720,541 | 89 | 2013-05-23T17:44:27Z | 16,720,752 | 82 | 2013-05-23T17:55:49Z | [
"python",
"regex"
] | I have a parameter file of the form
```
parameter-name parameter-value
```
where the parameters may be in any order but there is only one parameter per line. I want to replace one parameter's parameter-value with a new value.
I am using a line replace function posted previously ([Search and replace a line in a file ... | You are looking for [re.sub](http://docs.python.org/2/library/re.html#re.sub) function.
```
import re
s = "Example String"
replaced = re.sub('[ES]', 'a', s)
print replaced
```
will print `axample atring` |
Comparing two images pixel-wise with PIL (Python Imaging Library) | 16,720,594 | 3 | 2013-05-23T17:47:24Z | 16,721,373 | 7 | 2013-05-23T18:31:48Z | [
"python",
"image-processing",
"python-imaging-library"
] | I need a function which compares two PIL images of the same size. Let's call them A and B. The result is supposed to be a new image of the same size. If a pixels is the same in both A and B it's supposed to be set to a fixed color (e.g. black), otherwise it's supposed to be set to the same color as B.
Is there a libra... | Not sure about other libraries, but you can do this with PIL, with something like...
```
from PIL import Image, ImageChops
point_table = ([0] + ([255] * 255))
def black_or_b(a, b):
diff = ImageChops.difference(a, b)
diff = diff.convert('L')
diff = diff.point(point_table)
new = diff.convert('RGB')
... |
Using a while loop as a wait in python | 16,720,868 | 4 | 2013-05-23T18:03:43Z | 16,720,909 | 11 | 2013-05-23T18:05:24Z | [
"python",
"while-loop"
] | I have done this in C/C++ before where I have a while loop that acts as a wait holding the program up until the condition is broken. In Python I am trying to do the same with `while(GPIO.input(24) != 0):` and its says that it is expecting an indent. Is there anyway to get the script to hang on this statement until the ... | In Python, you need to use the `pass` statement whenever you want an empty block.
```
while (GPIO.input(24) != 0):
pass
``` |
Using a while loop as a wait in python | 16,720,868 | 4 | 2013-05-23T18:03:43Z | 16,720,959 | 8 | 2013-05-23T18:08:18Z | [
"python",
"while-loop"
] | I have done this in C/C++ before where I have a while loop that acts as a wait holding the program up until the condition is broken. In Python I am trying to do the same with `while(GPIO.input(24) != 0):` and its says that it is expecting an indent. Is there anyway to get the script to hang on this statement until the ... | Do note that an empty while loop will tend to hog resources, so if you don't mind decreasing the time resolution, you can include a `sleep` statement:
```
while (GPIO.input(24) != 0):
time.sleep(0.1)
```
That uses less CPU cycles, while still checking the condition with reasonable frequency. |
Django Auth LDAP - Direct Bind using sAMAccountName | 16,721,603 | 5 | 2013-05-23T18:45:56Z | 17,687,470 | 8 | 2013-07-16T21:38:03Z | [
"python",
"django",
"active-directory",
"django-authentication",
"django-auth-ldap"
] | There are two ways to authenticate a user using Django Auth LDAP
1. Search/Bind and
2. Direct Bind.
The first one involves connecting to the LDAP server either anonymously or with a fixed account and searching for the distinguished name of the authenticating user. Then we can attempt to bind again with the userâs p... | I had the same issue.
I ran accross: <https://bitbucket.org/psagers/django-auth-ldap/issue/21/cant-bind-and-search-on-activedirectory>
The author brought up a way to change the library files for django-auth-ldap so that it could do a direct bind.
It came down to changing /django\_auth\_ldap/backend.py to include two... |
Why when use sys.platform on Mac os it print "darwin"? | 16,721,940 | 5 | 2013-05-23T19:05:41Z | 16,721,976 | 8 | 2013-05-23T19:08:01Z | [
"python",
"osx"
] | In Python, when I type sys.platform on the Mac OS X the output is "darwin"? Why is this so? | Because the core of Mac OS X **is** [the Darwin OS](http://en.wikipedia.org/wiki/Darwin_%28operating_system%29).
Quoting from the linked WikiPedia page:
> Darwin forms the core set of components upon which Mac OS X and iOS are based.
Even the OS X platform itself reports itself as "Darwin" when you ask it:
```
$ un... |
How simplify list processing in Python? | 16,722,436 | 3 | 2013-05-23T19:37:13Z | 16,722,491 | 11 | 2013-05-23T19:41:02Z | [
"python",
"list"
] | Here's my first Python program, a little utility that converts from a Unix octal code for file permissions to the symbolic form:
```
s=raw_input("Octal? ");
digits=[int(s[0]),int(s[1]),int(s[2])];
lookup=['','x','w','wx','r','rx','rw','rwx'];
uout='u='+lookup[digits[0]];
gout='g='+lookup[digits[1]];
oout='o='+lookup[... | ```
digits=[int(s[0]),int(s[1]),int(s[2])];
```
can be written as:
```
digits = map(int,s)
```
or:
```
digits = [ int(x) for x in s ] #list comprehension
```
As it looks like you might be using python3.x (or planning on using it in the future based on your function-like print usage), you may want to opt for the l... |
How to `strftime` having timezone adjusted? | 16,722,464 | 8 | 2013-05-23T19:39:05Z | 16,722,505 | 12 | 2013-05-23T19:41:45Z | [
"python",
"datetime",
"python-2.7"
] | I store my datetime int UTC like so:
```
import pytz, datetime
timeUTC = datetime.datetime(2013, 5, 23, 19, 27, 50, 0)
timezoneLocal = pytz.timezone('Europe/Vilnius')
timeLocal = timezoneLocal.localize(timeUTC)
```
But when I try to print it, it just gives me regular UTC hours
```
>>> timeLocal.strftime('%H:%M:%S'... | Localize the date string as a UTC datetime, then use `astimezone` to convert it to the local timezone.
```
import pytz, datetime
timeUTC = datetime.datetime(2013, 5, 23, 19, 27, 50, 0)
timezoneLocal = pytz.timezone('Europe/Vilnius')
utc = pytz.utc
timeLocal = utc.localize(timeUTC).astimezone(timezoneLocal)
print(time... |
Python - return largest of N lists | 16,722,749 | 6 | 2013-05-23T19:56:01Z | 16,722,806 | 28 | 2013-05-23T19:58:20Z | [
"python",
"list"
] | I would like have a function return the largest of N list. With two items in the list I can write:
```
l1 = [3, 4, 5]
l2 = [4, 5, 6, 7]
def f(L):
if(len(L[0]) > len(L[1])):
return L[0]
else:
return L[1]
```
which I run with `f([l1, l2])`.
However, with more lists, it becomes a succession of ... | Use [`max`](http://docs.python.org/2/library/functions.html#max) with `key=len`.
```
In [3]: max([l1, l2], key=len)
Out[3]: [4, 5, 6, 7]
```
*This will retrieve the (first) longest list, for a list of lists.*
In fact, this will also work with strings (and other objects with a len attribute).
```
In [4]: max(['abcd'... |
A better way to import AUTH_USER_MODEL in Django 1.5 | 16,723,525 | 4 | 2013-05-23T20:41:24Z | 16,723,646 | 10 | 2013-05-23T20:49:33Z | [
"python",
"django"
] | I'm trying to make plugable apps more resilient under Django 1.5 where you now have a custom definable user model.
When adding foreign keys to a model I can do:
```
user = models.ForeignKey(settings.AUTH_USER_MODEL)
```
which saves me the import of User at the top of the file that breaks when `django.contrib.auth.mo... | One way you could do it is:
```
try:
from django.contrib.auth import get_user_model
except ImportError: # django < 1.5
from django.contrib.auth.models import User
else:
User = get_user_model()
``` |
Numpy inverse mask | 16,724,669 | 3 | 2013-05-23T22:04:26Z | 16,724,700 | 9 | 2013-05-23T22:08:17Z | [
"python",
"arrays",
"numpy",
"mask"
] | I want to inverse the true/false value in my numpy masked array.
So in the example below i don't want to mask out the second value in the data array, I want to mask out the first and third value.
Below is just an example. My masked array is created by a longer process than runs before. So I can not change the mask ar... | ```
import numpy
data = numpy.array([[ 1, 2, 5 ]])
mask = numpy.array([[0,1,0]])
numpy.ma.masked_array(data, ~mask) #note this probably wont work right for non-boolean (T/F) values
#or
numpy.ma.masked_array(data, numpy.logical_not(mask))
```
for example
```
>>> a = numpy.array([False,True,False])
>>> ~a
array([ True... |
Saving the highscore for a python game | 16,726,354 | 4 | 2013-05-24T01:17:53Z | 16,726,397 | 7 | 2013-05-24T01:27:27Z | [
"python",
"save",
"pygame",
"leaderboard"
] | I have made a very simple game in python using pygame. The score is based on whatever level the player reached. I have the level as a variable called `score`. I want to display the top level at the start or end of the game.
I would be even more happy to display more than one score, but all of the other threads I have ... | You can use the `pickle` module to save variables to disk and then reload them.
Example:
```
import pickle
# load the previous score if it exists
try:
with open('score.dat', 'rb') as file:
score = pickle.load(file)
except:
score = 0
print "High score: %d" % score
# your game code goes here
# let's ... |
what is the difference between [[],[]] and [[]] * 2 | 16,726,937 | 5 | 2013-05-24T02:45:25Z | 16,726,951 | 10 | 2013-05-24T02:47:29Z | [
"python"
] | ```
t0 = [[]] * 2
t1 = [[], []]
t0[0].append('hello')
print t0 ... | When you do `[[]] * 2`, it gives you a list containing two of *the same list*, rather than two lists. It is like doing:
```
a = []
b = [a, a]
```
The usual way to make a list containing several *different* empty lists (or other mutable objects) is to do this:
```
t1 = [[] for _ in range(5)]
``` |
what is the difference between [[],[]] and [[]] * 2 | 16,726,937 | 5 | 2013-05-24T02:45:25Z | 16,726,958 | 7 | 2013-05-24T02:48:15Z | [
"python"
] | ```
t0 = [[]] * 2
t1 = [[], []]
t0[0].append('hello')
print t0 ... | ```
[[]] * 2
```
makes a [shallow copy.](http://en.wikipedia.org/wiki/Object_copy#Shallow_copy) Equivalent to:
```
x = []
t0 = [x, x]
```
However
```
t1 = [[], []]
```
Uses two separate empty list literals, they are completely different so mutating one obviously doesn't mutate the other |
Installing Anaconda into a Virtual Environment | 16,727,171 | 16 | 2013-05-24T03:17:11Z | 17,164,151 | 20 | 2013-06-18T08:33:31Z | [
"python",
"virtualenv",
"anaconda"
] | I've currently got a working installation of the Enthought Python Distribution on my machine that I don't want to necessarily disrupt, but I'd like to look at moving over to Anaconda from Continuum.
I can easily install anaconda into the virtualenv directory I create, but I'm not sure how to tell that virtualenv to us... | I just tested the Anaconde 1.6 installer from <http://continuum.io/downloads>
After downloading, I did:
```
bash Anaconda-1.6.0-Linux-x86_64.sh
```
If you take the defaults, you'll end up with a directory `anaconda` in your home directory, completely separate from your EPD or system Python installation.
To activate... |
Object methods of same class have same id? | 16,727,490 | 8 | 2013-05-24T04:02:38Z | 16,727,572 | 11 | 2013-05-24T04:14:56Z | [
"python"
] | ```
class parent(object):
@classmethod
def a_class_method(cls):
print "in class method %s" % cls
@staticmethod
def a_static_method():
print "static method"
def useless_func(self):
pass
p1, p2 = parent(),parent()
id(p1) == id(p2) // False
id(p1.useless_func) == id(p2.useless_func) ... | This is a very interesting question!
Under your conditions, they do appear the same:
```
Python 2.7.2 (default, Oct 11 2012, 20:14:37)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo(object):
... def m... |
Object methods of same class have same id? | 16,727,490 | 8 | 2013-05-24T04:02:38Z | 16,727,621 | 7 | 2013-05-24T04:22:41Z | [
"python"
] | ```
class parent(object):
@classmethod
def a_class_method(cls):
print "in class method %s" % cls
@staticmethod
def a_static_method():
print "static method"
def useless_func(self):
pass
p1, p2 = parent(),parent()
id(p1) == id(p2) // False
id(p1.useless_func) == id(p2.useless_func) ... | Here is what I think is happening:
1. When you dereference `p1.useless_func`, a copy of it is created in memory. This memory location is returned by `id`
2. Since there are no references to the copy of the method just created, it gets reclaimed by the GC, and the memory address is available again
3. When you dereferen... |
How to check all the elements in a list that has a specific requirement? | 16,728,824 | 5 | 2013-05-24T06:23:54Z | 16,728,855 | 10 | 2013-05-24T06:26:42Z | [
"python",
"list"
] | I'm doing a homework about a heart game with different version. It says that if we are given a list **mycards** that contains all the cards that player currently hold in their hands. And **play** is a single card that representing a potential card.And if **all** their cards contain either HEART(`H`) or QUEEN OF SPADES(... | Your description maps directly to the solution:
Edited for clarity:
```
mycards= ['0H','8H','7H','6H','AH','QS']
all((x == 'QS' or 'H' in x) for x in mycards)
# True
``` |
Converting strings to floats in a DataFrame | 16,729,483 | 22 | 2013-05-24T07:10:54Z | 16,729,635 | 12 | 2013-05-24T07:20:32Z | [
"python",
"pandas"
] | How to covert a DataFrame column containing strings and `NaN` values to floats. And there is another column whose values are strings and floats; how to convert this entire column to floats. | You can try `df.column_name = df.column_name.astype(float)`. As for the `NaN` values, you need to specify how they should be converted, but you can use the `.fillna` method to do it.
*Example:*
```
In [12]: df
Out[12]:
a b
0 0.1 0.2
1 NaN 0.3
2 0.4 0.5
In [13]: df.a.values
Out[13]: array(['0.1', nan, ... |
Converting strings to floats in a DataFrame | 16,729,483 | 22 | 2013-05-24T07:10:54Z | 16,735,476 | 28 | 2013-05-24T12:54:51Z | [
"python",
"pandas"
] | How to covert a DataFrame column containing strings and `NaN` values to floats. And there is another column whose values are strings and floats; how to convert this entire column to floats. | This is available in 0.11. Forces conversion (or set's to nan)
This will work even when `astype` will fail; its also series by series
so it won't convert say a complete string column
```
In [10]: df = DataFrame(dict(A = Series(['1.0','1']), B = Series(['1.0','foo'])))
In [11]: df
Out[11]:
A B
0 1.0 1.0
1 ... |
How to get a value from a cell of a data frame? | 16,729,574 | 51 | 2013-05-24T07:17:06Z | 16,729,808 | 52 | 2013-05-24T07:31:09Z | [
"python",
"table",
"dataframe",
"pandas"
] | I have constructed a condition that extract exactly one row from my data frame:
```
d2 = df[(df['l_ext']==l_ext) & (df['item']==item) & (df['wn']==wn) & (df['wd']==1)]
```
Now I would like to take a value from a particular column:
```
val = d2['col_name']
```
But as a result I get a data frame that contains one row... | If you have a DataFrame with only one row, then access the first (only) row as a Series using `iloc`, and then the value using the column name:
```
In [3]: sub_df
Out[3]:
A B
2 -0.133653 -0.030854
In [4]: sub_df.iloc[0]
Out[4]:
A -0.133653
B -0.030854
Name: 2, dtype: float64
In [5]: sub_df.iloc... |
How to get a value from a cell of a data frame? | 16,729,574 | 51 | 2013-05-24T07:17:06Z | 16,735,536 | 32 | 2013-05-24T12:58:23Z | [
"python",
"table",
"dataframe",
"pandas"
] | I have constructed a condition that extract exactly one row from my data frame:
```
d2 = df[(df['l_ext']==l_ext) & (df['item']==item) & (df['wn']==wn) & (df['wd']==1)]
```
Now I would like to take a value from a particular column:
```
val = d2['col_name']
```
But as a result I get a data frame that contains one row... | These are fast access for scalars
```
In [15]: df = DataFrame(randn(5,3),columns=list('ABC'))
In [16]: df
Out[16]:
A B C
0 -0.074172 -0.090626 0.038272
1 -0.128545 0.762088 -0.714816
2 0.201498 -0.734963 0.558397
3 1.563307 -1.186415 0.848246
4 0.205171 0.962514 0.037709
In [17]: ... |
Python add item to the tuple | 16,730,339 | 46 | 2013-05-24T08:04:32Z | 16,730,367 | 96 | 2013-05-24T08:05:52Z | [
"python",
"python-2.7",
"tuples"
] | I have some object.ID-s which I try to store in the user session as tuple. When I add first one it works but tuple looks like `(u'2',)` but when I try to add new one using `mytuple = mytuple + new.id` got error `can only concatenate tuple (not "unicode") to tuple`. | You need to make the second element a 1-tuple, eg:
```
a = ('2',)
b = 'z'
new = a + (b,)
``` |
Python add item to the tuple | 16,730,339 | 46 | 2013-05-24T08:04:32Z | 16,730,368 | 9 | 2013-05-24T08:05:53Z | [
"python",
"python-2.7",
"tuples"
] | I have some object.ID-s which I try to store in the user session as tuple. When I add first one it works but tuple looks like `(u'2',)` but when I try to add new one using `mytuple = mytuple + new.id` got error `can only concatenate tuple (not "unicode") to tuple`. | ```
>>> x = (u'2',)
>>> x += u"random string"
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
x += u"random string"
TypeError: can only concatenate tuple (not "unicode") to tuple
>>> x += (u"random string", ) # concatenate a one-tuple instead
>>> x
(u'2', u'random string')
``` |
Python add item to the tuple | 16,730,339 | 46 | 2013-05-24T08:04:32Z | 16,730,584 | 9 | 2013-05-24T08:22:59Z | [
"python",
"python-2.7",
"tuples"
] | I have some object.ID-s which I try to store in the user session as tuple. When I add first one it works but tuple looks like `(u'2',)` but when I try to add new one using `mytuple = mytuple + new.id` got error `can only concatenate tuple (not "unicode") to tuple`. | From tuple to list to tuple :
```
a = ('2',)
b = 'b'
l = list(a)
l.append(b)
tuple(l)
```
Or with a longer list of items to append
```
a = ('2',)
items = ['o', 'k', 'd', 'o']
l = list(a)
for x in items:
l.append(x)
print tuple(l)
```
gives you
```
>>>
('2', 'o', 'k', 'd', 'o')
```
The point here is: Lis... |
Python add item to the tuple | 16,730,339 | 46 | 2013-05-24T08:04:32Z | 24,535,123 | 7 | 2014-07-02T15:25:34Z | [
"python",
"python-2.7",
"tuples"
] | I have some object.ID-s which I try to store in the user session as tuple. When I add first one it works but tuple looks like `(u'2',)` but when I try to add new one using `mytuple = mytuple + new.id` got error `can only concatenate tuple (not "unicode") to tuple`. | Tuple can only allow adding `tuple` to it. The best way to do it is:
```
mytuple =(u'2',)
mytuple +=(new.id,)
```
I tried the same scenario with the below data it all seems to be working fine.
```
>>> mytuple = (u'2',)
>>> mytuple += ('example text',)
>>> print mytuple
(u'2','example text')
``` |
sqlalchemy bulk update performance problems | 16,731,280 | 14 | 2013-05-24T09:05:24Z | 16,742,033 | 13 | 2013-05-24T19:08:22Z | [
"python",
"sqlite",
"sqlalchemy",
"sql-update",
"bulk-load"
] | I need to increment values in a column periodically with data I receive in a file. The table has > 400000 rows. So far, all my attempts result in very poor performance.
I have written an experiment that reflects my requirements:
```
#create table
engine = create_engine('sqlite:///bulk_update.db', echo=False)
metadata ... | You are using the correct approach by doing bulk update with single query.
The reason why it takes that long is because the table doesn't have index on the `sometable.column1`. It has only primary index on column `id`.
Your update query uses `sometable.column1` in where clause to identify record. So database has to s... |
stop / start / pause in python matplotlib animation | 16,732,379 | 9 | 2013-05-24T10:01:43Z | 16,733,373 | 17 | 2013-05-24T10:56:00Z | [
"python",
"animation",
"matplotlib"
] | I'm using FuncAnimation in matplotlib's animation module for some basic animation. This function perpetually loops through the animation. Is there a way by which I can pause and restart the animation by, say, mouse clicks? | Here is [a FuncAnimation example](http://scipyscriptrepo.com/wp/?p=9) which I modified to pause on mouse clicks.
Since the animation is driven by a generator function, `simData`, when the global variable `pause` is True, yielding the same data makes the animation appear paused.
The value of `paused` is toggled by sett... |
Get href Attribute Link from td tag BeautifulSoup Python | 16,733,109 | 2 | 2013-05-24T10:40:52Z | 16,950,329 | 11 | 2013-06-05T21:37:04Z | [
"python",
"beautifulsoup"
] | I am new in Python and someone suggested me to use Beautiful soup for Scrapping and i am struck in a problem to fetch the href attribute from a td tag Column 2 on the basis of year in column 4.
```
<table class="tableFile2" summary="Results">
<tr>
<th width="7%" scope="col">Filings</th>
... | This works for me in Python 2.7:
```
table = soup.find('table', {'class': 'tableFile2'})
rows = table.findAll('tr')
for tr in rows:
cols = tr.findAll('td')
if len(cols) >= 4 and "2013" in cols[3].text:
link = cols[1].find('a').get('href')
print link
```
A few issues with your previous code:
1... |
How to print negative zero in Python | 16,733,821 | 9 | 2013-05-24T11:21:38Z | 16,733,967 | 17 | 2013-05-24T11:30:40Z | [
"python",
"python-2.7"
] | I am converting decimal degrees to print as DMS. The conversion algorithm is what you would expect, using modf, with the addition that sign is taken out of the MS portion and left in only for the D portion.
Everything is fine except for the case where the Degree is negative zero, -0. An example is -0.391612 which shou... | Use `format()`
```
>>> format(-0.0)
'-0.0'
>>> format(0.0)
'0.0'
>>> print '''{: g}°{}'{}"'''.format(-0.0, 23, 29)
-0°23'29"
``` |
How to get every element in a list of list of lists? | 16,734,590 | 6 | 2013-05-24T12:07:24Z | 16,734,909 | 15 | 2013-05-24T12:23:27Z | [
"python"
] | I'm making a heart game for my assignment but I don't know how to get every element in a list of list:
```
>>>Cards = [[["QS","5H","AS"],["2H","8H"],["7C"]],[["9H","5C],["JH"]],[["7D"]]]
```
and what comes to my mind is :
```
for values in cards:
for value in values:
```
But I think I just got element that has ... | Like this:
```
>>> Cards = [[["QS","5H","AS"],["2H","8H"],["7C"]],[["9H","5C"],["JH"]],["7D"]]
>>> from compiler.ast import flatten
>>> flatten(Cards)
['QS', '5H', 'AS', '2H', '8H', '7C', '9H', '5C', 'JH', '7D']
```
As, nacholibre pointed out, the `compiler` package is deprecated. This is the source of `flatten`:
`... |
Random walk pandas | 16,734,621 | 5 | 2013-05-24T12:08:44Z | 16,735,521 | 9 | 2013-05-24T12:57:14Z | [
"python",
"pandas",
"random-walk"
] | I am trying to quickly create a simulated random walk series in pandas.
```
import pandas as pd
import numpy as np
dates = pd.date_range('2012-01-01', '2013-02-22')
y2 = np.random.randn(len(dates))/365
Y2 = pd.Series(y2, index=dates)
start_price = 100
```
would like to build another date series starting at start\_pri... | ```
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
def geometric_brownian_motion(T = 1, N = 100, mu = 0.1, sigma = 0.01, S0 = 20):
dt = float(T)/N
t = np.linspace(0, T, N)
W = np.random.standard_normal(size = N)
W = np.cumsum(W)*np.sqrt(dt) ### standard brownian motion ... |
How to generate unique equal hash for equal dictionaries? | 16,735,786 | 9 | 2013-05-24T13:11:09Z | 16,736,002 | 11 | 2013-05-24T13:21:24Z | [
"python"
] | eg:
```
>>> a = {'req_params': {'app': '12345', 'format': 'json'}, 'url_params': {'namespace': 'foo', 'id': 'baar'}, 'url_id': 'rest'}
>>> b = {'req_params': { 'format': 'json','app': '12345' }, 'url_params': { 'id': 'baar' ,'namespace':'foo' }, 'url_id': 'REST'.lower() }
>>> a == b
True
```
What is a good hash func... | The pprint module sorts the dict keys
```
from pprint import pformat
hash(pformat(a)) == hash(pformat(b))
```
If you want to persist the hashes, you should use a hash from hashlib. sha1 is plenty |
Change the file extension for files in a folder in Python | 16,736,080 | 8 | 2013-05-24T13:24:49Z | 16,736,283 | 7 | 2013-05-24T13:35:32Z | [
"python",
"file"
] | I would like to change the extension of the files in specific folder. i read about this topic in the forum. using does ideas, I have written following code and I expect that it would work but it does not. I would be thankful for any guidance to find my mistake.
```
import os,sys
folder = 'E:/.../1936342-G/test'
... | Something like this will rename all files in the executing directory that end in .txt to .text
```
import os, sys
for filename in os.listdir(os.path.dirname(os.path.abspath(__file__))):
base_file, ext = os.path.splitext(filename)
if ext == ".txt":
os.rename(filename, base_file + ".text")
``` |
Change the file extension for files in a folder in Python | 16,736,080 | 8 | 2013-05-24T13:24:49Z | 16,736,304 | 9 | 2013-05-24T13:36:21Z | [
"python",
"file"
] | I would like to change the extension of the files in specific folder. i read about this topic in the forum. using does ideas, I have written following code and I expect that it would work but it does not. I would be thankful for any guidance to find my mistake.
```
import os,sys
folder = 'E:/.../1936342-G/test'
... | The `open` on the source file is unnecessary, since `os.rename` only needs the source and destination paths to get the job done. Moreover, `os.rename` always returns `None`, so it doesn't make sense to call `open` on its return value.
```
import os,sys
folder = 'E:/.../1936342-G/test'
for filename in os.listdir(folder... |
Change the file extension for files in a folder in Python | 16,736,080 | 8 | 2013-05-24T13:24:49Z | 16,736,470 | 9 | 2013-05-24T13:45:20Z | [
"python",
"file"
] | I would like to change the extension of the files in specific folder. i read about this topic in the forum. using does ideas, I have written following code and I expect that it would work but it does not. I would be thankful for any guidance to find my mistake.
```
import os,sys
folder = 'E:/.../1936342-G/test'
... | You don't need to open the files to rename them, `os.rename` only needs their paths. Also consider using the [glob](http://docs.python.org/2/library/glob.html) module:
```
import glob, os
for filename in glob.iglob(os.path.join(folder, '*.grf')):
os.rename(filename, filename[:-4] + '.las')
``` |
python NameError: name 'file' is not defined | 16,736,833 | 12 | 2013-05-24T14:02:43Z | 27,177,607 | 39 | 2014-11-27T19:25:18Z | [
"python",
"pip",
"gunicorn"
] | I dont know much about python. I want to start working on the project and the setup instruction says:
```
pip install -r requirements-dev.txt
```
Simple enougth. The problem is that I get this:
```
Downloading/unpacking gunicorn==0.13.4 (from -r requirements.txt (line 7))
Running setup.py egg_info for package ... | Really guys! Why not answer the question with a straighforward solution.
```
file() is no supported in python3
```
use open() instead, see: <https://docs.python.org/release/3.0/library/functions.html#open> |
generate random -1 or 1 values in a single line of code | 16,737,123 | 2 | 2013-05-24T14:17:22Z | 16,737,148 | 10 | 2013-05-24T14:18:06Z | [
"python"
] | I'd like to generate random values equal to -1 or 1. I can do that by generating random integer values 0 or 1 times 2 and minus 1, but maybe there is a more simple way of doing this? | How about?
`random.choice([-1, 1])`
Example -
```
>>> from random import choice
>>> choice([-1, 1])
1
>>> choice([-1, 1])
-1
>>> choice([-1, 1])
1
>>> choice([-1, 1])
-1
>>> choice([-1, 1])
-1
>>> choice([-1, 1])
1
``` |
How to tell distutils to use gcc? | 16,737,260 | 29 | 2013-05-24T14:23:36Z | 16,737,674 | 22 | 2013-05-24T14:42:56Z | [
"python",
"compiler-construction",
"cython",
"distutils"
] | I want to wrap a test project containing C++ and OpenMP code with Cython, and build it with distutils via a `setup.py` file. The content of my file looks like this:
```
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
from Cython.Distutils import build_ext
... | Try setting the "CC" and "CXX" environment variables from inside the setup.py with os.environ. |
How to tell distutils to use gcc? | 16,737,260 | 29 | 2013-05-24T14:23:36Z | 16,737,696 | 7 | 2013-05-24T14:43:58Z | [
"python",
"compiler-construction",
"cython",
"distutils"
] | I want to wrap a test project containing C++ and OpenMP code with Cython, and build it with distutils via a `setup.py` file. The content of my file looks like this:
```
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
from Cython.Distutils import build_ext
... | I just took a look at the `distutils` source, and the `--compiler` option expects "unix", "msvc", "cygwin", "mingw32", "bcpp", or "emx". It checks the compiler name you want by checking the `CC` environment variable. Try calling build like this:
```
CC=gcc python setup.py build
```
You don't need to set `CXX`, it doe... |
How to tell distutils to use gcc? | 16,737,260 | 29 | 2013-05-24T14:23:36Z | 16,740,123 | 15 | 2013-05-24T17:02:00Z | [
"python",
"compiler-construction",
"cython",
"distutils"
] | I want to wrap a test project containing C++ and OpenMP code with Cython, and build it with distutils via a `setup.py` file. The content of my file looks like this:
```
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
from Cython.Distutils import build_ext
... | Just in case some others are facing the same problem under Windows (where CC environment variable wouldn't have any effect) :
* Create file "C:\Python27\Lib\distutils\distutils.cfg" and write this inside :
Code :
```
[build]
compiler = mingw32
```
* Remove all instances of "-mno-cygwin" gcc option from file "C:\Pyt... |
How to display progress of scipy.optimize function? | 16,739,065 | 14 | 2013-05-24T15:57:23Z | 18,471,343 | 14 | 2013-08-27T16:53:32Z | [
"python",
"numpy",
"scipy",
"output",
"mathematical-optimization"
] | I use `scipy.optimize` to minimize a function of 12 arguments.
I started the optimization a while ago and still waiting for results.
Is there a way to force `scipy.optimize` to display its progress (like how much is already done, what are the current best point)? | As mg007 suggested, some of the scipy.optimize routines allow for a callback function (unfortunately leastsq does not permit this at the moment). Below is an example using the "fmin\_bfgs" routine where I use a callback function to display the current value of the arguments and the value of the objective function at ea... |
Composing functions in python | 16,739,290 | 3 | 2013-05-24T16:10:18Z | 16,739,439 | 9 | 2013-05-24T16:17:49Z | [
"python",
"composition"
] | I have an array of functions and I'm trying to produce one function which consists of the composition of the elements in my array.
My approach is:
```
def compose(list):
if len(list) == 1:
return lambda x:list[0](x)
list.reverse()
final=lambda x:x
for f in list:
final=lambda x:f(final(x... | ```
def compose (*functions):
def inner(arg):
for f in reversed(functions):
arg = f(arg)
return arg
return inner
```
Example:
```
>>> def square (x):
return x ** 2
>>> def increment (x):
return x + 1
>>> def half (x):
return x / 2
>>> composed = compose(squ... |
Composing functions in python | 16,739,290 | 3 | 2013-05-24T16:10:18Z | 24,047,214 | 9 | 2014-06-04T20:43:36Z | [
"python",
"composition"
] | I have an array of functions and I'm trying to produce one function which consists of the composition of the elements in my array.
My approach is:
```
def compose(list):
if len(list) == 1:
return lambda x:list[0](x)
list.reverse()
final=lambda x:x
for f in list:
final=lambda x:f(final(x... | The easiest approach would be first to write a composition of 2 functions:
```
def compose2(f, g):
return lambda *a, **kw: f(g(*a, **kw))
```
And then use `reduce` to compose more functions:
```
def compose(*fs):
return reduce(compose2, fs)
```
Or you can use [some library](https://github.com/Suor/funcy), w... |
How to get Facebook access token using Python library? | 16,739,894 | 6 | 2013-05-24T16:47:09Z | 19,781,835 | 8 | 2013-11-05T04:13:44Z | [
"python",
"facebook",
"facebook-graph-api"
] | I've found [this Library](https://github.com/pythonforfacebook/facebook-sdk/) it seems it is the official one, then [found this](http://stackoverflow.com/questions/10488913/how-to-obtain-a-user-access-token-in-python), but everytime i find an answer the half of it are links to [Facebook API Documentation](https://devel... | Not sure if this helps anyone, but I was able to get an oauth\_access\_token by following this code.
```
from facepy import utils
app_id = 134134134134 # must be integer
app_secret = "XXXXXXXXXXXXXXXXXX"
oath_access_token = utils.get_application_access_token(app_id, app_secret)
```
Hope this helps. |
base64.b64encode error | 16,740,188 | 3 | 2013-05-24T17:05:49Z | 16,740,344 | 7 | 2013-05-24T17:15:06Z | [
"python",
"python-3.x"
] | I'm trying to encrypt and decrypt text in python, and I know how to do that - the problem is that I don't want to have to use a set amount of letters like 16 or 32. I want to be able to use as many letters/numbers as I want, and then encrypt the text without any errors.
base64 in python would be perfect, because I can... | In Python 3, you need to convert your string to bytes, since base64 encoding depends on the encoding of the string, and Python 3 doesn't make assumptions about string encoding. See [this question](http://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3).
```
import base64
# Assuming... |
How to handle incoming real time data with python pandas | 16,740,887 | 42 | 2013-05-24T17:53:51Z | 17,056,022 | 8 | 2013-06-12T00:40:02Z | [
"python",
"pandas"
] | Which is the most recommended/pythonic way of handling live incoming data with pandas?
Every few seconds I'm receiving a data point in the format below:
```
{'time' :'2013-01-01 00:00:00', 'stock' : 'BLAH',
'high' : 4.0, 'low' : 3.0, 'open' : 2.0, 'close' : 1.0}
```
I would like to append it to an existing DataFram... | You are actually trying to solve two problems: capturing real-time data and analyzing that data. The first problem can be solved with [Python logging](http://docs.python.org/2/library/logging.html), which is designed for this purpose. Then the other problem can be solved by reading that same log file. |
How to handle incoming real time data with python pandas | 16,740,887 | 42 | 2013-05-24T17:53:51Z | 34,282,362 | 7 | 2015-12-15T06:22:12Z | [
"python",
"pandas"
] | Which is the most recommended/pythonic way of handling live incoming data with pandas?
Every few seconds I'm receiving a data point in the format below:
```
{'time' :'2013-01-01 00:00:00', 'stock' : 'BLAH',
'high' : 4.0, 'low' : 3.0, 'open' : 2.0, 'close' : 1.0}
```
I would like to append it to an existing DataFram... | I would use HDF5/pytables as follows:
1. Keep the data as a python list "as long as possible".
2. Append your results to that list.
3. When it gets "big":
* push to HDF5 Store using pandas io (and an appendable table).
* clear the list.
4. Repeat.
In fact, the function I define uses a list for each "key" so tha... |
How to add stdout and stderr to logger file in flask | 16,741,834 | 5 | 2013-05-24T18:56:22Z | 16,743,284 | 10 | 2013-05-24T20:38:42Z | [
"python",
"flask"
] | I want to log the stdout & stderr to log files, and this is what I tried.
```
app = Flask(__name__)
app.logger.setLevel(logging.INFO) # use the native logger of flask
app.logger.disabled = False
handler = logging.handlers.RotatingFileHandler(
SYSTEM_LOG_FILENAME,
'a',
maxBytes=1024 * 1024 * 100,
backu... | The logging messages you mention don't come from flask's logger, the [come from](https://github.com/mitsuhiko/werkzeug/blob/60670cb98db1934b7aa7df454cbe4508c467f403/werkzeug/serving.py#L680) `werkzeug`'s [logger](https://github.com/mitsuhiko/werkzeug/blob/60670cb98db1934b7aa7df454cbe4508c467f403/werkzeug/_internal.py#L... |
Convert an integer to a 2 byte Hex value in Python | 16,742,022 | 6 | 2013-05-24T19:07:27Z | 16,742,052 | 10 | 2013-05-24T19:09:47Z | [
"python",
"python-2.7",
"int",
"hex",
"data-conversion"
] | For a tkinter GUI, I must read in a Hex address in the form of '0x00' to set an I2C address. The way I am currently doing it is by reading the input as a string, converting the string to an integer, then converting that integer to an actual Hex value as shown in the partial code below:
GUI initialization:
```
self.I2... | Use the [`format()` function](http://docs.python.org/2/library/functions.html#format):
```
format(addrint, '#04x')
```
This formats the input value as a 2 digit hexadecimal string with leading zeros to make up the length, and `#` includes the 'standard prefix', `0x` in this case. Note that the width of 4 includes tha... |
Create a python executable using setuptools | 16,742,203 | 7 | 2013-05-24T19:20:02Z | 16,745,122 | 9 | 2013-05-24T23:58:58Z | [
"python",
"unix",
"setuptools",
"egg"
] | I have a small python application that I would like to make into a downloadable / installable executable for UNIX-like systems. I am under the impression that setuptools would be the best way to make this happen but somehow this doesn't seem to be a common task.
My directory structure looks like this:
```
myappname/
... | The problem here is that your package layout is broken.
It happens to work in-place, at least in 2.x. Why? You're not accessing the package as `myappname`âbut the same directory that is that package's directory is also the top-level script directory, so you end up getting any of its siblings via old-style relative i... |
How to convert YouTube API duration to seconds? | 16,742,381 | 4 | 2013-05-24T19:31:46Z | 16,743,442 | 9 | 2013-05-24T20:48:33Z | [
"python",
"youtube-api"
] | For the sake of interest I want to convert video durations from YouTubes `ISO 8601` to seconds. To future proof my solution, I picked [a really long video](http://www.youtube.com/watch?v=2XwmldWC_Ls) to test it against.
The API provides this for its duration - `"duration": "P1W2DT6H21M32S"`
I tried parsing this durat... | Python's built-in dateutil module only supports parsing ISO 8601 dates, not ISO 8601 durations. For that, you can use the "isodate" library (in pypi at <https://pypi.python.org/pypi/isodate> -- install through pip or easy\_install). This library has full support for ISO 8601 durations, converting them to datetime.timed... |
ValueError: invalid literal for int() with base 10: 'stop' | 16,742,432 | 4 | 2013-05-24T19:35:22Z | 16,742,512 | 10 | 2013-05-24T19:42:05Z | [
"python",
"string",
"int"
] | Every time I try me code it works but when I type in `'stop'` it gives me an error:
> ValueError: invalid literal for int() with base 10: 'stop'
```
def guessingGame():
global randomNum
guessTry = 3
while True:
guess = input('Guess a Number between 1 - 10, You have 3 Tries, or Enter Stop: ')
... | The string passed to `int()` should only contain digits:
```
>>> int("stop")
Traceback (most recent call last):
File "<ipython-input-114-e5503af2dc1c>", line 1, in <module>
int("stop")
ValueError: invalid literal for int() with base 10: 'stop'
```
A quick fix will be to use [exception handling](http://docs.pyth... |
matplotlib 2d line line,=plot comma meaning | 16,742,765 | 6 | 2013-05-24T20:01:18Z | 16,742,860 | 8 | 2013-05-24T20:07:53Z | [
"python",
"matplotlib",
"line",
"tuples",
"comma"
] | I'm walking through basic tutorials for matplotlib,
and the example code that I'm working on is:
```
import numpy as np
import matplotlib.pylab as plt
x=[1,2,3,4]
y=[5,6,7,8]
line, = plt.plot(x,y,'-')
plt.show()
```
Does anyone know what the comma after line (`line,=plt.plot(x,y,'-')`) means?
I thought it was a t... | `plt.plot` returns a list of the `Line2D` objects plotted, even if you plot only one line.
That comma is unpacking the single value into `line`.
ex
```
a, b = [1, 2]
a, = [1, ]
``` |
Python: How to check for RSS updates with feedparser and etags | 16,745,083 | 7 | 2013-05-24T23:53:35Z | 16,769,953 | 14 | 2013-05-27T09:17:31Z | [
"python",
"rss",
"http-headers",
"etag",
"feedparser"
] | I'm trying to skip over RSS feeds that have not been modified using feedparser and etags.
Following the guidelines of the documentation: <http://pythonhosted.org/feedparser/http-etag.html>
```
import feedparser
d = feedparser.parse('http://www.wired.com/wiredscience/feed/')
d2 = feedparser.parse('http://www.wired.com... | Apparently this server is configured to check 'If-Modified-Since' header. You need to pass last modified time as well:
```
>>> d = feedparser.parse('http://www.wired.com/wiredscience/feed/')
>>> feedparser.parse('http://www.wired.com/wiredscience/feed/',
etag=d.etag, modified=d.modified).status
3... |
In Tornado, how can I see Exceptions rasied in a coroutine called by PeriodicCallback? | 16,745,152 | 9 | 2013-05-25T00:03:50Z | 16,817,681 | 7 | 2013-05-29T15:13:46Z | [
"python",
"asynchronous",
"tornado"
] | I wrote a program which has a coroutine called periodically from the main `ioloop` like this:
```
from tornado import ioloop, web, gen, log
tornado.log.enable_pretty_printing()
import logging; logging.basicConfig()
@gen.coroutine
def callback():
print 'get ready for an error...'
raise Exception()
result =... | `@tornado.gen.coroutine` makes function return `tornado.concurrent.Future` object so you don't have to wrap it into `tornado.gen.Task` but you can call it using `yield` keyword:
```
@tornado.gen.coroutine
def inner():
logging.info('inner')
@tornado.gen.coroutine
def outer():
logging.info('outer')
yield in... |
python 32-bit and 64-bit integer math with intentional overflow | 16,745,387 | 12 | 2013-05-25T00:50:20Z | 16,745,422 | 13 | 2013-05-25T00:56:28Z | [
"python",
"integer-math"
] | What's the best way to do integer math in 32- and 64-bit, so that overflow happens like it does in C?
e.g. (65536\*65536+1)\*(65536\*65536+1) should be 0x0000000200000001 in 64-bit math, and not its exact value (non-overflowing) 0x10000000200000001. | Just `&` the result with the appropriate 32- or 64-bit mask (`0xffffffff` or `0xffffffffffffffff`). |
python 32-bit and 64-bit integer math with intentional overflow | 16,745,387 | 12 | 2013-05-25T00:50:20Z | 16,745,427 | 8 | 2013-05-25T00:57:50Z | [
"python",
"integer-math"
] | What's the best way to do integer math in 32- and 64-bit, so that overflow happens like it does in C?
e.g. (65536\*65536+1)\*(65536\*65536+1) should be 0x0000000200000001 in 64-bit math, and not its exact value (non-overflowing) 0x10000000200000001. | Use [NumPy](http://www.numpy.org/) with the appropriate integer size and the overflow is more C like:
32 bit:
```
>>> np.uint32(2**32-3) + np.uint32(5)
__main__:1: RuntimeWarning: overflow encountered in uint_scalars
2
```
64 bit:
```
>>> i64=np.uint64(65536*65536+1)
>>> hex(i64*i64)
'0x200000001L'
```
Compare wit... |
What does Python's socket.recv() return for non-blocking sockets if no data is received until a timeout occurs? | 16,745,409 | 30 | 2013-05-25T00:53:49Z | 16,745,561 | 41 | 2013-05-25T01:26:26Z | [
"python",
"sockets",
"nonblocking",
"recv"
] | Basically, I've read in several places that `socket.recv()` will return whatever it can read, or an empty string signalling that the other side has shut down (the official docs don't even mention what it returns when the connection is shut down... great!). This is all fine and dandy for blocking sockets, since we know ... | In the case of a non blocking socket that has no data available, recv will throw the socket.error exception and the value of the exception will have the errno of either EAGAIN or EWOULDBLOCK. Example:
```
import sys
import socket
import fcntl, os
import errno
from time import sleep
s = socket.socket(socket.AF_INET, s... |
Tkinter: How to use threads to preventing main event loop from "freezing" | 16,745,507 | 13 | 2013-05-25T01:16:16Z | 16,747,734 | 21 | 2013-05-25T08:17:41Z | [
"python",
"multithreading",
"tkinter",
"progress-bar",
"event-loop"
] | I have a small GUI test with a "Start" button and a Progress bar. The desired behavior is:
* Click Start
* Progressbar oscillates for 5 seconds
* Progressbar stops
The observed behavior is the "Start" button freezes for 5 seconds, then a Progressbar is displayed (no oscillation).
Here is my code so far:
```
class G... | When you join the new thread in the main thread, it will wait until the thread finishes, so the GUI will block even though you are using multithreading.
If you want to place the logic portion in a different class, you can subclass Thread directly, and then start a new object of this class when you press the button. Th... |
comparison function must return int, not long | 16,745,695 | 3 | 2013-05-25T01:55:53Z | 16,745,700 | 7 | 2013-05-25T01:57:21Z | [
"python",
"sorting"
] | ```
class C:
def __init__(self,n,x):
self.n = n
self.x = x
a = C('a',1)
b = C('b',2)
c = C('c',3)
classList = [b,a,c]
for q in classList: print q.n,
classList.sort(lambda a,b: long(a.x - b.x))
for q in classList: print q.n,
```
Running the code above would get the error `TypeError: comparison ... | Use the built-in `cmp` function: `cmp(a.x, b.x)`
By the way, you can also utilize the `key` parameter of `sort`:
`classList.sort(key=lambda c: c.x)`
which is faster.
According to [wiki.python.org](http://wiki.python.org/moin/HowTo/Sorting/):
> This technique is fast because the key function is called exactly once
... |
Tkinter: Treeview widget | 16,746,387 | 6 | 2013-05-25T04:27:37Z | 16,748,186 | 15 | 2013-05-25T09:27:30Z | [
"python",
"treeview",
"tkinter",
"tk"
] | At the moment I am working on a program that has its own project files and inside that are like sub-files and I want to know how to use the treeview widget to display all the sub-files inside the project file, Any Ideas?
Thanks in advance! | There is an [example in the source code of CPython](http://hg.python.org/cpython/file/f4981d8eb401/Demo/tkinter/ttk/dirbrowser.py) of how to fill a Treeview recursively with the content of a directory, this is basically how it works (I have removed the event bindings and wrapped it in a class for better readability):
... |
Python Breadth First Search optimisation | 16,747,125 | 4 | 2013-05-25T06:38:08Z | 16,747,264 | 7 | 2013-05-25T07:00:24Z | [
"python",
"optimization",
"dictionary"
] | Given this code...
```
import Queue
def breadthFirstSearch(graph, start, end):
q = Queue.Queue()
path = [start]
q.put(path)
while not q.empty():
path = q.get()
lastNode = path[len(path) - 1]
if lastNode == end:
return path
for linkNode in graph[lastNode]:
... | Why not keep a set of visited nodes so that you don't keep hitting the same nodes? This should work since it doesn't look like you're using a weighted graph. Something like this:
```
import Queue
def bfs(graph, start, end):
q = Queue.Queue()
path = [start]
q.put(path)
visited = set([start])
while... |
Python assigning two variables on one line | 16,747,599 | 4 | 2013-05-25T07:54:22Z | 16,747,618 | 18 | 2013-05-25T07:56:50Z | [
"python",
"int",
"self"
] | ```
class Domin():
def __init__(self , a, b) :
self.a=a , self.b=b
def where(self):
print 'face : ' , self.a , "face : " ,self.b
def value(self):
print self.a + self.b
d1=Domin(1 , 5)
d1=Domin(20 , 15)
```
I get this error:
```
Traceback (most recent call last):
File "test... | You cannot put two statements on one line like that. Your code is being evaluated like this:
```
self.a = (a, self.b) = b
```
Either use a semicolon (on second thought, don't do that):
```
self.a = a; self.b = b
```
Or use sequence unpacking:
```
self.a, self.b = a, b
```
Or just split it into two lines:
```
sel... |
How to get source corresponding to a Python AST node? | 16,748,029 | 8 | 2013-05-25T09:07:23Z | 17,478,618 | 10 | 2013-07-04T22:02:21Z | [
"python",
"abstract-syntax-tree"
] | Python AST nodes have `lineno` and `col_offset` attributes, which indicate the beginning of respective code range. Is there an easy way to get also the end of the code range? A 3rd party library? | *EDIT: Latest code (tested in Python 3.4 and 3.5) is here: <https://bitbucket.org/plas/thonny/src/master/thonny/ast_utils.py>*
As I didn't find an easy way, here's a hard (and probably not optimal) way. Might crash and/or work incorrectly if there are more lineno/col\_offset bugs in Python parser than those mentioned ... |
Simple Access API (Developer Key) with Google Cloud Endpoint (Python) | 16,748,061 | 6 | 2013-05-25T09:11:46Z | 16,803,274 | 8 | 2013-05-28T23:42:29Z | [
"python",
"google-app-engine",
"google-cloud-endpoints"
] | Is there a way to use Simple Access API (Developer Key) instead of oAuth2 key with Google Cloud Endpoint? | Extra fields in your `protorpc` request object that aren't part of the definition are still stored with the request.
If you wanted to use a `key` field as a query parameter, you could access it via
```
request.get_unrecognized_field_info('key')
```
even if `key` is not a field in your message definition.
This is do... |
Suppress/ print without b' prefix for bytes in Python 3 | 16,748,083 | 26 | 2013-05-25T09:14:03Z | 16,748,087 | 24 | 2013-05-25T09:14:28Z | [
"python",
"string",
"python-3.x"
] | Just posting this so I can search for it later, as it always seems to stump me:
```
$ python3.2
Python 3.2 (r32:88445, Oct 20 2012, 14:09:50)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import curses
>>> print(curses.version)
b'2.2'
>>> print(str(curses.version))
b... | Use `decode`:
```
>>> print(curses.version.decode('utf-8'))
2.2
``` |
Python SSL connection "EOF occurred in violation of protocol" | 16,748,994 | 19 | 2013-05-25T11:18:18Z | 16,758,668 | 11 | 2013-05-26T11:11:54Z | [
"python",
"django",
"celery",
"python-requests",
"gevent"
] | I'm using Django Celery task to connect to Facebook Graph API with requests lib using Gevent. Issue I'm constantly running at is that every now and then I get EOF occurred in violation of protocol exception. I've searched around and various sources offer different fixes but none seems to work.
I've tried monkey patchi... | Using the forced [TLSv1 fix](http://stackoverflow.com/questions/14102416/python-requests-requests-exceptions-sslerror-errno-8-ssl-c504-eof-occurred) as suggested by J.F Sebastian fixed all the issues I was facing.
Hints for future questions regarding:
* DNSError exception - upgrading Gevent from 0.13.X to 1.0rc fixes... |
What does `<>` mean in Python? | 16,749,121 | 30 | 2013-05-25T11:33:54Z | 16,749,125 | 36 | 2013-05-25T11:34:17Z | [
"python",
"syntax",
"operators",
"python-2.x"
] | I'm trying to use in Python 3.3 an old library (dating from 2003!). When I import it, Python throws me an error because there are `<>` signs in the source file, e.g.:
```
if (cnum < 1000 and nnum <> 1000 and ntext[-1] <> "s":
...
```
I guess it's a now-abandoned sign in the language.
What exactly does it mean, a... | It means NOT EQUAL, but it is deprecated, use `!=` instead. |
What does `<>` mean in Python? | 16,749,121 | 30 | 2013-05-25T11:33:54Z | 16,749,135 | 70 | 2013-05-25T11:35:38Z | [
"python",
"syntax",
"operators",
"python-2.x"
] | I'm trying to use in Python 3.3 an old library (dating from 2003!). When I import it, Python throws me an error because there are `<>` signs in the source file, e.g.:
```
if (cnum < 1000 and nnum <> 1000 and ntext[-1] <> "s":
...
```
I guess it's a now-abandoned sign in the language.
What exactly does it mean, a... | It means not equal to. It was taken from `ABC` (python's predecessor) see [here](http://homepages.cwi.nl/~steven/abc/qr.html#TESTS):
> `x < y, x <= y, x >= y, x > y, x = y, x <> y, 0 <= d < 10`
>
> Order tests (`<>` means *'not equals'*)
I believe `ABC` took it from Pascal, a language Guido began programming with.
I... |
What does `<>` mean in Python? | 16,749,121 | 30 | 2013-05-25T11:33:54Z | 16,749,171 | 14 | 2013-05-25T11:40:14Z | [
"python",
"syntax",
"operators",
"python-2.x"
] | I'm trying to use in Python 3.3 an old library (dating from 2003!). When I import it, Python throws me an error because there are `<>` signs in the source file, e.g.:
```
if (cnum < 1000 and nnum <> 1000 and ntext[-1] <> "s":
...
```
I guess it's a now-abandoned sign in the language.
What exactly does it mean, a... | It is an old way of spelling `!=`, that was removed in Python 3. A library old enough to use it likely runs into various *other* incompatibilities with Python 3 as well: it is probably a good idea to run it through [2to3](http://docs.python.org/2/library/2to3.html), which automatically changes this, among many other th... |
What does `<>` mean in Python? | 16,749,121 | 30 | 2013-05-25T11:33:54Z | 16,753,097 | 9 | 2013-05-25T19:20:23Z | [
"python",
"syntax",
"operators",
"python-2.x"
] | I'm trying to use in Python 3.3 an old library (dating from 2003!). When I import it, Python throws me an error because there are `<>` signs in the source file, e.g.:
```
if (cnum < 1000 and nnum <> 1000 and ntext[-1] <> "s":
...
```
I guess it's a now-abandoned sign in the language.
What exactly does it mean, a... | It's **NOT EQUAL TO**....See below:
---
* `==` Checks if the value of two operands are equal or not, if yes then condition becomes true. (`a == b`) is not true.
---
* `!=` Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. (`a != b`) is true.
---
* `<>` Chec... |
What does `<>` mean in Python? | 16,749,121 | 30 | 2013-05-25T11:33:54Z | 16,775,211 | 11 | 2013-05-27T14:20:49Z | [
"python",
"syntax",
"operators",
"python-2.x"
] | I'm trying to use in Python 3.3 an old library (dating from 2003!). When I import it, Python throws me an error because there are `<>` signs in the source file, e.g.:
```
if (cnum < 1000 and nnum <> 1000 and ntext[-1] <> "s":
...
```
I guess it's a now-abandoned sign in the language.
What exactly does it mean, a... | It's worth knowing that you can use Python itself to find documentation, even for punctuation mark operators that Google can't cope with.
```
>>> help("<>")
```
> ## Comparisons
>
> Unlike C, all comparison operations in Python have the same priority,
> which is lower than that of any arithmetic, shifting or bitwise
... |
What's an efficient way to find if a point lies in the convex hull of a point cloud? | 16,750,618 | 20 | 2013-05-25T14:41:49Z | 16,898,636 | 31 | 2013-06-03T14:03:15Z | [
"python",
"numpy",
"convex-hull"
] | I have a point cloud of coordinates in numpy. For a high number of points, I want to find out if the points lie in the convex hull of the point cloud.
I tried pyhull but I cant figure out how to check if a point is in the `ConvexHull`:
```
hull = ConvexHull(np.array([(1, 2), (3, 4), (3, 6)]))
for s in hull.simplices:... | Here is an easy solution that requires only scipy:
```
def in_hull(p, hull):
"""
Test if points in `p` are in `hull`
`p` should be a `NxK` coordinates of `N` points in `K` dimensions
`hull` is either a scipy.spatial.Delaunay object or the `MxK` array of the
coordinates of `M` points in `K`dimensi... |
What's an efficient way to find if a point lies in the convex hull of a point cloud? | 16,750,618 | 20 | 2013-05-25T14:41:49Z | 16,906,278 | 11 | 2013-06-03T21:39:23Z | [
"python",
"numpy",
"convex-hull"
] | I have a point cloud of coordinates in numpy. For a high number of points, I want to find out if the points lie in the convex hull of the point cloud.
I tried pyhull but I cant figure out how to check if a point is in the `ConvexHull`:
```
hull = ConvexHull(np.array([(1, 2), (3, 4), (3, 6)]))
for s in hull.simplices:... | First, obtain the convex hull for your point cloud.
Then loop over all of the edges of the convex hull in counter-clockwise order. For each of the edges, check whether your target point lies to the "left" of that edge. When doing this, treat the edges as vectors pointing counter-clockwise around the convex hull. If th... |
What's an efficient way to find if a point lies in the convex hull of a point cloud? | 16,750,618 | 20 | 2013-05-25T14:41:49Z | 16,909,956 | 16 | 2013-06-04T04:42:48Z | [
"python",
"numpy",
"convex-hull"
] | I have a point cloud of coordinates in numpy. For a high number of points, I want to find out if the points lie in the convex hull of the point cloud.
I tried pyhull but I cant figure out how to check if a point is in the `ConvexHull`:
```
hull = ConvexHull(np.array([(1, 2), (3, 4), (3, 6)]))
for s in hull.simplices:... | Hi I am not sure about how to use your program library to achieve this. But there is a simple algorithm to achieve this described in words:
1. create a point that is definitely outside your hull. Call it Y
2. produce a line segment connecting your point in question (X) to the new point Y.
3. loop around all edge segme... |
Number Guessing Game in Python | 16,751,159 | 4 | 2013-05-25T15:39:13Z | 16,751,351 | 12 | 2013-05-25T16:00:09Z | [
"python",
"random"
] | I was trying to create a simple random number guessing game. The problem is even if I type the correct number it replies with a 'The number is less than'. Can somebody provide me a solution for this one ?
Thanks in advance
```
import random
import sys
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
user = raw_input('Guess The... | The biggest problem is that you're not saving the conversion to `int` so you're using the guess as the string the user entered. You need to save it by doing `user = int(raw_input('>>>'))`
There are other ways you can improve this code, however. You repeat yourself a bit, and you don't need `random.choice`, you can use... |
Python Flask-WTF - use same form template for add and edit operations | 16,752,963 | 8 | 2013-05-25T19:03:44Z | 16,755,436 | 11 | 2013-05-26T01:32:32Z | [
"python",
"flask",
"flask-sqlalchemy",
"flask-wtforms"
] | I'm just getting started with Flask / Flask-WTF / SQLAlchemy, and most example CRUD code I see shows separate templates for adding / editing. It seems repetitive to have two templates with almost identical form html (e.g. books\_add.html, books\_edit.html). Conceptually it makes more sense to me to have one template, s... | There is absolutely no reason to have separate templates for adding / editing different kinds of *things* even. Consider:
```
{# data.html #}
<!-- ... snip ... -->
{% block form %}
<section>
<h1>{{ action }} {{ data_type }}</h1>
<form action="{{ form_action }}" method="{{ method | d("POST") }}">
{% render_form(form) %... |
Mongodb bulk insert limit in Python | 16,753,366 | 2 | 2013-05-25T19:55:21Z | 16,753,859 | 9 | 2013-05-25T21:02:17Z | [
"python",
"mongodb",
"pymongo",
"bulkinsert"
] | Is there a limit to the number of documents one can bulk insert with PyMongo? And I don't mean the 16mb limit of document size for MongoDB, but the actual size of the list of documents I wish to insert in bulk through Python. | There is no limit on the **number** of documents for bulk insert via pymongo. According to the [docs](http://api.mongodb.org/python/current/tutorial.html#bulk-inserts), you can provide an iterable to the `collection.insert`, and it will
```
insert each document in the iterable, sending only a single command to the ser... |
Pickle Queue objects in python | 16,754,116 | 3 | 2013-05-25T21:34:11Z | 16,754,288 | 7 | 2013-05-25T21:56:10Z | [
"python",
"python-2.7",
"pickle"
] | I have a class that uses a list of Queue objects. I need to pickle this class including the information saved in the queue objects. For example:
```
import Queue
import pickle
class QueueTest(object):
def __init__(self):
self.queueList = []
def addQueue(self):
q = Queue.Queue()
q.put('... | I suggest replacing your uses of `Queue.Queue` with `collections.deque`. The `Queue` class is intended to be used for synchronized communication between threads, so it will have some unnecessary overhead when used as a regular data structure. `collections.deque` is a faster alternative. (The name "deque" is pronounced ... |
django - catch multiple exceptions | 16,755,015 | 7 | 2013-05-26T00:01:57Z | 16,755,021 | 8 | 2013-05-26T00:04:07Z | [
"python",
"django",
"exception"
] | I have this view function:
```
def forum(request):
qs = Forum.objects.all()
try:
f = Forum.objects.filter().order_by('-id')[0] <------------problem
return render_to_response("forum.html",{'qs':qs,'f':f},context_instance=RequestContext(request))
except Forum.DoesNotExist or IndexError:
return render_to_resp... | You can catch multiple exceptions in this manner
```
try:
...
except (Forum.DoesNotExist, IndexError) as e:
...
``` |
django - catch multiple exceptions | 16,755,015 | 7 | 2013-05-26T00:01:57Z | 16,755,045 | 12 | 2013-05-26T00:08:53Z | [
"python",
"django",
"exception"
] | I have this view function:
```
def forum(request):
qs = Forum.objects.all()
try:
f = Forum.objects.filter().order_by('-id')[0] <------------problem
return render_to_response("forum.html",{'qs':qs,'f':f},context_instance=RequestContext(request))
except Forum.DoesNotExist or IndexError:
return render_to_resp... | When you have this in your code:
```
except Forum.DoesNotExist or IndexError:
```
It's actually evaluated as this:
```
except (Forum.DoesNotExist or IndexError):
```
where the bit in parentheses is an evaluated expression. Since `or` returns the first of its arguments if it's truthy (which a class is), that's actua... |
Django admin change form load quite slow | 16,755,312 | 4 | 2013-05-26T01:05:55Z | 16,757,065 | 8 | 2013-05-26T07:26:32Z | [
"python",
"django",
"performance",
"django-models",
"django-admin"
] | One of my Django websites has following database models:
In Django App âcommonâ:
```
class Collection(models.Model):
name = models.CharField(max_length = 255, unique = True)
_short_name = models.CharField(db_column="short_name", max_length = 32, blank=True)
class Particle(models.Model):
content = mode... | It is not the magic of django Orm. It is magic of Form.
When you create a Foreign key in Model, then in ModelForm, a ModelChoiceField creates which has all choices of ForeignKey Model. And django Admin use all the properties of Form to create HTML.
So use this code.
```
from django import forms
class RelationForm(form... |
What is the easiest way to get current GMT time in Unix timestamp format? | 16,755,394 | 22 | 2013-05-26T01:24:03Z | 16,755,432 | 15 | 2013-05-26T01:31:38Z | [
"python"
] | Python provides different packages (`datetime`, `time`, `calendar`) as can be seen [here](http://stackoverflow.com/questions/8542723/change-datetime-to-unix-time-stamp-in-python) in order to deal with time. I made a big mistake by using the following to get current GMT time `time.mktime(datetime.datetime.utcnow().timet... | Does this help?
```
from datetime import datetime
import calendar
d = datetime.utcnow()
unixtime = calendar.timegm(d.utctimetuple())
print unixtime
```
[How to convert Python UTC datetime object to UNIX timestamp](http://web.archive.org/web/20150103034016/http://ruslanspivak.com/2011/07/20/how-to-convert-python-utc-... |
What is the easiest way to get current GMT time in Unix timestamp format? | 16,755,394 | 22 | 2013-05-26T01:24:03Z | 16,756,835 | 35 | 2013-05-26T06:42:47Z | [
"python"
] | Python provides different packages (`datetime`, `time`, `calendar`) as can be seen [here](http://stackoverflow.com/questions/8542723/change-datetime-to-unix-time-stamp-in-python) in order to deal with time. I made a big mistake by using the following to get current GMT time `time.mktime(datetime.datetime.utcnow().timet... | I would use time.time() to get a timestamp in seconds since the epoch.
```
import time
time.time()
```
Output:
```
1369550494.884832
```
For the standard CPython implementation on most platforms this will return a UTC value. |
Why does numpy.r_ use brackets instead of parentheses? | 16,755,482 | 12 | 2013-05-26T01:40:54Z | 16,755,528 | 11 | 2013-05-26T01:48:47Z | [
"python",
"numpy"
] | Numpy.r\_, .c\_ and .s\_ are the only Python functions I've come across that take arguments in square brackets rather than parentheses. Why is this the case? Is there something special about these functions? Can I make my own functions that use brackets (not that I want to; just curious)?
For example, the proper synta... | Any Python class can be made so that its instances accept either or both notation: it will accept parens by implementing a function called `__call__`, and brackets by implementing `__getitem__`.
`np.r_` happens to be of a class that implements `__getitem__` to do fancier things than its usual. That is, the class of `r... |
Best way to change words into numbers using specific word list | 16,755,598 | 2 | 2013-05-26T02:07:18Z | 16,755,612 | 8 | 2013-05-26T02:10:56Z | [
"python",
"regex",
"sed",
"awk"
] | I have a text file that contains tweets per line, that need to be altered for a machine learning format. Im using python and basic unix text manipulation (regex) to achieve a lot of my string manipulation, and im gettin the hang of sed, grep and pythons .re function....this next problem however is mindblower for me, an... | ```
from string import punctuation as pnc
tokens = {':)', 'cool', 'happy', 'fun'}
tweets = ['this has been a fun day :)', 'i find python cool! it makes me happy']
for tweet in tweets:
s = [(word in tokens or word.strip(pnc) in tokens) for word in tweet.split()]
print(' '.join('1' if t else '0' for t in s))
```
... |
break for nested loops without executing sub-sequential code | 16,755,620 | 2 | 2013-05-26T02:12:10Z | 16,755,658 | 7 | 2013-05-26T02:19:59Z | [
"python",
"for-loop"
] | I am trying to figure out How I can break a nested for loop to achieve the following:
1. When it breaks out the nested for loop, it's still inside the outer for loop
2. When it breaks out the nested for loop, it doesn't execute the remaining code anymore, in this case, the last line.
```
def for_loop_flow():
for ... | Any `for` loop with a `break` and a flag variable can be expressed as a `for` with an `else` clause. So in your case, you can get rid of the flag and use:
```
for a in range(2):
print "a = {:d}".format(a)
for b in range(3, 5):
print "b = {:d}".format(b)
if b == 4:
print "BREAK!"
... |
Functions in SymPy | 16,755,691 | 2 | 2013-05-26T02:27:02Z | 16,757,904 | 8 | 2013-05-26T09:30:53Z | [
"python",
"sympy"
] | I am new to Python objects and have a lot of questions. I need to pass a function to my object, and then evaluate the function. The code is similar to this:
```
from sympy import var
class eval:
def __init__(self, M):
self.M = M
def fun(self, x):
M = self.M
print M(x)
x = var('x')
a... | > I am new to Python objects...
Having questions is great, but the objects and classes behind SymPy are quite complex and learning the basics of the [Python object model](http://docs.python.org/2/reference/datamodel.html) before delving in such a library is strongly encouraged.
There are many issues with the suggeste... |
python one line function definition | 16,756,174 | 6 | 2013-05-26T04:12:23Z | 16,756,180 | 16 | 2013-05-26T04:13:36Z | [
"python"
] | This must be simple, but as an only occasional python user, fighting some syntax.
This works:
```
def perms (xs):
for x in itertools.permutations(xs): yield list(x)
```
But this won't parse:
```
def perms (xs): for x in itertools.permutations(xs): yield list(x)
```
Is there some restriction on the one-line func... | Yes, there is restrictions. No, you can't do that. Simply put, you can skip one line feed but not two. :-)
See <http://docs.python.org/2/reference/compound_stmts.html>
The reason for this it would allow you to do
```
if test1: if test2: print x
else:
print y
```
Which is ambiguous. |
Why doesn't Python hash lists using ID? | 16,756,615 | 3 | 2013-05-26T05:54:48Z | 16,756,627 | 10 | 2013-05-26T05:57:27Z | [
"python",
"list",
"hash",
"dictionary"
] | When using a dictionary in Python, the following is impossible:
```
d = {}
d[[1,2,3]] = 4
```
since `'list' is an unhashable type`. However, the `id` function in Python returns an integer for an object that is guaranteed to be unique for the object's lifetime.
Why doesn't Python use `id` to hash a dictionary? Are th... | The reason is right here ([Why must dictionary keys be immutable](http://docs.python.org/2/faq/design.html#why-must-dictionary-keys-be-immutable))
> Some unacceptable solutions that have been proposed:
>
> * Hash lists by their address (object ID). This doesnât work because if you construct a new list with the same ... |
'is' operator behaves differently when comparing strings with spaces | 16,756,699 | 26 | 2013-05-26T06:09:39Z | 16,756,740 | 15 | 2013-05-26T06:18:46Z | [
"python",
"python-3.x",
"operators"
] | I've started learning Python (python 3.3) and I was trying out the `is` operator. I tried this:
```
>>> b = 'is it the space?'
>>> a = 'is it the space?'
>>> a is b
False
>>> c = 'isitthespace'
>>> d = 'isitthespace'
>>> c is d
True
>>> e = 'isitthespace?'
>>> f = 'isitthespace?'
>>> e is f
False
```
It seems like th... | To expand on Ignacioâs answer a bit: The `is` operator is the identity operator. It is used to compare *object* identity. If you construct two objects with the same contents, then it is usually not the case that the object identity yields true. It works for some small strings because CPython, the reference implementa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.