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 |
|---|---|---|---|---|---|---|---|---|---|
Difference between Python float and numpy float32 | 16,963,956 | 12 | 2013-06-06T13:54:22Z | 16,964,006 | 11 | 2013-06-06T13:56:35Z | [
"python",
"numpy"
] | What is the difference between the built in `float` and `numpy.float32`?
**Example**
```
a = 58682.7578125
print type(a)
print a
print type(numpy.float32(a))
print numpy.float32(a)
```
Output:
```
<type 'float'>
58682.7578125
<type 'numpy.float32'>
58682.8
```
I've found [here](http://docs.scipy.org/doc/numpy/user... | Python's standard `float` type is a C `double`: <http://docs.python.org/2/library/stdtypes.html#typesnumeric>
NumPy's standard `numpy.float` is the same, and is also the same as `numpy.float64`. |
Reusing code from different IPython notebooks | 16,966,280 | 32 | 2013-06-06T15:34:05Z | 16,966,830 | 26 | 2013-06-06T16:00:36Z | [
"python",
"ipython",
"ipython-notebook"
] | I am using IPython and want to run functions from one notebook from another (without cutting and pasting them between different notebooks). Is this possible and reasonably easy to do? | Starting your notebook server with:
```
ipython notebook --script
```
will save the notebooks (`.ipynb`) as Python scripts (`.py`) as well, and you will be able to import them.
Or have a look at: <http://nbviewer.ipython.org/5491090/> that contains 2 notebook, one executing the other. |
Reusing code from different IPython notebooks | 16,966,280 | 32 | 2013-06-06T15:34:05Z | 18,221,612 | 7 | 2013-08-14T01:01:18Z | [
"python",
"ipython",
"ipython-notebook"
] | I am using IPython and want to run functions from one notebook from another (without cutting and pasting them between different notebooks). Is this possible and reasonably easy to do? | Ipythons `%run` magic allows you execute python files and ipython scripts in a notebook. I sometimes use the `-i` option so it runs in the notebooks namespace. Execute a cell with `%run?` in it for more info.
You can use the `ipython --script` to save notebooks also as `.py` files on each save or uncomment the line `c... |
Reusing code from different IPython notebooks | 16,966,280 | 32 | 2013-06-06T15:34:05Z | 21,839,635 | 10 | 2014-02-17T21:30:08Z | [
"python",
"ipython",
"ipython-notebook"
] | I am using IPython and want to run functions from one notebook from another (without cutting and pasting them between different notebooks). Is this possible and reasonably easy to do? | In IPython 2.0 you can simply `%run 'my_shared_code.ipynb'` to share code between notebooks. See for example <http://nbviewer.ipython.org/gist/edrex/9044756>. |
Getting the average of a certain hour on weekdays over several years in a pandas dataframe | 16,967,165 | 7 | 2013-06-06T16:18:05Z | 16,967,466 | 12 | 2013-06-06T16:33:54Z | [
"python",
"datetime",
"pandas",
"average",
"statistics"
] | I have an hourly dataframe in the following format over several years:
```
Date/Time Value
01.03.2010 00:00:00 60
01.03.2010 01:00:00 50
01.03.2010 02:00:00 52
01.03.2010 03:00:00 49
.
.
.
31.12.2013 23:00:00 77
```
I would like to average the data so I can get the average of hour 0, hour 1... hour 23... | *Note: Now that Series have the dt accessor it's less important that date is the index, though Date/Time still needs to be a datetime64.*
Update: You can do the groupby more directly (without the lambda):
```
In [21]: df.groupby([df["Date/Time"].dt.year, df["Date/Time"].dt.hour]).mean()
Out[21]:
... |
argparse, two arguments depend on each other | 16,967,790 | 5 | 2013-06-06T16:51:09Z | 16,967,896 | 7 | 2013-06-06T16:56:33Z | [
"python",
"argparse"
] | I would like to make the parser like `cmd [-a xxx -b xxx] -c xxx -d xxx`
When `-a` is used, I want `-b` to be used too. likewise, if `-b` is used, `-a` must be used too. It's ok both `-a` and `-b` are not used.
How do I do that? I have tried custom actions, but it does not go well. | Argparse doesn't natively support this type of use.
The most effective thing to do is check and see if those types of conditions are met after parsing:
```
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-b')
parser.add_argument('-c')
args = parser.parse_args()
required_together = ('b','c')... |
argparse, two arguments depend on each other | 16,967,790 | 5 | 2013-06-06T16:51:09Z | 16,968,580 | 7 | 2013-06-06T17:35:58Z | [
"python",
"argparse"
] | I would like to make the parser like `cmd [-a xxx -b xxx] -c xxx -d xxx`
When `-a` is used, I want `-b` to be used too. likewise, if `-b` is used, `-a` must be used too. It's ok both `-a` and `-b` are not used.
How do I do that? I have tried custom actions, but it does not go well. | A better design would be to have a single option that takes two arguments:
```
parser.add_argument('-a', narg=2)
```
Then you either specify the option with 2 arguments, or you don't specify it at all.
```
$ script -a 1 2
```
or
```
$ script
```
A custom action (or postprocessing) can split the tuple `args.a` int... |
Custom arrow style for matplotlib, pyplot.annotate | 16,968,007 | 8 | 2013-06-06T17:02:38Z | 17,009,403 | 7 | 2013-06-09T12:03:55Z | [
"python",
"matplotlib",
"plot",
"customization",
"annotate"
] | I am using matplotlib.pyplot.annotate to draw an arrow on my plot, like so:
```
import matplotlib.pyplot as plt
plt.annotate("",(x,ybottom),(x,ytop),arrowprops=dict(arrowstyle="->"))
```
I want to use an arrow style that has a flat line at one end and an arrow at the other, so combining the styles "|-|" and "->" to m... | In the last example in your code you could have used `headwidth`, `frac` and `width` to customize the arrow, the result is `arrow0` shown below. For highly customized arrows you can used arbitrary polygons. Below you can see the code I used to produce the figures.
To add more polygons you have to edit `polygons` dicti... |
Error when trying to apply log method to pandas data frame column in Python | 16,968,433 | 6 | 2013-06-06T17:27:34Z | 16,968,491 | 9 | 2013-06-06T17:30:40Z | [
"python",
"numpy",
"pandas",
"dataframe"
] | So, I am very new to Python and Pandas (and programming in general), but am having trouble with a seemingly simple function. So I created the following dataframe using data pulled with a SQL query (if you need to see the SQL query, let me know and I'll paste it)
```
spydata = pd.DataFrame(row,columns=['date','ticker',... | This happens when the datatype of the column is not numeric. Try
```
arr['retlog'] = log(arr['close'].astype('float64')/arr['close'].astype('float64').shift(1))
```
I suspect that the numbers are stored as generic 'object' types, which I know causes log to throw that error. Here is a simple illustration of the proble... |
Sending Email to a Microsoft Exchange group using Python? | 16,968,758 | 3 | 2013-06-06T17:46:39Z | 16,969,608 | 7 | 2013-06-06T18:35:33Z | [
"python",
"smtplib"
] | I've written a python script to send out emails, but now I'm wondering if it's possible to send emails to Microsoft exchange groups using python? I've tried including the group in the cc and to fields but that doesn't seem to do the trick. It shows up, but doesn't seem to correspond to a group of emails; it's just plai... | This is definitely possible. Your exchange server should recognize it if you treat it as a full address. For example if you want to send it to person1, person2, and group3, use the following:
```
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
address_book = ['person... |
Scrapy: How to manually insert a request from a spider_idle event callback? | 16,970,112 | 8 | 2013-06-06T19:01:24Z | 16,971,379 | 14 | 2013-06-06T20:16:25Z | [
"python",
"scrapy"
] | I've created a spider, and have linked a method to the spider\_idle event.
How do I add a request manually? I can't just return the item from parse -- parse is not running in this case, as all known URLs have been parsed. I have a method to generate new requests, and I would like to run it from the spider\_idle callba... | ```
class FooSpider(BaseSpider):
def __init__(self, *args, **kwargs):
super(FooSpider, self).__init__(*args, **kwargs)
dispatcher.connect(self.dont_close_me, signals.spider_idle)
def dont_close_me(self, spider):
if spider != self:
return
self.crawler.engine.crawl(se... |
Custom Authentication for Google Cloud Endpoints (instead of OAuth2) | 16,970,327 | 53 | 2013-06-06T19:13:53Z | 20,342,757 | 14 | 2013-12-03T04:13:30Z | [
"python",
"google-app-engine",
"google-cloud-endpoints"
] | We are super excited about App Engine's support for [Google Cloud Endpoints](https://developers.google.com/appengine/docs/python/endpoints/).
That said we don't use OAuth2 yet and usually authenticate users with username/password
so we can support customers that don't have Google accounts.
We want to migrate our API ... | I'm using webapp2 Authentication system for my entire application. So I tried to reuse this for Google Cloud Authentication and I get it!
webapp2\_extras.auth uses webapp2\_extras.sessions to store auth information. And it this session could be stored in 3 different formats: securecookie, datastore or memcache.
Secur... |
Find unique rows in numpy.array | 16,970,982 | 88 | 2013-06-06T19:51:36Z | 16,971,180 | 16 | 2013-06-06T20:04:06Z | [
"python",
"arrays",
"numpy",
"unique"
] | I need to find unique rows in a `numpy.array`.
For example:
```
>>> a # I have
array([[1, 1, 1, 0, 0, 0],
[0, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 0, 0],
[1, 1, 1, 0, 0, 0],
[1, 1, 1, 1, 1, 0]])
>>> new_a # I want to get to
array([[1, 1, 1, 0, 0, 0],
[0, 1, 1, 1, 0, 0],
[1, 1, 1, 1, ... | `np.unique` when I run it on `np.random.random(100).reshape(10,10)` returns all the unique individual elements, but you want the unique rows, so first you need to put them into tuples:
```
array = #your numpy array of lists
new_array = [tuple(row) for row in array]
uniques = np.unique(new_array)
```
That is the only ... |
Find unique rows in numpy.array | 16,970,982 | 88 | 2013-06-06T19:51:36Z | 16,971,224 | 23 | 2013-06-06T20:06:48Z | [
"python",
"arrays",
"numpy",
"unique"
] | I need to find unique rows in a `numpy.array`.
For example:
```
>>> a # I have
array([[1, 1, 1, 0, 0, 0],
[0, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 0, 0],
[1, 1, 1, 0, 0, 0],
[1, 1, 1, 1, 1, 0]])
>>> new_a # I want to get to
array([[1, 1, 1, 0, 0, 0],
[0, 1, 1, 1, 0, 0],
[1, 1, 1, 1, ... | If you want to avoid the memory expense of converting to a series of tuples or another similar data structure, you can exploit numpy's structured arrays.
The trick is to view your original array as a structured array where each item corresponds to a row of the original array. This doesn't make a copy, and is quite eff... |
Find unique rows in numpy.array | 16,970,982 | 88 | 2013-06-06T19:51:36Z | 16,971,324 | 13 | 2013-06-06T20:13:15Z | [
"python",
"arrays",
"numpy",
"unique"
] | I need to find unique rows in a `numpy.array`.
For example:
```
>>> a # I have
array([[1, 1, 1, 0, 0, 0],
[0, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 0, 0],
[1, 1, 1, 0, 0, 0],
[1, 1, 1, 1, 1, 0]])
>>> new_a # I want to get to
array([[1, 1, 1, 0, 0, 0],
[0, 1, 1, 1, 0, 0],
[1, 1, 1, 1, ... | np.unique works by sorting a flattened array, then looking at whether each item is equal to the previous. This can be done manually without flattening:
```
ind = np.lexsort(a.T)
a[ind[np.concatenate(([True],np.any(a[ind[1:]]!=a[ind[:-1]],axis=1)))]]
```
This method does not use tuples, and should be much faster and s... |
Find unique rows in numpy.array | 16,970,982 | 88 | 2013-06-06T19:51:36Z | 16,973,510 | 77 | 2013-06-06T22:47:34Z | [
"python",
"arrays",
"numpy",
"unique"
] | I need to find unique rows in a `numpy.array`.
For example:
```
>>> a # I have
array([[1, 1, 1, 0, 0, 0],
[0, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 0, 0],
[1, 1, 1, 0, 0, 0],
[1, 1, 1, 1, 1, 0]])
>>> new_a # I want to get to
array([[1, 1, 1, 0, 0, 0],
[0, 1, 1, 1, 0, 0],
[1, 1, 1, 1, ... | Another option to the use of structured arrays is using a view of a `void` type that joins the whole row into a single item:
```
a = np.array([[1, 1, 1, 0, 0, 0],
[0, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 0, 0],
[1, 1, 1, 0, 0, 0],
[1, 1, 1, 1, 1, 0]])
b = np.ascontiguou... |
Find unique rows in numpy.array | 16,970,982 | 88 | 2013-06-06T19:51:36Z | 22,941,699 | 59 | 2014-04-08T15:37:39Z | [
"python",
"arrays",
"numpy",
"unique"
] | I need to find unique rows in a `numpy.array`.
For example:
```
>>> a # I have
array([[1, 1, 1, 0, 0, 0],
[0, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 0, 0],
[1, 1, 1, 0, 0, 0],
[1, 1, 1, 1, 1, 0]])
>>> new_a # I want to get to
array([[1, 1, 1, 0, 0, 0],
[0, 1, 1, 1, 0, 0],
[1, 1, 1, 1, ... | Yet another possible solution
```
np.vstack({tuple(row) for row in a})
``` |
Serialization of a pandas DataFrame | 16,971,803 | 5 | 2013-06-06T20:42:05Z | 16,971,876 | 7 | 2013-06-06T20:46:28Z | [
"python",
"pandas"
] | Is there a fast way to do serialization of a DataFrame?
I have a grid system which can run pandas analysis in parallel. In the end, I want to collect all the results (as a DataFrame) from each grid job and aggregate them into a giant DataFrame.
How can I save data frame in a binary format that can be loaded rapidly? | The easiest way is just to use [to\_pickle](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.to_pickle.html) (as a [pickle](http://docs.python.org/2/library/pickle.html)), see [pickling from the docs api page](http://pandas.pydata.org/pandas-docs/stable/api.html#pickling):
```
df.to_pickle(file_name... |
Python: Something went wrong somewhere in the list comprehension? | 16,972,442 | 6 | 2013-06-06T21:24:54Z | 16,972,519 | 11 | 2013-06-06T21:29:14Z | [
"python",
"list-comprehension",
"primes"
] | ```
>>> [l for l in range(2,100) if litheor(l)!=l in sieve(100)]
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
>>> 2 in sieve(100)
True
>>> litheor(2)
True
```
So `litheor(2)` is `True` and `2 in sieve(100)` is `True`, so the `if` clause in the list comprehension is `... | Ok, at first it sounds crazy, but:
```
>>> True != 2 in [2,3,5]
True
>>> (True != 2) in [2,3,5]
False
>>> True != (2 in [2,3,5])
False
```
When you realise that this is not a simple precedence issue, looking at the AST is the only remaining option:
```
>>> ast.dump(ast.parse("True != 2 in [2,3,5]"))
"Module(body=[Ex... |
Numpy size of data type | 16,972,501 | 15 | 2013-06-06T21:27:37Z | 16,972,612 | 21 | 2013-06-06T21:35:53Z | [
"python",
"numpy"
] | In numpy, I can get the size (in bytes) of a particular data type by:
```
datatype(...).itemsize
```
or:
```
datatype(...).nbytes
```
e.g.:
```
np.float32(5).itemsize #4
np.float32(5).nbytes #4
```
I have 2 questions. First, Is there a way to get this information *without creating an instance* of the datatype? ... | You need an instance of the `dtype` to get the itemsize, but you shouldn't need an instance of the `ndarray`. (As will become clear in a second, `nbytes` is a property of the array, not the dtype.)
E.g.
```
print np.dtype(float).itemsize
print np.dtype(np.float32).itemsize
print np.dtype('|S10').itemsize
```
As far ... |
Numpy size of data type | 16,972,501 | 15 | 2013-06-06T21:27:37Z | 16,972,949 | 11 | 2013-06-06T22:01:32Z | [
"python",
"numpy"
] | In numpy, I can get the size (in bytes) of a particular data type by:
```
datatype(...).itemsize
```
or:
```
datatype(...).nbytes
```
e.g.:
```
np.float32(5).itemsize #4
np.float32(5).nbytes #4
```
I have 2 questions. First, Is there a way to get this information *without creating an instance* of the datatype? ... | Looking at the Numpy C source file, this is the comment:
```
size : int
Number of elements in the array.
itemsize : int
The memory use of each array element in bytes.
nbytes : int
The total number of bytes required to store the array data,
i.e., ``itemsize * size``.
```
So in numpy:
```
>>> x = np.ze... |
Odd SciPy ODE Integration error | 16,973,036 | 3 | 2013-06-06T22:07:11Z | 16,974,153 | 7 | 2013-06-06T23:58:58Z | [
"python",
"scipy",
"ode"
] | I'm implementing a very simple Susceptible-Infected-Recovered model with a steady population for an idle side project - normally a pretty trivial task. But I'm running into solver errors using either PysCeS or SciPy, both of which use lsoda as their underlying solver. This only happens for particular values of a parame... | I think that for the parameters you've chosen you're running into problems with [stiffness](http://en.wikipedia.org/wiki/Stiff_equation) - due to numerical instability the solver's step size is getting pushed into becoming very small in regions where the slope of the solution curve is actually quite shallow. The Fortra... |
Python max( ) function incorrect when key has '%' sign as first character | 16,973,069 | 2 | 2013-06-06T22:10:40Z | 16,973,084 | 8 | 2013-06-06T22:12:08Z | [
"python"
] | I'm trying to parse a set of data where some of the keys have percent signs as the first character. Why does the max( ) function return the incorrect answer if a percent sign is the first character in a key?
```
>>> mdict = {'a' : 1, 'b' : 2, '%c' : 4}
>>> max(mdict)
'b'
```
Is there a way around this without remap... | You are getting the maximum *key* (by lexographical order). `max()` looks at the keys only, **not** the values, unless you tell it to with a `key` function. `%c` sorts before `a` or `b`, so the maximum key is `b`:
```
>>> max({'a': 100, 'b': 0, '%c': 50})
'b'
>>> min({'a': 100, 'b': 0, '%c': 50})
'%c'
```
If you expe... |
how to get item index or number along with key,value in dict | 16,973,701 | 2 | 2013-06-06T23:09:36Z | 16,973,713 | 10 | 2013-06-06T23:10:18Z | [
"python"
] | For dictionary I want to keep track of number of items that have been parsed. Is there a better way to do that compared to what is shown below?
```
count = 0
for key,value in my_dict.iteritems():
count += 1
print key,value, count
``` | You can use the [`enumerate()` function](http://docs.python.org/2/library/functions.html#enumerate):
```
for count, (key, value) in enumerate(my_dict.iteritems(), 1):
print key, value, count
```
`enumerate()` efficiently adds a count to the iterator you are looping over. In the above example I tell `enumerate()` ... |
Efficient way to find missing elements in an integer sequence | 16,974,047 | 6 | 2013-06-06T23:45:58Z | 16,974,075 | 19 | 2013-06-06T23:49:58Z | [
"python",
"indexing"
] | Suppose we have two items missing in a sequence of consecutive integers and the missing elements lie between the first and last elements. I did write a code that does accomplish the task. However, I wanted to make it efficient using less loops if possible. Any help will be appreciated. Also what about the condition whe... | You could use the sets here, and take the start and end values from the input list:
```
def missing_elements(L):
start, end = L[0], L[-1]
return sorted(set(range(start, end + 1)).difference(L))
```
This assumes Python 3; for Python 2, use `xrange()` to avoid building a list first.
The `sorted()` call is opti... |
Python Script returns unintended "None" after execution of a function | 16,974,901 | 2 | 2013-06-07T01:29:48Z | 16,974,912 | 7 | 2013-06-07T01:31:16Z | [
"python",
"printing",
"syntax",
"python-3.x",
"nonetype"
] | Specs: Ubuntu 13.04 Python 3.3.1
Background: total beginner to Python; searched about this question but the answer I found was more about "what" than "why";
What I intended to do: Creating a function that takes test score input from the user and output letter grades according to a grade scale/curve; Here is the code:... | In python the default return value of a function is `None`.
```
>>> def func():pass
>>> print func() #print or print() prints the return Value
None
>>> func() #remove print and the returned value is not printed.
>>>
```
So, just use:
`letter_grade(score) #remove the print`
Another alternative is to r... |
unittest.mock: asserting partial match for method argument | 16,976,264 | 18 | 2013-06-07T04:32:08Z | 16,976,500 | 22 | 2013-06-07T04:57:11Z | [
"python",
"unit-testing",
"mocking"
] | Rubyist writing Python here. I've got some code that looks kinda like this:
```
result = database.Query('complicated sql with an id: %s' % id)
```
`database.Query` is mocked out, and I want to test that the ID gets injected in correctly without hardcoding the entire SQL statement into my test. In Ruby/RR, I would hav... | ```
import mock
class AnyStringWith(str):
def __eq__(self, other):
return self in other
...
result = database.Query('complicated sql with an id: %s' % id)
database.Query.assert_called_once_with(AnyStringWith(id))
...
```
**EDIT: preemptively requires a matching string**
```
def arg_should_contain(x):
... |
sqlalchemy multiple foreign keys to same table | 16,976,967 | 2 | 2013-06-07T05:41:01Z | 16,991,346 | 11 | 2013-06-07T19:13:04Z | [
"python",
"postgresql",
"sqlalchemy",
"flask-sqlalchemy"
] | I have a postgres database that looks something like this:
```
Table "public.entities"
Column | Type | Modifiers
---------------+-----------------------------+------------------------------------------------
id | bigint ... | It's not completely clear what exactly is causing the problem since you omitted the most important part -- code that throws that exception but if adding relationship properties to class *PostModel* throws that try to add *foreign\_keys* parameter to *relationship* call as the following:
```
class PostModel(...):
#... |
How to make two objects have the same id in python? | 16,977,196 | 4 | 2013-06-07T05:57:54Z | 16,977,347 | 8 | 2013-06-07T06:07:53Z | [
"python",
"object",
"identity"
] | If I have a class like below:
```
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
```
And have 2 objects:
```
a = Point(1,2)
b = Point(1,2)
```
How can I modify class Point to make `id(a) == id(b)`? | ```
class Point(object):
__cache = {}
def __new__(cls, x, y):
if (x, y) in Point.__cache:
return Point.__cache[(x, y)]
else:
o = object.__new__(cls)
o.x = x
o.y = y
Point.__cache[(x, y)] = o
return o
>>> Point(1, 2)
<__mai... |
Does python have built in type values? | 16,977,490 | 4 | 2013-06-07T06:17:39Z | 16,977,512 | 7 | 2013-06-07T06:19:12Z | [
"python",
"types"
] | Not a typo. I mean type values. Values who's type is 'type'.
I want to write a confition to ask:
```
if type(f) is a function : do_something()
```
Do I NEED to created a temporary function and do:
```
if type(f) == type(any_function_name_here) : do_something()
```
or is that a built-in set of type types that I can... | For functions you would usually check
```
>>> callable(lambda: 0)
True
```
to respect duck typing. However there is the `types` module:
```
>>> import types
>>> dir(types)
['BooleanType', 'BufferType', 'BuiltinFunctionType', 'BuiltinMethodType', 'ClassType', 'CodeType', 'ComplexType', 'DictProxyType', 'DictType', 'D... |
How do I use Node.js to send an email every 10 seconds? | 16,978,674 | 3 | 2013-06-07T07:36:12Z | 16,978,872 | 8 | 2013-06-07T07:47:30Z | [
"javascript",
"python",
"node.js"
] | I'm not sure what's the best way to add a delay of 10 seconds.
setTimeouts don't work, I'm not sure...
In python, I'm used to doing "time.sleep"
I'm not asking for how to send an email. I'm asking how to execute a command every 10 seconds. | `setTimeout` will work but you have to recreate the timeout at the end of each function call.
You'd do that like this.
```
function sendEmail() {
email.send(to, headers, body);
setTimeout(sendEmail, 10*1000);
}
setTimeout(sendEmail, 10*1000);
```
What you probably want is `setInterval`.
```
function sendEmail()... |
How to run scrapy server as a daemon | 16,978,806 | 2 | 2013-06-07T07:44:05Z | 16,979,033 | 8 | 2013-06-07T07:58:05Z | [
"python",
"scrapy",
"scrapyd"
] | I am trying to run scrapy server as a daemon. I have tried [this link](http://scrapyd.readthedocs.org/en/latest/) but i getting error
whenever i run this command:
```
sudo apt-get install scrapyd-0.14
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate pa... | You need to add the Ubuntu repository first. Run the following commands under root permission:
```
$ curl -s http://archive.scrapy.org/ubuntu/archive.key | sudo apt-key add -
$ echo "deb http://archive.scrapy.org/ubuntu precise main" >> /etc/apt/sources.list
$ apt-get update
$ apt-get install scrapyd-0.14
```
Also no... |
How to change the text "optional arguments" in argparse | 16,981,106 | 5 | 2013-06-07T09:49:11Z | 16,981,688 | 7 | 2013-06-07T10:15:13Z | [
"python",
"argparse"
] | For some reason I do not use positional arguments in my program but accept "optional" arguments only, controlling whether an argument is truly optional by facilities like `narg='?'` or `action='store_true'`. Thus the "optional arguments" in the help text will be misleading. Can I display it simply as "arguments"? Thank... | Well, looking at the `argparse` source it seems to me that it's as simple as overwriting the `title` of `parser._optionals`, like this:
```
parser._optionals.title = "my mandatory arguments, they are actually optionals, but I'll check for their presence"
```
Probably I should mention that it's a dirty hack, and your ... |
get request parameters in Tastypie | 16,981,191 | 3 | 2013-06-07T09:53:36Z | 16,982,952 | 9 | 2013-06-07T11:24:03Z | [
"python",
"django",
"rest",
"nosql",
"tastypie"
] | I am building a REST API for my application that uses a NoSQL db (Neo4j) using Tastypie.
So I overrode some main methods of the class `tastypie.resources.Resource` to do so, and currently struggling to implement `def obj_get_list(self, request=None, **kwargs):` which is supposed to return a list of objects.
Actually,... | Currently positional argument `request` is not passed to`obj_get_list`.
So you should:
```
def obj_get_list(self, bundle, **kwargs):
param = bundle.request.GET['param']
#fetch objects based on param
return objects
``` |
Relative imports in Python 3 | 16,981,921 | 178 | 2013-06-07T10:26:50Z | 16,985,066 | 144 | 2013-06-07T13:14:23Z | [
"python",
"python-3.x",
"python-import"
] | I want to import a function from another file in the same directory.
Sometimes it works for me with `from .mymodule import myfunction` but sometimes I get a
> SystemError: Parent module '' not loaded, cannot perform relative import
Sometimes it works with `from mymodule import myfunction`, but sometimes I also get a... | > unfortunately, this module needs to be inside the package, and it also
> needs to be runnable as a script, sometimes. Any idea how I could
> achieve that?
It's quite common to have a layout like this...
```
main.py
mypackage/
__init__.py
mymodule.py
myothermodule.py
```
...with a `mymodule.py` like thi... |
Relative imports in Python 3 | 16,981,921 | 178 | 2013-06-07T10:26:50Z | 28,151,907 | 12 | 2015-01-26T14:21:36Z | [
"python",
"python-3.x",
"python-import"
] | I want to import a function from another file in the same directory.
Sometimes it works for me with `from .mymodule import myfunction` but sometimes I get a
> SystemError: Parent module '' not loaded, cannot perform relative import
Sometimes it works with `from mymodule import myfunction`, but sometimes I also get a... | I ran into this issue. A Hack work around is using a try/except block like this:
```
#!/usr/bin/env python3
#myothermodule
try:
from .mymodule import as_int
except ImportError:
from mymodule import as_int
# Exported function
def add(a, b):
return as_int(a) + as_int(b)
# Test function for module
def _... |
Relative imports in Python 3 | 16,981,921 | 178 | 2013-06-07T10:26:50Z | 28,154,841 | 52 | 2015-01-26T16:54:06Z | [
"python",
"python-3.x",
"python-import"
] | I want to import a function from another file in the same directory.
Sometimes it works for me with `from .mymodule import myfunction` but sometimes I get a
> SystemError: Parent module '' not loaded, cannot perform relative import
Sometimes it works with `from mymodule import myfunction`, but sometimes I also get a... | ## Explanation
Once [PEP 338](https://www.python.org/dev/peps/pep-0338/) conflicted with [PEP 328](https://www.python.org/dev/peps/pep-0328/):
> ... relative imports rely on *\_\_name\_\_* to determine the current
> module's position in the package hierarchy. In a main module, the
> value of *\_\_name\_\_* is always ... |
Pandas: Combine TimeGrouper with another Groupby argument | 16,982,370 | 7 | 2013-06-07T10:52:30Z | 28,311,327 | 8 | 2015-02-04T00:21:06Z | [
"python",
"group-by",
"pandas"
] | I have the following DataFrame:
```
df = pd.DataFrame({
'Branch' : 'A A A A A B'.split(),
'Buyer': 'Carl Mark Carl Joe Joe Carl'.split(),
'Quantity': [1,3,5,8,9,3],
'Date' : [
DT.datetime(2013,1,1,13,0),
DT.datetime(2013,1,1,13,5),
DT.datetime(2013,10,1,20,0),
DT.datetime(2013,10,2,10,0),
DT.datetime(2013,12,2,12,0), ... | You can now use a TimeGrouper with another column (as of IIRC pandas [version 0.14](https://github.com/pydata/pandas/pull/6350)):
```
In [11]: df1 = df.set_index('Date')
In [12]: g = df1.groupby([pd.TimeGrouper('20D'), 'Branch'])
In [13]: g.sum()
Out[13]:
Quantity
Date Bran... |
is Pandas concat an in-place function? | 16,982,936 | 6 | 2013-06-07T11:23:06Z | 16,986,732 | 7 | 2013-06-07T14:37:11Z | [
"python",
"pandas"
] | I guess this question needs some insight into the implementation of concat.
Say, I have 30 files, 1G each, and I can only use up to 32 G memory. I loaded the files into a list of DataFrames, called 'list\_of\_pieces'. This list\_of\_pieces should be ~ 30G in size, right?
if I do 'pd.concat(list\_of\_pieces)', does co... | The answer is no, this is not an in-place operation; np.concatenate is used under the hood, see here: [Concatenate Numpy arrays without copying](http://stackoverflow.com/questions/7869095/concatenate-numpy-arrays-without-copying)
A better approach to the problem is to write each of these pieces to an `HDFStore` table,... |
How to make try-except-KeyError shorter in python? | 16,983,282 | 8 | 2013-06-07T11:42:14Z | 16,983,292 | 18 | 2013-06-07T11:42:50Z | [
"python",
"exception",
"syntax",
"try-catch",
"keyerror"
] | Very often I use the following construction:
```
try:
x = d[i]
except KeyError:
x = '?'
```
Sometimes, instread of '?' I use 0 or `None`. I do not like this construction. It is too verbose. Is there a shorter way to do what I do (just in one line). Something like.
```
x = get(d[i],'?')
``` | You are looking for this:
```
x = d.get(i, '?')
``` |
Fast interpolation of grid data | 16,983,843 | 12 | 2013-06-07T12:12:31Z | 16,984,081 | 26 | 2013-06-07T12:24:20Z | [
"python",
"numpy",
"scipy",
"interpolation"
] | I have a large 3d np.ndarray of data that represents a physical variable sampled over a volume in a regular grid fashion (as in the value in array[0,0,0] represents the value at physical coords (0,0,0)).
I would like to go to a finer grid spacing by interpolating the data in the rough grid. At the moment I'm using sci... | Sure! There are two options that do different things but both exploit the regularly-gridded nature of the original data.
The first is [`scipy.ndimage.zoom`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.interpolation.zoom.html#scipy.ndimage.interpolation.zoom). If you just want to produce a denser ... |
Multipying and adding inside of a too large array | 16,986,317 | 6 | 2013-06-07T14:16:34Z | 16,986,775 | 7 | 2013-06-07T14:39:21Z | [
"python",
"numpy"
] | I have an array A that is of the shape (M,N) now I'd like to do the operation
`R = (A[:,newaxis,:] * A[newaxis,:,:]).sum(2)`
which should yield an (MxM) array. Now the problem is that the array is quite large and I get a Memory error, because the MxMxN array won't fit into memory.
what would be the best strategy to ... | I'm not sure how large you arrays are but the following is equivalent:
```
R = np.einsum('ij,kj',A,A)
```
And can be quite a bit faster and is much less memory intensive:
```
In [7]: A = np.random.random(size=(500,400))
In [8]: %timeit R = (A[:,np.newaxis,:] * A[np.newaxis,:,:]).sum(2)
1 loops, best of 3: 1.21 s pe... |
How to ignore local python when building python from source | 16,986,952 | 10 | 2013-06-07T14:47:19Z | 16,990,281 | 8 | 2013-06-07T18:02:44Z | [
"python",
"configure"
] | When I try to build my own version of Python using:
```
./configure --enable-shared --prefix=/app/vendor/python-dev && make && make install
```
I see some errors during installation:
> /usr/bin/ld: /usr/local/lib/libpython2.7.a(abstract.o): relocation
> R\_X86\_64\_32 against `.rodata.str1.8' can not be used when ma... | This looks to be a misfeature of the `setup.py` script always including `/usr/local` in the search path when `make` builds the target `sharedmods`.
You'll have to manually frob the `setup.py`, so do the...
```
./configure --enable-shared --prefix=/app/vendor/python-dev
```
...first, then edit `setup.py`, find lines ... |
Importing Large Tab Delimited .txt file Into Python | 16,989,647 | 7 | 2013-06-07T17:19:00Z | 16,999,000 | 17 | 2013-06-08T11:21:18Z | [
"python",
"arrays",
"list",
"csv",
"tab-delimited"
] | I have a tab delimited .txt file that I'm trying to import into a matrix array in python of the same format as the text file is as shown below:
123088 266 248 244 266 244 277
123425 275 244 241 289 248 231
123540 156 654 189 354 156 987
Note there are many, many more rows of the stuff above (roughly 200) that I wan... | First, you are loading it into a dictionary, which is not going to get the list of lists that you want.
It's dead simple to use the csv module to generate a list of lists like this:
```
import csv
with open(path) as f:
reader = csv.reader(f, delimiter="\t")
d = list(reader)
print d[0][2] # 248
```
That would... |
Multidimensional Scaling Fitting in Numpy, Pandas and Sklearn (ValueError) | 16,990,996 | 12 | 2013-06-07T18:50:18Z | 20,461,929 | 7 | 2013-12-09T02:10:27Z | [
"python",
"numpy",
"pandas",
"scikit-learn"
] | I'm trying out multidimensional scaling with sklearn, pandas and numpy. The data file Im using has 10 numerical columns and no missing values. I am trying to take this ten dimensional data and visualize it in 2 dimensions with sklearn.manifold's multidimensional scaling as follows:
```
import numpy as np
import pandas... | I ran across the same problem; it turned out that my data was an array of `np.float32` and the reduced float precision caused the distance matrix to be asymmetric. I fixed the issue by converting my data to `np.float64` before running MDS on it.
Here's an example that uses random data to illustrate the issue:
```
imp... |
detect if a variable is a datetime object | 16,991,948 | 5 | 2013-06-07T19:53:00Z | 16,991,985 | 19 | 2013-06-07T19:55:35Z | [
"python",
"datetime"
] | I have a variable and I need to know if it is a datetime object.
So far I have been using the following hack in the function to detect datetime object:
```
if 'datetime.datetime' in str(type(variable)): print 'yes'
```
But there really should be a way to detect what type of object something is. just like I can do:
... | You need `isinstance(variable, datetime.datetime)`:
```
>>> import datetime
>>> now = datetime.datetime.now()
>>> isinstance(now, datetime.datetime)
True
``` |
Translate every element in numpy array according to key | 16,992,713 | 12 | 2013-06-07T20:49:12Z | 16,992,783 | 14 | 2013-06-07T20:53:57Z | [
"python",
"numpy"
] | I am trying to translate every element of a `numpy.array` according to a given key:
For example:
```
a = np.array([[1,2,3],
[3,2,4]])
my_dict = {1:23, 2:34, 3:36, 4:45}
```
I want to get:
```
array([[ 23., 34., 36.],
[ 36., 34., 45.]])
```
I can see how to do it with a loop:
```
def loop... | I don't know about efficient, but you could use `np.vectorize` on the `.get` method of dictionaries:
```
>>> a = np.array([[1,2,3],
[3,2,4]])
>>> my_dict = {1:23, 2:34, 3:36, 4:45}
>>> np.vectorize(my_dict.get)(a)
array([[23, 34, 36],
[36, 34, 45]])
``` |
How to programmatically calculate Chrome extension ID? | 16,993,486 | 6 | 2013-06-07T21:48:20Z | 16,993,487 | 7 | 2013-06-07T21:48:20Z | [
"python",
"google-chrome",
"google-chrome-extension",
"sha256"
] | I'm building an automated process to produce extensions. Is there a code example of calculating the extension-ID directly and entirely bypassing interaction with the browser?
(I'm answering my own question, below.) | I was only able to find a related article with a Ruby fragment, and it's only available in the IA: <http://web.archive.org/web/20120606044635/http://supercollider.dk/2010/01/calculating-chrome-extension-id-from-your-private-key-233>
Important to know:
1. This depends on a DER-encoded public key (raw binary), not a PE... |
Using Cython To Link Python To A Shared Library | 16,993,927 | 24 | 2013-06-07T22:35:16Z | 16,994,414 | 40 | 2013-06-07T23:35:27Z | [
"python",
"c",
"linker",
"cython",
"distutils"
] | I am trying to integrate a third party library written in `C` with my `python` application using `Cython`. I have all of the python code written for a test. I am having trouble finding an example for setting this up.
I have a `pyd/pyx` file I created manually. The third party has given me a `header file (*.h)` and a `... | Sure !
(In the following, I assume that you already know how to deal with `cimport` and the interactions between `.pxd` and `.pyx`. If this is not completely the case, just ask and I will develop that part as well)
The sample (grabbed from a C++ project of mine, but a C project would work pretty much the same) :
**1... |
Using python requests library to login to website | 16,994,044 | 3 | 2013-06-07T22:47:50Z | 16,994,114 | 7 | 2013-06-07T22:55:50Z | [
"python",
"python-requests",
"http-request"
] | I have looked through many SO threads on how to create a session using the [requests](http://docs.python-requests.org/en/latest/index.html) library, but none of the methods I tried actually log me in. I have very little experience with web design and protocols, so please point out any basics that I might need to unders... | @DanAlbert pointed out that I was telling you to use HTTP Auth which isn't what you're trying to do. I assumed since everything looked correct that it might just be HTTP Auth that you needed.
However, looking at the form it looks like maybe you're just using the wrong variable name in your dict:
```
import requests
s... |
In Flask: How to access app Logger within Blueprint | 16,994,174 | 16 | 2013-06-07T23:03:54Z | 16,994,175 | 29 | 2013-06-07T23:03:54Z | [
"python",
"logging",
"flask"
] | What is the standard way for a blueprint to access the application logger? | **inside the blueprint add:**
```
from flask import current_app
```
**and when needed call:**
```
current_app.logger.info('grolsh')
``` |
ImportError: No module named PyQt4 | 16,994,232 | 9 | 2013-06-07T23:11:56Z | 17,066,007 | 18 | 2013-06-12T12:52:27Z | [
"python",
"pyqt4",
"homebrew"
] | I installed pyqt4 by using Homebrew. But when I import PyQt4 in python interpreter, It said that "No module named PyQt4". Can somebody help me with that? | After `brew install pyqt`, you can `brew test pyqt` which will use the python you have got in your PATH in oder to do the test (show a Qt window).
For non-brewed Python, you'll have to set your PYTHONPATH as `brew info pyqt` will tell.
Sometimes it is necessary to open a new shell or tap in order to use the freshly b... |
Is file object in python an iterable | 16,994,552 | 4 | 2013-06-07T23:54:38Z | 16,994,568 | 18 | 2013-06-07T23:57:22Z | [
"python",
"iterable"
] | I have a file "test.txt":
```
this is 1st line
this is 2nd line
this is 3rd line
```
the following code
```
lines = open("test.txt", 'r')
for line in lines:
print "loop 1:"+line
for line in lines:
print "loop 2:"+line
```
only prints:
```
loop 1:this is 1st line
loop 1:this is 2nd line
loop 1:this is 3rd... | It is not only an *iterable*, it is an *iterator*, which is why it can only traverse the file once. You may reset the file cursor with `.seek(0)` as many have suggested but you should, in most cases, only iterate a file once. |
python get time stamp on file in mm/dd/yyyy format | 16,994,696 | 4 | 2013-06-08T00:15:27Z | 16,994,713 | 14 | 2013-06-08T00:17:40Z | [
"python",
"date",
"unix-timestamp"
] | I'm trying to get the datestamp on the file in mm/dd/yyyy format
```
time.ctime(os.path.getmtime(file))
```
gives me detailed time stamp `Fri Jun 07 16:54:31 2013`
How can I display the output as `06/07/2013` | You want to use [`time.strftime()`](http://docs.python.org/2/library/time.html#time.strftime) to format the timestamp; convert it to a time tuple first using either [`time.gmtime()`](http://docs.python.org/2/library/time.html#time.gmtime) or [`time.localtime()`](http://docs.python.org/2/library/time.html#time.localtime... |
numpy array that is (n,1) and (n,) | 16,995,071 | 6 | 2013-06-08T01:23:21Z | 16,995,405 | 8 | 2013-06-08T02:24:33Z | [
"python",
"arrays",
"numpy",
"dimensions"
] | What is the difference between a numpy array (lets say X) that has a shape of (N,1) and (N,). Aren't both of them Nx1 matrices ? The reason I ask is because sometimes computations return either one or the other. | This is a 1D array:
```
>>> np.array([1, 2, 3]).shape
(3,)
```
This array is a 2D but there is only one element in the first dimension:
```
>>> np.array([[1, 2, 3]]).shape
(1, 3)
```
Transposing gives the shape you are asking for:
```
>>> np.array([[1, 2, 3]]).T.shape
(3, 1)
```
Now, look at the array. Only the f... |
No usable temporary directory found | 16,996,125 | 9 | 2013-06-08T04:42:04Z | 16,996,431 | 14 | 2013-06-08T05:30:19Z | [
"python"
] | I am trying to find a temp directory ,
but when i am trying to get the directory using
```
tempfile.gettempdir()
```
it's giving me error of
```
File "/usr/lib/python2.6/tempfile.py", line 254, in gettempdir
tempdir = _get_default_tempdir()
File "/usr/lib/python2.6/tempfile.py", line 201, in _get_default_temp... | This kind of error occured in two case
1. permission(should be drwxrwxrwt and owened by root)
2. space
To check space(disk usage)just run the command on terminal
```
df -h
```
Will list the disk usage on unix and get the output like
```
Filesystem Size Used Avail Use% Mounted on
/dev/sda5 28G 15G ... |
No usable temporary directory found | 16,996,125 | 9 | 2013-06-08T04:42:04Z | 20,684,060 | 7 | 2013-12-19T14:19:38Z | [
"python"
] | I am trying to find a temp directory ,
but when i am trying to get the directory using
```
tempfile.gettempdir()
```
it's giving me error of
```
File "/usr/lib/python2.6/tempfile.py", line 254, in gettempdir
tempdir = _get_default_tempdir()
File "/usr/lib/python2.6/tempfile.py", line 201, in _get_default_temp... | This error can occur when the file system has been switched to read-only mode. |
Prime factorization - list | 16,996,217 | 13 | 2013-06-08T04:56:51Z | 16,996,439 | 21 | 2013-06-08T05:32:03Z | [
"python",
"python-3.x",
"prime-factoring"
] | I am trying to implement a function `primeFac()` that takes as input a positive integer `n` and returns a list containing all the numbers in the prime factorization of `n`.
I have gotten this far but I think it would be better to use recursion here, not sure how to create a recursive code here, what would be the base ... | A simple trial division:
```
def primes(n):
primfac = []
d = 2
while d*d <= n:
while (n % d) == 0:
primfac.append(d) # supposing you want multiple factors repeated
n //= d
d += 1
if n > 1:
primfac.append(n)
return primfac
```
with `O(sqrt(n))` comple... |
Prime factorization - list | 16,996,217 | 13 | 2013-06-08T04:56:51Z | 16,996,526 | 9 | 2013-06-08T05:46:58Z | [
"python",
"python-3.x",
"prime-factoring"
] | I am trying to implement a function `primeFac()` that takes as input a positive integer `n` and returns a list containing all the numbers in the prime factorization of `n`.
I have gotten this far but I think it would be better to use recursion here, not sure how to create a recursive code here, what would be the base ... | This is a comprehension based solution, it might be the closest you can get to a recursive solution in Python while being possible to use for large numbers.
You can get proper divisors with one line:
```
divisors = [ d for d in xrange(2,int(math.sqrt(n)) if n % d == 0 ]
```
then we can test for a number in divisors ... |
Can't figure out how to bind the enter key to a function in tkinter | 16,996,432 | 8 | 2013-06-08T05:30:29Z | 16,996,475 | 16 | 2013-06-08T05:39:23Z | [
"python",
"python-3.x",
"tkinter",
"key-bindings"
] | I'm a Python beginning self-learner, running on MacOS.
I must be blind, because I've looked everywhere and can't find an answer to this that works...
I'm making a prog with a text parser gui in tkinter, where you type a command in a `Entry` widget, and hit a `Button` widget, which triggers my `parse()` funct, ect, pr... | Try running the following program. You just have to be sure your window has the focus when you hit Return--to ensure that it does, first click the button a couple of times until you see some output, then without clicking anywhere else hit Return.
```
import tkinter as tk
root = tk.Tk()
root.geometry("300x200")
def f... |
What is the python for Java's BigDecimal? | 16,996,527 | 4 | 2013-06-08T05:47:06Z | 16,996,544 | 10 | 2013-06-08T05:50:49Z | [
"python",
"google-app-engine",
"python-2.7",
"gae-datastore",
"money"
] | In Java, when we program money it is recommended to use the class BigDecimal for money. Is there something similar in python? I would like something object-oriented that can have a currency and an exchange rate, has that been done?
I store money as integers of cents (I think) and multiply with 100 to get dollars but I... | The [java.math.BigDecimal](http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html) in Java's equivalent is [decimal.Decimal](http://www.python.org/doc/current/lib/module-decimal.html) in Python. You can even go through the [documentation](http://www.python.org/dev/peps/pep-0327/) for more. [mpmath](https://c... |
How does one append large amounts of data to a Pandas HDFStore and get a natural unique index? | 16,997,048 | 8 | 2013-06-08T07:09:21Z | 16,999,397 | 10 | 2013-06-08T12:10:01Z | [
"python",
"indexing",
"pandas",
"dataframe",
"hdfstore"
] | I'm importing large amounts of http logs (80GB+) into a Pandas HDFStore for statistical processing. Even within a single import file I need to batch the content as I load it. My tactic thus far has been to read the parsed lines into a DataFrame then store the DataFrame into the HDFStore. My goal is to have the index ke... | You can do it like this. Only trick is that the first time the store table doesn't exist, so `get_storer` will raise.
```
import pandas as pd
import numpy as np
import os
files = ['test1.csv','test2.csv']
for f in files:
pd.DataFrame(np.random.randn(10,2),columns=list('AB')).to_csv(f)
path = 'test.h5'
if os.path... |
python create several lists from one list | 16,998,380 | 3 | 2013-06-08T10:06:54Z | 16,998,391 | 9 | 2013-06-08T10:08:31Z | [
"python",
"python-2.7"
] | I have list something like `mylist = [1,2,3,4,5,6]` now I need to loop over this list and create 3 new lists like this
```
new1 = [1,4]
new2 = [2,5]
new3 = [3,6]
```
What is the easiest way to do this? | Use slicing:
```
>>> mylist = [1,2,3,4,5,6]
>>> mylist[::3]
[1, 4]
>>> mylist[1::3]
[2, 5]
>>> mylist[2::3]
[3, 6]
>>> lis = range(1,21)
>>> new1, new2, new3 = [lis[i::3] for i in xrange(3)]
>>> new1
[1, 4, 7, 10, 13, 16, 19]
>>> new2
[2, 5, 8, 11, 14, 17, 20]
>>> new3
[3, 6, 9, 12, 15, 18]
```
A good read in case y... |
Scrapy: Why extracted strings are in this format? | 17,000,640 | 7 | 2013-06-08T14:44:23Z | 17,000,677 | 8 | 2013-06-08T14:48:30Z | [
"python",
"scrapy"
] | I'm doing
```
item['desc'] = site.select('a/text()').extract()
```
but this will be printed like this
```
[u'\n A mano libera\n ']
```
What must I do to tim and remove strange chars like [u'\n , the traling space and '] ?
I cannot trim (strip)
```
exceptions.AttributeError: 'li... | The html page may very well contains these whitespaces characters.
What you retrieve a **list** of unicode strings, which is why you can't simply call `strip` on it. If you want to strip these whitespaces characters from *each* string in this list, you can run the following:
```
>>> [s.strip() for s in [u'\n ... |
Scrapy: Why extracted strings are in this format? | 17,000,640 | 7 | 2013-06-08T14:44:23Z | 17,034,590 | 8 | 2013-06-10T23:50:38Z | [
"python",
"scrapy"
] | I'm doing
```
item['desc'] = site.select('a/text()').extract()
```
but this will be printed like this
```
[u'\n A mano libera\n ']
```
What must I do to tim and remove strange chars like [u'\n , the traling space and '] ?
I cannot trim (strip)
```
exceptions.AttributeError: 'li... | There's a nice solution to this using [Item Loaders](http://doc.scrapy.org/en/0.16/topics/loaders.html). Item Loaders are objects that get data from responses, process the data and build Items for you. Here's an example of an Item Loader that will strip the strings and return the first value that matches the XPath, if ... |
Scrapy: how to disable or change log? | 17,000,764 | 6 | 2013-06-08T14:58:43Z | 17,000,781 | 8 | 2013-06-08T15:01:34Z | [
"python",
"scrapy"
] | I've followed the [official tutoral of Scrapy](http://doc.scrapy.org/en/latest/intro/tutorial.html), it's wonderful!
I'd like to remove all of DEBUG messages from console output. Is there a way?
```
2013-06-08 14:51:48+0000 [scrapy] DEBUG: Telnet console listening on 0.0.0.0:6029
2013-06-08 14:51:48+0000 [scrapy] DEB... | You add need to add the following to your `settings.py`:
```
LOG_LEVEL = 'INFO'
```
See [the documentation](http://doc.scrapy.org/en/latest/topics/settings.html#log-level). |
How to run unittest discover from "python setup.py test"? | 17,001,010 | 31 | 2013-06-08T15:27:11Z | 21,726,329 | 11 | 2014-02-12T11:13:28Z | [
"python",
"unit-testing",
"nose",
"py.test",
"unittest2"
] | I'm trying to figure out how to get `python setup.py test` to run the equivalent of `python -m unittest discover`. I don't want to use a run\_tests.py script and I don't want to use any external test tools (like `nose` or `py.test`). It's OK if the solution only works on python 2.7.
In `setup.py`, I think I need to ad... | If you use py27+ or py32+, the solution is pretty simple:
```
test_suite="tests",
``` |
How to run unittest discover from "python setup.py test"? | 17,001,010 | 31 | 2013-06-08T15:27:11Z | 23,307,488 | 9 | 2014-04-26T06:26:17Z | [
"python",
"unit-testing",
"nose",
"py.test",
"unittest2"
] | I'm trying to figure out how to get `python setup.py test` to run the equivalent of `python -m unittest discover`. I don't want to use a run\_tests.py script and I don't want to use any external test tools (like `nose` or `py.test`). It's OK if the solution only works on python 2.7.
In `setup.py`, I think I need to ad... | You don't need config to get this working. There are basically two main ways to do it:
**The quick way**
Rename your `test_module.py` to `module_test.py` (basically add `_test` as a suffix to tests for a particular module), and python will find it automatically. Just make sure to add this to `setup.py`:
```
from set... |
pandas resample documentation | 17,001,389 | 80 | 2013-06-08T16:09:43Z | 17,001,474 | 106 | 2013-06-08T16:20:07Z | [
"python",
"documentation",
"pandas"
] | So I completely understand how to use [resample](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.resample.html), but the documentation does not do a good job explaining the options.
So most options in the `resample` function are pretty straight forward except for these two:
* rule : the offset str... | ```
B business day frequency
C custom business day frequency (experimental)
D calendar day frequency
W weekly frequency
M month end frequency
BM business month end frequency
CBM custom business month end frequency
MS month start frequency
BMS business month start frequenc... |
pandas resample documentation | 17,001,389 | 80 | 2013-06-08T16:09:43Z | 19,821,311 | 54 | 2013-11-06T19:43:41Z | [
"python",
"documentation",
"pandas"
] | So I completely understand how to use [resample](http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.resample.html), but the documentation does not do a good job explaining the options.
So most options in the `resample` function are pretty straight forward except for these two:
* rule : the offset str... | There's more to it than this, but you're probably looking for this list:
```
B business day frequency
C custom business day frequency (experimental)
D calendar day frequency
W weekly frequency
M month end frequency
BM business month end frequency
MS month start frequency
BMS business month start frequency
... |
"Uncatching" an exception in python | 17,001,473 | 18 | 2013-06-08T16:20:06Z | 17,002,257 | 8 | 2013-06-08T17:54:10Z | [
"python",
"exception",
"exception-handling"
] | How should I "rethrow" an exception, that is, suppose:
* I try something in my code, and unfortunately it fails.
* I try some "clever" workaround, which happens to also fail this time
If I throw the exception from the (failing) workaround, it's going to be pretty darn confusing for the user, so I *think* it may be be... | Here is something totally nutty that I wasn't sure would work, but it works in both python 2 and 3. (It does however, require the exception to be encapsulated into a function...)
```
def f():
print ("Fail!")
raise Exception("sparrow")
def g():
print ("Workaround fail.")
raise Exception("coconut")
def a... |
"Uncatching" an exception in python | 17,001,473 | 18 | 2013-06-08T16:20:06Z | 18,634,604 | 9 | 2013-09-05T11:01:42Z | [
"python",
"exception",
"exception-handling"
] | How should I "rethrow" an exception, that is, suppose:
* I try something in my code, and unfortunately it fails.
* I try some "clever" workaround, which happens to also fail this time
If I throw the exception from the (failing) workaround, it's going to be pretty darn confusing for the user, so I *think* it may be be... | If you want to make it appear to the end user that you never called `g()`, then you need to store the traceback from the first error, call the second function and then throw the original with the original traceback. (otherwise, in Python2, bare raise re-raises the second exception rather than the first). The problem is... |
A Nose plugin to specify the order of unit test execution | 17,002,707 | 9 | 2013-06-08T18:46:00Z | 18,627,017 | 9 | 2013-09-05T02:57:10Z | [
"python",
"nose",
"nosetests"
] | I have a desire to use Nose for an over the wire integration test suite. However, the order of execution of some of these tests is important.
That said, I thought I would toss together a quick plugin to decorate a test with the order I want it executed: <https://gist.github.com/Redsz/5736166>
```
def Foo(unittest.Tes... | From the [documentation](http://nose.readthedocs.org/en/latest/writing_tests.html):
> [...] nose runs functional tests in the order in which they appear in the module file. TestCase-derived tests and other test classes are run in alphabetical order.
So a simple solution might be to rename the tests in your test case:... |
Extracting entire pdf data with python pdfminer | 17,003,185 | 3 | 2013-06-08T19:45:00Z | 17,004,623 | 7 | 2013-06-08T22:44:34Z | [
"python",
"pdf-reader"
] | I am using pdfminer to extract data from pdf files using python. I would like to extract all the data present in pdf irrespective of wheather it is an image or text or whatever it is. Can we do that in a single line(or two if needed, without much work). Any help is appreciated. Thanks in advance | > Can we do that in a single line(or two if needed, without much work).
No, you cannot. Pdfminer is powerful but it's rather low-level.
Unfortunately, the documentation is not exactly exhaustive. I was able to find my way around it thanks to some code by Denis Papathanasiou. The code is discussed in [his blog](http:/... |
Python threading questions | 17,004,443 | 2 | 2013-06-08T22:21:00Z | 17,004,562 | 7 | 2013-06-08T22:36:55Z | [
"python",
"multithreading"
] | I have something like the following:
```
d = {...} #a dictionary with strings
l1 = [...] #a list with stuff
l2 = [...] #a list with numbers
...
for i in l1:
for key in l2:
#do some stuff
...
if d[key] == i:
print d[key]
```
and I would like to do the same using threads (for p... | Traditional threading in Python (<http://docs.python.org/2/library/threading.html>) is limited in most common runtimes by a ["Global Interpreter Lock" (GIL)](http://wiki.python.org/moin/GlobalInterpreterLock), which prevents multiple threads from executing simultaneously regardless of however many cores or CPUs you hav... |
How do I create pandas DataFrame (with index or multiindex) from list of namedtuple instances? | 17,004,985 | 11 | 2013-06-08T23:37:23Z | 17,005,204 | 13 | 2013-06-09T00:19:32Z | [
"python",
"pandas"
] | Simple example:
```
>>> from collections import namedtuple
>>> import pandas
>>> Price = namedtuple('Price', 'ticker date price')
>>> a = Price('GE', '2010-01-01', 30.00)
>>> b = Price('GE', '2010-01-02', 31.00)
>>> l = [a, b]
>>> df = pandas.DataFrame.from_records(l, index='ticker')
Traceback (most recent call last)... | To get a Series from a namedtuple you could use the `_fields` attribute:
```
In [11]: pd.Series(a, a._fields)
Out[11]:
ticker GE
date 2010-01-01
price 30
dtype: object
```
Similarly you can create a DataFrame like this:
```
In [12]: df = pd.DataFrame(l, columns=l[0]._fields)
In [13]: df
... |
Use list to filter another list in python | 17,005,126 | 2 | 2013-06-09T00:00:41Z | 17,005,171 | 9 | 2013-06-09T00:10:20Z | [
"python"
] | I have a list:
```
data_list = ['a.1','b.2','c.3']
```
And I want to retrieve only strings that start with strings from another list:
```
test_list = ['a.','c.']
```
`a.1` and `c.3` should be returned.
I suppose I could use a double for-loop:
```
for data in data_list:
for test in test_list:
if data.st... | `str.startswith` can also take a *tuple* (but not a list) of prefixes:
```
test_tuple=tuple(test_list)
for data in data_list:
if data.startswith(test_tuple):
...
```
which means a simple list comprehension will give you the filtered list:
```
matching_strings = [ x for x in data_list if x.startswith(test... |
Python importing class attributes into method local namespace | 17,006,127 | 11 | 2013-06-09T03:28:55Z | 17,006,268 | 21 | 2013-06-09T03:58:31Z | [
"python",
"class",
"namespaces"
] | I have been wondering for a while if there is easier way to assign class attributes to method local namespace. For example, in `dosomething` method, I explicitly make references to `self.a` and `self.b`:
```
class test:
def __init__(self):
self.a = 10
self.b = 20
def dosomething(self):
... | > Q. Is there any way to do this more compact way?
**1.** If the variables are read-only, it would be reasonably Pythonic to factor-out a multi-variable accessor method:
```
class Test:
def __init__(self):
self.a = 10
self.b = 20
self.c = 30
def _read_vars(self):
return self.... |
Python Pandas -- merging mostly duplicated rows | 17,006,476 | 5 | 2013-06-09T04:39:23Z | 17,006,674 | 7 | 2013-06-09T05:14:01Z | [
"python",
"duplicates",
"pandas",
"dataframe"
] | Some of my data looks like:
```
date, name, value1, value2, value3, value4
1/1/2001,ABC,1,1,,
1/1/2001,ABC,,,2,
1/1/2001,ABC,,,,35
```
I am trying to get to the point where I can run
```
data.set_index(['date', 'name'])
```
But, with the data as-is, there are of course duplicates (as shown in the above), so I canno... | Let's imagine you have some function `combine_it` that, given a set of rows that would have duplicate values, returns a single row. First, group by `date` and `name`:
```
grouped = data.groupby(['date', 'name'])
```
Then just apply the aggregation function and *boom* you're done:
```
result = grouped.agg(combine_it)... |
Single Line Nested For Loops | 17,006,641 | 31 | 2013-06-09T05:08:31Z | 17,006,736 | 57 | 2013-06-09T05:26:17Z | [
"python",
"loops",
"for-loop",
"nested",
"nested-loops"
] | Wrote this function in python that transposes a matrix:
```
def transpose(m):
height = len(m)
width = len(m[0])
return [ [ m[i][j] for i in range(0, height) ] for j in range(0, width) ]
```
In the process I realized I don't fully understand how single line nested for loops execute. Please help me understa... | The best source of information is the [official Python tutorial on list comprehensions](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions). List comprehensions are nearly the same as for loops (certainly any list comprehension can be written as a for-loop) but they are often faster than using a ... |
Single Line Nested For Loops | 17,006,641 | 31 | 2013-06-09T05:08:31Z | 17,008,559 | 12 | 2013-06-09T10:13:00Z | [
"python",
"loops",
"for-loop",
"nested",
"nested-loops"
] | Wrote this function in python that transposes a matrix:
```
def transpose(m):
height = len(m)
width = len(m[0])
return [ [ m[i][j] for i in range(0, height) ] for j in range(0, width) ]
```
In the process I realized I don't fully understand how single line nested for loops execute. Please help me understa... | You might be interested in [`itertools.product`](http://docs.python.org/2/library/itertools.html#itertools.product), which returns an iterable yielding tuples of values from all the iterables you pass it. That is, `itertools.product(A, B)` yields all values of the form `(a, b)`, where the `a` values come from `A` and t... |
Python 3 Finding the last number in a string | 17,007,257 | 3 | 2013-06-09T07:03:30Z | 17,007,268 | 8 | 2013-06-09T07:05:17Z | [
"python",
"string",
"parsing",
"search",
"python-3.x"
] | How can I find the last number in any big string?
For eg in the following string I want 47 as the output:
`'tr bgcolor="aa77bb"td>font face="verdana"color="white" size="2">b>Total/b>/font>/td>\td>font face="verdana"color="white" size="2">b>47/b>/font>/td>/tr>'`
PS: We don't know the number. The number 47 is just an ... | ```
>>> import re
>>> text = 'tr bgcolor="aa77bb"td>font face="verdana"color="white" size="2">b>Total/b>/font>/td>\td>font face="verdana"color="white" size="2">b>47/b>/font>/td>/tr>'
>>> re.findall(r'\d+', text)[-1]
'47'
```
If you need to match floating points there's always [this](http://stackoverflow.com/a/385597/1... |
Quadratic Program (QP) Solver that only depends on NumPy/SciPy? | 17,009,774 | 22 | 2013-06-09T12:50:55Z | 17,025,929 | 22 | 2013-06-10T14:12:32Z | [
"python",
"numpy",
"scipy",
"mathematical-optimization"
] | I would like students to solve a quadratic program in an assignment without them having to install extra software like cvxopt etc. Is there a python implementation available that only depends on NumPy/SciPy? | I'm not very familiar with quadratic programming, but I think you can solve this sort of problem just using `scipy.optimize`'s constrained minimization algorithms. Here's an example:
```
import numpy as np
from scipy import optimize
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D
#... |
What is the difference between 'content' and 'text' | 17,011,357 | 21 | 2013-06-09T15:51:09Z | 17,011,420 | 27 | 2013-06-09T15:57:44Z | [
"python",
"python-requests"
] | I am using the terrific [Python Requests](http://www.python-requests.org/) library. I notice that the [fine documentation](http://www.python-requests.org/en/latest/user/quickstart/) has many examples of *how* to do something without explaining the *why*. For instance, both `r.text` and `r.content` are shown as examples... | The [developer interface](http://www.python-requests.org/en/latest/api/#classes) has more details:
`r.text` is the content of the response in unicode, and `r.content` is the content of the response in bytes. |
(Django tutorial) importing 'views' from 'polls' app - syntax error PyCharm | 17,012,558 | 4 | 2013-06-09T17:59:15Z | 17,013,408 | 7 | 2013-06-09T19:37:09Z | [
"python",
"django",
"pycharm"
] | Is it incorrect to use:
```
from [app name] import views
```
when you're inside that app?
I'm following the tutorial from the Django documentation website; and everything is working; however, I'm getting a syntax error (it still works though) every time I do the following:
 as f:
byte = f.read(1)
while byte != b"":
byte = f.read(1)
print ((byte))
```
I'm getting bytes like:
`b'\x00'`
How do I get rid of this `b''`?
Let's say I wanna save the bytes to a list, and then save this list as the same image aga... | You can use bytes.decode function if you really need to "get rid of b": <http://docs.python.org/3.3/library/stdtypes.html#bytes.decode>
But it seems from your code that you do not really need to do this, you really need to work with bytes. |
How to create a delayed queue in RabbitMQ? | 17,014,584 | 30 | 2013-06-09T21:58:47Z | 17,014,585 | 63 | 2013-06-09T21:58:47Z | [
"python",
"queue",
"rabbitmq",
"delay",
"pika"
] | What is the easiest way to create a delay (or parking) queue with Python, Pika and RabbitMQ? I have seen an similar [questions](http://stackoverflow.com/questions/4444208/delayed-message-in-rabbitmq), but none for Python.
I find this an useful idea when designing applications, as it allows us to throttle messages that... | I found this extremely useful when developing my applications. As it gives you an alternative to simply re-queuing your messages. This can easily reduce the complexity of your code, and is one of many powerful hidden features in RabbitMQ.
**Steps**
First we need to set up two basic channels, one for the main queue, a... |
How to create a delayed queue in RabbitMQ? | 17,014,584 | 30 | 2013-06-09T21:58:47Z | 24,129,302 | 7 | 2014-06-09T21:22:28Z | [
"python",
"queue",
"rabbitmq",
"delay",
"pika"
] | What is the easiest way to create a delay (or parking) queue with Python, Pika and RabbitMQ? I have seen an similar [questions](http://stackoverflow.com/questions/4444208/delayed-message-in-rabbitmq), but none for Python.
I find this an useful idea when designing applications, as it allows us to throttle messages that... | FYI, how to do this in Spring 3.2.x.
```
<rabbit:queue name="delayQueue" durable="true" queue-arguments="delayQueueArguments"/>
<rabbit:queue-arguments id="delayQueueArguments">
<entry key="x-message-ttl">
<value type="java.lang.Long">10000</value>
</entry>
<entry key="x-dead-letter-exchange" value="finalDe... |
Are nested try/except blocks in python a good programming practice? | 17,015,230 | 63 | 2013-06-09T23:37:30Z | 17,015,298 | 11 | 2013-06-09T23:46:11Z | [
"python"
] | I'm writing my own container, which needs to give access to a dictionary inside by attribute calls. The typical use of the container would be like this:
```
temp_container = DictContainer()
dict_container['foo'] = bar
...
print dict_container.foo
```
I know that it might be stupid to write something like this, but th... | While in Java its indeed a bad practice to use Exceptions for flow control (mainly because exceptions force the jvm to gather resources ([more here](http://stackoverflow.com/questions/6092992/why-is-it-easier-to-ask-forgiveness-than-permission-in-python-but-not-in-java))), in Python you have 2 important principles: [Du... |
Are nested try/except blocks in python a good programming practice? | 17,015,230 | 63 | 2013-06-09T23:37:30Z | 17,015,303 | 64 | 2013-06-09T23:46:45Z | [
"python"
] | I'm writing my own container, which needs to give access to a dictionary inside by attribute calls. The typical use of the container would be like this:
```
temp_container = DictContainer()
dict_container['foo'] = bar
...
print dict_container.foo
```
I know that it might be stupid to write something like this, but th... | Your first example is perfectly fine. Even the official Python docs recommend this style known as [EAFP](http://docs.python.org/3/glossary.html#term-eafp).
Personally, I prefer to avoid nesting when it's not necessary:
```
def __getattribute__(self, item):
try:
return object.__getattribute__(item)
exc... |
Python: given a list of lists, create a list ordered by the number of occurrences in inner list | 17,015,356 | 3 | 2013-06-09T23:54:19Z | 17,015,398 | 7 | 2013-06-10T00:00:46Z | [
"python",
"list"
] | I have a list of lists:
```
[['a','b','c'], ['a'], ['a','b']]
```
I want to sort it and return a single list so the output looks like this:
```
['a', 'b', 'c']
```
i.e. ordered by the number of times each element appears. a appears 3 times, b appears twice, and c appears once.
How do I go about doing this? | Use [`collections.Counter`](http://docs.python.org/3.3/library/collections.html#collections.Counter), [`itertools.chain.from_iterable`](http://docs.python.org/3.3/library/itertools.html#itertools.chain.from_iterable), and a [list comprehension](http://docs.python.org/3.3/tutorial/datastructures.html#list-comprehensions... |
Multiline user input python | 17,016,240 | 2 | 2013-06-10T02:45:30Z | 17,016,290 | 8 | 2013-06-10T02:52:00Z | [
"python",
"input"
] | I would like to know how to write a simple program that can accept multiple lines of input, then the input can be submitted like in the lynx browser, where you use a blank line and then a period to submit the input.
i want to use it in an email program. | Here's a simple way:
```
#!/usr/bin/python
input_list = []
while True:
input_str = raw_input(">")
if input_str == "." and input_list[-1] == "":
break
else:
input_list.append(input_str)
for line in input_list:
print line
``` |
How to configure Python Kivy for PyCharm on Windows? | 17,016,259 | 10 | 2013-06-10T02:47:27Z | 19,768,743 | 18 | 2013-11-04T13:30:06Z | [
"python",
"windows",
"python-2.7",
"pycharm",
"kivy"
] | I'm having trouble getting Kivy to work with PyCharm on Windows 7. I've managed to add most of the external libraries through File > Settings > Python interpreters > Paths Tab.
I'm using the Kivy version of Python.
When I run a Kivy app that works fine with using the [right click > send to > kivy.bat] method in PyChar... | Install and open `PyCharm`
1. If you already had it installed and have a project open, click `File -> Settings (Ctrl + Alt + S)`. (If not, create a new project, and click the '`...`' (or  ) next to interpreter, and skip step 2)
2. Under Project Settings, click `Proj... |
Is scikit-learn suitable for big data tasks? | 17,017,878 | 12 | 2013-06-10T06:19:16Z | 17,018,759 | 33 | 2013-06-10T07:24:44Z | [
"python",
"machine-learning",
"scikit-learn"
] | I'm working on a TREC task involving use of machine learning techniques, where the dataset consists of more than 5 terabytes of web documents, from which bag-of-words vectors are planned to be extracted. `scikit-learn` has a nice set of functionalities that seems to fit my need, but I don't know whether it is going to ... | `HashingVectorizer` will work if you iteratively chunk your data into batches of 10k or 100k documents that fit in memory for instance.
You can then pass the batch of transformed documents to a linear classifier that supports the `partial_fit` method (e.g. `SGDClassifier` or `PassiveAggressiveClassifier`) and then ite... |
Scikit-learn predict_proba gives wrong answers | 17,017,882 | 11 | 2013-06-10T06:19:38Z | 17,019,830 | 12 | 2013-06-10T08:34:23Z | [
"python",
"scikit-learn"
] | This is a follow-up question from [How to know what classes are represented in return array from predict\_proba in Scikit-learn](http://stackoverflow.com/questions/16937243/how-to-know-what-classes-are-represented-in-return-array-from-predict-proba-in-s)
In that question, I quoted the following code:
```
>>> import s... | `predict_probas` is using the Platt scaling feature of libsvm to callibrate probabilities, see:
* [How does sklearn.svm.svc's function predict\_proba() work internally?](http://stackoverflow.com/questions/15111408/how-does-sklearn-svm-svcs-function-predict-proba-work-internally)
So indeed the hyperplane predictions a... |
Scikit-learn predict_proba gives wrong answers | 17,017,882 | 11 | 2013-06-10T06:19:38Z | 17,142,391 | 8 | 2013-06-17T07:28:55Z | [
"python",
"scikit-learn"
] | This is a follow-up question from [How to know what classes are represented in return array from predict\_proba in Scikit-learn](http://stackoverflow.com/questions/16937243/how-to-know-what-classes-are-represented-in-return-array-from-predict-proba-in-s)
In that question, I quoted the following code:
```
>>> import s... | if you use `svm.LinearSVC()` as estimator, and `.decision_function()` (which is like svm.SVC's .predict\_proba()) for sorting the results from most probable class to the least probable one. this agrees with `.predict()` function. Plus, this estimator is faster and gives almost the same results with `svm.SVC()`
the onl... |
Why is there a difference between inspect.ismethod and inspect.isfunction from python 2 -> 3? | 17,019,949 | 7 | 2013-06-10T08:43:09Z | 17,019,983 | 11 | 2013-06-10T08:45:02Z | [
"python"
] | So this code:
```
from inspect import *
class X(object):
def y(self):
pass
methods = getmembers(X, predicate=ismethod)
functions = getmembers(X, predicate=isfunction)
print("%r" % methods)
print("%r" % functions)
```
From python2.7 yields:
```
[('y', <unbound method X.y>)]
[]
```
and from python3.3 yields:... | Not specifically a difference with `inspect` but Python 3 in general see [here](http://docs.python.org/3.0/whatsnew/3.0.html)
> The concept of âunbound methodsâ has been removed from the language. When referencing a method as a class attribute, you now get a plain function object.
My suggestion for cross-platform... |
How to use __setattr__ correctly, avoiding infinite recursion | 17,020,115 | 16 | 2013-06-10T08:53:13Z | 17,020,163 | 19 | 2013-06-10T08:55:55Z | [
"python",
"python-2.7",
"getattr",
"setattr"
] | I want to define a class containing `read` and `write` methode, which can be called as follows:
```
instance.read
instance.write
instance.device.read
instance.device.write
```
To not use interlaced classes, my idea was to overwrite the `__getattr__` and `__setattr__` methods and to check, if the given name is `device... | You must call the parent class `__setattr__` method:
```
class MyTest(object):
def __init__(self, x):
self.x = x
def __setattr__(self, name, value):
if name=="device":
print "device test"
else:
super(MyTest, self).__setattr__(name, value)
# in pytho... |
Why doesn't str.translate work in Python 3? | 17,020,661 | 14 | 2013-06-10T09:27:02Z | 17,020,684 | 32 | 2013-06-10T09:28:17Z | [
"python",
"python-3.x"
] | Why does `'a'.translate({'a':'b'})` return `'a'` instead of `'b'`? I'm using Python 3. | The keys used are the ordinals of the characters, not the characters themselves:
```
'a'.translate({ord('a'): 'b'})
```
It's easier to use `str.maketrans`
```
>>> 'a'.translate(str.maketrans('a', 'b'))
'b'
>>> help(str.translate)
Help on method_descriptor:
translate(...)
S.translate(table) -> str
Return a... |
Re-read an open file Python | 17,021,863 | 5 | 2013-06-10T10:34:19Z | 17,021,894 | 9 | 2013-06-10T10:36:34Z | [
"python",
"file",
"testing"
] | I have a script that reads a file and then completes tests based on that file however I am running into a problem because the file reloads after one hour and I cannot get the script to re-read the file after or at that point in time.
So:
GETS NEW FILE TO READ
Reads file
performs tests on file
GET NEW FILE TO READ (wit... | You can move the cursor to the beginning of the file the following way:
```
file.seek(0)
```
Then you can successfully read it. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.