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
Calling list() twice on reversed() returns an empty list the second time
18,802,417
2
2013-09-14T13:48:08Z
18,802,432
7
2013-09-14T13:50:02Z
[ "python" ]
I don't understand the result of this code: ``` aa = 'hello, world' bb = reversed(aa) print(bb) print(list(bb)) print(bb) dd = list(bb) print(dd) print(''.join(dd)) ``` The result: ``` <reversed object at 0x025C8C90> ['d', 'l', 'r', 'o', 'w', ' ', ',', 'o', 'l', 'l', 'e', 'h'] <reversed object at 0x025C8C90> [] ``` ...
That's because [`reversed`](https://docs.python.org/3/library/functions.html#reversed) creates an iterator, which is already spent when you're calling `list(bb)` for the second time. ``` aa = 'hello, world' bb = reversed(aa) # Creates an iterator, not a list print(bb) # Prints "<reversed object at 0x10c6...
How to turn on line numbers in IDLE?
18,805,203
55
2013-09-14T18:45:03Z
18,805,352
72
2013-09-14T19:02:32Z
[ "python", "python-idle" ]
In the main shell of IDLE, errors always return a line number but the development environment doesn't even have line numbers. Is there anyway to turn on line numbers?
Unfortunately there is not an option to display line numbers in IDLE although there is an [enhancement request](http://bugs.python.org/issue17535) open for this. However, there are a couple of ways to work around this: 1. Under the edit menu there is a go to line option (there is a default shortcut of Alt+G for this)...
How to turn on line numbers in IDLE?
18,805,203
55
2013-09-14T18:45:03Z
23,335,500
7
2014-04-28T07:55:49Z
[ "python", "python-idle" ]
In the main shell of IDLE, errors always return a line number but the development environment doesn't even have line numbers. Is there anyway to turn on line numbers?
There's a set of useful extensions to IDLE called IDLEX that works with MacOS and Windows <http://idlex.sourceforge.net/> It includes line numbering and I find it quite handy & free. Otherwise there are a bunch of other IDEs some of which are free: <https://wiki.python.org/moin/IntegratedDevelopmentEnvironments>
Most pythonic way to convert a string to a octal number
18,806,772
8
2013-09-14T21:54:16Z
18,806,794
22
2013-09-14T21:56:59Z
[ "python", "python-2.6" ]
I am looking to change permissions on a file with the file mask stored in a configuration file. Since os.chmod() requires an octal number, I need to convert a string to an octal number. For example: ``` '000' ==> 0000 (or 0o000 for you python 3 folks) '644' ==> 0644 (or 0o644) '777' ==> 0777 (or 0o777) ``` After an o...
Have you just tried specifying base 8 to `int`: ``` num = int(your_str, 8) ``` Example: ``` s = '644' i = int(s, 8) # 420 decimal print i == 0644 # True ```
Selecting elements of python dictionary greater than a certain value
18,807,079
7
2013-09-14T22:36:19Z
18,807,120
9
2013-09-14T22:41:08Z
[ "python", "dictionary" ]
I need to select elements of a dictionary of a certain value or greater. I am aware of how to do this with lists [Return list of items in list greater than some value](http://stackoverflow.com/questions/4587915/return-list-of-items-in-list-greater-than-some-value) but I am not sure how to translate that into something...
`.items()` will return `(key, value)` pairs that you can use to reconstruct a filtered `dict` using a [list comprehension](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions) that is feed into the [`dict()` constructor](http://docs.python.org/2/library/stdtypes.html#dict), that will accept an ite...
sqlalchemy foreign key relationship attributes
18,807,322
17
2013-09-14T23:15:28Z
18,854,791
22
2013-09-17T16:12:48Z
[ "python", "sqlalchemy", "flask-sqlalchemy" ]
I have a User table and a Friend table. The Friend table holds two foreign keys both to my User table as well as a status field. I am trying to be able to call attributes from my User table on a Friend object. For example, I would love to be able to do something like, friend.name, or friend.email. ``` class User(Base)...
First, if you're using `flask-sqlalchemy`, why are you using directly sqlalchemy instead of the Flask's `db.Model`? I strongly reccomend to use [`flask-sqlalchemy`](http://pythonhosted.org/Flask-SQLAlchemy/) extension since it leverages the sessions and some other neat things. Creating a proxy convenience object is s...
how to show tick labels on top of matplotlib plot?
18,808,304
6
2013-09-15T02:18:15Z
18,814,475
7
2013-09-15T16:06:43Z
[ "python", "matplotlib" ]
In matplotlib what is the way to have tick labels both at the bottom and in the top x axis? I have searched a lot and still can't find how to do it.
Sorry, I lied in the comments. You can do this easily (but it seems to be badly documented) ``` fig, ax = plt.subplots(1, 1) ax.xaxis.set_tick_params(labeltop='on') ``` ![output](http://i.stack.imgur.com/mHKrA.png)
python find substrings based on a delimiter
18,808,707
4
2013-09-15T03:41:42Z
18,808,721
7
2013-09-15T03:44:14Z
[ "python", "regex", "string" ]
I am new to python , so I might be missing some thing simple. I am given a example ``` string = "The , world , is , a , happy , place " ``` I have to create substrings separated by , and print them and process instances separately . i.e. in this example i should be able to print ``` The world is a happy place ...
Try using the `split` function. In your example: ``` string = "The , world , is , a , happy , place " array = string.split(",") for word in array: print word ``` Your approach failed because you indexed it to yield the string from beginning until the first ",". This could work if you then index it from that firs...
Running an Android phone as a stable webserver (for a Python CGI script)
18,809,214
5
2013-09-15T05:30:17Z
18,950,775
8
2013-09-23T01:58:21Z
[ "android", "python", "webserver", "cgi", "sl4a" ]
I'm new to Android. I have a Python program that is both a CGI script as well as an SMS-based interaction system for a small database. It is an extremely low demand system (a handful of users) being run by a grassroots organisation. But it requires stability, in the sense of not having random crashes or down time. For ...
**TLDR**: CherryPy is a dependable server, and Android may be dependable enough to build servers on these days. --- I used to maintain a project which used CherryPy and SL4A, with ws4py for websockets. CherryPy 3.2.2 worked perfectly on Python 2.6 and Python 3.2. The application was often running for a day or two. ...
Iterator vs Iterable?
18,809,475
2
2013-09-15T06:17:43Z
18,809,506
8
2013-09-15T06:23:29Z
[ "python", "iterator" ]
**(For python 3)** In the python docs, [you can see](http://docs.python.org/3/library/functions.html#func-list) that the `list()` function takes an iterable. In the python docs, [you can also see](http://docs.python.org/3/library/functions.html#next) that the `next()` funciton takes an iterator. So I did this in IDL...
An iterator is an iterable, but an iterable is not necessarily an iterator. An iterable is anything that has an `__iter__` method defined - e.g. lists and tuples, as well as iterators. Iterators are a subset of iterables whose values cannot all be accessed at the same time, as they are not all stored in memory at onc...
reading the response in python requests
18,810,777
2
2013-09-15T09:17:12Z
18,810,889
10
2013-09-15T09:34:53Z
[ "python", "python-requests" ]
I have 2 python scripts. One uses the urllib2 library and one uses the requests library. I have found requests much easier to implement but I can't seem to find the equivalent to read() when using the requests library. For example: ``` ... response = url.urlopen(req) print response.geturl() print response.getcode() da...
There isn't one. ``` >>> import requests >>> response = requests.get("http://www.google.com") >>> print response.content '<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage"><head>....' >>> print response.content == response.text True ``` It looks like the POST request you are making is returning n...
How to check if a input is in binary format(1 and 0)?
18,812,047
2
2013-09-15T11:51:25Z
18,812,083
8
2013-09-15T11:55:11Z
[ "python", "python-2.7" ]
I have made a program however I wanted to add an exception if the user inputs is not in a binary format. I have tried many times adding exceptions but I can't seem to get it to work. The below is the program code. I would appreciate if someone could help. ``` import time error=True n=0 while n!=1: print"***Welcome...
Better to ask for forgiveness. Try to convert it to integer using [`int(value, 2)`](http://docs.python.org/2/library/functions.html#int): ``` while True: try: decnum = int(raw_input("Please enter a binary number: "), 2) except ValueError: print "Enter a Binary number. Please try again.\n" e...
Type error on calling validate in wtforms
18,812,240
5
2013-09-15T12:12:34Z
18,814,224
13
2013-09-15T15:42:58Z
[ "python", "python-2.7", "flask", "wtforms", "flask-wtforms" ]
I have TypeError in line where I call 'validate()' on my form. **The error is:** ``` Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1836, in __call__ return self.wsgi_app(environ, start_response) File "/usr/local/lib/python2.7/dist-packages/flask/app.py"...
You need to *instanciate* your validators: ``` org_name = TextField(u'Название организации', [validators.Required()]) ``` Note the `()` after `Required`; this applies to all your validators. The instance is then called again to validate the input.
Embedding a Python library in my own package
18,812,614
10
2013-09-15T12:54:08Z
18,812,776
12
2013-09-15T13:11:37Z
[ "python" ]
Ho can I 'embed' a Python library in my own Python package? Take the [Requests library](http://docs.python-requests.org/en/latest/user/install/#install), for instance. How could I integrate it into my own package, the objective being to allow me to run my application on different machines without actually installing R...
If it's a pure python library (no compiled modules) you can simply place the library in a folder in your project and add that folder to your module search path. Here's an example project: ``` |- application.py |- lib | `- ... |- docs | `- ... `- vendor |- requests | |- __init__.py | `- ... `- other lib...
Get timezone used by datetime.datetime.fromtimestamp()
18,812,638
12
2013-09-15T12:57:09Z
18,817,656
8
2013-09-15T21:25:34Z
[ "python", "timezone" ]
Is it possible, and if yes, how, to get the time zone (i.e. the UTC offset or a `datetime.timezone` instance with that offset) that is used by `datetime.datetime.fromtimestamp()` to convert a *POSIX timestamp* (seconds since the epoch) to a `datetime` object? `datetime.datetime.fromtimestamp()` converts a POSIX timest...
From the [Python documentation](http://docs.python.org/3.3/library/datetime.html#datetime.datetime.fromtimestamp): > *classmethod* `datetime`**`.fromtimestamp`**(*`timestamp, tz=None`*) > > Return the local date and time corresponding to the POSIX timestamp, such as is returned by `time.time()`. If optional argument *...
Get timezone used by datetime.datetime.fromtimestamp()
18,812,638
12
2013-09-15T12:57:09Z
27,918,285
8
2015-01-13T09:01:25Z
[ "python", "timezone" ]
Is it possible, and if yes, how, to get the time zone (i.e. the UTC offset or a `datetime.timezone` instance with that offset) that is used by `datetime.datetime.fromtimestamp()` to convert a *POSIX timestamp* (seconds since the epoch) to a `datetime` object? `datetime.datetime.fromtimestamp()` converts a POSIX timest...
`datetime.fromtimestamp(ts)` converts "seconds since the epoch" to a naive datetime object that represents local time. `tzinfo` is always `None` in this case. Local timezone may have had a different UTC offset in the past. On some systems that provide access to a historical timezone database, `fromtimestamp()` may tak...
Convert string to binary in python
18,815,820
27
2013-09-15T18:19:16Z
18,815,890
38
2013-09-15T18:24:53Z
[ "python", "string", "binary" ]
I am in need of a way to get the binary representation of a string in python. e.g. ``` st = "hello world" toBinary(st) ``` Is there a module of some neat way of doing this?
Something like this? ``` >>> st = "hello world" >>> ' '.join(format(ord(x), 'b') for x in st) '1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100' #using `bytearray` >>> ' '.join(format(x, 'b') for x in bytearray(st)) '1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 ...
Convert string to binary in python
18,815,820
27
2013-09-15T18:19:16Z
30,642,051
14
2015-06-04T10:58:12Z
[ "python", "string", "binary" ]
I am in need of a way to get the binary representation of a string in python. e.g. ``` st = "hello world" toBinary(st) ``` Is there a module of some neat way of doing this?
As a more pythonic way you can first convert your string to byte array then use `bin` function within `map` : ``` >>> st = "hello world" >>> map(bin,bytearray(st)) ['0b1101000', '0b1100101', '0b1101100', '0b1101100', '0b1101111', '0b100000', '0b1110111', '0b1101111', '0b1110010', '0b1101100', '0b1100100'] ``` Or you ...
Python datetime add
18,817,750
7
2013-09-15T21:37:29Z
18,817,994
16
2013-09-15T22:11:12Z
[ "python", "datetime" ]
I have a datetime value in string format. How can I change the format from a "-" separated date to a "." separated date. I also need to add 6 hours to let the data be in my time zone. ``` s = '2013-08-11 09:48:49' from datetime import datetime,timedelta mytime = datetime.strptime(s,"%Y-%m-%d %H:%M:%S") time = mytime.s...
You are adding the *string representation* of the `timedelta()`: ``` >>> from datetime import timedelta >>> print timedelta(minutes=6*60) 6:00:00 ``` Sum `datetime` and `timedelta` objects, not their string representations; only create a string **after** summing the objects: ``` from datetime import datetime, timede...
python read() and write() in large blocks / memory management
18,818,819
4
2013-09-16T00:14:47Z
18,818,982
8
2013-09-16T00:43:17Z
[ "python", "memory-management", "file-io" ]
I'm writing some python code that splices together large files at various points. I've done something similar in C where I allocated a 1MB char array and used that as the read/write buffer. And it was very simple: read 1MB into the char array then write it out. But with python I'm assuming it is different, each time I...
Search site docs.python.org for `readinto` to find docs appropriate for the version of Python you're using. `readinto` is a low-level feature. They'll look a lot like this: > readinto(b) > Read up to len(b) bytes into bytearray b and return the number of bytes read. > > Like read(), multiple reads may be issued to the...
Find duplicate lists where element order is insignificant but repeat list elements are significant
18,819,101
3
2013-09-16T01:02:57Z
18,819,146
7
2013-09-16T01:11:37Z
[ "python", "python-2.7" ]
I've got an odd problem where I need to find duplicate collections of items where the order doesn't matter but the presence of duplicate values within a collection does matter. For example, say I have the following list of lists: ``` lol = [ ['red'], ['blue', 'orange'], ['orange', 'red'], ['red', 'oran...
I think what you're looking for is the [Counter](http://docs.python.org/2/library/collections.html#collections.Counter). Sort each entry and then turn it into a tuple so it can be compared. The counter will keep track of the count of each unique entry: ``` >>> from collections import Counter >>> counted = Counter(tupl...
WebDriverException: Message: 'The browser appears to have exited before we could connect. The output was: Error: no display specified
18,820,410
6
2013-09-16T04:26:26Z
18,822,515
9
2013-09-16T07:29:14Z
[ "python", "selenium", "webdriver", "selenium-webdriver", "robotframework" ]
When run my test case, any my test program try to start firefox, I got Error. I am using robotframework, Selenium2Library and python 2.7. ``` 1Login [ WARN ] Keyword 'Capture Page Screenshot' could not be run on failure: No browser is open | FAIL | WebDriverException: Message: 'The browser appears to have exited bef...
Selenium needs a display and as Linux does not have one , you need to download a virtual display ([xvnc](http://grox.net/doc/apps/vnc/xvnc.html)/[xvfb](http://en.wikipedia.org/wiki/Xvfb)). Then start the virtual display server and `export` the display. *Then* it should work
Shuffling in python
18,820,684
4
2013-09-16T05:04:23Z
18,820,697
13
2013-09-16T05:06:05Z
[ "python" ]
I'm trying to shuffle an array of functions in python. My code goes like this: ``` import random def func1(): ... def func2(): ... def func3(): ... x=[func1,func2,func3] y=random.shuffle(x) ``` And I think it might be working, the thing is that I don't know how to call the functions after I shuffle th...
Firstly, [`random.shuffle()`](http://docs.python.org/2/library/random.html#random.shuffle) shuffles the list in place. It does not return the shuffled list, so `y = None`. That is why it does nothing when you type `y`. To call each function, you can loop through `x` and call each function like so: ``` for function in...
How can i get list of font family(or Name of Font) in matplotlib
18,821,795
7
2013-09-16T06:41:53Z
18,821,968
8
2013-09-16T06:54:17Z
[ "python", "python-2.7", "matplotlib" ]
How can i get list of font family(or Name of Font) in matplotlib. ``` import matplotlib.font_manager matplotlib.font_manager.findSystemFonts(fontpaths=None, fontext='ttf') ``` With help of this code i can get only directory of font. How can i get list of Font-Name like > "Century Schoolbook L", "Ubuntu".... etc Tha...
Try following: ``` >>> import matplotlib.font_manager >>> [f.name for f in matplotlib.font_manager.fontManager.ttflist] ['cmb10', 'cmex10', 'STIXNonUnicode', 'STIXNonUnicode', 'STIXSizeThreeSym', 'STIXSizeTwoSym', 'cmtt10', 'STIXGeneral', 'STIXSizeThreeSym', 'STIXSizeFiveSym', 'STIXSizeOneSym', 'STIXGeneral', 'cmr10',...
Writing multi-line strings to cells using xlwt module
18,822,440
10
2013-09-16T07:24:02Z
18,822,775
11
2013-09-16T07:45:28Z
[ "python", "xlwt" ]
Python: Is there a way to write multi-line strings into an excel cell with just the xlwt module? (I saw answers suggesting use of openpyxl module) The `sheet.write()` method ignores the \n escape sequence. So, just xlwt, is it possible? Thanks in advance.
I found the answer in the [python-excel Google Group](https://groups.google.com/d/topic/python-excel/9eMr2npsKXY/discussion). Using `sheet.write()` with the optional `style` argument, enabling word wrap for the cell, does the trick. Here is a minimum working example: ``` import xlwt book = xlwt.Workbook() sheet = book...
Python: powerset of a given set with generators
18,826,571
5
2013-09-16T11:13:56Z
18,826,666
13
2013-09-16T11:19:13Z
[ "python", "algorithm", "set", "generator", "powerset" ]
I am trying to build a list of subsets of a given set in Python with **generators**. Say I have `set([1, 2, 3])` as input, I should have `[set([1, 2, 3]), set([2, 3]), set([1, 3]), set([3]), set([1, 2]), set([2]), set([1]), set([])]` as output. How can I achieve this?
The fastest way is by using itertools, especially chain and combinations: ``` >>> from itertools import chain, combinations >>> i = set([1, 2, 3]) >>> for z in chain.from_iterable(combinations(i, r) for r in range(len(i)+1)): print z () (1,) (2,) (3,) (1, 2) (1, 3) (2, 3) (1, 2, 3) >>> ``` If you need a generato...
Python - Count number of words in a list strings
18,827,198
2
2013-09-16T11:45:46Z
18,827,299
13
2013-09-16T11:50:45Z
[ "python", "string", "list", "counter" ]
Im trying to find the number of whole words in a list of strings, heres the list ``` mylist = ["Mahon Point retail park", "Finglas","Blackpool Mahon", "mahon point blanchardstown"] ``` expected outcome: ``` 4 1 2 3 ``` There are 4 words in mylist[0], 1 in mylist[1] and so on ``` for x, word in enumerate(mylist): ...
Use `str.split`: ``` >>> mylist = ["Mahon Point retail park", "Finglas","Blackpool Mahon", "mahon point blanchardstown"] >>> for item in mylist: ... print len(item.split()) ... 4 1 2 3 ```
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 0: ordinal not in range(128)
18,827,396
12
2013-09-16T11:55:33Z
18,827,478
17
2013-09-16T11:59:57Z
[ "python", "django", "encoding", "utf-8", "redhat" ]
I'm having troubles in encoding characters in utf-8. I'm using Django, and I get this error when I tried to send an Android notification with non-plain text. I tried to find where the source of the error and I managed to figure out that the source of the error is not in my project. In python shell, I type: ``` 'ç'.e...
You're trying to encode / decode strings, not Unicode strings. The following statements do work: ``` u'ç'.encode('utf8') u'á'.encode('utf-8') unicode(u'ç') u'ç'.encode('utf-8','ignore') ```
Python: Get most frequent item in list
18,827,897
2
2013-09-16T12:20:23Z
18,828,003
9
2013-09-16T12:25:14Z
[ "python", "list", "group-by", "max" ]
I've got a list of tuples, and I want to get the most frequently occurring tuple BUT if there are "joint winners" it should pick between them at random. ``` tups = [ (1,2), (3,4), (5,6), (1,2), (3,4) ] ``` so I want something that would return either (1,2) or (3,4) at random for the above list
Use `collections.Counter`: ``` >>> collections.Counter([ (1,2), (3,4), (5,6), (1,2), (3,4) ]).most_common()[0] ((1, 2), 2) ``` This is `O(n log(n))`.
Difference between various numpy random functions
18,829,185
16
2013-09-16T13:25:20Z
18,829,377
17
2013-09-16T13:33:50Z
[ "python", "numpy" ]
The [numpy.random](http://docs.scipy.org/doc/numpy/reference/routines.random.html) module defines the following 4 functions that all seem to return a float betweeb [0, 1.0) from the continuous uniform distribution. What (if any) is the difference between these functions? > random\_sample([size]) Return random floats i...
Nothing. They're just aliases to `random_sample`: ``` In [660]: np.random.random Out[660]: <function random_sample> In [661]: np.random.ranf Out[661]: <function random_sample> In [662]: np.random.sample Out[662]: <function random_sample> In [663]: np.random.random_sample is np.random.random Out[663]: True In [664...
Pythonic and compact way to compare the key in dict
18,829,997
3
2013-09-16T14:03:21Z
18,830,075
8
2013-09-16T14:07:43Z
[ "python", "dictionary" ]
Just want to know a good way how to do this: ``` a = {'key':'value'} if 'key' in a: if a['key'] == 'value': # do something ... ``` The problem is sometimes I need to handle cases whe `"key"` is actually `"@key"`, So I don't want to duplicate the same code with `if '@key' in a: ....` So the question is ho...
Here's how I would go about doing this: ``` a = {'key':'value'} if any(a.get(key, None) == 'value' for key in ('key','@key')): # do something ... ```
Can I run line_profiler over a pytest test?
18,830,232
10
2013-09-16T14:14:43Z
24,391,977
15
2014-06-24T16:39:40Z
[ "python", "py.test", "cprofile" ]
I have identified some long running pytest tests with ``` py.test --durations=10 ``` I would like to instrument one of those tests now with something like line\_profiler or cprofile. I really want to get the profile data from the test itself as the pytest setup or tear down could well be part of what is slow. Howeve...
Run pytest like this: ``` python -m cProfile -o profile $(which py.test) ``` You can even pass in optional arguments: ``` python -m cProfile -o profile $(which py.test) \ tests/worker/test_tasks.py -s campaigns ``` This will create a binary file called `profile` in your current directory. This can be analyzed w...
How to get values from dictionary in jinja when key is a variable?
18,830,393
8
2013-09-16T14:22:39Z
18,830,576
16
2013-09-16T14:31:56Z
[ "python", "variables", "dictionary", "jinja2", "substitution" ]
I'm trying to retrieve entries from a python dictionary in jinja2, but the problem is I don't know what key I want to access ahead of time - the key is stored in a variable called `s.course`. So my problem is I need to double-substitute this variable. I don't want to use a `for` loop because that will go through the di...
You can use `course_codes.get(s.course)`: ``` >>> import jinja2 >>> env = jinja2.Environment() >>> t = env.from_string('{{ codes.get(mycode) }}') >>> t.generate(codes={'a': '123'}, mycode='a').next() u'123' ```
Should I, and how to, add methods to int in python?
18,831,083
4
2013-09-16T14:54:54Z
18,831,195
10
2013-09-16T14:59:52Z
[ "python", "class", "oop", "methods", "int" ]
(This is a learning related question, so any advice in why should I do or not do anything, as well as recommended resources to get these things better, are more than wellcome.) I'm trying to learn about OOP in python, and have done a simple "Time" class like this: ``` class Time(object): """A time representation...
No, you cannot really add methods to int. You *could* subclass int, and return that from your `__int__` method, but that won't help you much, since calling `int()` on that will still return a regular int. Your idea of using a regular function to convert back to `Time()` is right, but it might be nice to make it a clas...
How can I from bs4 import BeautifulSoup?
18,831,380
3
2013-09-16T15:08:20Z
18,831,754
9
2013-09-16T15:27:28Z
[ "python", "beautifulsoup" ]
This code: ``` from bs4 import BeautifulSoup ``` Doesn't work, and gives this error : ``` raise AttributeError, "'%s' object has no attribute '%s'" % (self.__class__.__name__,attr) ^ SyntaxError: invalid syntax ``` What should i do ?
You should be using `pip` to install, so you can simply do ``` pip install beautifulsoup4 ``` That will install the latest BS4, which is 4.3.1 as of 2013-08-15. It supports Python 3.
How to catch this Python exception: error: [Errno 10054] An existing connection was forcibly closed by the remote host
18,832,643
8
2013-09-16T16:11:06Z
20,187,674
9
2013-11-25T08:22:08Z
[ "python", "sockets", "exception", "python-2.7" ]
I am trying to catch this particular exception (and only this exception) in Python 2.7, but I can't seem to find documentation on the exception class. Is there one? ``` [Errno 10054] An existing connection was forcibly closed by the remote host ``` My code so far: ``` try: # Deleting filename self.ftp.delete(fil...
The error type is socket.error, the documentation is [here](http://docs.python.org/2/library/socket.html). Try modiffying your code like this: ``` import socket import errno try: Deleting filename self.ftp.delete(filename) return True except (error_reply, error_perm, error_temp): return False except...
Drawing directions fields
18,832,763
5
2013-09-16T16:17:09Z
18,833,385
7
2013-09-16T16:56:07Z
[ "python", "math" ]
Is there a way to draw direction fields in python? My attempt is to modify <http://www.compdigitec.com/labs/files/slopefields.py> giving ``` #!/usr/bin/python import math from subprocess import CalledProcessError, call, check_call def dy_dx(x, y): try: # declare your dy/dx here: return x**2-x-2 ...
You can use this matplotlib code as a base. Modify it for your needs. I have updated the code to show same length arrows. It is also possible to change the axis form "boxes" to "arrows". Let me know if you need that change and I could add it. ![enter image description here](http://i.stack.imgur.com/9vGcx.png) ``` im...
AttributeError in python/numpy when constructing function for certain values
18,833,639
3
2013-09-16T17:11:13Z
18,833,893
10
2013-09-16T17:29:30Z
[ "python", "numpy", "scipy" ]
I'm writing Python code to generate and plot 'super-Gaussian' functions, as: ``` def supergaussian(x, A, mu, sigma, offset, N=8): """Supergaussian function, amplitude A, centroid mu, st dev sigma, exponent N, with constant offset""" return A * (1/(2**(1+1/N)*sigma*2*scipy.special.gamma(1+1/N))) * numpy.exp(-nu...
The error is due to some numpy dtype weirdness. I'm not sure exactly how it works internally, but for some reason `2*25**14` triggers a change in how Numpy handles the datatypes: ``` >>> type(np.max(-numpy.absolute(numpy.power(init_x-0,13)))/(2*25**13)) <type 'numpy.float64'> >>> type(np.max(-numpy.absolute(numpy.powe...
Force python to print entire number
18,833,777
3
2013-09-16T17:20:52Z
18,833,804
7
2013-09-16T17:22:20Z
[ "python", "python-2.7" ]
Here is my problem: If I try for example to print the result of : ``` 2**64 ``` will print: ``` 18446744073709551616L ``` But now if I want to print the result of : ``` 1.8446744*10**19 ``` This will print: ``` 1.8446744e+19 ``` So my question is : how can I print the entire result of 1.8446744e+19 I want to s...
First the L at the end of your number means the type is a 'long' you can check the type by: ``` >>> type(18446744000000000000) long ``` Then to get your result not as a scientific notation you can just convert your number to a long: ``` >>> long(1.8446744*10**19) 18446744000000000000L ``` You can try to convert it ...
Python XML File Open
18,834,393
2
2013-09-16T18:00:05Z
18,838,275
7
2013-09-16T22:21:59Z
[ "python", "xml" ]
I am trying to open an xml file and parse it, but when I try to open it the file never seems to open at all it just keeps running, any ideas? ``` from xml.dom import minidom Test_file = open('C::/test_file.xml','r') xmldoc = minidom.parse(Test_file) Test_file.close() for i in xmldoc: print('test') ``` The file...
**Running your Python code with a few adjustments:** ``` from xml.dom import minidom Test_file = open('C:/test_file.xml','r') xmldoc = minidom.parse(Test_file) Test_file.close() def printNode(node): print node for child in node.childNodes: printNode(child) printNode(xmldoc.documentElement) ``` **With th...
Random word generator- Python
18,834,636
10
2013-09-16T18:17:00Z
18,835,426
26
2013-09-16T19:07:47Z
[ "python", "random", "python-3.3" ]
So i'm basically working on a project where the computer takes a word from a list of words and jumbles it up for the user. there's only one problem: I don't want to keep having to write tons of words in the list, so i'm wondering if there's a way to import a ton of random words so even I don't know what it is, and then...
# Reading a local word list If you're doing this repeatedly, I would download it locally and pull from the local file. \*nix users can use `/usr/share/dict/words`. Example: ``` word_file = "/usr/share/dict/words" WORDS = open(word_file).read().splitlines() ``` # Pulling from a remote dictionary If you want to pull...
selecting from multi-index pandas
18,835,077
19
2013-09-16T18:45:37Z
18,835,121
22
2013-09-16T18:48:54Z
[ "python", "pandas" ]
I have a multi-index data frame with columns 'A' and 'B'. Is there is a way to select rows by filtering on one column of the multi-index without reseting the index to single column index. For Example. ``` # has multi-index (A,B) df #can i do this? I know this doesnt work because index is multi-index so I need to ...
One way is to use the `get_level_values` Index method: ``` In [11]: df Out[11]: 0 A B 1 4 1 2 5 2 3 6 3 In [12]: df.iloc[df.index.get_level_values('A') == 1] Out[12]: 0 A B 1 4 1 ``` In 0.13 you'll be able to use [`xs` with `drop_level` argument](https://github.com/pydata/pandas/pull/4180): ``` df.xs(...
selecting from multi-index pandas
18,835,077
19
2013-09-16T18:45:37Z
18,835,174
8
2013-09-16T18:51:42Z
[ "python", "pandas" ]
I have a multi-index data frame with columns 'A' and 'B'. Is there is a way to select rows by filtering on one column of the multi-index without reseting the index to single column index. For Example. ``` # has multi-index (A,B) df #can i do this? I know this doesnt work because index is multi-index so I need to ...
You can use `DataFrame.xs()`: ``` In [36]: df = DataFrame(randn(10, 4)) In [37]: df.columns = [np.random.choice(['a', 'b'], size=4).tolist(), np.random.choice(['c', 'd'], size=4)] In [38]: df.columns.names = ['A', 'B'] In [39]: df Out[39]: A b a B d d d d 0 -1.406 0.548 -0.635 ...
Element-wise 'and' for lists in python?
18,835,525
4
2013-09-16T19:13:47Z
18,835,553
9
2013-09-16T19:15:41Z
[ "python" ]
I have two lists: ``` X = [True,False] Y = [True,True] ``` I am trying to compare X[0] with Y[0] and X[1] with Y[1]. I tried ``` in [7]: X and Y Out[7]: [True, True] ``` but the result I was expecting was [True,False]. What should I be doing?
All non-empty lists evaluate to `True` in a boolean context, and `and` evaluates to the last expression it evaluated (`Y` in this case), which is why you get the result you do. You want something like this: ``` [x and y for x, y in zip(X, Y)] ```
Element-wise 'and' for lists in python?
18,835,525
4
2013-09-16T19:13:47Z
18,835,572
14
2013-09-16T19:17:03Z
[ "python" ]
I have two lists: ``` X = [True,False] Y = [True,True] ``` I am trying to compare X[0] with Y[0] and X[1] with Y[1]. I tried ``` in [7]: X and Y Out[7]: [True, True] ``` but the result I was expecting was [True,False]. What should I be doing?
This is a perfect opportunity to use `map`, because `and` can be represented with a built-in function: ``` import operator X = [True,False] Y = [True,True] map(operator.and_, X,Y) #=> [True, False] ``` The reason why you get the behaviour you did is that `and` performs operations on the operands as if they had `bool`...
pymongo method of getting statistics for collection byte usage?
18,836,064
7
2013-09-16T19:45:36Z
18,855,712
13
2013-09-17T17:02:16Z
[ "python", "mongodb", "python-3.x", "pymongo" ]
The [MongoDB Application FAQ mentions](http://docs.mongodb.org/manual/faq/developers/#how-do-i-optimize-storage-use-for-small-documents) that short field names are a technique that can be used for small documents. This led me to thinking, "what's a small document anyway?" I'm using pymongo, is there any way I can writ...
There is no builtin way to get the ratio of space used for keys in BSON documents versus space used for actual field values. However, the [collstats](http://docs.mongodb.org/manual/reference/command/collStats/) and [dbstats](http://docs.mongodb.org/manual/reference/command/dbStats/) commands can give you useful informa...
Convert Python dict into a dataframe
18,837,262
43
2013-09-16T21:02:22Z
18,837,389
77
2013-09-16T21:12:01Z
[ "python", "pandas", "dataframe" ]
I have a Python dictionary like the following: ``` {u'2012-06-08': 388, u'2012-06-09': 388, u'2012-06-10': 388, u'2012-06-11': 389, u'2012-06-12': 389, u'2012-06-13': 389, u'2012-06-14': 389, u'2012-06-15': 389, u'2012-06-16': 389, u'2012-06-17': 389, u'2012-06-18': 390, u'2012-06-19': 390, u'2012-06-20': ...
The error here, is since calling the DataFrame constructor with scalar values (where it expects values to be a list/dict/... i.e. have multiple columns): ``` pd.DataFrame(d) ValueError: If using all scalar values, you must must pass an index ``` You could take the items from the dictionary (i.e. the key-value pairs):...
Convert Python dict into a dataframe
18,837,262
43
2013-09-16T21:02:22Z
32,344,037
22
2015-09-02T03:07:48Z
[ "python", "pandas", "dataframe" ]
I have a Python dictionary like the following: ``` {u'2012-06-08': 388, u'2012-06-09': 388, u'2012-06-10': 388, u'2012-06-11': 389, u'2012-06-12': 389, u'2012-06-13': 389, u'2012-06-14': 389, u'2012-06-15': 389, u'2012-06-16': 389, u'2012-06-17': 389, u'2012-06-18': 390, u'2012-06-19': 390, u'2012-06-20': ...
As explained on another answer using `pandas.DataFrame()` directly here will not act as you think. What you can do is use `pandas.DataFrame.from_dict`with **`orient='index'`**: ``` In[7]: pandas.DataFrame.from_dict({u'2012-06-08': 388, u'2012-06-09': 388, u'2012-06-10': 388, u'2012-06-11': 389, u'2012-06-12': 389...
Why Is There a ':' In All Examples of Python's format's mini-language?
18,837,455
3
2013-09-16T21:16:05Z
18,837,518
7
2013-09-16T21:19:45Z
[ "python", "string-formatting" ]
I was looking at this specific example: ``` x = 3.45678 print({':.2f'}.format(x)) ``` And I cannot for the life of me find any documentation referring to the colon. <http://docs.python.org/2/library/string.html#grammar-token-precision> I really prefer if someone could point out where I could've learned this on my ow...
It is in the document you mentioned but under [Format String Syntax](http://docs.python.org/2/library/string.html#format-string-syntax). > The field\_name is optionally followed by a conversion field, which is preceded by an exclamation point '!', and a format\_spec, which is preceded by a colon ':'. These specify a n...
Scrapy Very Basic Example
18,838,494
7
2013-09-16T22:40:39Z
18,838,597
12
2013-09-16T22:49:58Z
[ "python", "web-scraping", "scrapy" ]
Hi I have Python Scrapy installed on my mac and I was trying to follow the v[ery first example](http://doc.scrapy.org/en/0.18/intro/overview.html#run-the-spider-to-extract-the-data) on their web. They were trying to run the command: ``` scrapy crawl mininova.org -o scraped_data.json -t json ``` I don't quite underst...
You may have better luck looking through [the tutorial](http://doc.scrapy.org/en/0.18/intro/tutorial.html#intro-tutorial) first, as opposed to the "Scrapy at a glance" webpage. The tutorial implies that Scrapy is, in fact, a separate program. Running the command `scrapy startproject tutorial` will create a folder call...
Scrapy Very Basic Example
18,838,494
7
2013-09-16T22:40:39Z
27,744,766
28
2015-01-02T15:53:18Z
[ "python", "web-scraping", "scrapy" ]
Hi I have Python Scrapy installed on my mac and I was trying to follow the v[ery first example](http://doc.scrapy.org/en/0.18/intro/overview.html#run-the-spider-to-extract-the-data) on their web. They were trying to run the command: ``` scrapy crawl mininova.org -o scraped_data.json -t json ``` I don't quite underst...
**TL;DR:** see [Self-contained minimum example script to run scrapy](https://gist.github.com/alecxe/fc1527d6d9492b59c610). First of all, having a normal Scrapy project with a separate `.cfg`, `settings.py`, `pipelines.py`, `items.py`, `spiders` package etc is a recommended way to keep and handle your web-scraping logi...
Argparse"ArgumentError: argument -h/--help: conflicting option string(s): -h, --help"
18,839,957
8
2013-09-17T01:36:06Z
18,840,050
11
2013-09-17T01:48:41Z
[ "python", "argparse" ]
Recently, I am learning argparse module, Argument error occurred below the code ``` import argparse import sys class ExecuteShell(object): def create(self, args): """aaaaaaa""" print('aaaaaaa') return args def list(self, args): """ccccccc""" print('ccccccc') r...
`argparse` adds `--help` and `-h` options by default. If you don't want to use the built-in help feature, you need to disable it with: ``` parser = argparse.ArgumentParser(add_help=False) ``` See the [documentation](http://docs.python.org/dev/library/argparse.html#add-help)
Cannot Install Python Modules after Installing Anaconda
18,840,292
3
2013-09-17T02:21:27Z
18,863,503
7
2013-09-18T03:47:48Z
[ "python", "windows", "python-2.7", "pyodbc", "anaconda" ]
[New Note: I cannot install through binstar or anaconda. Why can't I install in python, outside of anaconda? Is there a way to get my computer to stop using the anaconda install of python when I don't luanch it specifically through the continuum launcher?] I have an install of Python 2.7 on a windows machine. I just r...
You could try to find someone who's built this package on [binstar](https://binstar.org), which is the package hosting site for Anaconda. I found <https://binstar.org/dhirschfeld/pyodbc/3.0.7/files>, which may work for you if you have 64-bit Windows. You can try `conda install -c https://conda.binstar.org/dhirschfeld ...
TimedRotatingFileHandler doesn't work fine in Django with multi-instance
18,840,785
4
2013-09-17T03:20:20Z
18,843,553
8
2013-09-17T07:14:46Z
[ "python", "django", "logging" ]
I use TimedRotatingFileHandler to logging Django log and rotate every day, but check the log file, strange issue is yesterday log is truncated and logging few today's log, yesterday log is lost! Django 1.4 uwsgi 1.4.9 Python 2.6 I start 8 django instance with uwsgi. The setting.py is ``` 'handlers': { 'apilo...
You should not be logging to a file-based handler from multiple processes concurrently - that is not supported, as there is no portable OS support for it. To log to a single destination from multiple processes, you can use one of the following approaches: * Use something like [`ConcurrentLogHandler`](https://pypi.pyt...
will using list comprehension to read a file automagically call close()
18,840,880
8
2013-09-17T03:31:51Z
18,840,918
8
2013-09-17T03:36:53Z
[ "python" ]
Does the following syntax close the file: ``` lines = [line.strip() for line in open('/somefile/somewhere')] ``` Bonus points if you can demonstrate how it does or does not... TIA!
This is how you *should* do it ``` with open('/somefile/somewhere') as f: lines = [line.strip() for line in f] ``` In CPython the file should be closed right away as there are no references to it left, but **Python language does not guarantee this**. In Jython, the file won't be closed until the garbage collecto...
will using list comprehension to read a file automagically call close()
18,840,880
8
2013-09-17T03:31:51Z
18,840,920
12
2013-09-17T03:37:08Z
[ "python" ]
Does the following syntax close the file: ``` lines = [line.strip() for line in open('/somefile/somewhere')] ``` Bonus points if you can demonstrate how it does or does not... TIA!
It should close the file, yes, though when exactly it does so is implementation dependent. The reason is that there is no reference to the open file after the end of the list comprehension, so it will be garbage collected, and that will close the file. In cpython (the regular interpreter version from python.org), it w...
Hyphen in verbose regex comment causes error
18,841,384
4
2013-09-17T04:37:03Z
18,841,435
7
2013-09-17T04:42:50Z
[ "python", "regex" ]
What's wrong with the following code - I pinpointed it to the hyphen in the comment, but why should that cause an error? ``` import re valid = re.compile(r'''[^ \uFFFE\uFFFF # non-characters ]''', re.VERBOSE) Traceback (most recent call last): File "valid.py", line 5, in <module> ]''', re.VERBOSE) File "/...
According to the documentation (emphasis mine): > `re.X` > `re.VERBOSE` > > This flag allows you to write regular expressions that look nicer. **Whitespace within the pattern is ignored, except when in a character class or preceded by an unescaped backslash, and, when a line contains a '#' neither in a character cla...
Using PI in python 2.7
18,841,703
6
2013-09-17T05:11:04Z
18,841,730
22
2013-09-17T05:13:23Z
[ "python", "python-2.7" ]
I am trying to access the value of pi in Python 2.7, but it seems as if Python doesn't recognize math.pi. I am using IDLE, and when I try to print the value of math.pi, it says that "Math is not defined" or "math is not defined". I can't upgrade to the next version without risk, so is there a way to access pi in Python...
``` Python 2.7.5 (default, May 15 2013, 22:44:16) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import math >>> math.pi 3.141592653589793 ``` Check out the [Python tutorial on modules](http://docs.python.org/2/tutorial/modules.html) and how to use them....
String concatenation without '+' operator in python
18,842,779
41
2013-09-17T06:34:07Z
18,842,890
35
2013-09-17T06:40:04Z
[ "python", "string", "optimization", "concatenation", "string-concatenation" ]
I was playing with python and I realized we don't need to use '+' operator to concatenate strings unless it is used directly. For example: ``` string1 = 'Hello' 'World' #1 works fine string2 = 'Hello' + 'World' #2 also works fine string3 = 'Hello' string4 = 'World' string5 = string3 string4 #3 causes syntax e...
From the [docs](http://docs.python.org/2/reference/lexical_analysis.html#string-literal-concatenation): > Multiple adjacent string literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same as their concatenation. Thus, "hello" 'world' is equivalent to ...
Get Outlook To-Do-list using Python
18,845,512
10
2013-09-17T09:01:06Z
19,044,929
8
2013-09-27T07:18:26Z
[ "python", "windows", "python-2.7", "outlook-2010" ]
I am accessing Outlook with the [win32com module](http://docs.activestate.com/activepython/2.4/pywin32/html/com/win32com/HTML/docindex.html). I want to get a hold of the task and flagged mails - Outlook has a lot of different names for them and look at them as to different type of "objects". However I want to get the ...
[Here is an article](http://www.add-in-express.com/creating-addins-blog/2013/06/12/outlook-tasks-create-get-delete/.) that explains everything: > It is easy to confuse a To-do item with a task, but bear in mind that a To-do item can either be an e-mail, contact or task. An Outlook item becomes a to-do item as soon as ...
How to define when a class is empty
18,848,599
6
2013-09-17T11:26:13Z
18,848,648
12
2013-09-17T11:28:50Z
[ "python", "class" ]
I wrote my own vector class: ``` #! /usr/bin/env python3 class V: """Defines a 2D vector""" def __init__(self,x,y): self.x = x self.y = y def __add__(self,other): newx = self.x + other.x newy = self.y + other.y return V(newx,newy) def __sub__(self,other): ...
You can implement the special method [`__bool__`](http://docs.python.org/3/reference/datamodel.html#object.__bool__): ``` def __bool__ (self): return self.x != 0 or self.y != 0 ``` Note that in Python 2, the special method is named [`__nonzero__`](http://docs.python.org/2.7/reference/datamodel.html#object.__nonze...
Stream child process output in flowing mode
18,849,112
8
2013-09-17T11:50:58Z
18,849,329
8
2013-09-17T12:01:12Z
[ "javascript", "python", "node.js" ]
I have custom command line written using Python which prints its output using "print" statement. I am using it from Node.js by spawning a child process and sending commands to it using **child.stdin.write** method. Here's source: ``` var childProcess = require('child_process'), spawn = childProcess.spawn; var chi...
You need to flush the output in the child process. Probably you think this isn't necessary because when testing and letting the output happen on a terminal, then the library flushes itself (e. g. when a line is complete). This is not done when printing goes to a pipe (due to performance reasons). Flush yourself: ```...
How to write/update data into cells of existing XLSX workbook using xlsxwriter in python
18,849,535
13
2013-09-17T12:12:19Z
18,850,144
28
2013-09-17T12:40:39Z
[ "python", "excel", "xlsxwriter" ]
I am able to write into new xlsx workbook using ``` import xlsxwriter def write_column(csvlist): workbook = xlsxwriter.Workbook("filename.xlsx",{'strings_to_numbers': True}) worksheet = workbook.add_worksheet() row = 0 col = 0 for i in csvlist: worksheet.write(col,row, i) col += 1...
Quote from `xlsxwriter` module [documentation](https://xlsxwriter.readthedocs.org/en/latest/introduction.html): > This module cannot be used to modify or write to an existing Excel > XLSX file. If you want to modify existing `xlsx` workbook, consider using [openpyxl](https://openpyxl.readthedocs.org) module. See als...
How to write/update data into cells of existing XLSX workbook using xlsxwriter in python
18,849,535
13
2013-09-17T12:12:19Z
34,559,425
8
2016-01-01T19:44:11Z
[ "python", "excel", "xlsxwriter" ]
I am able to write into new xlsx workbook using ``` import xlsxwriter def write_column(csvlist): workbook = xlsxwriter.Workbook("filename.xlsx",{'strings_to_numbers': True}) worksheet = workbook.add_worksheet() row = 0 col = 0 for i in csvlist: worksheet.write(col,row, i) col += 1...
you can use this code to open (test.xlsx) file and modify A1 cell and then save it with a new name ``` import openpyxl xfile = openpyxl.load_workbook('test.xlsx') sheet = xfile.get_sheet_by_name('Sheet1') sheet['A1'] = 'hello world' xfile.save('text2.xlsx') ```
Adding more values on existing python dictionary key
18,851,325
9
2013-09-17T13:32:30Z
18,851,384
15
2013-09-17T13:34:35Z
[ "python", "dictionary" ]
I am new to python and i am stuck while making a dictionary.. please help :) **This is what I am starting with :** ``` dict = {} dict['a']={'ra':7, 'dec':8} dict['b']={'ra':3, 'dec':5} ``` **Everything perfect till now. I get :** ``` In [93]: dict Out[93]: {'a': {'dec':8 , 'ra': 7}, 'b': {'dec': 5, 'ra': 3}} ``` *...
``` >>> d = {} >>> d['a'] = {'ra':7, 'dec':8} >>> d['b'] = {'ra':3, 'dec':5} >>> d['a']['dist'] = 12 >>> d {'a': {'dec': 8, 'dist': 12, 'ra': 7}, 'b': {'dec': 5, 'ra': 3}} ``` If you want to update dictionary from another dictionary, use [update()](http://docs.python.org/2/library/stdtypes.html#dict.update): > Update...
TypeError: sequence item 0: expected string, NoneType found
18,852,324
4
2013-09-17T14:15:03Z
20,271,297
35
2013-11-28T16:53:41Z
[ "python", "typeerror" ]
I'm trying to improve a game of battleships. The original version works fine with no errors. I have written code to help overcome the fact that the first version places the ships in the same place every time so I have started with one ship (made of two squares). I have done this by creating two functions: the first gen...
If you've arrived here because you were looking for the root cause of "`TypeError: sequence item 0: expected string, NoneType found`", it can come from doing something along these lines... ``` ','.join([None]) ```
What is the best way to compute the trace of a matrix product in numpy?
18,854,425
9
2013-09-17T15:53:45Z
18,855,277
9
2013-09-17T16:39:24Z
[ "python", "numpy", "matrix" ]
If I have numpy arrays `A` and `B`, then I can compute the trace of their matrix product with: ``` tr = numpy.linalg.trace(A.dot(B)) ``` However, the matrix multiplication `A.dot(B)` unnecessarily computes all of the off-diagonal entries in the matrix product, when only the diagonal elements are used in the trace. In...
You can improve on @Bill's solution by reducing intermediate storage to the diagonal elements only: ``` from numpy.core.umath_tests import inner1d m, n = 1000, 500 a = np.random.rand(m, n) b = np.random.rand(n, m) # They all should give the same result print np.trace(a.dot(b)) print np.sum(a*b.T) print np.sum(inner...
What's the best way to split a string into fixed length chunks and work with them in Python?
18,854,620
11
2013-09-17T16:04:26Z
18,854,817
21
2013-09-17T16:14:19Z
[ "python" ]
I am reading in a line from a text file using: ``` file = urllib2.urlopen("http://192.168.100.17/test.txt").read().splitlines() ``` and outputting it to an LCD display, which is 16 characters wide, in a telnetlib.write command. In the event that the line read is longer than 16 characters I want to break it down in...
One solution would be to use this function: ``` def chunkstring(string, length): return (string[0+i:length+i] for i in range(0, len(string), length)) ``` This function returns a generator, using a generator comprehension. The generator returns the string sliced, from 0 + a multiple of the length of the chunks, to...
Adding bookmarks using PyPDF2
18,855,907
6
2013-09-17T17:12:32Z
18,867,646
7
2013-09-18T08:46:08Z
[ "python", "pdf" ]
The documentation for [PyPDF2](https://github.com/mstamy2/PyPDF2/) states that it's possible to add nested bookmarks to PDF files, and the code appears (upon reading) to support this. Adding a bookmark to the root tree is easy (see code below), but I can't figure out what I need to pass as the `parent` argument to cre...
The `addBookmark` method returns a reference to the bookmark it created, which can be used as the parent to another bookmark. e.g. ``` #!/usr/bin/env python from PyPDF2 import PdfFileWriter, PdfFileReader output = PdfFileWriter() input1 = PdfFileReader(open('introduction.pdf', 'rb')) output.addPage(input1.getPage(0)) ...
make facebook wall post in python
18,857,028
4
2013-09-17T18:16:13Z
19,066,265
8
2013-09-28T11:07:29Z
[ "python", "facebook" ]
I want to make a simple Wall Post on my facebook fanpage. I have my APP\_ID + APP SECRET and I'm able to get the access token but I'm struggeling with facebook.GraphAPI() This is the code: ``` # -*- coding: utf-8 -*- import urllib import facebook FACEBOOK_APP_ID = '12345' FACEBOOK_APP_SECRET = '123456789' FACEBOOK_P...
The Facebook package on PyPI is messed up. It's not [`facebook`](https://pypi.python.org/pypi/facebook) that you want, but [`facebook-sdk`](https://pypi.python.org/pypi/facebook-sdk). Make sure you have the right one: ``` pip uninstall facebook # Remove the broken package pip install facebook-sdk # Install the corr...
Python - Remove very last character in file
18,857,352
10
2013-09-17T18:34:15Z
18,857,381
25
2013-09-17T18:36:25Z
[ "python", "file" ]
After looking all over the internet, I've come to this. Let's say I have an already made text file that reads: `Hello World` Well I want to remove the very last character --In this case`d`-- from the text file. So now the text file should look like this: `Hello Worl` But I have no idea how to do this. All I want...
Use [`file.seek()`](http://docs.python.org/2/library/stdtypes.html#file.seek) to seek 1 position from the end, then use [`file.truncate()`](http://docs.python.org/2/library/stdtypes.html#file.truncate) to remove the remainder of the file: ``` with open(filename, 'rb+') as filehandle: filehandle.seek(-1, os.SEEK_EN...
Overlaying the numeric value of median/variance in boxplots
18,861,075
5
2013-09-17T22:42:19Z
18,861,734
10
2013-09-17T23:51:20Z
[ "python", "matplotlib", "boxplot" ]
When using box plots in Python, is there any way to automatically/easily overlay the value of the median & variance on top of each box (or at least the numerical value of the median)? E.g. in the boxplot below, I would like to overlay the text (median, +- std) on each box plot. ![enter image description here](http://...
Assuming you are using the boxplot function to draw the boxplots, it returns a dictionary that holds the components of the graph. Note that the box represent the inner quartile range (25 to 75th percentile) and not the standard deviation. ``` >>> bp_dict = boxplot(data, vert=False) # draw horizontal boxplot >>> bp_dic...
Character by character in UTF8 file
18,861,506
2
2013-09-17T23:24:22Z
18,861,547
8
2013-09-17T23:30:29Z
[ "python", "utf-8" ]
Suppose I had a ASCII file (called 'test.txt') like this: ``` A B C D X Y Z ^ EOF, no CR after the 'Z'... ``` In Python, I could read the last byte (the last character) something like this: ``` with open('test.txt', 'r') as f: f.seek(-1, os.SEEK_END) ch=f.read(1) ``` I could truncate the last 3 chara...
You can do it, but not as individual characters. Treat the file as bytes. Each UTF-8 character will consist of 1 to 4 bytes. To read the end of the file, read the last 4\*n bytes and start looking for character boundaries. The first byte of a UTF-8 character have the top bit pattern of `0` or `11`, all other bytes inb...
Python Docs Wrong About Regular Expression "\b"?
18,862,306
5
2013-09-18T01:07:22Z
18,862,488
20
2013-09-18T01:30:14Z
[ "python", "regex" ]
As a result of getting help with a question I had yesterday - [Python 2.7 - find and replace from text file, using dictionary, to new text file](http://stackoverflow.com/questions/18840640/python-2-7-find-and-replace-from-text-file-using-dictionary-to-new-text-file) - I started learning regular expressions today to und...
> I would actually expect 'foo' to print to the console since it matches the empty string at the beginning and the end of a word. Did you mean to write `' foo '`, with space on each end? It doesn't capture the spaces because `\b` matches *transitions*, gaps **between** characters, not characters themselves. --- ## S...
pytz.astimezone not accounting for daylight savings?
18,862,683
8
2013-09-18T01:54:53Z
18,862,958
14
2013-09-18T02:32:44Z
[ "python", "dst", "pytz" ]
On 2013 Jun 1 I expect the "PST8PDT" timezone to behave like GMT+7, as it is daylight savings in that timezone. However, it behaves like GMT+8: ``` >>> import pytz, datetime >>> Pacific = pytz.timezone("PST8PDT") >>> datetime.datetime(2013, 6, 1, 12, tzinfo=Pacific).astimezone(pytz.utc) datetime.datetime(2013, 6, 1, 2...
You can't assign the timezone in the `datetime` constructor, because it doesn't give the timezone object a chance to adjust for daylight savings - the date isn't accessible to it. This causes even more problems for certain parts of the world, where the name and offset of the timezone have changed over the years. From ...
How to open file using argparse?
18,862,836
14
2013-09-18T02:16:54Z
18,863,004
26
2013-09-18T02:40:10Z
[ "python", "argparse" ]
I want to open file for reading using argparse. In cmd it must look like: my\_program.py /filepath That's my try: ``` parser = argparse.ArgumentParser() parser.add_argument('file', type = file) args = parser.parse_args() ```
The type of the argument should be string (which is default anyway). So make it like this: ``` parser = argparse.ArgumentParser() parser.add_argument('filename') args = parser.parse_args() with open(args.filename) as file: # do stuff here ```
How to open file using argparse?
18,862,836
14
2013-09-18T02:16:54Z
18,863,046
78
2013-09-18T02:46:16Z
[ "python", "argparse" ]
I want to open file for reading using argparse. In cmd it must look like: my\_program.py /filepath That's my try: ``` parser = argparse.ArgumentParser() parser.add_argument('file', type = file) args = parser.parse_args() ```
Take a look at the documentation: <http://docs.python.org/2/library/argparse.html#type> ``` import argparse parser = argparse.ArgumentParser() parser.add_argument('file', type=argparse.FileType('r')) args = parser.parse_args() print args.file.readlines() ```
Non-zero arithmetic check in Python
18,862,852
2
2013-09-18T02:19:02Z
18,862,867
12
2013-09-18T02:20:45Z
[ "python", "math", "python-2.7", "command-line", "floating-point" ]
This math equation... ``` (4195835 / 3145727) * 3145727 - 4195835 ``` is supposed to equate to `0`. According to the book Software Testing (2nd Ed), > If you get anything else, you have an old Intel Pentium CPU with a > floating-point division buga software bug burned into a computer chip > and reproduced over and o...
You did integer math and not floating point math. ``` >>> (4195835 / 3145727) * 3145727 - 4195835 -1050108 >>> (4195835. / 3145727.) * 3145727. - 4195835. 0.0 ``` Note that you can get the behavior you want from integers using py3k or [PEP238](http://www.python.org/dev/peps/pep-0238/) division. ``` >>> from __future...
Non-zero arithmetic check in Python
18,862,852
2
2013-09-18T02:19:02Z
18,862,877
9
2013-09-18T02:22:44Z
[ "python", "math", "python-2.7", "command-line", "floating-point" ]
This math equation... ``` (4195835 / 3145727) * 3145727 - 4195835 ``` is supposed to equate to `0`. According to the book Software Testing (2nd Ed), > If you get anything else, you have an old Intel Pentium CPU with a > floating-point division buga software bug burned into a computer chip > and reproduced over and o...
With integer math (which is what you're using), `(4195835 / 3145727)` will give you `1.33382...` rounded down to the integer `1`. So you effectively end up with: ``` (4195835 / 3145727) * 3145727 - 4195835 = 1 * 3145727 - 4195835 = 3145727 - 4195835 = ...
Why is "import" implemented this way?
18,863,483
18
2013-09-18T03:46:05Z
18,863,528
10
2013-09-18T03:50:55Z
[ "python", "import", "module" ]
``` >>> import math >>> math.pi 3.141592653589793 >>> math.pi = 3 >>> math.pi 3 >>> import math >>> math.pi 3 ``` **Initial question: Why can't I get `math.pi` back?** I thought `import` would import all the defined variables and functions to the current scope. And if a variable name already exists in current scope, ...
A module may be imported many times. An `import` statement just loads the reference from [`sys.modules`](http://docs.python.org/3/library/sys#sys.modules). If the `import` statement also reloaded the module from disk, it would be quite slow. Modifying a module like this is very unusual and is only done under rare, docu...
Why is "import" implemented this way?
18,863,483
18
2013-09-18T03:46:05Z
18,863,573
13
2013-09-18T03:56:19Z
[ "python", "import", "module" ]
``` >>> import math >>> math.pi 3.141592653589793 >>> math.pi = 3 >>> math.pi 3 >>> import math >>> math.pi 3 ``` **Initial question: Why can't I get `math.pi` back?** I thought `import` would import all the defined variables and functions to the current scope. And if a variable name already exists in current scope, ...
Python only creates one copy of any given module. Importing a module repeatedly reuses the original. This is because if modules A and B imported C and D, which imported E and F, etc., C and D would get loaded twice, and E and F would get loaded 4 times, etc. With any but the most trivial of dependency graphs, you'd spe...
Why can functions in Python print variables in enclosing scope but cannot use them in assignment?
18,864,041
16
2013-09-18T04:46:03Z
18,864,212
23
2013-09-18T05:02:29Z
[ "python", "scope" ]
If I run the following code: ``` x = 1 class Incr: print(x) x = x + 1 print(x) print(x) ``` It prints: ``` 1 2 1 ``` Okay no problems, that's exactly what I expected. And if I do the following: ``` x = 1 class Incr: global x print(x) x = x + 1 print(x) print(x) ``` It prints: ``` ...
Classes and functions are different, variables inside a class are actually actually assigned to the class's namespace as its attributes, while inside a function the variables are just normal variables that cannot be accessed outside of it. The local variables inside a function are actually decided when the function ge...
Python: Executing multiple functions simultaneously
18,864,859
6
2013-09-18T05:57:59Z
18,865,028
13
2013-09-18T06:10:44Z
[ "python" ]
I'm trying to run two functions simultaneously in Python. I have tried the below code which uses `multiprocessing` but when I execute the code, the second function starts only after the first is done. ``` from multiprocessing import Process def func1: #does something def func2: #does something if __name__=...
You are doing it correctly. :) Try running this silly code: ``` from multiprocessing import Process import sys rocket = 0 def func1(): global rocket print 'start func1' while rocket < sys.maxint: rocket += 1 print 'end func1' def func2(): global rocket print 'start func2' while ...
Extract Values between two strings in a text file using python
18,865,058
4
2013-09-18T06:12:44Z
18,865,133
17
2013-09-18T06:17:56Z
[ "python" ]
Lets say I have a Text file with the below content ``` fdsjhgjhg fdshkjhk Start Good Morning Hello World End dashjkhjk dsfjkhk ``` Now I need to write a Python code which will read the text file and copy the contents between Start and end to another file. I wrote the following code. ``` inFile = open("data.txt") ou...
``` with open('path/to/input') as infile, open('path/to/output', 'w') as outfile: copy = False for line in infile: if line.strip() == "Start": copy = True elif line.strip() == "End": copy = False elif copy: outfile.write(line) ```
Using Python mock to spy on calls to an existing object
18,869,141
8
2013-09-18T09:55:50Z
20,130,972
11
2013-11-21T20:12:30Z
[ "python", "unit-testing", "mocking" ]
I'm using the Python mock module for tests. I would like to replace an active object with a mock, and automatically have all calls made to the mock object forwarded to the original object. I think this is called a "Spy" in standard testing terminology. At the moment I'm doing inside a test: ``` # Insert a mock replace...
I seem to have stumbled accross the solution: ``` import mock class A(object): def meth(self, a): return a a = A() ma = mock.Mock(wraps=a) ``` Seems to work OK for functions, methods and properties, but not for class or instance attributes.
Why does an object still work properly without the class
18,869,342
7
2013-09-18T10:06:24Z
18,869,377
9
2013-09-18T10:08:16Z
[ "python" ]
I'm a newbie in Python. After reading some chapters of *Python Tutorial Release 2.7.5*, I'm confused about Python scopes and namespaces. This question may be duplicated because I don't know what to search for. I created a class and an instance. Then I deleted the class using `del`. But the instance still works properl...
Python is a [garbage collected](http://en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29) language. When you do `del MyClass`, you do not actually delete the 'class object' (classes are objects too), but you only remove the 'name' `MyClass` from the current namespace, which is some sort of reference to th...
Supervisord - Start a backgroup python script
18,869,925
3
2013-09-18T10:35:07Z
20,740,860
11
2013-12-23T09:47:24Z
[ "python", "bash", "supervisord" ]
I create bash to run python script `start_queue.sh` content of start\_queue.sh ``` python /tmp/my_python_script.py & ``` It's work when I run it in terminal. But I want to manage it using supervisord since I have few django website already manage by supervisord. But I just get the error when start ``` supervisor: ...
Add #!/bin/sh at the beginning of script.
In OpenCV (Python), why am I getting 3 channel images from a grayscale image?
18,870,603
12
2013-09-18T11:07:10Z
18,871,394
12
2013-09-18T11:46:39Z
[ "python", "opencv", "image-processing", "jpeg", "grayscale" ]
I am using Python (2.7) and bindings for OpenCV 2.4.6 on Ubuntu 12.04 I load an image ``` image = cv2.imread('image.jpg') ``` I then check the shape of the image array ``` print image.shape ``` I get (480, 640, 3), which I expect for a 640x480 colour image. I then convert the image to grayscale and check t...
Your code is correct, it seems that `cv2.imread` load an image with three channels unless `CV_LOAD_IMAGE_GRAYSCALE` is set. ``` >>> import cv2 >>> image = cv2.imread('foo.jpg') >>> print image.shape (184, 300, 3) >>> gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) >>> print gray_image.shape (184, 300) >>> cv2....
ImportError: No module named pjsip
18,870,809
2
2013-09-18T11:17:42Z
18,870,973
8
2013-09-18T11:25:52Z
[ "python", "linux", "makefile", "debian", "pjsip" ]
I'm currently trying to set up pjsip and it's python wrapper for a small sip project. I followed the instructions here: <http://trac.pjsip.org/repos/wiki/Python_SIP/Build_Install> which basically breaks down to: 1. Check out pjsip from svn 2. Compile pjsip 3. Compile python module All the commands needed were ``` $ ...
You probably need do: ``` sudo make install ``` or possibly: ``` sudo python setup.py install ``` The best bet would be to read any README files you can find in the download.
How to custom-sort a list of dict to use in json.dumps
18,871,217
7
2013-09-18T11:37:54Z
18,871,434
11
2013-09-18T11:48:24Z
[ "python", "json", "list", "sorting", "dictionary" ]
I have a list similar to ``` allsites = [ { 'A5': 'G', 'A10': 'G', 'site': 'example1.com', 'A1': 'G' }, { 'A5': 'R', 'A10': 'Y', 'site': 'example2.com', 'A1': 'G' } ] ``` Which I use in a `json.dumps`: ``` data = { 'Author':"joe", ...
Since python dicts are unordered collections, use [`collections.OrderedDict`](http://docs.python.org/2/library/collections.html#collections.OrderedDict) with a custom sort: ``` from collections import OrderedDict import json allsites = [ { 'A5': 'G', 'A10': 'G', 'site': 'example1.com', ...
check if two words are related to each other
18,871,706
3
2013-09-18T12:00:39Z
18,872,777
8
2013-09-18T12:52:01Z
[ "python", "python-2.7", "nlp", "nltk" ]
I have two lists: one, the interests of the user; and second, the keywords about a book. I want to recommend the book to the user based on his given interests list. I am using the `SequenceMatcher` class of Python library `difflib` to match similar words like "game", "games", "gaming", "gamer", etc. The `ratio` functio...
Firstly **a word can have many senses** and when you try to find similar words you might need some word sense disambiguation <http://en.wikipedia.org/wiki/Word-sense_disambiguation>. Given a pair of words, if we take the most similar pair of senses as the gauge of whether two words are similar, we can try this: ``` f...
Merging a list with a list of lists
18,872,717
5
2013-09-18T12:49:13Z
18,872,770
29
2013-09-18T12:51:41Z
[ "python", "python-2.7" ]
I have a list of lists: ``` [['John', 'Sergeant '], ['Jack', 'Commander '], ['Jill', 'Captain ']] ``` How can I merge it with a single list like: ``` ['800','854','453'] ``` So that the end result looks like: ``` [['John', 'Sergeant', '800'], ['Jack', 'Commander', '854'], ['Jill', 'Captain', '453']] ``` Initially...
``` a = [['John', 'Sergeant '], ['Jack', 'Commander '], ['Jill', 'Captain ']] b = ['800', '854', '453'] c = [x+[y] for x,y in zip(a,b)] print c ``` Result: ``` [['John', 'Sergeant ', '800'], ['Jack', 'Commander ', '854'], ['Jill', 'Captain ', '453']] ```
Getting task_id inside a Celery task
18,872,854
7
2013-09-18T12:55:12Z
18,873,036
10
2013-09-18T13:03:39Z
[ "python", "object", "celery" ]
This is probably a stupid question but its got me stumped coming from a Ruby background. I have an object that looks like this when I try to print it. ``` print celery.AsyncResult.task_id >>><property object at 0x10c383838> ``` I was expecting the actual value of the task\_id property to be printed here. How do I ge...
You are accessing the [`property`](http://docs.python.org/2/library/functions.html#property) from the class, while `task_id` is a property of *instances* of `AsynchResult`. To obtain the value of `task_id` you first have to create an instance of that class, afterwards accessing `asynch_result_instance.task_id` will re...
Pretty JSON Formatting in IPython Notebook
18,873,066
9
2013-09-18T13:05:04Z
18,873,131
9
2013-09-18T13:08:02Z
[ "python", "json", "ipython-notebook" ]
Is there an existing way to get `json.dumps()` output to appear as "pretty" formatted JSON inside ipython notebook?
`json.dumps` has an `indent` argument, printing the result should be enough: ``` print(json.dumps(obj, indent=2)) ```
How to plot pcolor colorbar in a different subplot - matplotlib
18,874,135
7
2013-09-18T13:53:58Z
18,874,357
10
2013-09-18T14:03:16Z
[ "python", "matplotlib", "plot", "subplot", "colorbar" ]
I am trying to split my plots in different subplots.. What I want to achieve is to put a colorbar for a subplot in a different subplot. Right now I am using: ``` # first graph axes = plt.subplot2grid((4, 2), (0, 0), rowspan=3) pc = plt.pcolor(df1, cmap='jet') # second graph axes = plt.subplot2grid((4, 2), (3, 0)) plt...
`colorbar()` accepts a `cax` keyword argument that allows you to specify the `axes` object that the colorbar will be drawn on. In your case, you would change your colorbar call to the following: ``` # colorbar axes = plt.subplot2grid((4, 2), (0, 1), rowspan=3) plt.colorbar(pc, cax=axes) ``` This will take up the who...
"No module named abc_base"
18,875,511
3
2013-09-18T14:50:22Z
18,876,638
12
2013-09-18T15:39:55Z
[ "python", "django", "python-2.x" ]
I'm trying to implement an abstract class in python (actually in a django app) and am running up against this madness: ``` >python concreteChildClass.py Traceback (most recent call last): File"concreteChildClass.py, line 1, in <module> from abc_base import AbstractBaseClass ImportError: No module named abc...
I'm assuming that you're following [this](http://pymotw.com/2/abc/) tutorial? The mistake that you've made (and to be fair, the tutorial is unclear on this), is assuming that `abc_base` is the name of some module that lives inside the standard library. Rather, it just happens to be the name of the very first python f...
Comparing two numpy arrays of different length
18,875,970
6
2013-09-18T15:09:43Z
18,876,279
9
2013-09-18T15:23:03Z
[ "python", "numpy" ]
I need to find the indices of the first less than or equal occurrence of elements of one array in another array. One way that works is this: ``` import numpy a = numpy.array([10,7,2,0]) b = numpy.array([10,9,8,7,6,5,4,3,2,1]) indices = [numpy.where(a<=x)[0][0] for x in b] ``` *indices* has the value [0, 1, 1, 1, 2, 2...
This may be a special case, but you should be able to use numpy [digitize](http://docs.scipy.org/doc/numpy/reference/generated/numpy.digitize.html). The caveat here is the bins must be monotonically decreasing or increasing. ``` >>> import numpy >>> a = numpy.array([10,7,2,0]) >>> b = numpy.array([10,9,8,7,6,5,4,3,2,1...
How to avoid memory leak with shared_ptr and SWIG
18,878,179
6
2013-09-18T17:03:28Z
18,904,285
8
2013-09-19T20:25:57Z
[ "c++", "python", "file-io", "memory-leaks", "swig" ]
I'm trying to use `boost::shared_ptr`'s to allow for me to use c++ file I/O stream objects in my python script. However, the generated wrapper warns me that it is leaking memory. Here's a minimal `.i` file exhibiting the problem: ``` %module ptrtest %include "boost_shared_ptr.i" %include "std_string.i" %shared_ptr(...
Your example is missing two parts to get the destructor to run: 1. Since SWIG knows absolutely nothing about `std::ofstream` the default behaviour is to do nothing beyond pass an opaque handle around. See [another answer of mine](http://stackoverflow.com/a/13593596/168175) for a further discussion of this. The fix...
Pandas: Reindex Unsorts Dataframe
18,878,308
10
2013-09-18T17:11:03Z
18,878,413
25
2013-09-18T17:16:30Z
[ "python", "sorting", "pandas", "reindex" ]
I'm having some trouble sorting and then resetting my Index in Pandas: ``` dfm = dfm.sort(['delt'],ascending=False) dfm = dfm.reindex(index=range(1,len(dfm))) ``` The dataframe returns unsorted after I reindex. My ultimate goal is to have a sorted dataframe with index numbers from 1 --> len(dfm) so if there's a bette...
Instead of reindexing, just change the actual index: ``` dfm.index = range(1,len(dfm) + 1) ``` Then that wont change the order, just the index
How can I plot ca. 20 million points as a scatterplot?
18,879,267
4
2013-09-18T18:06:33Z
18,880,782
12
2013-09-18T19:33:57Z
[ "python", "numpy", "matplotlib" ]
I am trying to create a scatterplot with matplotlib that consists of ca. ca. 20 million data points. Even after setting the alpha value to its lowest before ending up with no visible data at all the result is just a completely black plot. ``` plt.scatter(timedPlotData, plotData, alpha=0.01, marker='.') ``` The x-axis...
There's more than one way to do this. A lot of folks have suggested a heatmap/kernel-density-estimate/2d-histogram. @Bucky suggesed using a moving average. In addition, you can fill between a moving min and moving max, and plot the moving mean over the top. I often call this a "chunkplot", but that's a terrible name. T...