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 concatenate text files | 13,613,336 | 57 | 2012-11-28T19:54:46Z | 13,613,375 | 109 | 2012-11-28T19:57:47Z | [
"python",
"file-io",
"concatenation"
] | I have a list of 20 file names, like `['file1.txt', 'file2.txt', ...]`. I want to write a Python script to concatenate these files into a new file. I could open each file by `f = open(...)`, read line by line by calling `f.readline()`, and write each line into that new file. It doesn't seem very "elegant" to me, especi... | This should do it
**For large files:**
```
filenames = ['file1.txt', 'file2.txt', ...]
with open('path/to/output/file', 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
for line in infile:
outfile.write(line)
```
**For small files:**
```
filenames = ['file... |
Python concatenate text files | 13,613,336 | 57 | 2012-11-28T19:54:46Z | 13,613,527 | 37 | 2012-11-28T20:07:45Z | [
"python",
"file-io",
"concatenation"
] | I have a list of 20 file names, like `['file1.txt', 'file2.txt', ...]`. I want to write a Python script to concatenate these files into a new file. I could open each file by `f = open(...)`, read line by line by calling `f.readline()`, and write each line into that new file. It doesn't seem very "elegant" to me, especi... | That's exactly what [fileinput](http://docs.python.org/3/library/fileinput.html) is for:
```
import fileinput
with open(outfilename, 'w') as fout, fileinput.input(filenames) as fin:
for line in fin:
fout.write(line)
```
For this use case, it's really not much simpler than just iterating over the files man... |
Python concatenate text files | 13,613,336 | 57 | 2012-11-28T19:54:46Z | 27,077,437 | 38 | 2014-11-22T12:35:15Z | [
"python",
"file-io",
"concatenation"
] | I have a list of 20 file names, like `['file1.txt', 'file2.txt', ...]`. I want to write a Python script to concatenate these files into a new file. I could open each file by `f = open(...)`, read line by line by calling `f.readline()`, and write each line into that new file. It doesn't seem very "elegant" to me, especi... | Use `shutil.copyfileobj`. It should be more efficient.
```
with open('output_file.txt','wb') as wfd:
for f in ['seg1.txt','seg2.txt','seg3.txt']:
with open(f,'rb') as fd:
shutil.copyfileobj(fd, wfd, 1024*1024*10)
#10MB per writing chunk to avoid reading big file into memory.
``` |
Print Dictionary Keys without Dictionary Name? How/why? | 13,613,577 | 2 | 2012-11-28T20:10:53Z | 13,613,668 | 10 | 2012-11-28T20:18:14Z | [
"python",
"printing",
"dictionary",
"python-3.x",
"key"
] | So I created a dictionary for setting difficulty level on a little game.
```
diff_dict = {'easy':0.2, 'medium':0.1, 'hard':0.05} # difficulty level dict
```
Keys are going to be the difficulty names and the values some ratios that i would use to compute the difficulty.
So I was trying to figure out how to print only... | The thing is, in Python 3 dict's method `keys()` does not return a list, but rather a special [view object](http://docs.python.org/3/library/stdtypes.html#dictionary-view-objects). That object has a [magic `__str__` method](http://docs.python.org/3/reference/datamodel.html#object.__str__) that is called on an object un... |
Insert substring if found | 13,613,811 | 2 | 2012-11-28T20:27:47Z | 13,613,847 | 8 | 2012-11-28T20:30:11Z | [
"python",
"string"
] | I'm given a string `my_str` in Python. What I want to do is: If `my_str` contains a substring `str1`, then insert a string `str2` right after the substring `str1` (and leave the rest of `my_str` intact.) Otherwise, do nothing. (Let's say that `my_str` contains no more than one substring being `str1`.)
The way I'm thin... | The easiest method is with `str.replace()`:
```
>>> str1 = "blah"
>>> str2 = "new"
>>> "testblah".replace(str1, str1+str2)
'testblahnew'
>>> "testblahtest".replace(str1, str1+str2)
'testblahnewtest'
>>> "test".replace(str1, str1+str2)
'test'
>>> "blahtestblah".replace(str1, str1+str2)
'blahnewtestblahnew'
```
We simp... |
Is there a Python module for creating test files of specific sizes? | 13,614,774 | 2 | 2012-11-28T21:29:39Z | 13,614,831 | 8 | 2012-11-28T21:34:33Z | [
"python",
"file",
"testing"
] | I have a server that has files uploaded to it. I need to profile the upload/response time for various file sizes to that server i.e. how long it takes to upload a 10kb file, a 100mb file, and many other sizes. I want to avoid manually creating all of the files and storing them.
Is there a Python module that lets you c... | You don't really need to write 1MB to create a 1MB file:
```
with open('bigfile', 'wb') as bigfile:
bigfile.seek(1048575)
bigfile.write('0')
```
On the other hand, do you really need a file at all? Many APIs take any "file-like object". It's not always clear whether that means `read`, `read` and `seek`, itera... |
why does the console has space when it prints python | 13,615,059 | 2 | 2012-11-28T21:52:51Z | 13,615,090 | 7 | 2012-11-28T21:55:26Z | [
"python"
] | I just noticed something weird
In python, if I do this
```
>>> k = 1
>>> j = 2
>>> print k,",",j
1 , 2 # prints this
```
I expected that it would be:
```
1,2
```
Why is there a space between these two, whereas
```
>>> print str(k) + "," + str(j)
1,2
```
Thanks | The first example passes the 3 arguments to `print` directly, which then converts them to strings and concatenates them together, separated by spaces. The second example first converts and concatenates the string, then passes the entire string to `print` as a single argument. If you were to do `print str(k), ",", str(j... |
Finding Sum of a Column in a List Getting "TypeError: cannot perform reduce with flexible type" | 13,616,303 | 5 | 2012-11-28T23:29:58Z | 13,616,758 | 7 | 2012-11-29T00:17:28Z | [
"python",
"numpy",
"sum",
"typeerror",
"flexible-type"
] | So I am new to python and have searched for this answer but most responses are over my head. I have a list like this:
```
right point point 1.76999998093
right fear fear 1.62700009346
right sit sit 1.46899986267
right chord chord 1.47900009155
right speed speeed 1.71300005913
right system system 1.69799995422
right ha... | Generate a list and sum the elements:
```
import numpy as np
right = open('right.txt').readlines()
mylist = []
for line in right:
l = line.split()
mylist.append(float(l[3])) # add to list "mylist"
rightsum = np.sum(mylist)
print rightsum
```
Or, alternatively
```
mylist = [float(line.split()[3]) for ... |
Why does a chained dictionary .get() in python return a tuple when the default provided is not a tuple? | 13,616,455 | 4 | 2012-11-28T23:45:43Z | 13,616,484 | 9 | 2012-11-28T23:48:16Z | [
"python",
"dictionary",
"get",
"tuples",
"chained"
] | Python 2.6.6 when I call .get on the results of a .get the result is a tuple. This is making no sense to me. Example:
```
box = {}.get('test1',{}).get('test2','hrmm'),
print type(box)
```
prints out
```
<type 'tuple'>
```
this makes no sense to me. clearly the default in the second get is a simple string. so what g... | You have a trailing comma at the end of the line, so you are getting the result of `{}.get('test1',{}).get('test2','hrmm')` in a one-element tuple.
Here is an example of how this works with a simple literal:
```
>>> box = 1,
>>> box
(1,)
>>> type(box)
<type 'tuple'>
``` |
How to use g.user global in flask | 13,617,231 | 39 | 2012-11-29T01:12:22Z | 13,631,541 | 50 | 2012-11-29T17:40:32Z | [
"python",
"flask",
"jinja2",
"flask-login"
] | As I understand the g variable in Flask, it should provide me with a global place to stash data like holding the current user after login. Is this correct?
I would like my navigation to display my user's name, once logged in, across the site.
My views contain
```
from Flask import g #among other things
```
During l... | `g` is a [thread local](http://flask.pocoo.org/docs/advanced_foreword/#thread-locals-in-flask) and is per-request (See [A Note On Proxies](http://flask.pocoo.org/docs/reqcontext/#notes-on-proxies)). The `session` is *also* a thread local, but in the default context is persisted to a MAC-signed cookie and sent to the cl... |
How to use g.user global in flask | 13,617,231 | 39 | 2012-11-29T01:12:22Z | 33,006,037 | 7 | 2015-10-08T03:20:39Z | [
"python",
"flask",
"jinja2",
"flask-login"
] | As I understand the g variable in Flask, it should provide me with a global place to stash data like holding the current user after login. Is this correct?
I would like my navigation to display my user's name, once logged in, across the site.
My views contain
```
from Flask import g #among other things
```
During l... | Minor correction, the g object is bound to the application context now instead of the request context.
["Starting with Flask 0.10 this is stored on the application context and no longer on the request context which means it becomes available if only the application context is bound and not yet a request."](http://flas... |
wtforms hidden field value | 13,619,558 | 7 | 2012-11-29T05:40:49Z | 13,632,225 | 9 | 2012-11-29T18:24:02Z | [
"python",
"wtforms"
] | I am no programmer, so please be gentle with me. I am using WTForms, quite successfully, but I have a problem with hidden fields not returning values, whereas the docs say they should. I have constructed a simple example, hope this is clear;
**forms.py:**
```
from wtforms import (Form, TextField, HiddenField)
class ... | I suspect your hidden field is either (1) not getting a value set, or (2) the render\_field macro isn't building it correctly. If I had to bet, I'd say your "mydata" object doesn't have the values you expect.
I stripped your code down to the bare minimum, and this works for me. Note I am explicitly giving a value to b... |
How to generate temporary file in django and then destroy | 13,619,600 | 13 | 2012-11-29T05:44:45Z | 13,619,653 | 31 | 2012-11-29T05:49:33Z | [
"python",
"django"
] | I am doing some file processing and for generating the file i need to generate some temporary file from existing data and then use that file as input to my function.
But i am confused where should i save that file and then delete it.
Is there any temp location where files automatically gets deleted after user session | Python has [tempfile module](http://docs.python.org/2/library/tempfile.html) for exactly this purpose. You do not need to worry about the location/deletion of the file, it works on all supported platforms.
There are three types of temporary files:
* `tempfile.TemporaryFile` - just basic temporary file,
* `tempfile.Na... |
pytest and coverage combination does not work | 13,621,466 | 4 | 2012-11-29T08:18:22Z | 13,623,467 | 7 | 2012-11-29T10:16:48Z | [
"python",
"code-coverage",
"py.test"
] | I installed plugin for pytest from here:http://pypi.python.org/pypi/pytest-cov. Then I have a simple test code:
pytest.py:
```
class TestNumbers:
def test_int_float(self):
assert 1 == 1.0
def test_int_str(self):
assert 1 == 1
```
I tried to test it with command: 'py.test --cov-report term --... | Try:
`text
py.test --cov-report term --cov=. test.py`
The `--cov` parameter takes an argument saying which paths to cover. In your example, `--cov` would consume `test.py`, but then there were no arguments left for py.test about which files to test.
**UPDATE**: as @hpk42 points out, you need to call your example som... |
import a file from different directory | 13,621,540 | 2 | 2012-11-29T08:23:23Z | 13,621,619 | 7 | 2012-11-29T08:28:22Z | [
"python",
"python-2.7"
] | i'm using python 2.7. I have written a script, i need to import a function from some other file which is there in different folder.
my script is in the path
```
C:\python\xyz\xls.py
```
Path of File having function that i need to call is
```
C:\python\abc.py
```
i tried like this
```
from python.abc import *
```
... | You can dynamically load a module from a file:
```
import imp
modl = imp.load_source('modulename', '/path/to/module.py')
```
The [imp module docs](http://docs.python.org/2/library/imp.html) will give you more details. |
How to protect myself from a gzip or bzip2 bomb? | 13,622,706 | 17 | 2012-11-29T09:35:06Z | 14,024,198 | 9 | 2012-12-24T17:39:02Z | [
"python",
"security",
"gzip",
"bzip2"
] | This is related to the question [about zip bombs](http://stackoverflow.com/questions/1459080/how-can-i-protect-myself-from-a-zip-bomb), but having gzip or bzip2 compression in mind, e.g. a web service accepting `.tar.gz` files.
Python provides a handy [tarfile module](http://docs.python.org/2/library/tarfile.html) tha... | You could use [`resource` module](http://docs.python.org/2/library/resource.html) to limit resources available to your process and its children.
If you need to decompress in memory then you could set `resource.RLIMIT_AS` (or `RLIMIT_DATA`, `RLIMIT_STACK`) e.g., using a context manager to automatically restore it to a ... |
Python 3 Map function is not Calling up function | 13,623,634 | 3 | 2012-11-29T10:26:07Z | 13,623,676 | 9 | 2012-11-29T10:28:07Z | [
"python",
"python-3.x",
"functional-programming",
"map-function"
] | Why doesn't following code print anything:
```
#!/usr/bin/python3
class test:
def do_someting(self,value):
print(value)
return value
def fun1(self):
map(self.do_someting,range(10))
if __name__=="__main__":
t = test()
t.fun1()
```
I'm executing the above code in Python 3. I th... | [`map()` returns an iterator](http://docs.python.org/3/library/functions.html#map), and will not process elements until you ask it to.
Turn it into a list to force all elements to be processed:
```
list(map(self.do_someting,range(10)))
```
or use `collections.deque()` with the length set to 0 to not produce a list i... |
python how to register dynamic class in module | 13,624,603 | 7 | 2012-11-29T11:19:09Z | 13,624,643 | 10 | 2012-11-29T11:21:29Z | [
"python",
"class",
"module",
"metaprogramming"
] | I have module foo, inside this module I dynamically created class:
```
def superClassCreator():
return type("Bar", (object,), {})
```
Now, what I want to achieve is to make this new dynamic class visible as a class of this module:
```
import foo
dir(foo)
>>> [... 'Bar' ...]
```
Do you know how to do this? | You can use `Bar = superClassCreator()` in `foo` (at the module level).
Alternatively, from another module, you can add `Bar` as an attribute on `foo`:
```
import foo
foo.Bar = superClassCreator()
```
or, if the name must be taken from the generated class:
```
import foo
generatedClass = superClassCreator()
setat... |
Setting focus to specific TKinter entry widget | 13,626,406 | 6 | 2012-11-29T13:00:21Z | 13,626,607 | 9 | 2012-11-29T13:11:48Z | [
"python",
"tkinter"
] | I'd like to set the focus of my program to a specific `entry` widget so that I can start entering data straight-away - how can I do this?
**My current code**
```
from Tkinter import *
root = Tk()
frame=Frame(root,width=100,heigh=100,bd=11)
frame.pack()
label = Label(frame,text="Enter a digit that you guessed:").pack(... | Use `entry.focus()`:
```
from Tkinter import *
root = Tk()
frame=Frame(root,width=100,heigh=100,bd=11)
frame.pack()
label = Label(frame,text="Enter a digit that you guessed:").pack()
entry= Entry(frame,bd=4)
entry.pack()
entry.focus()
button1=Button(root,width=4,height=1,text='ok')
button1.pack()
root.mainloop()
``` |
Unit Test not running | 13,626,524 | 12 | 2012-11-29T13:07:02Z | 13,626,588 | 26 | 2012-11-29T13:10:21Z | [
"python",
"unit-testing"
] | I'm getting stuck with some unittests.
Here's the simplest example I could come up with:
```
#testito.py
import unittest
class Prueba(unittest.TestCase):
def setUp(self):
pass
def printsTrue(self):
self.assertTrue(True)
if __name__=="__main__":
unittest.main()
```
Problem is, running t... | By default, only functions whose name that start with `test` are run:
```
class Prueba(unittest.TestCase):
def setUp(self):
pass
def testPrintsTrue(self):
self.assertTrue(True)
```
From the [unittest basic example](http://docs.python.org/2/library/unittest.html#basic-example):
> A testcase i... |
How to avoid creation of .pyc files on OS X 10.8 with Python 2.7? | 13,627,686 | 5 | 2012-11-29T14:13:51Z | 13,888,591 | 12 | 2012-12-15T01:55:45Z | [
"python",
"osx",
"python-2.7",
"osx-mountain-lion",
"pyc"
] | It seems that on OS X 10.8 (with Python 2.7) the `.pyc` files are created even if you setup the environment variable `PYTHONDONTWRITEBYTECODE=1`
How can I prevent this from happening, or how can I convince Python not to create this files in the same location as the source files. | I just tested this, and it works fine on 10.8.2 with the Apple-installed Python 2.7.
```
$ echo -e 'import bar\n' > foo.py
$ echo -e 'pass\n' > bar.py
$ export PYTHONDONTWRITEBYTECODE=1
$ python foo.py
$ ls -l bar.py*
-rw-r--r-- 1 abarnert staff 6 Dec 14 17:25 bar.py
$ unset PYTHONDONTWRITEBYTECODE
$ python foo.p... |
Does this Python expression make sense? | 13,628,661 | 5 | 2012-11-29T15:06:05Z | 13,628,695 | 14 | 2012-11-29T15:07:43Z | [
"python",
"logic",
"expression"
] | I found this kind of expression several times in a python program:
```
if variable is not None:
dothings(variable)
```
It seems strange to me, and I think that it has no more sense than:
```
if variable:
dothings(variable)
```
Maybe I don't know Python enough, and the expression is explained somewhere? | `variable` could be `0`, or `False`, or `[]`, or `()`; be 'falsy' in other words, and then the `if` statement would be skipped.
See [Truth testing](http://docs.python.org/2/library/stdtypes.html#truth-value-testing) for more detail on what is considered false in a boolean context.
In short, testing if `variable is no... |
How do I implement a sliding window in Python? | 13,628,710 | 2 | 2012-11-29T15:08:27Z | 13,628,783 | 10 | 2012-11-29T15:11:41Z | [
"python",
"arrays",
"matrix",
"sliding-window"
] | I have a matrix for instance
```
a=[12,2,4,67,8,9,23]
```
and I would like a code that appends a value say 45 to it and removes the first value '12'
so in essence I want to make
```
a = [2,4,67,8,9,23,45]
```
I want to work with regular matrices not numpy matrices so I can't use hstack or vstack
How do I do this in... | Use a deque.
<http://docs.python.org/2/library/collections.html#collections.deque>
```
>>> import collections
>>> d = collections.deque(maxlen=7)
>>> d.extend([12,2,4,67,8,9,23])
>>> d.append(45)
>>> print d
deque([2, 4, 67, 8, 9, 23, 45], maxlen=7)
``` |
How do I check whether an int is between the two numbers? | 13,628,791 | 65 | 2012-11-29T15:11:59Z | 13,628,824 | 21 | 2012-11-29T15:13:34Z | [
"python"
] | I'm using 2.3 IDLE and I'm having problems.
I need to check whether a number is between two other numbers, 10000 and 30000:
```
if number >= 10000 and number >= 30000:
print ("you have to pay 5% taxes")
```
It's not working too well. | Your operator is incorrect. Should be `if number >= 10000 and number <= 30000:`. Additionally, Python has a shorthand for this sort of thing, `if 10000 <= number <= 30000:`. |
How do I check whether an int is between the two numbers? | 13,628,791 | 65 | 2012-11-29T15:11:59Z | 13,628,825 | 235 | 2012-11-29T15:13:36Z | [
"python"
] | I'm using 2.3 IDLE and I'm having problems.
I need to check whether a number is between two other numbers, 10000 and 30000:
```
if number >= 10000 and number >= 30000:
print ("you have to pay 5% taxes")
```
It's not working too well. | ```
if 10000 <= number <= 30000:
pass
``` |
How do I check whether an int is between the two numbers? | 13,628,791 | 65 | 2012-11-29T15:11:59Z | 13,628,830 | 7 | 2012-11-29T15:13:43Z | [
"python"
] | I'm using 2.3 IDLE and I'm having problems.
I need to check whether a number is between two other numbers, 10000 and 30000:
```
if number >= 10000 and number >= 30000:
print ("you have to pay 5% taxes")
```
It's not working too well. | Your code snippet,
```
if number >= 10000 and number >= 30000:
print ("you have to pay 5% taxes")
```
actually checks if number is larger than both 10000 and 30000.
Assuming you want to check that the number is in the range 10000 - 30000, you could use the Python interval comparison:
```
if 10000 <= number <= 3... |
How do I check whether an int is between the two numbers? | 13,628,791 | 65 | 2012-11-29T15:11:59Z | 20,623,994 | 22 | 2013-12-17T00:59:25Z | [
"python"
] | I'm using 2.3 IDLE and I'm having problems.
I need to check whether a number is between two other numbers, 10000 and 30000:
```
if number >= 10000 and number >= 30000:
print ("you have to pay 5% taxes")
```
It's not working too well. | ```
r=range(1,4)
>>> 1 in r
True
>>> 2 in r
True
>>> 3 in r
True
>>> 4 in r
False
>>> 5 in r
False
>>> 0 in r
False
``` |
Setuptools. How to make package contain extra data folder and all folders inside | 13,628,979 | 4 | 2012-11-29T15:22:46Z | 13,629,066 | 8 | 2012-11-29T15:26:49Z | [
"python",
"filenames",
"setuptools"
] | So i'm making setuptool package.
To include extra data files in package i need to specefy `data_file` parameter inside `setup()`.
**Code Example:**
```
datadir = os.path.join('share','data')
datafiles = [(datadir, [f for f in glob.glob(os.path.join(datadir, '*'))])]
import metainfo # a file with relevant information... | Use [`os.walk()`](http://docs.python.org/2/library/os.html#os.walk) to generate that information:
```
datafiles = [(root, [os.path.join(root, f) for f in files])
for root, dirs, files in os.walk(datadir)]
```
That'll produce absolute paths; you can process the `root` variable a little more to make them relative t... |
Numpy mask based on if a value is in some other list | 13,629,061 | 7 | 2012-11-29T15:26:42Z | 13,629,115 | 13 | 2012-11-29T15:29:29Z | [
"python",
"numpy"
] | I have searched high and low and just cant find a way to do it (Its possible i was searching for the wrong terms.)
I would like to create a mask (eg [True False False True True]) based on whether each value is in some other list.
```
a=np.array([11,12,13,14,15,16,17])
mask= a in [14,16,8] #(this doesnt work at all!)
... | Use [`numpy.in1d()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html#numpy.in1d):
```
In [6]: np.in1d(a, [14, 16, 18])
Out[6]: array([False, False, False, True, False, True, False], dtype=bool)
``` |
Celery: How to ignore task result in chord or chain? | 13,629,507 | 19 | 2012-11-29T15:51:06Z | 13,788,495 | 29 | 2012-12-09T14:51:37Z | [
"python",
"asynchronous",
"task",
"celery"
] | I'm using celery, I have several tasks which needed to be executed in order.
For example I have this task:
```
@celery.task
def tprint(word):
print word
```
And I want to do something like this:
```
>>> chain(tprint.s('a') | tprint.s('b'))()
```
Then I get `TypeError: tprint() takes exactly 1 argument (2 given... | There is a built-in functionality to ignore result in chaining and others - immutable subtask. You can use .si() shortcut instead of .s() or .subtask(immutable=True)
More details here: <http://docs.celeryproject.org/en/master/userguide/canvas.html#immutability> |
new pythonic style for shared axes square subplots in matplotlib? | 13,629,994 | 13 | 2012-11-29T16:15:17Z | 13,663,328 | 15 | 2012-12-01T20:16:11Z | [
"python",
"numpy",
"matplotlib",
"scipy"
] | Related to: [plotting autoscaled subplots with fixed limits in matplotlib](http://stackoverflow.com/questions/13612610/plotting-autoscaled-subplots-with-fixed-limits-in-matplotlib)
I would like to make a set of subplots that are all on the same scale, using the `subplots` new compact style, as in <http://matplotlib.or... | Just use `adjustable='box-forced'` instead of `adjustable='box'`.
As @cronos mentions, you can pass it in using the `subplot_kw` kwarg (additional keyword arguments to `subplots` are passed on to the `Figure` not the `Axes`, thus the need for `subplot_kw`).
Instead, I'm going to use `setp`, which basically just does ... |
Contents of locmem cache in django? | 13,630,237 | 7 | 2012-11-29T16:28:18Z | 13,630,516 | 12 | 2012-11-29T16:42:48Z | [
"python",
"django",
"caching"
] | I was trying to use locmem cache for my web application but couldn't find any concrete documentation on how can i get the contents of the cache. I mean I want to check if my keys are being set correctly in the cache. How can I list all the keys in this cache or is that even possible?
[Get list of Cache Keys in Django]... | The thing about locmem is that it really is just a local memory storage. Looking at [the code](https://github.com/django/django/blob/master/django/core/cache/backends/locmem.py), it's clear that the data is just being saved in a module-level variable, `_caches`, in that module. So you can just do
```
from django.core.... |
how to (simply) build a integer and float mixed numpy array | 13,630,295 | 4 | 2012-11-29T16:31:00Z | 13,630,806 | 10 | 2012-11-29T16:57:45Z | [
"python",
"multidimensional-array",
"numpy"
] | I would simply like to create a numpy array of size(N,m) that has just the first column made of integer, and the rest by default float.
So that, if initialized to zero it should be results:
```
array([[ 0, 0., 0., 0., 0.],
[ 0, 0., 0., 0., 0.],
[ 0, 0., 0., 0., 0.],
[ 0, 0., 0., 0.,... | You could use an array with `dtype = object`:
```
>>> arr = np.ndarray((10,4),dtype = object)
>>> arr[:,0] = int(10)
>>> arr[:,1:] = float(10)
>>> arr
array([[10, 10.0, 10.0, 10.0],
[10, 10.0, 10.0, 10.0],
[10, 10.0, 10.0, 10.0],
[10, 10.0, 10.0, 10.0],
[10, 10.0, 10.0, 10.0],
[10, 1... |
When does Django look up the primary key of foreign keys? | 13,631,211 | 21 | 2012-11-29T17:19:45Z | 13,632,341 | 10 | 2012-11-29T18:30:56Z | [
"python",
"django",
"django-orm"
] | I have two simple models, one representing a movie an the other representing a rating for a movie.
```
class Movie(models.Model):
id = models.AutoField(primary_key=True)
title = models.TextField()
class Rating(models.Model):
id = models.AutoField(primary_key=True)
movie = models.ForeignKey(Movie)
... | As stated by the docs:
> The keyword arguments are simply the names of the fields youâve
> defined on your model. Note that instantiating a model in no way
> touches your database; for that, you need to save().
Add a classmethod on the model class:
```
class Book(models.Model):
title = models.CharField(max_len... |
When does Django look up the primary key of foreign keys? | 13,631,211 | 21 | 2012-11-29T17:19:45Z | 13,701,646 | 10 | 2012-12-04T11:15:30Z | [
"python",
"django",
"django-orm"
] | I have two simple models, one representing a movie an the other representing a rating for a movie.
```
class Movie(models.Model):
id = models.AutoField(primary_key=True)
title = models.TextField()
class Rating(models.Model):
id = models.AutoField(primary_key=True)
movie = models.ForeignKey(Movie)
... | The main issue has to do with side effects that are wanted or not. And with variables really being pointers to objects in Python.
When you create an object out of a model, it doesn't have a primary key yet as you haven't saved it yet. But, when saving it, should Django have to make sure it updates attributes on the al... |
When does Django look up the primary key of foreign keys? | 13,631,211 | 21 | 2012-11-29T17:19:45Z | 13,800,717 | 9 | 2012-12-10T12:13:21Z | [
"python",
"django",
"django-orm"
] | I have two simple models, one representing a movie an the other representing a rating for a movie.
```
class Movie(models.Model):
id = models.AutoField(primary_key=True)
title = models.TextField()
class Rating(models.Model):
id = models.AutoField(primary_key=True)
movie = models.ForeignKey(Movie)
... | Looking in the [Django source](https://github.com/django/django/blob/1.4/django/db/models/fields/related.py#L287), the answer lies in some of the magic Django uses to provide its nice API.
When you instantiate a `Rating` object, Django sets (though with some more indirection to make this generic) `self.movie` to `the_... |
How to change attributes of a networkx / matplotlib graph drawing? | 13,631,553 | 6 | 2012-11-29T17:41:37Z | 13,631,815 | 9 | 2012-11-29T17:57:43Z | [
"python",
"matplotlib",
"networkx",
"ipython-notebook"
] | NetworkX includes [functions](http://networkx.lanl.gov/reference/drawing.html) for drawing a graph using [matplotlib](http://matplotlib.org/). This is an example using the great IPython Notebook (started with `ipython3 notebook --pylab inline`):

Nice... | IPython is a great tool for finding out what functions (and objects) can do. If you type
```
[1]: import networkx as nx
[2]: nx.draw?
```
you see
> Definition: nx.draw(G, pos=None, ax=None, hold=None, \*\*kwds)
>
> ```
> **kwds: optional keywords
> See networkx.draw_networkx() for a description of optional keywor... |
Python list comprehension: test function return | 13,632,280 | 5 | 2012-11-29T18:27:00Z | 13,632,308 | 10 | 2012-11-29T18:28:52Z | [
"python",
"list-comprehension"
] | Is there a way to test the return of a function in a list (or dict) comprehension? I'd like to avoid writing that:
```
lst = []
for x in range(10):
bar = foo(x)
if bar:
lst.append(bar)
```
and use a list comprehension instead. Obviously, I don't want to write:
```
[foo(x) for x in range(10) if foo(x)]
```
s... | How about
```
filter(None, map(foo, range(10)))
```
If you don't want to keep the intermediate list, replace `map()` with [`itertools.imap()`](http://docs.python.org/2/library/itertools.html#itertools.imap). And with [`itertools.ifilter()`](http://docs.python.org/2/library/itertools.html#itertools.ifilter), the whole... |
How do you pass arguments from one function to another? | 13,632,347 | 5 | 2012-11-29T18:31:31Z | 13,632,367 | 7 | 2012-11-29T18:32:48Z | [
"python"
] | Sorry for the newbie question guys, but I'm relatively new to python. I want to write a function that passes keyword and value arguments into another function:
e.g.
```
def function_that_passes_arguments(arguments):
some_other_function(arguments)
```
so when I call the first function they are passed into the sec... | Accept `*args, **kwargs` and pass those to the called function:
```
def function_that_passes_arguments(*args, **kwargs):
some_other_function(*args, **kwargs)
```
In both places you can also use regular arguments - the only requirement is that the `*` and `**` arguments are the last ones. |
Emacs python autocompletion | 13,632,415 | 4 | 2012-11-29T18:35:53Z | 13,660,345 | 10 | 2012-12-01T14:23:58Z | [
"python",
"emacs"
] | I've installed python-mode, pymacs and pycomplete+ from el-get on emacs24. But i am not able to get auto-completion for python in emacs. | I'd recommend you to try [emacs-jedi](https://github.com/tkf/emacs-jedi). The author is really trying to bring the best Python autocompletion experience to Emacs. (It uses the [Jedi](https://github.com/davidhalter/jedi) autocompletion library). |
Plot 2-dimensional NumPy array using specific columns | 13,634,349 | 8 | 2012-11-29T20:41:04Z | 13,634,612 | 14 | 2012-11-29T20:59:40Z | [
"python",
"numpy",
"matplotlib"
] | I have a 2D numpy array that's created like this:
```
data = np.empty((number_of_elements, 7))
```
Each row with 7 (or whatever) floats represents an object's properties. The first two for example are the `x` and `y` position of the object, the others are various properties that could even be used to apply color info... | Setting up a basic matplotlib figure is easy:
```
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
```
Picking off the columns for `x`, `y` and `color` might look something like this:
```
N = 100
data = np.random.random((N, 7))
x = data[:,0]
y = data[:,1]
points = d... |
Is using Python `isinstance` ever right? | 13,636,149 | 6 | 2012-11-29T22:45:19Z | 13,636,295 | 7 | 2012-11-29T22:55:42Z | [
"python",
"oop",
"dynamic",
"instance"
] | I've got a 2D array of different blocks, all inheriting from Block. I want to check if the block that I clicked on is a Dirt type block, like this:
```
clickedblock = getClickedBlock()
if isinstance(clickedblock, Dirt):
place a block
else:
don't place a block
```
I've heard that `isinstance` is bad, and sho... | Your example seems like a legitimate use case of `isinstance()`.
It's not that `isinstance()` is bad, often polymorphism can be used for the same purpose (which results in cleaner code in where the class is used).
But sometimes, `isinstance()` is what you need. For example, the pythonic way of detecting whether a var... |
How to sort a Pandas DataFrame according to multiple criteria? | 13,636,592 | 21 | 2012-11-29T23:20:44Z | 13,866,073 | 25 | 2012-12-13T18:24:51Z | [
"python",
"pandas"
] | I have the following DataFrame containing song names, their peak chart positions and the number of weeks they spent at position no 1:
```
Song Peak Weeks
76 Paperback Writer 1 16
117 ... | On pandas 0.9.1 and higher this should work (this is with 0.10.0b1):
```
In [23]: songs.sort_index(by=['Peak', 'Weeks'], ascending=[True, False])
Out[23]:
Song Peak Weeks
10 She Loves You 1 36
118 Hey Jude 1 ... |
How to sort a Pandas DataFrame according to multiple criteria? | 13,636,592 | 21 | 2012-11-29T23:20:44Z | 19,473,752 | 16 | 2013-10-20T03:52:08Z | [
"python",
"pandas"
] | I have the following DataFrame containing song names, their peak chart positions and the number of weeks they spent at position no 1:
```
Song Peak Weeks
76 Paperback Writer 1 16
117 ... | ```
df.sort(['Peak', 'Weeks'], ascending=[True, False], inplace=True)
```
If you want the sorted result for future use, `inplace=True` is required. |
How to sort a Pandas DataFrame according to multiple criteria? | 13,636,592 | 21 | 2012-11-29T23:20:44Z | 35,768,306 | 10 | 2016-03-03T09:38:20Z | [
"python",
"pandas"
] | I have the following DataFrame containing song names, their peak chart positions and the number of weeks they spent at position no 1:
```
Song Peak Weeks
76 Paperback Writer 1 16
117 ... | Since pandas 0.17.0, [`sort`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort.html) is deprecated and replaced by [`sort_values`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html):
```
df.sort_values(['Peak', 'Weeks'], ascending=[True, False], inplace=... |
python - checking odd/even numbers and changing outputs on number size | 13,636,640 | 24 | 2012-11-29T23:24:37Z | 13,636,743 | 42 | 2012-11-29T23:32:28Z | [
"python",
"numbers"
] | I have a couple of problems to solve for an assignment, and am a bit stuck.
The question is to write a program that gets the user to input an odd number (check it's odd), then print an upside down pyramid of stars based on the size of the input.
For example, if you enter 5, it comes up with
```
*****
***
*
```
My... | Giving you the complete answer would have no point at all since this is homework, so here are a few pointers :
**Even or Odd**:
```
number % 2 == 0
```
definitely is a very good way to find whether your number is even.
In case you do not know `%`, this does modulo which is here the remainder of the division of `num... |
Invalid group reference in python 2.7+ | 13,636,733 | 3 | 2012-11-29T23:31:47Z | 13,636,766 | 13 | 2012-11-29T23:34:00Z | [
"python",
"regex",
"django"
] | I am trying to convert all WikiLink type of strings in my webpage(created in django) to html links.
I am using the following expression
```
import re
expr = r'\s+[A-Z][a-z]+[A-Z][a-z]+\s'
repl=r'<a href="/photos/\1">\1</a>'
mystr = 'this is a string to Test whether WikiLink will work ProPerly'
parser=re.compile(expr... | The problem here is that you don't have any captured groups in the `expr`.
Whatever part of the match you want to show up as `\1`, you need to put in parentheses. For example:
```
>>> expr = r'\s+([A-Z][a-z]+[A-Z][a-z]+)\s'
>>> parser=re.compile(expr)
>>> parser.sub(repl, mystr)
'this is a string to Test whether<a hr... |
is it possible to do fuzzy match merge with python pandas? | 13,636,848 | 15 | 2012-11-29T23:44:17Z | 13,680,953 | 23 | 2012-12-03T10:06:04Z | [
"python",
"pandas"
] | I have two DataFrames which I want to merge based on a column. However, due to alternate spellings, different number of spaces, absence/presence of diacritical marks, I would like to be able to merge as long as they are similar to one another.
Any similarity algorithm will do (soundex, Levenshtein, difflib's).
Say on... | Similar to @locojay suggestion, you can apply [`difflib`](http://docs.python.org/2/library/difflib.html)'s [`get_closest_matches`](http://docs.python.org/2/library/difflib.html#difflib.get_close_matches) to `df2`'s index and then apply a [`join`](http://pandas.pydata.org/pandas-docs/dev/merging.html#joining-on-index):
... |
Why do I get ValueError : math domain error? | 13,637,400 | 4 | 2012-11-30T00:48:21Z | 13,637,532 | 7 | 2012-11-30T01:05:28Z | [
"python"
] | I wrote a function named `analyze_the_shape` that takes a list of 2D vertices such that the list is in the order of a clockwise traversal of the vertices in the 2D Euclidean space.
I call it in the interpreter and give `[(0, 0), (0, 4.0), (4.0, 4.0), (4.0, 0)]` as input but I get `ValueError : math domain error`. I ex... | This exception means that `cos_angle` is not a valid parameter for `math.acos`.
Specifically, in this example, it is just below -1, which is out of `acos` definition.
You could probably try to force your returned `cos_angle` within `[-1,1]` with something like :
```
def clean_cos(cos_angle):
return min(1,max(cos... |
How to use filter, map, and reduce in Python 3 | 13,638,898 | 101 | 2012-11-30T04:12:53Z | 13,638,931 | 31 | 2012-11-30T04:17:44Z | [
"python",
"python-3.x"
] | `filter`, `map`, and `reduce` work perfectly in Python 2. Here is an example:
```
>>> def f(x):
return x % 2 != 0 and x % 3 != 0
>>> filter(f, range(2, 25))
[5, 7, 11, 13, 17, 19, 23]
>>> def cube(x):
return x*x*x
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>> def add(x... | The functionality of `map` and `filter` was intentionally changed to return iterators, and reduce was removed from being a built-in and placed in `functools.reduce`.
So, for `filter` and `map`, you can wrap them with `list()` to see the results like you did before.
```
>>> def f(x): return x % 2 != 0 and x % 3 != 0
.... |
How to use filter, map, and reduce in Python 3 | 13,638,898 | 101 | 2012-11-30T04:12:53Z | 13,638,960 | 115 | 2012-11-30T04:22:03Z | [
"python",
"python-3.x"
] | `filter`, `map`, and `reduce` work perfectly in Python 2. Here is an example:
```
>>> def f(x):
return x % 2 != 0 and x % 3 != 0
>>> filter(f, range(2, 25))
[5, 7, 11, 13, 17, 19, 23]
>>> def cube(x):
return x*x*x
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>> def add(x... | You can read about the changes in [What's New In Python 3.0](http://docs.python.org/3.0/whatsnew/3.0.html). You should read it thoroughly when you move from 2.x to 3.x since a lot has been changed.
The whole answer here are quotes from the documentation.
**[Views And Iterators Instead Of Lists](http://docs.python.org... |
Javascript equivalent to python's .format() | 13,639,464 | 4 | 2012-11-30T05:18:53Z | 13,639,670 | 8 | 2012-11-30T05:37:42Z | [
"javascript",
"python",
"string",
"formatting",
"string-formatting"
] | I would like a javascript function that mimics the python .format() function that works like
```
.format(*args, **kwargs)
```
A previous question gives a possible (but not complete) solution for '.format(\*args)
[JavaScript equivalent to printf/string.format](http://stackoverflow.com/questions/610406/javascript-equi... | Ok, here's what I got for you so far..... based on [JavaScript equivalent to printf/string.format](http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format)
I got the last 3 examples working. Only the first one with no keys isn't working yet.
EDIT: Ok, all done... works for all your cas... |
SQLAlchemy - Writing a hybrid method for child count | 13,640,298 | 11 | 2012-11-30T06:44:58Z | 13,642,708 | 13 | 2012-11-30T09:52:32Z | [
"python",
"sqlalchemy",
"flask"
] | I'm using Flask-SQLAlchemy, and I'm trying to write a [hybrid method](http://docs.sqlalchemy.org/en/rel_0_7/orm/extensions/hybrid.html) in a parent model that returns the number of children it has, so I can use it for filtering, sorting, etc. Here's some stripped down code of what I'm trying:
```
# parent.py
from prog... | The code below shows it all.
```
class Parent(Base):
__tablename__ = 'parents'
# ...
@hybrid_property
def child_count(self):
#return len(self.children) # @note: use when non-dynamic relationship
return self.children.count()# @note: use when dynamic relationship
@child_count.expr... |
How and where does py.test find fixtures | 13,641,973 | 14 | 2012-11-30T09:05:52Z | 13,643,170 | 12 | 2012-11-30T10:17:24Z | [
"python",
"fixtures",
"py.test"
] | Where and how does py.test look for fixtures? I have the same code in 2 files in the same folder. When I delete conftest.py, cmdopt cannot be found running test\_conf.py (also in same folder. Why is sonoftest.py not searched?
```
# content of test_sample.py
def test_answer(cmdopt):
if cmdopt == "type1":
pr... | py.test will import `conftest.py` and all Python files that match the `python_files` pattern, by default `test_*.py`. If you have a test fixture, you need to include or import it from `conftest.py` or from the test files that depend on it:
```
from sonoftest import pytest_addoption, cmdopt
``` |
How and where does py.test find fixtures | 13,641,973 | 14 | 2012-11-30T09:05:52Z | 13,686,206 | 11 | 2012-12-03T15:19:40Z | [
"python",
"fixtures",
"py.test"
] | Where and how does py.test look for fixtures? I have the same code in 2 files in the same folder. When I delete conftest.py, cmdopt cannot be found running test\_conf.py (also in same folder. Why is sonoftest.py not searched?
```
# content of test_sample.py
def test_answer(cmdopt):
if cmdopt == "type1":
pr... | Here is the order and where py.test looks for fixtures (and tests) (taken from [here](http://pytest.org/latest/plugins.html#plugin-discovery-order-at-tool-startup)):
py.test loads plugin modules at tool startup in the following way:
> 1. by loading all builtin plugins
> 2. by loading all plugins registered through se... |
How to export figures to files from IPython Notebook | 13,642,528 | 22 | 2012-11-30T09:42:04Z | 13,642,865 | 23 | 2012-11-30T10:00:53Z | [
"python",
"matplotlib",
"ipython-notebook"
] | I use the IPython Notebook with the `--pylab inline` option, since I don't want plots to show up in a different window. Now I'd like to save the plots I see in the notebook to PDF or PNG files.
Some code examples use
```
import matplotlib as plt
plt.savefig("figure.png") # save as png
```
but this does not seem to ... | try this (note that the files get saved to the default notebook folder):
```
plot(range(80))
xlabel('foo')
ylabel('bar')
legend(['myline'])
axis([0, 80, 0, 120])
savefig('sample.pdf')
```
if you want `png` just change it to `'sample.png'`.
Note that the `savefig()` call should be in the *same notebook cell* as the p... |
Linear regression of arrays containing NANs in Python/Numpy | 13,643,363 | 5 | 2012-11-30T10:29:09Z | 13,643,460 | 11 | 2012-11-30T10:34:27Z | [
"python",
"math",
"numpy",
"scipy"
] | I have two arrays, say varx and vary. Both contain NAN values at various positions. However, I would like to do a linear regression on both to show how much the two arrays correlate.
This was very helpful so far: <http://glowingpython.blogspot.de/2012/03/linear-regression-with-numpy.html>
However, using this:
```
slo... | You can remove NaNs using a mask:
```
mask = ~np.isnan(varx) & ~np.isnan(vary)
slope, intercept, r_value, p_value, std_err = stats.linregress(varx[mask], vary[mask])
``` |
Libssl and libcrypto causing dyld: Library not loaded: /usr/lib/libpq.5.dylib | 13,643,452 | 5 | 2012-11-30T10:33:52Z | 13,652,361 | 12 | 2012-11-30T20:05:38Z | [
"python",
"postgresql",
"pip",
"psycopg2",
"libssl"
] | I recently uninstalled postgresql and installed pyscopg2 via pip.
I know there's some trickery involved with libcrypto and libssl
Currently i have them symlinked to:
```
$ ls -lah libssl.*
-rwxr-xr-x 1 root wheel 402K Aug 28 11:06 libssl.0.9.7.dylib
-rwxr-xr-x 1 root wheel 589K Aug 28 11:06 libssl.0.9.8.dyli... | Turns out /usr/lib/libpq.5.dylib was absent but /usr/lib/libpq.5.4.dylib was not.
```
sudo ln -s /usr/lib/libpq.5.4.dylib /usr/lib/libpq.5.dylib
```
fixed the issue. |
Is it possible to make abstract classes in python? | 13,646,245 | 83 | 2012-11-30T13:29:16Z | 13,646,263 | 169 | 2012-11-30T13:30:44Z | [
"python",
"class",
"inheritance",
"abstract-class",
"abstract"
] | How can I make a class or method abstract in Python?
I tried redefining `__new__()` like so:
```
class F:
def __new__(cls):
raise Exception("Unable to create an instance of abstract class %s" %cls)
```
but now if I create a class `G` that inherits from `F` like so:
```
class G(F):
pass
```
then I c... | Use the [`abc`](http://docs.python.org/library/abc.html) module to create abstract classes. Use the [`abstractmethod`](https://docs.python.org/library/abc.html#abc.abstractmethod) decorator to declare a method abstract, and declare a class abstract using one of three ways, depending upon your Python version.
In Python... |
Is it possible to make abstract classes in python? | 13,646,245 | 83 | 2012-11-30T13:29:16Z | 25,300,153 | 35 | 2014-08-14T04:33:19Z | [
"python",
"class",
"inheritance",
"abstract-class",
"abstract"
] | How can I make a class or method abstract in Python?
I tried redefining `__new__()` like so:
```
class F:
def __new__(cls):
raise Exception("Unable to create an instance of abstract class %s" %cls)
```
but now if I create a class `G` that inherits from `F` like so:
```
class G(F):
pass
```
then I c... | The old-school (pre-[PEP 3119](http://www.python.org/dev/peps/pep-3119/)) way to do this is just to `raise NotImplementedError` in the abstract class when an abstract method is called.
```
class Abstract(object):
def foo(self):
raise NotImplementedError('subclasses must override foo()!')
class Derived(Abs... |
python: iterator from a function | 13,646,918 | 12 | 2012-11-30T14:15:29Z | 13,646,967 | 17 | 2012-11-30T14:19:27Z | [
"python"
] | What is an [idiomatic](http://stackoverflow.com/questions/302459/what-is-a-programming-idiom) way to create an infinite iterator from a function? For example
```
from itertools import islice
import random
rand_characters = to_iterator( random.randint(0,256) )
print ' '.join( islice( rand_characters, 100))
```
would p... | You want an iterator which continuously yields values until you stop asking it for new ones? Simply use
```
it = iter(function, sentinel)
```
which calls `function()` for each iteration step until the result `== sentinel`.
So choose a sentinel which can never be returned by your wanted function, such as `None`, in y... |
python: iterator from a function | 13,646,918 | 12 | 2012-11-30T14:15:29Z | 13,647,233 | 8 | 2012-11-30T14:34:38Z | [
"python"
] | What is an [idiomatic](http://stackoverflow.com/questions/302459/what-is-a-programming-idiom) way to create an infinite iterator from a function? For example
```
from itertools import islice
import random
rand_characters = to_iterator( random.randint(0,256) )
print ' '.join( islice( rand_characters, 100))
```
would p... | Every time I see `iter` with 2 arguments, I need to scratch my head an look up the documentation to figure out exactly what is going on. Simply because of that, I would probably roll my own:
```
def call_forever(callback):
while True:
yield callback()
```
---
Or, as stated in the comments by Jon Clements... |
Calculating Pearson correlation | 13,648,318 | 4 | 2012-11-30T15:37:50Z | 13,648,814 | 10 | 2012-11-30T16:09:54Z | [
"python",
"numpy",
"statistics",
"scipy"
] | I'm trying to calculate the Pearson correlation coefficient of two variables. These variables are to determine if there is a relationship between number of postal codes to a range of distances. So I want to see if the number of postal codes increases/decreases as the distance ranges changes.
I'll have one list which w... | Use scipy :
```
scipy.stats.pearsonr(x, y)
```
> Calculates a Pearson correlation coefficient and the p-value for testing non-correlation.
>
> The Pearson correlation coefficient measures the linear relationship between two datasets. Strictly speaking, Pearsonâs correlation requires that each dataset be normally di... |
Get year, month or day from numpy datetime64 | 13,648,774 | 21 | 2012-11-30T16:07:16Z | 13,652,262 | 20 | 2012-11-30T19:59:02Z | [
"python",
"datetime",
"numpy"
] | I have an array of datetime64 type:
```
dates = np.datetime64(['2010-10-17', '2011-05-13', "2012-01-15"])
```
Is there a better way than looping through each element just to get np.array of years:
```
years = f(dates)
#output:
array([2010, 2011, 2012], dtype=int8) #or dtype = string
```
I'm using stable numpy versi... | As datetime is not stable in numpy I would use pandas for this:
```
In [52]: import pandas as pd
In [53]: dates = pd.DatetimeIndex(['2010-10-17', '2011-05-13', "2012-01-15"])
In [54]: dates.year
Out[54]: array([2010, 2011, 2012], dtype=int32)
```
Pandas uses numpy datetime internally, but seems to avoid the shortag... |
Get year, month or day from numpy datetime64 | 13,648,774 | 21 | 2012-11-30T16:07:16Z | 26,895,491 | 7 | 2014-11-12T19:58:59Z | [
"python",
"datetime",
"numpy"
] | I have an array of datetime64 type:
```
dates = np.datetime64(['2010-10-17', '2011-05-13', "2012-01-15"])
```
Is there a better way than looping through each element just to get np.array of years:
```
years = f(dates)
#output:
array([2010, 2011, 2012], dtype=int8) #or dtype = string
```
I'm using stable numpy versi... | I find the following tricks give between 2x and 4x speed increase versus the pandas method described above (i.e. `pd.DatetimeIndex(dates).year` etc.). The speed of `[dt.year for dt in dates.astype(object)]` I find to be similar to the pandas method. Also these tricks can be applied directly to ndarrays of any shape (2D... |
What is the pythonic way to count the leading spaces in a string? | 13,648,813 | 17 | 2012-11-30T16:09:52Z | 13,648,932 | 11 | 2012-11-30T16:16:29Z | [
"python"
] | I know I can count the leading spaces in a string with this:
```
>>> a = " foo bar baz qua \n"
>>> print "Leading spaces", len(a) - len(a.lstrip())
Leading spaces 3
>>>
```
But is there a more pythonic way? | You could use `itertools.takewhile`
```
sum( 1 for _ in itertools.takewhile(str.isspace,a) )
```
And demonstrating that it gives the same result as your code:
```
>>> import itertools
>>> a = " leading spaces"
>>> print sum( 1 for _ in itertools.takewhile(str.isspace,a) )
4
>>> print "Leading spaces", len(a) - le... |
What is the pythonic way to count the leading spaces in a string? | 13,648,813 | 17 | 2012-11-30T16:09:52Z | 13,649,013 | 29 | 2012-11-30T16:21:13Z | [
"python"
] | I know I can count the leading spaces in a string with this:
```
>>> a = " foo bar baz qua \n"
>>> print "Leading spaces", len(a) - len(a.lstrip())
Leading spaces 3
>>>
```
But is there a more pythonic way? | Your way is pythonic but incorrect, it will also count other whitespace chars, to count only spaces be explicit `a.lstrip(' ')`:
```
a = " \r\t\n\tfoo bar baz qua \n"
print "Leading spaces", len(a) - len(a.lstrip())
>>> Leading spaces 7
print "Leading spaces", len(a) - len(a.lstrip(' '))
>>> Leading spaces 3
``` |
How to use logging with python's fileConfig and configure the logfile filename | 13,649,664 | 11 | 2012-11-30T17:00:53Z | 20,243,458 | 22 | 2013-11-27T13:11:38Z | [
"python",
"file",
"logging",
"console"
] | I have a logging configuration file for logging to console and a file with different formats and levels. In my python script I can load this configuration and basically console and file output are ok.
I set the file name in the config file as shown below.
Is it possible to set that file name in the python script itse... | Change your `handler_fileHandler` section like so:
```
[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=fileFormatter
args=('%(logfilename)s',)
```
and then add a `defaults` argument to the fileConfig call
```
logging.fileConfig(loginipath, defaults={'logfilename': '/var/log/mylog.log'})
``` |
Understanding Python's "is" operator | 13,650,293 | 32 | 2012-11-30T17:39:14Z | 13,650,309 | 65 | 2012-11-30T17:40:23Z | [
"python",
"python-3.x",
"operators"
] | > The `is` operator does not match the values of the variables, but the
> instances themselves.
What does it really mean?
I declared two variables named `x` and `y` assigning the same values in both variables, but it returns false when I use the `is` operator.
I need a clarification. Here is my code.
```
x = [1, 2,... | You misunderstood what the `is` operator tests. It tests if two variables point the *same object*, not if two variables have the same value.
From the documentation for the [`is` operator](http://docs.python.org/2/reference/expressions.html#not-in):
> The operators `is` and `is not` test for object identity: `x is y` ... |
Understanding Python's "is" operator | 13,650,293 | 32 | 2012-11-30T17:39:14Z | 25,758,019 | 8 | 2014-09-10T05:38:57Z | [
"python",
"python-3.x",
"operators"
] | > The `is` operator does not match the values of the variables, but the
> instances themselves.
What does it really mean?
I declared two variables named `x` and `y` assigning the same values in both variables, but it returns false when I use the `is` operator.
I need a clarification. Here is my code.
```
x = [1, 2,... | [Another duplicate](http://stackoverflow.com/questions/25757465/why-does-a-bc-result-in-a-different-non-is-string-from-abc) was asking why two equal strings are generally not identical, which isn't really answered here:
```
>>> x = 'a'
>>> x += 'bc'
>>> y = 'abc'
>>> x == y
True
>>> x is y
False
```
So, why aren't t... |
User input variables in cx_Oracle? | 13,650,632 | 3 | 2012-11-30T18:01:22Z | 13,651,314 | 7 | 2012-11-30T18:53:39Z | [
"python",
"oracle",
"cx-oracle"
] | I'm using cx\_Oracle to access our database. I would like the user to be able to input the station ID, for example:
stationID=(whatever the user inputs upon prompting)
```
cursor.execute('''select cruise, station, stratum
from union_fscs_svsta
where station=stationID
order by cruise''')
... | How *not* to do it:
```
id = raw_input("Enter the Station ID")
query = "select foo from bar where station={station_id}"
cursor.execute(query.format(station_id=id))
```
If someone enters a malicious sql string, it will be executed.
Instead of using python to format the string, let the database backend handle it for y... |
Exception in Thread:must be a sequence, not instance | 13,653,669 | 19 | 2012-11-30T21:47:41Z | 13,653,866 | 30 | 2012-11-30T22:05:14Z | [
"python",
"multithreading",
"ipc"
] | Im working on python and im trying to execute a thread that takes 1 parameter "q", but when im trying to execute it a strange exception occurs, here's my code:
```
class Workspace(QMainWindow, Ui_MainWindow):
""" This class is for managing the whole GUI `Workspace'.
Currently a Workspace is similar to a Ma... | The `args` parameter to `threading.Thread` should be a tuple and you are passing `(q)` which is not - it is the same as `q`.
I guess you wanted a 1-element tuple: you should would write `(q,)`. |
How to catch an exception in the for loop iterator | 13,653,783 | 11 | 2012-11-30T21:57:35Z | 13,654,229 | 17 | 2012-11-30T22:41:14Z | [
"python",
"exception"
] | This is a `for` loop in Python:
```
for_stmt ::= "for" target_list "in" expression_list ":" suite
```
Normally, when yielding a value from the `expression_list` raises an exception, the loop aborts. Is there an elegant way (short of rewriting the loop using `while True` or something similar) to catch this exception ... | If your inner iterable can be continued after an exception, all you need to wrap it is a trivial generator:
```
def wrapper(gen):
while True:
try:
yield next(gen)
except StopIteration:
raise
except Exception as e:
print(e) # or whatever kind of logging you want
pass
```
For examp... |
TypeError: Can't convert 'int' object to str implicitly | 13,654,168 | 22 | 2012-11-30T22:34:05Z | 13,654,181 | 52 | 2012-11-30T22:36:25Z | [
"python",
"string",
"int",
"implicit"
] | I am trying to write a text game and I have run into an error in the function I am defining that lets you basically spend your skill points after you make your character. At first, the error stated that I was attempting to subtract a string from an integer in this part of the code:`balance - strength`. Obviously that w... | You cannot concatenate a string with an int. You would need to convert your `int` to `string` using `str` function, or use `formatting` to format your output.
Change: -
```
print("Ok. Your balance is now at " + balanceAfterStrength + " skill points.")
```
to: -
```
print("Ok. Your balance is now at {} skill points.... |
List comprehension throws exception when list is empty | 13,654,413 | 3 | 2012-11-30T22:59:56Z | 13,654,490 | 7 | 2012-11-30T23:06:52Z | [
"python",
"list",
"list-comprehension"
] | I have a function that filters list items if their date is in the past (smaller than current date).
```
meetings = []
def clean_old():
meetings = [meeting for meeting in meetings if time.mktime(meeting) >= time.localtime()]
```
When the list is empty, this code crashes.
Why does it crash? It says `for meeting in... | I assume that you are seeing this exception:
```
UnboundLocalError: local variable 'meetings' referenced before assignment
```
What you're experiencing here doesn't actually have anything to do with list comprehensions. This error occurs because you initially defined `meetings` outside of your function, but you are t... |
Error: Segmentation fault (core dumped) | 13,654,449 | 15 | 2012-11-30T23:03:26Z | 13,654,489 | 33 | 2012-11-30T23:06:51Z | [
"python"
] | Im new in python and am getting a strange error:
```
Segmentation fault (core dumped)
```
When i execute the following code:
```
class Workspace(QMainWindow, Ui_MainWindow):
""" This class is for managing the whole GUI `Workspace'.
Currently a Workspace is similar to a MainWindow
"""
def __ini... | `"Segmentation fault (core dumped)"` is the string that linux prints when a program exists with a `SIGSEGV` signal and you have core creation enabled. This means *some* program has crashed.
If you're actually getting this error from running Python, this means the Python interpreter has crashed. There are only a few re... |
Error: Segmentation fault (core dumped) | 13,654,449 | 15 | 2012-11-30T23:03:26Z | 31,048,386 | 17 | 2015-06-25T10:56:37Z | [
"python"
] | Im new in python and am getting a strange error:
```
Segmentation fault (core dumped)
```
When i execute the following code:
```
class Workspace(QMainWindow, Ui_MainWindow):
""" This class is for managing the whole GUI `Workspace'.
Currently a Workspace is similar to a MainWindow
"""
def __ini... | There is one more reason for such failure which I came to know when mine failed
* You might be working with a lot of data and your RAM is full
This might not apply in this case but it also throws the same error |
How to use scrypt to generate hash for password and salt in Python | 13,654,492 | 8 | 2012-11-30T23:06:56Z | 13,663,335 | 8 | 2012-12-01T20:17:21Z | [
"python",
"password-encryption",
"scrypt"
] | I would like to use scrypt to create a hash for my users' passwords and salts. I have found [two](http://aleccolocco.blogspot.com/2011/09/how-to-protect-passwords-with-python.html) [references](http://kevinryan.me/using-scrypt-in-python-and-postgresql/), but there are things I don't understand about them.
They use the... | You're correct - the scrypt functions those two links are playing with are the scrypt file encryption utility, not the underlying kdf. I've been slowly working on creating a standalone scrypt-based password hash for python, and ran into this issue myself.
The scrypt file utility does the following: picks scrypt's n/r/... |
What is the correct way to leave gunicorn running? | 13,654,688 | 6 | 2012-11-30T23:33:27Z | 13,654,996 | 9 | 2012-12-01T00:09:01Z | [
"python",
"nginx",
"flask",
"gunicorn"
] | I want to make a Flask+Nginx+Gunicorn deployment. I have Nginx setup and running and I run gunicorn as described in the docs:
```
gunicorn app:app
```
But when I logout of the server the gunicorn process exits? What is the correct way to make sure it stay running for Nginx to connect to, and restarts if it crashes? | I'd look into something like [Supervisor](http://supervisord.org/). |
Reindexing pandas timeseries from object dtype to datetime dtype | 13,654,699 | 21 | 2012-11-30T23:35:15Z | 13,655,271 | 31 | 2012-12-01T00:51:12Z | [
"python",
"datetime",
"python-2.7",
"pandas"
] | I have a time-series that is not recognized as a DatetimeIndex despite being indexed by standard YYYY-MM-DD strings with valid dates. Coercing them to a valid DatetimeIndex seems to be inelegant enough to make me think I'm doing something wrong.
I read in (someone else's lazily formatted) data that contains invalid da... | You could use `pd.to_datetime`:
```
In [1]: import pandas as pd
In [2]: pd.to_datetime('2008-02-27')
Out[2]: datetime.datetime(2008, 2, 27, 0, 0)
```
This allows you to "clean" the index (or similarly a column) by applying it to the Series:
```
df.index = pd.to_datetime(df.index)
```
or
```
df['date_col'] = df['d... |
Is there a way to make collections.Counter (Python2.7) aware that its input list is sorted? | 13,655,169 | 9 | 2012-12-01T00:37:21Z | 13,655,225 | 7 | 2012-12-01T00:44:55Z | [
"python",
"performance",
"python-2.7",
"counter"
] | # The Problem
I've been playing around with different ways (in Python 2.7) to extract a list of (word, frequency) tuples from a corpus, or list of strings, and comparing their efficiency. As far as I can tell, in the normal case with an unsorted list, the `Counter`method from the `collections` module is superior to an... | Given a sorted list of words as you mention, have you tried the traditional Pythonic approach of `itertools.groupby`?
```
from itertools import groupby
some_data = ['a', 'a', 'b', 'c', 'c', 'c']
count = dict( (k, sum(1 for i in v)) for k, v in groupby(some_data) ) # or
count = {k:sum(1 for i in v) for k, v in groupby(... |
CORS errors with Flask and gevent | 13,655,301 | 6 | 2012-12-01T00:56:37Z | 13,813,574 | 7 | 2012-12-11T04:20:14Z | [
"javascript",
"python",
"flask",
"cors",
"gevent"
] | I have an API running, using Flask, Flask-SQLAlchemy, and Flask-Restless, and am trying to make POST/PUT/DELETE requests from javascript (backbone.js, to be precise). However, I keep running into CORS errors - everything except GET returns an HTTP OPTIONS 501 Not Implemented Error in the browser.
Initially, I tried ad... | There is a flask snippet [Decorator for the HTTP Access Control](http://flask.pocoo.org/snippets/56/), you can use @crossdomain(origin='\*') decorator. |
Python- insert a character into a string | 13,655,392 | 7 | 2012-12-01T01:11:44Z | 13,655,397 | 8 | 2012-12-01T01:14:36Z | [
"python",
"string"
] | I think this should be relatively simple, but I can't figure it out. I have a string that represents coordinates, `+27.5916+086.5640` and I need to put a comma in between the longitude and latitude so I get `+27.5916,+086.5640`.
I'm looking through the API but I can't seem to find something for this.
Oh and I have to... | If your coordinates are `c`, then this would work. Note, however, this will not work for negative values. Do you have to deal with negatives as well?
```
",+".join(c.rsplit("+", 1))
```
For dealing with negatives as well.
```
import re
parts = re.split("([\+\-])", c)
parts.insert(3, ',')
print "".join(parts[1:])
```... |
Can I make matplotlib sliders more discrete? | 13,656,387 | 8 | 2012-12-01T04:34:03Z | 13,661,005 | 17 | 2012-12-01T15:48:10Z | [
"python",
"matplotlib",
"slider"
] | I'm using matplotlib sliders, similar to [this demo](http://matplotlib.org/examples/widgets/slider_demo.html). The sliders currently use 2 decimal places and 'feel' quite continuous (though they have to be discrete on some level). Can I decide on what level they are discrete? Integer steps? 0.1-sized steps? 0.5? My goo... | If you just want integer values, just pass in an approriate `valfmt` when you create the slider (e.g. `valfmt='%0.0f'`)
However, if you want non-integer invervals, you'll need to manually set the text value each time. Even if you do this, though, the slider will still progress smoothly, and it won't "feel" like discre... |
pyicu failed to link icu4c on Mountain Lion | 13,656,756 | 2 | 2012-12-01T05:38:14Z | 13,666,383 | 9 | 2012-12-02T04:22:57Z | [
"python",
"pip",
"homebrew",
"dyld"
] | I use `brew install icu4c` with `pip install pyicu` to install python ICU support but in the end I cannot make in work on my Mountain Lion.
```
$ brew install icu4c
dyld: DYLD_ environment variables being ignored because main executable (/usr/bin/sudo) is setuid or setgid
==> Downloading http://download.icu-project.or... | Finally I made it work by downgrading the `icu4c` version to 4.8.1.1.
```
$ brew uninstall icu4c
$ pip uninstall pyicu
$ brew versions icu4c
4.8.1.1 git checkout 3f0fb81 /usr/local/Library/Formula/icu4c.rb
50.1 git checkout 03ed757 /usr/local/Library/Formula/icu4c.rb
49.1.2 git checkout c25fd2f /usr/local/Lib... |
How do I append new data to existing XML using Python ElementTree? | 13,657,341 | 4 | 2012-12-01T07:19:47Z | 13,657,728 | 8 | 2012-12-01T08:20:56Z | [
"python",
"elementtree"
] | I am new to Python/[ElementTree](http://docs.python.org/2/library/xml.etree.elementtree.html). I have the following XML sample:
```
<users>
<user username="admin" fullname="admin" password="" uid="1000"/>
<user username="user1" fullname="user1" password="" grant_admin_rights="yes"><group>my_group</group><grou... | In ElementTree, Element objects have an "append" method. By using this method you can directly add the new XML tag.
For example:
```
user = Element('user')
user.append((Element.fromstring('<user username="admin" fullname="admin" password="xx" uid="1000"/>')))
```
where "Element" comes from `from xml.etree.ElementTr... |
Simple Assignment Operator become Complicated in Python | 13,657,704 | 3 | 2012-12-01T08:16:58Z | 13,657,725 | 13 | 2012-12-01T08:20:05Z | [
"python",
"operators",
"variable-assignment"
] | I have declared four variables [a=1,b=2,c=3,d=0] in python and swapping them in one line code using ',' and '=' (Simple Assignment Operator).
I have got multiple Answers and got confused. please help me...
**Case 1:**
```
a=1
b=2
c=3
d=0
a=a,b=b,c
print "a = " + str(a)
print "b = " + str(b)
print "c = " + str(c)
pri... | tl;dr: multiple assignments (multiple `=` statements on one line) are evaluated from left-to-right, not from right-to-left (after evaluating the right-hand-side expression).
To complicate matters, you are using tuple assignment and 'normal' assignment in a heady mix.
Tuple assignment uses one assignment operator, so ... |
Where do I put my blueprint before_request | 13,657,711 | 7 | 2012-12-01T08:18:08Z | 18,465,265 | 11 | 2013-08-27T12:20:48Z | [
"python",
"flask"
] | So I have the before request routing for my user module. But now I want to access g.users from other blueprints as well. I found the only way to do it, is to copy the code below to every single blueprint.
I tried putting it in my app.py for @app.before\_request, but then you have errors because you have to import sess... | A little late here but:
This is what I do:
**Use the Blueprint variable to set the before request**
```
myblueprint = Blueprint('myblueprint', __name__, template_folder="templates")
def before_myblueprint():
#code here
myblueprint.before_request(before_myblueprint)
``` |
Why am I getting DistributionNotFound error when I try to run Pyramid project? | 13,658,930 | 7 | 2012-12-01T11:23:35Z | 13,665,764 | 12 | 2012-12-02T02:07:43Z | [
"python",
"pyramid"
] | **I installed in my new Windows 8 (x64):**
* python-2.7
* pywin32-218.win32-py2.7
* setuptools-0.6c11.win32-py2.7
* and pyramid (via easy\_install)
I tried to run my pyramid project:
```
pserve I:\Projects\PyramidProject\development.ini
```
and pkg\_resources.DistributionNotFound(req) was raised:
.
Recommended workaround: just replace `os.rename` with `shutil.move` in `django/contrib/sessions/backends/file.py`:
```
+import shutil
....
-os.rename... |
Running a flask app with nginx and gunicorn | 13,660,118 | 16 | 2012-12-01T13:54:38Z | 13,661,593 | 22 | 2012-12-01T17:04:14Z | [
"python",
"nginx",
"flask",
"gunicorn"
] | I'm new at this and have only been using nginx to serve static files. I have now installed flask and gunicorn. If I run `gunicorn -b 127.0.0.2:8000 hello:app` and then wget it from the server it works well. If I try to access it from a browser, however, it returns a 404 error (I am running this on a server that hosts a... | This is how I serve my flask apps in Nginx:
Run gunicorn daemonized using a socket:
```
sudo gunicorn app:app --bind unix:/tmp/gunicorn_flask.sock -w 4 -D
```
Related nginx config:
```
upstream flask_server {
# swap the commented lines below to switch between socket and port
server unix:/tmp/g... |
python propery: list-like object | 13,660,346 | 4 | 2012-12-01T14:24:00Z | 13,660,372 | 8 | 2012-12-01T14:27:02Z | [
"python",
"properties"
] | I'm trying to create an object with properties acting like a list. Here is what I mean.
```
class Unit:
def __init__(self):
self.val = 0
class Bundle:
def __init__(self, N=3):
self.units = [ Unit() for i in range(N) ]
def getvals(self):
return [ unit.val for unit in self.units ]... | In Python 2, `property` only works correctly for *new style* objects; your `Bundle` class *must* inherit from `object`:
```
class Bundle(object):
...
```
Once you make that correction, the property works as expected:
```
>>> b.vals = [4,5,6]
>>> b.vals
[4, 5, 6]
>>> b.getvals()
[4, 5, 6]
>>> [unit.val for unit i... |
checking if a string is in alphabetical order in python | 13,661,479 | 6 | 2012-12-01T16:50:13Z | 13,661,536 | 7 | 2012-12-01T16:57:03Z | [
"python",
"string",
"sorting"
] | I've put together the following code to check if a string/word is alphabetically ordered:
```
def isInAlphabeticalOrder(word):
word1=sorted(word)
word2=[]
for i in word:
word2.append(i)
if word2 == word1:
return True
else:
return False
```
but I feel like there must be a mo... | This is a simple (and Python idiomatic) way to do this:
```
def isInAlphabeticalOrder(word):
return word==''.join(sorted(word))
>>> isInAlphabeticalOrder('abc')
True
>>> isInAlphabeticalOrder('acb')
False
``` |
checking if a string is in alphabetical order in python | 13,661,479 | 6 | 2012-12-01T16:50:13Z | 13,661,634 | 7 | 2012-12-01T17:08:18Z | [
"python",
"string",
"sorting"
] | I've put together the following code to check if a string/word is alphabetically ordered:
```
def isInAlphabeticalOrder(word):
word1=sorted(word)
word2=[]
for i in word:
word2.append(i)
if word2 == word1:
return True
else:
return False
```
but I feel like there must be a mo... | This has the advantage of being O(n) (sorting a string is O(n log n)). A character (or string) in Python is "less than" another character if it comes before it in alphabetical order, so in order to see if a string is in alphabetical order we just need to compare each pair of adjacent characters. Also, note that you tak... |
Python: fast way to compute the average of several (same length) lists? | 13,661,677 | 3 | 2012-12-01T17:13:17Z | 13,661,740 | 8 | 2012-12-01T17:21:21Z | [
"python"
] | Is there a simple way to calculate the mean of several (same length) lists in Python? Say, I have `[[1, 2, 3], [5, 6, 7]]`, and want to obtain `[3,4,5]`. This is to be doing 100000 times, so want it to be fast. | In case you're using `numpy` (which seems to be more appropriate here):
```
>>> import numpy as np
>>> data = np.array([[1, 2, 3], [5, 6, 7]])
>>> np.average(data, axis=0)
array([ 3., 4., 5.])
``` |
Custom user model in django does not allow setting password in admin | 13,661,865 | 4 | 2012-12-01T17:33:37Z | 13,661,977 | 8 | 2012-12-01T17:45:34Z | [
"python",
"django",
"django-admin",
"django-1.5"
] | I have created a custom user model which I am successfully using within my app.
The problem is that within the Admin, on the user edit screen, I get a display of the present password hash, instead of the very useful interface for setting the password.
I am using Django 1.5b1 on Python 2.7.
How can I convince the Dja... | Documentation suggest that you need to register the custom model with admin and also define few methods as well so that admin interface works with custom user model.
You may also have to define built-in forms for User.
From [Custom users and django.contrib.admin](https://docs.djangoproject.com/en/1.5/topics/auth/cust... |
Convert UTC time to python datetime | 13,662,789 | 2 | 2012-12-01T19:14:12Z | 13,662,809 | 7 | 2012-12-01T19:16:42Z | [
"python",
"datetime",
"utc",
"rfc3339"
] | I have numerous UTC time stamps in the following format:
`2012-04-30T23:08:56+00:00`
I want to convert them to python datetime objects but am having trouble.
My code:
```
for time in data:
pythondata[i]=datetime.strptime(time,"%y-%m-%dT%H:%M:%S+00:00")
```
I get the following error:
```
ValueError: time data '2... | Change the year marker in your time format string to `%Y`:
```
time = '2012-03-01T00:05:55+00:00'
datetime.strptime(time, "%Y-%m-%dT%H:%M:%S+00:00")
# => datetime.datetime(2012, 3, 1, 0, 5, 55)
```
See [`strftime()` and `strptime()` behavior](http://docs.python.org/2/library/datetime.html#strftime-strptime-behavior). |
Inserting only unique rows into SQLite (python) | 13,663,164 | 3 | 2012-12-01T19:58:51Z | 13,664,179 | 10 | 2012-12-01T22:02:34Z | [
"python",
"sqlite"
] | I'm using `cursor.executemany` to insert batches of rows from CSV files into a SQLite table, some of which are expected to be duplicates based on the primary key field. When I execute the command, I predictably get an Integrity Error and nothing gets inserted.
How do I selectively insert only non-duplicate rows withou... | Simply use `INSERT OR IGNORE` to ignore the duplicates.
<http://sqlite.org/lang_insert.html> |
Get the Gmail attachment filename without downloading it | 13,663,672 | 12 | 2012-12-01T20:57:36Z | 13,663,947 | 8 | 2012-12-01T21:31:00Z | [
"python",
"gmail",
"attachment",
"imaplib"
] | I'm trying to get all the messages from a Gmail account that may contain some large attachments (about 30MB). I just need the names, not the whole files. I found a piece of code to get a message and the attachment's name, but it downloads the file and then read its name:
```
import imaplib, email
#log in and select t... | Rather than fetch `RFC822`, which is the full content, you could specify `BODYSTRUCTURE`.
The resulting data structure from `imaplib` is pretty confusing, but you should be able to find the filename, content-type and sizes of each part of the message without downloading the entire thing. |
limit how much data is read with numpy.genfromtxt for matplotlib | 13,663,721 | 12 | 2012-12-01T21:04:15Z | 13,663,832 | 12 | 2012-12-01T21:17:52Z | [
"python",
"numpy",
"matplotlib"
] | I am creating a graph in python using a text file for the source data and matplotlib to plot the graph.
The simple logic below works well.
But is there a way to get have numpy.gentfromtxt only read the first 50 lines from the file 'temperature\_logging'? Currently it reads the entire file.
```
temp = numpy.genfromtxt... | `numpy.genfromtxt` accepts iterators as well as files. That means it will accept the output of `itertools.islice`. Here, `test.txt` is a five-line file:
```
>>> import itertools, numpy
>>> with open('test.txt') as t_in:
... numpy.genfromtxt(itertools.islice(t_in, 3))
...
array([[ 1., 2., 3., 4., 5.],
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.