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
Sudoku Checker in Python
17,605,898
3
2013-07-12T00:50:12Z
17,606,526
8
2013-07-12T02:20:09Z
[ "python", "sudoku" ]
I am trying to create a sudoku checker in python: ``` ill_formed = [[5,3,4,6,7,8,9,1,2], [6,7,2,1,9,5,3,4,8], [1,9,8,3,4,2,5,6,7], [8,5,9,7,6,1,4,2,3], [4,2,6,8,5,3,7,9], # <--- [7,1,3,9,2,4,8,5,6], [9,6,1,5,3,7,2,8,4], ...
Remember, you're not searching for duplicates -- merely nonzero duplicates. Summing a set works for this. You can also check the legality of the row/column at the same time: ``` def sudoku_ok(line): return (len(line) == 9 and sum(line) == sum(set(line))) def check_sudoku(grid): bad_rows = [row for row in grid...
ssl SSLError outines:SSL_CTX_use_certificate_chain_file:PEM lib
17,605,908
4
2013-07-12T00:51:55Z
17,647,496
9
2013-07-15T05:44:03Z
[ "python", "ssl", "openssl", "flask", "apple-push-notifications" ]
While trying to make a push test to my app I'm getting the following error: ``` Traceback (most recent call last): File "test.py", line 16, in <module> wrapper.notify() File "/usr/local/lib/python2.7/dist-packages/APNSWrapper-0.6.1-py2.7.egg/APNSWrapper/notifications.py", line 194, in notify apnsConnection...
I've not run across that specific error before in Python, but it looks very much like OpenSSL choked on your .pem file - I'd speculate that the .pem file you are using isn't the right format for what Python asked OpenSSL to do. I've opened one of my known good .pem files, replaced the my personally identifying informat...
sorting a list in python
17,608,210
4
2013-07-12T05:49:51Z
17,608,338
8
2013-07-12T05:59:02Z
[ "python", "sorting" ]
My aim is to sort a list of strings where words have to be sorted alphabetically.Except words starting with "s" should be at the start of the list (they should be sorted as well), followed by the other words. The below function does that for me. ``` def mysort(words): mylist1 = sorted([i for i in words if i[:1] =...
Could do it in one line like ``` sorted(words, key=lambda x: 'a'+x if x[:1] == 's' else 'b'+x) ``` or alternatively: ``` sorted(words, key=lambda x: 'a'+x if x.startswith('s') else 'b'+x) ``` (More readable.) sorted() takes a keyword argument 'key' which is used to "translate" the values in the list before compari...
Reverse Indexing in Python?
17,610,096
5
2013-07-12T07:51:56Z
17,610,131
7
2013-07-12T07:53:30Z
[ "python" ]
I know that **a[end:start:-1]** slices a list in a reverse order. **For example** ``` a = range(20) print a[15:10:-1] # prints [15, ..., 11] print a[15:0:-1] # prints [15, ..., 1] ``` but you cannot get to the first element (0 in the example). It seems that -1 is a special value. ``` print a[15:-1:-1] # prints [] `...
Omit the end index: ``` print a[15::-1] ```
Reverse Indexing in Python?
17,610,096
5
2013-07-12T07:51:56Z
17,610,461
7
2013-07-12T08:13:59Z
[ "python" ]
I know that **a[end:start:-1]** slices a list in a reverse order. **For example** ``` a = range(20) print a[15:10:-1] # prints [15, ..., 11] print a[15:0:-1] # prints [15, ..., 1] ``` but you cannot get to the first element (0 in the example). It seems that -1 is a special value. ``` print a[15:-1:-1] # prints [] `...
You can assign your variable to `None`: ``` >>> a = range(20) >>> a[15:None:-1] [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] >>> ```
Python string.format() percentage to one decimal place
17,610,698
17
2013-07-12T08:30:01Z
17,610,905
12
2013-07-12T08:44:07Z
[ "python", "floating-point", "string.format" ]
In the example below I would like to format to 1 decimal place but python seems to like rounding up the number, is there a way to make it not round the number up? ``` >>> '{:.1%}'.format(0.9995) '100.0%' >>> '{:.2%}'.format(0.9995) '99.95%' ``` Thanks! :)
If you want to round down *always* (instead of rounding to the nearest precision), then do so, explicitly, with the [`math.floor()` function](http://docs.python.org/2/library/math.html#math.floor): ``` from math import floor def floored_percentage(val, digits): val *= 10 ** (digits + 2) return '{1:.{0}f}%'.fo...
Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4
17,610,732
61
2013-07-12T08:32:46Z
17,610,791
13
2013-07-12T08:37:25Z
[ "python", "django", "uwsgi" ]
I have a error message on django 1.4: > dictionary update sequence element #0 has length 1; 2 is required [EDIT] It happened when I tried when using template tag like: `{% for v in values %}: ``` dictionary update sequence element #0 has length 1; 2 is required Request Method: GET Request URL: ... Django Ve...
Error in your question is raised when you try something like following: ``` >>> a_dictionary = {} >>> a_dictionary.update([[1]]) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: dictionary update sequence element #0 has length 1; 2 is required ``` *It's hard to tell where is the ca...
Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4
17,610,732
61
2013-07-12T08:32:46Z
19,670,235
178
2013-10-29T22:17:48Z
[ "python", "django", "uwsgi" ]
I have a error message on django 1.4: > dictionary update sequence element #0 has length 1; 2 is required [EDIT] It happened when I tried when using template tag like: `{% for v in values %}: ``` dictionary update sequence element #0 has length 1; 2 is required Request Method: GET Request URL: ... Django Ve...
Just ran into this problem. I don't know if it's the same thing that hit your code, but for me the root cause was because I forgot to put `name=` on the last argument of the `url` function call. For instance, the following throws the error from the question: ``` url(r'^foo/(?P<bar>[A-Za-z]+)/$', FooBar.as_view(), 'fo...
Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4
17,610,732
61
2013-07-12T08:32:46Z
20,587,088
8
2013-12-14T19:07:14Z
[ "python", "django", "uwsgi" ]
I have a error message on django 1.4: > dictionary update sequence element #0 has length 1; 2 is required [EDIT] It happened when I tried when using template tag like: `{% for v in values %}: ``` dictionary update sequence element #0 has length 1; 2 is required Request Method: GET Request URL: ... Django Ve...
Here is the reproduced error. ``` >>> d = {} >>> d.update([(1,)]) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: dictionary update sequence element #0 has length 1; 2 is required >>> >>> d {} >>> >>> d.update([(1, 2)]) >>> d {1: 2} >>> >>> d.update('hello_some_string') Tracebac...
Why is my python output delayed to the end of the program?
17,610,870
3
2013-07-12T08:41:41Z
17,610,891
7
2013-07-12T08:43:11Z
[ "python", "delay", "stdout" ]
I've got an extremely simple application: ``` import sys from time import sleep for i in range(3): sys.stdout.write('.') sleep(1) print('Welcome!') ``` I expect it to print out a dot every second (3 times), after which it should display "Welcome!". Unfortunately, it simply waits three seconds, and then prin...
It's because `sys.stdout` is buffered. Use `flush`: ``` import sys from time import sleep for i in range(3): sys.stdout.write('.') sys.stdout.flush() sleep(1) print('Welcome!') ```
BeautifulSoup: <div class <span class></span><span class>TEXT I WANT</span>
17,613,606
2
2013-07-12T11:10:13Z
17,613,662
8
2013-07-12T11:13:21Z
[ "python" ]
I am trying to extract the string enclosed by the span with id="titleDescription" using BeautifulSoup. ``` <div class="itemText"> <div class="wrapper"> <span class="itemPromo">Customer Choice Award Winner</span> <a href="http://www.newegg.com/Product/Product.aspx?Item=N82E16819116501" title="View D...
``` spans = soup.find_all('span', attrs={'id':'titleDescriptionID'}) for span in spans: print span.string ``` In your code, `wrapper_href.descendants` contains at least 4 elements, 2 span tags and 2 string enclosed by the 2 span tags. It searches its children recursively.
Removes spaces from a string
17,613,936
3
2013-07-12T11:27:37Z
17,613,982
7
2013-07-12T11:30:27Z
[ "python", "string" ]
I can't, and I can't figure out what's wrong. The lists I'm trying to strip of spaces are like this: ``` ['L500', ' ', '622651 ', '2007', ' 452295.00', ' 7420', ' 0'] ``` but with spaces inbetween. I've tried `lstrip`, `rstrip`, `regex`, `split`, `join`, `replace`, and nothing works. The list doesn't...
Strings in python (and many other languages) are immutable. That means that when you do operations on a string, you get back a new instance of that string, instead of changing existing items. To do what you want, you have to reasign the items in the list. ``` for index, item in enumerate(row): row[index] = item.st...
try except unnecessary step
17,614,818
4
2013-07-12T12:21:58Z
17,614,841
11
2013-07-12T12:23:20Z
[ "python", "performance", "try-except" ]
Is it always safe to use hello2 instead of hello1 ? ``` def hello1(): try: aaa = foo() return aaa except baz: return None def hello2(): try: return foo() except baz: return None ```
Yes, it is. Assigning first then returning makes no difference when it comes to catching exceptions. The assignment to `aaa` is entirely redundant.
What is the best approach in python: multiple OR or IN in if statement?
17,615,020
6
2013-07-12T12:33:08Z
17,615,033
12
2013-07-12T12:33:55Z
[ "python", "performance", "python-2.7", "design-patterns" ]
What is the best approach in python: *multiple OR* or *IN* in if statement? Considering performance and best pratices. ``` if cond == '1' or cond == '2' or cond == '3' or cond == '4' (etc...) : ``` OR ``` if cond in ['1','2','3','4']: ``` Thank you.
The best approach is to use a *set*: ``` if cond in {'1','2','3','4'}: ``` as membership testing in a set is O(1) (constant cost). The other two approaches are equal in complexity; merely a difference in constant costs. Both the `in` test on a list and the `or` chain short-circuit; terminate as soon as a match is fo...
How to convert 'binary string' to normal string in Python3?
17,615,414
58
2013-07-12T12:55:06Z
17,615,424
78
2013-07-12T12:55:43Z
[ "python", "string", "python-3.x", "binary" ]
For example, I have a string like this(return value of `subprocess.check_output`): ``` >>> b'a string' b'a string' ``` Whatever I did to it, it is always printed with the annoying `b'` before the string: ``` >>> print(b'a string') b'a string' >>> print(str(b'a string')) b'a string' ``` Does anyone have any ideas ab...
Decode it. ``` >>> b'a string'.decode('ascii') 'a string' ``` To get bytes from string, encode it. ``` >>> 'a string'.encode('ascii') b'a string' ```
PyQt - How to set QComboBox in a table view using QItemDelegate
17,615,997
3
2013-07-12T13:26:36Z
17,617,147
14
2013-07-12T14:21:37Z
[ "python", "qt", "pyqt" ]
I am trying to display a combo box in my table, so that I can set the selected index from the table model, as with the other cells in the table. I have pieced this together from other examples but still cannot understand how the interaction works to set the selected index of the QComboBox. This is the simplest example...
You're using `paint` method incorrectly. It should be used when you want to change displaying behavior of the view. Also creating new widget each time you want to paint it is very expensive. But you want to change editing behavior so you need to change entire logic of your program. See the [fixed code](https://gist.gi...
Python command line: ignore indentation
17,616,044
25
2013-07-12T13:28:17Z
17,616,148
45
2013-07-12T13:32:46Z
[ "python", "testing", "text-editor", "indentation", "copy-paste" ]
*I am new to Python.* **In short:** During scripting I continuously want to test small bits and pieces of my programs by copying/pasting some line(s) of code from my text editor to the command line Python interpreter. When these lines are indented (for example because they are part of a function), I'd like the interp...
In such case, I use following trick (prepend `if 1:`): ``` >>> if 1: ... print 1 ... 1 ```
Python command line: ignore indentation
17,616,044
25
2013-07-12T13:28:17Z
17,616,166
33
2013-07-12T13:33:33Z
[ "python", "testing", "text-editor", "indentation", "copy-paste" ]
*I am new to Python.* **In short:** During scripting I continuously want to test small bits and pieces of my programs by copying/pasting some line(s) of code from my text editor to the command line Python interpreter. When these lines are indented (for example because they are part of a function), I'd like the interp...
The ipython `%cpaste` function will allow you to paste indented code and work properly: ``` In [5]: %cpaste Pasting code; enter '--' alone on the line to stop or use Ctrl-D. : print "This is my function called with value 1." : print "Done." :^D<EOF> This is my function called with value 1. Done. ```
Divide string by line break or period with Python regular expressions
17,618,149
4
2013-07-12T15:09:05Z
17,618,181
7
2013-07-12T15:10:24Z
[ "python", "regex", "string", "split" ]
I have a string: ``` """Hello. It's good to meet you. My name is Bob.""" ``` I'm trying to find the best way to split this into a list divided by periods and linebreaks: ``` ["Hello", "It's good to meet you", "My name is Bob"] ``` I'm pretty sure I should use regular expressions, but, having no experience with them...
You don't need regex. ``` >>> txt = """Hello. It's good to meet you. ... My name is Bob.""" >>> txt.split('.') ['Hello', " It's good to meet you", '\nMy name is Bob', ''] >>> [x for x in map(str.strip, txt.split('.')) if x] ['Hello', "It's good to meet you", 'My name is Bob'] ```
Can't install Beautifulsoup ("bs4 does not exist")
17,618,589
6
2013-07-12T15:34:05Z
17,645,074
10
2013-07-15T00:14:47Z
[ "python", "beautifulsoup" ]
I'm struggling to get BeautifulSoup installed on Windows. So far, I have: 1. downloaded BeautifulSoup to "My Downloads". 2. unzipped/ extracted it in the downloads folder. 3. At the command prompt, I ran: ``` C:<path to python33> "C:path to beautiful soup\setup.py" install ``` The process generated the mess...
You need to be in the directory containing `setup.py` to run it. Make sure your working directory is correct.
How to sort pandas data frame using values from several columns?
17,618,981
17
2013-07-12T15:54:28Z
17,619,032
15
2013-07-12T15:57:02Z
[ "python", "sorting", "dataframe", "pandas" ]
I have the following data frame: ``` df = pandas.DataFrame([{'c1':3,'c2':10},{'c1':2, 'c2':30},{'c1':1,'c2':20},{'c1':2,'c2':15},{'c1':2,'c2':100}]) ``` Or, in human readable form: ``` c1 c2 0 3 10 1 2 30 2 1 20 3 2 15 4 2 100 ``` The following sorting-command works as expected: ``` df.sort...
Your code works for me. ``` >>> import pandas >>> df = pandas.DataFrame([{'c1':3,'c2':10},{'c1':2, 'c2':30},{'c1':1,'c2':20},{'c1':2,'c2':15},{'c1':2,'c2':100}]) >>> df.sort(['c1','c2'], ascending=[False,True]) c1 c2 0 3 10 3 2 15 1 2 30 4 2 100 2 1 20 ``` --- Did you paste as is? ``` >>> df...
How do I combine two numpy arrays element wise in python?
17,619,415
8
2013-07-12T16:18:14Z
17,620,056
7
2013-07-12T16:53:31Z
[ "python", "arrays", "python-2.7", "numpy" ]
I have two numpy arrays: ``` A = np.array([1, 3, 5, 7]) B = np.array([2, 4, 6, 8]) ``` and I want to get the following from combining the two: ``` C = [1, 2, 3, 4, 5, 6, 7, 8] ``` I'm able to get something close by using `zip`, but not quite what I'm looking for: ``` >>> zip(A, B) [(1, 2), (3, 4), (5, 6), (7, 8)] ...
Use [`np.insert`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.insert.html): ``` >>> A = np.array([1, 3, 5, 7]) >>> B = np.array([2, 4, 6, 8]) >>> np.insert(B, np.arange(len(A)), A) array([1, 2, 3, 4, 5, 6, 7, 8]) ```
iframe not rendering in ipython-notebook
17,619,964
2
2013-07-12T16:48:54Z
22,512,364
9
2014-03-19T16:34:20Z
[ "python", "iframe", "ipython", "ipython-notebook" ]
The following iframe will not render in an ipython-notebook ``` from IPython.display import HTML HTML('<iframe src=http://stackoverflow.com width=700 height=350></iframe>') ``` but, this one will render (note, .com versus .org) ``` from IPython.display import HTML HTML('<iframe src=http://stackoverflow.org width=700...
IPython now supports IFrame directly: ``` from IPython.display import IFrame IFrame('http://stackoverflow.org', width=700, height=350) ``` For more on IPython embeds check out this [IPython notebook.](http://nbviewer.ipython.org/github/ipython/ipython/blob/master/examples/notebooks/Part%205%20-%20Rich%20Display%20Sys...
How to install MySQLdb in Python 2.6 CentOS
17,620,483
3
2013-07-12T17:18:15Z
17,620,670
13
2013-07-12T17:29:18Z
[ "python", "centos", "mysql-python" ]
I am getting this message when I use `yum install mysql-python` to install MySQLdb. ``` Loaded plugins: fastestmirror Loading mirror speeds from cached hostfile * base: mirrors.sin3.sg.voxel.net * extras: mirrors.sin3.sg.voxel.net * updates: mirrors.sin3.sg.voxel.net base ...
You can install it via `yum`, it is case sensitive: ``` [root@localhost ~]# yum install MySQL-python Loaded plugins: fastestmirror Loading mirror speeds from cached hostfile * base: mirrors.nfsi.pt * extras: mirrors.nfsi.pt * updates: mirrors.nfsi.pt Setting up Install Process Resolving Dependencies --> Running tra...
making an array of sets in python
17,620,537
2
2013-07-12T17:21:13Z
17,620,566
9
2013-07-12T17:22:58Z
[ "python", "set" ]
I am having trouble with a list of sets and I think it is because I initialized it wrong, is this a valid way to initialize and add to a list of 5000 sets? ``` sets = [set()]*5000 i = 0 for each in f: line = each.split() if (some statement): i = line[1] else: sets[i].add(line[0]) ``` any ...
You are storing a copy of reference to a single set in each of your list indices. So, modifying one will change the others too. To create a list of multiple sets, you can use list comprehension: ``` sets = [set() for _ in xrange(5000)] ```
Django: Access Admin User in Python Shell
17,620,783
3
2013-07-12T17:35:07Z
17,620,817
8
2013-07-12T17:37:47Z
[ "python", "django", "user", "profile" ]
I am using Django Userena, but when trying to login to the django admin screen userena is creating a fuss: `Profile matching query does not exist`. How can I create a profile for the admin user using the shell? Here is my Profile model, but I don't know how to access the key for the admin user to create a Profile obje...
You can do something like this: ``` $ ./manage.py shell > from django.contrib.auth.models import User > from <profile_package>.models import Profile > user = User.objects.get(username='<admin_user_name>') > profile = Profile(user=user) > profile.save() ```
Run bash script on `cd` command
17,620,875
3
2013-07-12T17:41:03Z
17,620,935
8
2013-07-12T17:44:55Z
[ "python", "ruby", "linux" ]
I'm python developer and most frequently I use [buildout](http://www.buildout.org/en/latest/) for managing my projects. In this case I dont ever need to run any command to activate my dependencies environment. However, sometime I use virtualenv when buildout is to complicated for this particular case. Recently I star...
One feature of Unix shells is that they let you create *shell functions*, which are much like functions in other languages; they are essentially named groups of commands. For example, you can write a function named `mycd` that first runs `cd`, and then runs other commands: ``` function mycd () { cd "$@" if ......
Python ternary operator can't return multiple values?
17,622,853
6
2013-07-12T19:43:35Z
17,622,882
11
2013-07-12T19:45:07Z
[ "python" ]
I know it's frowned upon by some, but I like using Python's ternary operator, as it makes simple `if`/`else` statements cleaner to read (I think). In any event, I've found that I can't do this: ``` >>> a,b = 1,2 if True else 0,0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: too m...
It's parsing that as three values, which are: ``` 1, 2 if True else 0, 0 ``` Therefore it becomes three values (`1,2,0`), which is more than the two values on the left side of the expression. Try: ``` a,b = (1,2) if True else (0,0) ```
numpy convert row vector to column vector
17,622,905
16
2013-07-12T19:46:50Z
17,623,020
13
2013-07-12T19:55:56Z
[ "python", "arrays", "numpy", "matrix" ]
``` matrix1 = np.array([[1,2,3],[4,5,6]]) vector1 = matrix1[:,0] # this should have shape (2,1) but actually has (2,) matrix2 = np.array([[2,3],[5,6]]) np.hstack((vector1, matrix2)) ValueError: all the input arrays must have same number of dimensions ``` The problem is that when I select the first column of matrix1 a...
Here are three other options: 1. You can tidy up your solution a bit by allowing the row dimension of the vector to be set implicitly: ``` np.hstack((vector1.reshape(-1, 1), matrix2)) ``` 2. You can index with `np.newaxis` (or equivalently, `None`) to insert a new axis of size 1: ``` np.hstack((vector...
numpy convert row vector to column vector
17,622,905
16
2013-07-12T19:46:50Z
17,623,029
20
2013-07-12T19:56:23Z
[ "python", "arrays", "numpy", "matrix" ]
``` matrix1 = np.array([[1,2,3],[4,5,6]]) vector1 = matrix1[:,0] # this should have shape (2,1) but actually has (2,) matrix2 = np.array([[2,3],[5,6]]) np.hstack((vector1, matrix2)) ValueError: all the input arrays must have same number of dimensions ``` The problem is that when I select the first column of matrix1 a...
The easier way is ``` vector1 = matrix1[:,0:1] ``` For the reason, let me refer you to [another answer of mine](http://stackoverflow.com/a/15165416/56541): > When you write something like `a[4]`, that's accessing the fifth element of the array, not giving you a view of some section of the original array. So for inst...
Django SimpleLazyObject
17,623,234
5
2013-07-12T20:11:06Z
17,623,278
12
2013-07-12T20:13:18Z
[ "python", "django", "django-templates", "django-views" ]
When I try to submit, I get a TypeError: > int() argument must be a string or a number, not 'SimpleLazyObject' My views.py: ``` def bookmark_save_page(request): if request.method == 'POST': form = BookmarkSaveForm(request.POST) if form.is_valid(): # Create or get link. lin...
`request.user`, by default is of type `SimpleLazyObject`. To resolve it, ``` bookmark, created = Bookmark.objects.get_or_create( user = request.user, link = link ) ``` should be ``` bookmark, created = Bookmark.objects.get_or_create( user = request.user.id, ...
Can I stream a Python pickle list, tuple, or other iterable data type?
17,623,523
7
2013-07-12T20:30:07Z
17,623,631
8
2013-07-12T20:37:28Z
[ "python", "streaming", "ipython", "pickle" ]
I work with comma/tab-separated data files often that might look like this: ``` key1,1,2.02,hello,4 key2,3,4.01,goodbye,6 ... ``` I might read and pre-process this in Python into a list of lists, like this: ``` [ [ key1, 1, 2.02, 'hello', 4 ], [ key2, 3, 4.01, 'goodbye', 6 ] ] ``` Sometimes, I like saving this list...
This would work. What is does however is unpickle one object from the file, and then print the rest of the file's content to `stdout` What you could do is something like: ``` import cPickle with open( 'big_pickled_list.pkl' ) as p: try: while True: print cPickle.load(p) except EOFError: ...
Can't import MongoClient
17,624,416
12
2013-07-12T21:38:24Z
17,624,552
22
2013-07-12T21:49:00Z
[ "python", "mongodb", "ubuntu", "python-2.7" ]
I am unable to do this: ``` from pymongo import MongoClient ``` I get: ``` >>> import pymongo >>> from pymongo import MongoClient Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: cannot import name MongoClient >>> ``` I am able to `import pymongo` without issues. I am running `...
That package is probably outdated or broken. Run `sudo apt-get purge python-pymongo`, then `sudo apt-get install python-pip`, then finally `sudo pip install pymongo`.
Get type of data stored in a string in python
17,624,624
5
2013-07-12T21:54:44Z
17,624,700
7
2013-07-12T22:01:23Z
[ "python" ]
Is there any way to understand what data type that a string holds... The question is of little logic but see below cases ``` varname = '444' somefunc(varname) => int varname = 'somestring' somefunc(varname) => String varname = '1.2323' somefunc(varname) => float ``` My Case: I get a mixed data in a list but they're...
You can use ast.literal\_eval() and type(): ``` import ast stringy_value = '333' try: the_type = type(ast.literal_eval(stringy_value)) except: the_type = type('string') ```
Get type of data stored in a string in python
17,624,624
5
2013-07-12T21:54:44Z
17,624,733
14
2013-07-12T22:04:14Z
[ "python" ]
Is there any way to understand what data type that a string holds... The question is of little logic but see below cases ``` varname = '444' somefunc(varname) => int varname = 'somestring' somefunc(varname) => String varname = '1.2323' somefunc(varname) => float ``` My Case: I get a mixed data in a list but they're...
``` from ast import literal_eval def str_to_type(s): try: k=literal_eval(s) return type(k) except: return type(s) l = ['444', '1.2', 'foo', '[1,2]', '[1'] for v in l: print str_to_type(v) ``` *Output* ``` <type 'int'> <type 'float'> <type 'str'> <type 'list'> <type 'str'> ```
What is the best way to sort this list?
17,624,754
2
2013-07-12T22:06:08Z
17,624,820
8
2013-07-12T22:12:06Z
[ "python", "list", "sorting", "sorted" ]
I have the following list: ``` my_list = ['name.13','name.1', 'name.2','name.4', 'name.32'] ``` And I would like sort the list and print it out in order, like this ``` name.1 name.2 name.4 name.13 name.32 ``` What I have tried so far is: ``` print sorted(my_list) name.1 name.13 name.2 name.32 name.4 ``` The sort...
You could try it similarly to [this](http://stackoverflow.com/a/2669523/2280602) answer: ``` >>> my_list = ['name.13','name.1', 'name.2','name.4', 'name.32'] >>> sorted(my_list, key=lambda a: (int(a.split('.')[1]))) ['name.1', 'name.2', 'name.4', 'name.13', 'name.32'] ``` Or with tuples: ``` >>> tuple_list = [('i','...
Is it possible to change a function's default parameters in Python?
17,625,695
7
2013-07-13T00:05:17Z
17,625,730
18
2013-07-13T00:11:10Z
[ "python", "function" ]
In Python, is it possible to redefine the default parameters of a function at runtime? I defined a function with 3 parameters here: ``` def multiplyNumbers(x,y,z): return x*y*z print(multiplyNumbers(x=2,y=3,z=3)) ``` Next, I tried (unsuccessfully) to set the default parameter value for y, and then I tried calli...
Just use [functools.partial](http://docs.python.org/2/library/functools.html#functools.partial) ``` multiplyNumbers = functools.partial(multiplyNumbers, y = 42) ``` One problem here: you will not be able to call it as `multiplyNumbers(5, 7, 9);` you should manually say `y=7` If you need to remove default arguments ...
Remove Python UserWarning
17,626,694
31
2013-07-13T03:28:10Z
17,626,702
7
2013-07-13T03:30:01Z
[ "python" ]
I just finished installing my `MySQLdb` package for Python 2.6, and now when I import it using `import MySQLdb`, a user warning appear will appear ``` /usr/lib/python2.6/site-packages/setuptools-0.8-py2.6.egg/pkg_resources.py:1054: UserWarning: /home/sgpromot/.python-eggs is writable by group/others and vulnerable to...
You can suppress warnings using the [`-W ignore`](http://docs.python.org/2/using/cmdline.html#cmdoption-W): ``` python -W ignore yourscript.py ``` [If you want to supress warnings in your script (quote from docs):](http://docs.python.org/2/library/warnings.html#temporarily-suppressing-warnings) > If you are using co...
Remove Python UserWarning
17,626,694
31
2013-07-13T03:28:10Z
17,626,733
68
2013-07-13T03:35:54Z
[ "python" ]
I just finished installing my `MySQLdb` package for Python 2.6, and now when I import it using `import MySQLdb`, a user warning appear will appear ``` /usr/lib/python2.6/site-packages/setuptools-0.8-py2.6.egg/pkg_resources.py:1054: UserWarning: /home/sgpromot/.python-eggs is writable by group/others and vulnerable to...
You can change `~/.python-eggs` to not be writeable by group/everyone. I think this works: ``` chmod g-wx,o-wx ~/.python-eggs ```
What's the fastest way in Python to calculate cosine similarity given sparse matrix data?
17,627,219
22
2013-07-13T05:18:07Z
20,687,984
17
2013-12-19T17:26:53Z
[ "python", "numpy", "pandas", "similarity", "cosine-similarity" ]
Given a sparse matrix listing, what's the best way to calculate the cosine similarity between each of the columns (or rows) in the matrix? I would rather not iterate n-choose-two times. Say the input matrix is: ``` A= [0 1 0 0 1 0 0 1 1 1 1 1 0 1 0] ``` The sparse representation is: ``` A = 0, 1 0, 4 1, 2 1, 3 ...
The following method is about 30 times faster than `scipy.spatial.distance.pdist`. It works pretty quickly on large matrices (assuming you have enough RAM) See below for a discussion of how to optimize for sparsity. ``` # base similarity matrix (all dot products) # replace this with A.dot(A.T).toarray() for sparse re...
Sort list of date strings
17,627,531
7
2013-07-13T06:13:16Z
17,627,575
18
2013-07-13T06:20:47Z
[ "python", "datetime" ]
I have an arbitrary list of date strings (mm-yyyy) as follows: ``` d = ['09-2012', '04-2007', '11-2012', '05-2013', '12-2006', '05-2006', '08-2007'...] ``` I need this list to be sorted first by the level of years (ascending), then on the level of months (ascending)..so that the logical ordering can be: ``` d_ordere...
Try this: ``` import datetime d = ['09-2012', '04-2007', '11-2012', '05-2013', '12-2006', '05-2006', '08-2007'] sorted(d, key=lambda x: datetime.datetime.strptime(x, '%m-%Y')) ```
Django unique=True not working
17,627,556
15
2013-07-13T06:17:58Z
17,627,648
28
2013-07-13T06:30:40Z
[ "python", "django" ]
This is from django's documentation: > Field.unique > > If True, this field must be unique throughout the table. > > This is enforced at the database level and by model validation. > If you try to save a model with a duplicate value in a unique field, a django > .db.IntegrityError will be raised by the model’s save(...
If you added the `unique=True` after the table was already created, then even if you do `syncdb` later, the unique condition will not be added to your table. I can confirm with `sqlite3` that Django 1.5 happily saves duplicate objects with `MyModel(url="blah").save()` if the unique constraint does not exist in the dat...
Convert an int value to unicode
17,627,834
5
2013-07-13T07:00:16Z
33,672,032
8
2015-11-12T13:01:28Z
[ "python", "character-encoding", "ascii", "pyserial" ]
I am using pyserial and need to send some values less than 255. If I send the int itself the the ascii value of the int gets sent. So now I am converting the int into a unicode value and sending it through the serial port. ``` unichr(numlessthan255); However it throws this error: 'ascii' codec can't encode character ...
In Python 2 - Turn it into a string first, then into unicode. ``` str(integer).decode("utf-8") ``` Best way I think. Works with any integer, plus still works if you put a string in as the input. Updated edit due to a comment: For Python 2 and 3 - This works on both but a bit messy: ``` str(integer).encode("utf-8")....
What is inf and nan?
17,628,613
10
2013-07-13T08:59:18Z
17,628,637
21
2013-07-13T09:03:21Z
[ "python", "python-2.7" ]
Just a question that I'm kind of confused about So I was messing around with `float('inf')` and kind of wondering what it is used for. Also I noticed that if I add `-inf + inf` i get `nan` is that the same as Zero or not. I'm confused about what the uses of these two values are. Also when I do `nan - inf` I don't g...
`inf` is infinity - a value that is greater than any other value. `-inf` is therefore smaller than any other value. `nan` stands for Not A Number, and this is not equal to `0`. Although positive and negative infinity can be said to be symmetric about `0`, the same can be said for any value `n`, meaning that the resul...
Setting a default value in the selectfield, using wtforms and flask
17,629,291
11
2013-07-13T10:26:27Z
17,633,245
9
2013-07-13T18:54:18Z
[ "python", "flask", "wtforms" ]
I am creating a product edit form and I need the form to be pre-populated with the previous data. I am doing the following: ``` Product(form): product = TextField('name') category = SelectField('category', choice=[(1,'one'),(2,'two')]) ``` In the view: ``` form.product.data = 'A product name from the databa...
From the WTForms documentation > Note that the choices keyword is only evaluated once, so if you want to make a dynamic drop-down list, you’ll want to assign the choices list to the field after instantiation. ``` Product(form): product = TextField('name') category = SelectField('category') ``` And then in ...
Setting a default value in the selectfield, using wtforms and flask
17,629,291
11
2013-07-13T10:26:27Z
17,638,018
13
2013-07-14T09:09:18Z
[ "python", "flask", "wtforms" ]
I am creating a product edit form and I need the form to be pre-populated with the previous data. I am doing the following: ``` Product(form): product = TextField('name') category = SelectField('category', choice=[(1,'one'),(2,'two')]) ``` In the view: ``` form.product.data = 'A product name from the databa...
If you want set default value to render page with form you can create own form or set value: ``` class Product(Form): product = TextField('name') category = SelectField('category', choices=[(1,'one'),(2,'two')]) # create instance with predefined value: form1 = Product(category=2) # form1.product == <input id=...
Simple python library for recognition text from image
17,630,650
4
2013-07-13T13:29:45Z
17,631,073
7
2013-07-13T14:26:56Z
[ "python", "python-3.x", "ocr" ]
I'm looking for a simple python library for text recognition from images. Images are similar to this: ![enter image description here](http://i.stack.imgur.com/nEdDT.png) The image contains a very pure and simple - one line, numbers and hyphens, but the resolution is low. I would like something similar (in an ideal):...
I used [pytesser](https://code.google.com/p/pytesser/). Very easy to learn, and did a great job for me. If you don't like this option, search for 'python OCR library'
Python: '#' Comments after backslash
17,630,835
14
2013-07-13T13:54:27Z
17,630,918
19
2013-07-13T14:08:14Z
[ "python", "comments", "format", "multiline", "backslash" ]
This doesn't work: ``` something = \ line_of_code * \ # Comment another_line_of_code * \ # Comment and_another_one * \ # Comment etc ``` Neither does this: ``` something = \ # Comment \ line_of_code * \ # Comment \ another_line_of_code * ... ``` Neither does this: ...
Do it like that: ``` a, b, c, d = range(1, 5) result = ( # First is 1 a * # Then goes 2, result is 2 now b * # And then 3, result is 6 c * # And 4, result should be 24 d ) ``` Actually, [according to PEP8](http://www.python.org/dev/peps/pep-0008/#maximum-line-length) parentheses are p...
When using Pandas DataFrame.sort(), can I make it actually renumber the rows?
17,631,779
8
2013-07-13T15:52:14Z
17,631,857
15
2013-07-13T16:03:16Z
[ "python", "pandas" ]
I am always surprised by this: ``` > data = DataFrame({'x':[1, 2], 'y':[2, 1]}) > data = data.sort('y') > data x y 1 2 1 0 1 2 > data['x'][0] 1 ``` Is there a way I can cause the indices to be reassigned to fit the new ordering?
For my part, I'm glad that sort doesn't throw away the index information. If it did, there wouldn't be much point to having an index in the first place, as opposed to another column. If you want to reset the index to a range, you could: ``` >>> data x y 1 2 1 0 1 2 >>> data.reset_index(drop=True) x y 0 2...
How can we get tweets from specific country
17,633,378
6
2013-07-13T19:14:00Z
17,633,753
11
2013-07-13T20:01:49Z
[ "python", "twitter", "geocoding", "tweets", "country" ]
I've read a lot about this part and what I found is to write the geocode and search for tweets for example <https://api.twitter.com/1.1/search/tweets.json?geocode=37.781157,-122.398720,1mi&count=10> according to what i found in twitter website Returns tweets by users located within a given radius of the given latitude...
One way is to use twitter [geo search API](https://dev.twitter.com/docs/api/1.1/get/geo/search), get the place id and then perform regular search using `place:place_id`. Example, using [tweepy](https://github.com/tweepy/tweepy): ``` import tweepy auth = tweepy.OAuthHandler(..., ...) auth.set_access_token(..., ...) a...
Why use dict.keys?
17,634,177
7
2013-07-13T20:58:30Z
17,634,287
12
2013-07-13T21:15:04Z
[ "python", "dictionary" ]
I recently wrote some code that looked something like this: ``` # dct is a dictionary if "key" in dct.keys(): ``` However, I later found that I could achieve the same results with: ``` if "key" in dct: ``` This discovery got me thinking and I began to run some tests to see if there could be a scenario when I *must*...
On Python 3, use `dct.keys()` to get a [*dictionary view object*](http://docs.python.org/3/library/stdtypes.html#dictionary-view-objects), which lets you do set operations on just the keys: ``` >>> for sharedkey in dct1.keys() & dct2.keys(): # intersection of two dictionaries ... print(dct1[sharedkey], dct2[share...
Unexpected format string behavior
17,634,450
3
2013-07-13T21:40:20Z
17,634,479
8
2013-07-13T21:44:55Z
[ "python", "c", "printf", "string-formatting" ]
I just ran into what seemed to me to be bizarre string formatting behavior in python. It turned out to be caused by carriage return characters ('\r') I didn't know were there. Here's an example: ``` >>> text = 'hello\r' >>> '(SUBJECT "%s")' % (text) '(SUBJECT "hello\r")' >>> print '(SUBJECT "%s")' % (text) ")UBJECT "h...
It (\r) is a carridge return without a linefeed so the cursor moves back to the start of the current line without moving onto a new line and therefore overwriting what is already displayed. The behaviour depends on your console and whether it interprets CR and LF as individual operations.
Getting 'TypeError: ObjectId('') is not JSON serializable' when using Flask 0.10.1
17,635,015
8
2013-07-13T23:11:59Z
17,667,946
10
2013-07-16T04:21:30Z
[ "python", "json", "flask", "pymongo" ]
I forked the Flask example, Minitwit, to work with MongoDB and it was working fine on Flask 0.9, but after upgrading to 0.10.1 I get the error in title when I login when I try to set the session id. It seems there was [changes](http://lucumr.pocoo.org/2013/6/13/werkzeug-and-flask-releases/) in Flask 0.10.1 related to ...
EDIT: Even easier fix. You don't even need to do any JSON encoding/decoding. Just save the session['\_id'] as a string: ``` user = db.minitwit.user.find_one({'username': request.form['username']}) session['_id'] = str(user['_id']) ``` And then everywhere you want to do something with the session['\_id'] you have to ...
Why l.insert(0, i) is slower than l.append(i) in python?
17,635,811
7
2013-07-14T01:43:04Z
17,635,825
10
2013-07-14T01:45:17Z
[ "python", "algorithm", "list", "reverse" ]
I tested two different ways to reverse a list in python. ``` import timeit value = [i for i in range(100)] def rev1(): v = [] for i in value: v.append(i) v.reverse() def rev2(): v = [] for i in value: v.insert(0, i) print timeit.timeit(rev1) print timeit.timeit(rev2) ``` Interes...
`insert` is an `O(n)` operation as it requires all elements at or after the insert position to be shifted up by one. `append`, on the other hand, is generally `O(1)` (and `O(n)` in the worst case, when more space must be allocated). This explains the substantial time difference. The time complexities of these methods ...
ttk Entry background colour
17,635,905
4
2013-07-14T02:05:42Z
17,639,955
11
2013-07-14T13:47:36Z
[ "python", "tkinter", "ttk" ]
How exactly do I change the background colour of an Entry widget from ttk? What I have so far is: ``` self.estyle = ttk.Style() self.estyle.configure("EntryStyle.TEntry", background='black') self.estyle.map("EntryStyle.TEntry", foreground=[('disabled', 'yellow'), ...
I've figured it out, after a *lot* of digging. As hard as I had to search to figure this out, I suppose others would benefit from this: The standard style applied to ttk.Entry simply doesn't take a fieldbackground option, which would be what changes the colour of the text entry field. The solution is this to create a ...
Python: initialize multi-dimensional list
17,636,567
3
2013-07-14T04:40:35Z
17,636,593
7
2013-07-14T04:44:59Z
[ "python", "list" ]
I want to initialize a multidimensional list. Basically, I want a 10x10 grid - a list of 10 lists each containing 10 items. Each list value should be initialized to the integer 0. The obvious way to do this in a one-liner: `myList = [[0]*10]*10` won't work because it produces a list of 10 references to one list, so c...
You can do it quite efficiently with comprehension: ``` a = [[0] * number_cols for i in range(number_rows)] ```
Finding key with minimum value in OrderedDict
17,638,308
6
2013-07-14T09:55:02Z
17,638,325
24
2013-07-14T09:57:01Z
[ "python", "dictionary" ]
I need to find the key whose value is the lowest in the ordered dictionary but only when it is True for the position in my\_list. ``` from collections import OrderedDict my_list = [True,False,False,True,True,False,False,False,] my_lookup = OrderedDict([('a', 2), ('b', 9), ('c', 4), ('d', 7), ...
You can use [`itertools.compress`](http://docs.python.org/2/library/itertools.html#itertools.compress) with key to `min` being `get` method, ``` >>> from itertools import compress >>> min(compress(my_lookup, my_list), key=my_lookup.get) a ```
Python doc string: Triple-double quote v.s. Double quote
17,643,894
10
2013-07-14T21:22:19Z
17,643,916
12
2013-07-14T21:24:44Z
[ "python", "quote" ]
What is the preferred way to write Python doc string? `"""` or `"` In the book `Dive Into Python`: <http://www.diveintopython.net/getting_to_know_python/documenting_functions.html>, the author provides the following example: ``` def buildConnectionString(params): """Build a connection string from a dictionary of...
From the [PEP8 Style Guide](http://www.python.org/dev/peps/pep-0008/): * [PEP 257](http://www.python.org/dev/peps/pep-0257/#one-line-docstrings) describes good docstring conventions. Note that most importantly, the """ that ends a multiline docstring should be on a line by itself, e.g.: ``` """Return a fooban...
Create hourly/minutely time range using pandas
17,644,100
7
2013-07-14T21:45:51Z
17,645,475
15
2013-07-15T01:19:54Z
[ "python", "time", "pandas", "range" ]
Is there a way to generate time range in pandas similar to date\_range? something like: ``` pandas.time_range("11:00", "21:30", freq="30min") ```
A time range doesn't exist as a standalone index type. Generate using a single date ``` In [1]: pandas.date_range("11:00", "21:30", freq="30min") Out[1]: <class 'pandas.tseries.index.DatetimeIndex'> [2013-07-14 11:00:00, ..., 2013-07-14 21:30:00] Length: 22, Freq: 30T, Timezone: None ``` The time objects ``` In [2]...
when to use pre_save, save, post_save in django?
17,645,801
13
2013-07-15T02:09:39Z
17,658,156
13
2013-07-15T15:38:33Z
[ "python", "django", "model", "save", "django-signals" ]
I see I can override or define `pre_save, save, post_save` to do what I want when a model instance gets saved. Which one is preferred in which situation and why?
I shall try my best to explain it with an example: [`pre_save`](https://docs.djangoproject.com/en/dev/ref/signals/#pre-save) and [`post_save`](https://docs.djangoproject.com/en/dev/ref/signals/#post-save) are [signals](https://docs.djangoproject.com/en/dev/ref/signals/#signals) that are sent by the model. In simpler w...
for or while loop to do something n times
17,647,907
2
2013-07-15T06:22:58Z
17,647,919
9
2013-07-15T06:24:09Z
[ "python", "performance", "loops", "for-loop", "while-loop" ]
In Python you have two fine ways to repeat some action more than once. One of them is `while` loop and the other - `for` loop. So let's have a look on two simple pieces of code: ``` for i in range(n): do_sth() ``` And the other: ``` i = 0 while i < n: do_sth() i += 1 ``` My question is which of them is ...
> but on the other hand it creates a completely useless list of integers just to loop over them. Isn't it a waste of memory, especially as far as big numbers of iterations are concerned? That is what `xrange(n)` is for. It avoids creating a list of numbers, and instead just provides an iterator object. In Python 3, `...
How to find out the date of the last Saturday in Linux shell script or python?
17,648,762
2
2013-07-15T07:23:12Z
17,648,845
9
2013-07-15T07:27:59Z
[ "python", "linux", "shell" ]
I have python script which i need to run daily for backups. Now i need to find the date of last saturday because i need that in my script to get the backups i did on last saturdy. Suppose on saturday i made this file `weekly_user1_Jul-13-2013.sql` I ned to get that name in script which i run daily. so for script run...
``` $ date +"%b-%d-%Y" -d "last saturday" Jul-13-2013 ```
Python re.sub() beginning-of-line anchoring
17,648,999
2
2013-07-15T07:37:11Z
17,649,039
8
2013-07-15T07:39:42Z
[ "python", "regex", "string", "replace" ]
Consider the following multiline string: ``` >> print s shall i compare thee to a summer's day? thou art more lovely and more temperate rough winds do shake the darling buds of may, and summer's lease hath all too short a date. ``` `re.sub()` replaces all the occurrence of `and` with `AND`: ``` >>> print re.sub("and...
You forgot to enable multiline mode. ``` re.sub("^and", "AND", s, flags=re.M) ``` > `re.M` > `re.MULTILINE` > > When specified, the pattern character `'^'` matches at the beginning of the string and at the beginning of each line (immediately following each newline); and the pattern character `'$'` matches at the en...
Why does random.shuffle return None?
17,649,875
28
2013-07-15T08:33:41Z
17,649,901
36
2013-07-15T08:35:20Z
[ "python", "list", "random", "shuffle" ]
Why is `random.shuffle` returning `None` in python? ``` >>> x = ['foo','bar','black','sheep'] >>> from random import shuffle >>> print shuffle(x) None ``` How do I get the shuffled value instead of `None`?
`random.shuffle()` changes the `x` list **in place**. Python API methods that alter a structure in-place generally return `None`, not the modified data structure. If you wanted to create a **new** randomly-shuffled list based of an existing one, where the existing list is kept in order, you could use [`random.sample(...
Why does random.shuffle return None?
17,649,875
28
2013-07-15T08:33:41Z
27,882,193
15
2015-01-10T23:15:34Z
[ "python", "list", "random", "shuffle" ]
Why is `random.shuffle` returning `None` in python? ``` >>> x = ['foo','bar','black','sheep'] >>> from random import shuffle >>> print shuffle(x) None ``` How do I get the shuffled value instead of `None`?
I Think this method works too. ``` import random shuffled = random.sample(original, len(original)) ```
Python post osx notification
17,651,017
20
2013-07-15T09:35:16Z
17,651,702
30
2013-07-15T10:08:20Z
[ "python", "osx", "osx-mavericks" ]
Using python I am wanting to post a message to the OSX Notification Center. What library do I need to use? should i write a program in objective-c and then call that program from python? --- **update** How do I access the features of notification center for 10.9 such as the buttons and the text field?
You should install [terminal-notifier](https://github.com/alloy/terminal-notifier) first with Ruby for example: ``` $ [sudo] gem install terminal-notifier ``` And then you can use this code: ``` import os # The notifier function def notify(title, subtitle, message): t = '-title {!r}'.format(title) s = '-sub...
Python post osx notification
17,651,017
20
2013-07-15T09:35:16Z
23,980,561
11
2014-06-01T13:51:02Z
[ "python", "osx", "osx-mavericks" ]
Using python I am wanting to post a message to the OSX Notification Center. What library do I need to use? should i write a program in objective-c and then call that program from python? --- **update** How do I access the features of notification center for 10.9 such as the buttons and the text field?
copy from: <https://gist.github.com/baliw/4020619> following works for me. ``` import Foundation import objc import AppKit import sys NSUserNotification = objc.lookUpClass('NSUserNotification') NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter') def notify(title, subtitle, info_text, delay=0, so...
Python: Remove division decimal
17,651,384
6
2013-07-15T09:53:11Z
17,651,389
15
2013-07-15T09:53:46Z
[ "python", "decimal", "division" ]
I have made a program that divides numbers and then returns the number, But the thing is that when it returns the number it has a decimal like this: ``` 2.0 ``` But I want it to give me: ``` 2 ``` so is there anyway I can do this? Thanks in Advance!
You can call `int()` on the end result: ``` >>> int(2.0) 2 ```
Python: Remove division decimal
17,651,384
6
2013-07-15T09:53:11Z
17,651,594
17
2013-07-15T10:03:19Z
[ "python", "decimal", "division" ]
I have made a program that divides numbers and then returns the number, But the thing is that when it returns the number it has a decimal like this: ``` 2.0 ``` But I want it to give me: ``` 2 ``` so is there anyway I can do this? Thanks in Advance!
When a number as a decimal it is usually a [`float`](http://docs.python.org/2/library/functions.html#float) in Python. If you want to remove the decimal and keep it an integer ([`int`](http://docs.python.org/2/library/functions.html#int)). You can call the `int()` method on it like so... ``` >>> int(2.0) 2 ``` Howev...
Optimal multiple return values in scientific python
17,651,724
3
2013-07-15T10:10:09Z
17,651,850
7
2013-07-15T10:17:09Z
[ "python", "numpy", "scipy", "ipython" ]
I'm using scipy/numpy for research code instead of matlab. There is one flaw, I was running into frequently. I found a work-around solution, but want to check for a *best practice* and better solution. Imagine some mathematical optimisation: ``` def calculation (data, max_it=10000, tol = 1e-5): k = 0 rmse = np...
You could specify that you want more info returned using an `info=True` argument when calling `calculation`. This is the approach taken by [np.unique](http://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html#numpy-unique) (with its `return_inverse` and `return_index` parameters) and [scipy.optimize.leastsq...
How to build a flask application around an already existing database?
17,652,937
33
2013-07-15T11:14:09Z
17,653,975
45
2013-07-15T12:11:29Z
[ "python", "mysql", "sqlalchemy", "flask", "flask-sqlalchemy" ]
I already have an existing Database that has a lot of tables and a lot of data in `MySQL`. I intend to create a `Flask` app and use sqlalchemy along with it. Now I asked out on irc and looked around on google and tried the following ideas: **First** I used [sqlacodegen](https://pypi.python.org/pypi/sqlacodegen) to gen...
I'd say your question has nothing to do with flask at all. For example, you don't have a problem with the templates, routes, views or logon decorators. Where you struggle at is at SQLAlchemy. So my suggestion is to ignore Flask for a while and get used to SQLAlchemy first. You need to get used to your existing databa...
How to build a flask application around an already existing database?
17,652,937
33
2013-07-15T11:14:09Z
17,656,945
12
2013-07-15T14:40:26Z
[ "python", "mysql", "sqlalchemy", "flask", "flask-sqlalchemy" ]
I already have an existing Database that has a lot of tables and a lot of data in `MySQL`. I intend to create a `Flask` app and use sqlalchemy along with it. Now I asked out on irc and looked around on google and tried the following ideas: **First** I used [sqlacodegen](https://pypi.python.org/pypi/sqlacodegen) to gen...
I recently went through the same thing, with the additional challenge of linking the models across two databases. I used [Flask-SQLAlchemy](http://pythonhosted.org/Flask-SQLAlchemy/) and all I had to do was define my models in the same way as my database tables looked, and I was away laughing. What I found difficult w...
How to build a flask application around an already existing database?
17,652,937
33
2013-07-15T11:14:09Z
19,064,993
24
2013-09-28T08:32:27Z
[ "python", "mysql", "sqlalchemy", "flask", "flask-sqlalchemy" ]
I already have an existing Database that has a lot of tables and a lot of data in `MySQL`. I intend to create a `Flask` app and use sqlalchemy along with it. Now I asked out on irc and looked around on google and tried the following ideas: **First** I used [sqlacodegen](https://pypi.python.org/pypi/sqlacodegen) to gen...
The key to connecting Holger's answer to a flask context is that `db.Model` is a `declarative_base` object like `Base`. Took me a while to notice this important sentence in flask-sqlalchemy's [documentation](http://pythonhosted.org/Flask-SQLAlchemy/quickstart.html) Below are the steps I used for my app: 1. initiate a...
Using Python in vimscript: How to export a value from a python script back to vim?
17,656,320
13
2013-07-15T14:11:31Z
17,657,288
14
2013-07-15T14:57:06Z
[ "python", "variables", "vim" ]
I'm struggling with Python in vim. I still haven't found out how I can import a value from a python script (in a vim function) back to vim p.e. ``` function! myvimscript() python << endpython import vim, random, sys s = vim.eval("mylist") # do operation with variable "s" in python endpython " imp...
First of all, please define your function name starting with uppercase. Here is an example for your two questions. I hope it helps: ``` function! TestPy() range let startline = line("'<") let endline = line("'>") echo "vim-start:".startline . " vim-endline:".endline python << EOF import vim s = "I was se...
how to play wav file in python?
17,657,103
13
2013-07-15T14:47:08Z
17,657,304
13
2013-07-15T14:57:33Z
[ "python", "audio", "pygame", "pyglet" ]
I tried pygame for playing wav file like this: ``` import pygame pygame.init() pygame.mixer.music.load("mysound.wav") pygame.mixer.music.play() pygame.event.wait() ``` but It change the voice and I don't know why! I read [this link](http://stackoverflow.com/questions/307305/play-a-sound-with-python) solutions and ca...
You can use [PyAudio](http://people.csail.mit.edu/hubert/pyaudio/docs/#class-pyaudio). An example here on my Linux it works: ``` #!usr/bin/env python #coding=utf-8 import pyaudio import wave #define stream chunk chunk = 1024 #open a wav format music f = wave.open(r"/usr/share/sounds/alsa/Rear_Center....
How to code the tkinter "scrolledtext" module
17,657,212
5
2013-07-15T14:53:08Z
17,658,025
13
2013-07-15T15:31:27Z
[ "python", "tkinter", "scrollbar" ]
The code below produces an ugly but functional example of using a scroll bar in a text widget and results in a couple of questions. Note: this is done using Python 3 on a windows box. 1. The scroll bar that appears is attached to the frame and although it scrolls the text box contents, I would prefer that it was attac...
You were right, you can use the `ScrolledText` widget from `tkinter.scrolledtext` module, like this: ``` import tkinter as tk import tkinter.scrolledtext as tkst win = tk.Tk() frame1 = tk.Frame( master = win, bg = '#808000' ) frame1.pack(fill='both', expand='yes') editArea = tkst.ScrolledText( master = fr...
Python unittest setUp function
17,657,543
3
2013-07-15T15:08:47Z
17,657,661
7
2013-07-15T15:14:17Z
[ "python" ]
I am relatively new to Python. According to [unittest.setUp](http://docs.python.org/dev/library/unittest.html#unittest.TestCase.setUp) documentation: > setUp() > Method called to prepare the test fixture. **This is called immediately before calling the test method**; any exception raised by this method will be consi...
1. setUp() and tearDown() methods are automatically used when they are available in your classes inheriting from unittest.TestCase. 2. They should be named setUp() and tearDown(), only those are used when test methods are executed. Example: ``` class MyTestCase(unittest.TestCase): def setUp(self): self.setUpMy...
python list comprehension double for
17,657,720
18
2013-07-15T15:17:20Z
17,657,966
37
2013-07-15T15:29:04Z
[ "python", "list-comprehension" ]
``` vec = [[1,2,3], [4,5,6], [7,8,9]] print [num for elem in vec for num in elem] <----- this >>> [1, 2, 3, 4, 5, 6, 7, 8, 9] ``` This is tricking me out. I understand elem is the lists inside of the list from `for elem in vic` I don't quite understand the usage of `num` and `for num in elem` in the beginnin...
Lets break it down. A simple list-comprehension: ``` [x for x in collection] ``` This is easy to understand if we break it into parts: `[A for B in C]` * `A` is the item that will be in the resulting list * `B` is each item in the collection `C` * `C` is the collection itself. In this way, one could write: ``` [x...
Unable to find vcvarsall.bat using Python 3.3 in Windows 8
17,658,092
18
2013-07-15T15:34:27Z
18,026,585
8
2013-08-02T21:45:04Z
[ "python", "visual-studio", "python-3.x", "mingw", "pip" ]
I am having an issue when I try to run: ``` pip install numpy ``` I get: ``` unable to find vcvarsall.bat. ``` I followed this procedure: [How to use MinGW's gcc compiler when installing Python package using Pip?](http://stackoverflow.com/questions/3297254/how-to-use-mingws-gcc-compiler-when-installing-python-packa...
I am using the same setup and installing visual studio 2010 express was the easiest solution for me. <http://www.microsoft.com/visualstudio/eng/downloads#d-2010-express> Python 3.3 was built using VS 2010. <http://blog.python.org/2012/05/recent-windows-changes-in-python-33.html>
Unable to find vcvarsall.bat using Python 3.3 in Windows 8
17,658,092
18
2013-07-15T15:34:27Z
23,007,466
9
2014-04-11T08:34:16Z
[ "python", "visual-studio", "python-3.x", "mingw", "pip" ]
I am having an issue when I try to run: ``` pip install numpy ``` I get: ``` unable to find vcvarsall.bat. ``` I followed this procedure: [How to use MinGW's gcc compiler when installing Python package using Pip?](http://stackoverflow.com/questions/3297254/how-to-use-mingws-gcc-compiler-when-installing-python-packa...
As other people have already mentioned, it appears that you do not have Microsoft Visual Studio 2010 installed on your computer. Older versions of Python used Visual Studio 2008, but now the 2010 version is used. The 2010 version in particular is used to compile some of the code (not 2008, 2013, or any other version). ...
How to pipe input to python line by line from linux program?
17,658,512
19
2013-07-15T15:56:13Z
17,658,680
40
2013-07-15T16:04:35Z
[ "python", "pipe" ]
I want to pipe the output of `ps -ef` to python line by line. The script I am using is this (first.py) - ``` #! /usr/bin/python import sys for line in sys.argv: print line ``` Unfortunately, the "line" is split into words separated by whitespace. So, for example, if I do ``` echo "days go by and still" | xargs...
I do not quite understand why you want to use commandline arguments instead of simply reading from **standard input**. Python has a simple idiom for iterating over lines at stdin: ``` import sys for line in sys.stdin: sys.stdout.write(line) ``` My usage example: ``` $ echo -e "first line\nsecond line" | python ...
What is more 'pythonic' for 'not'
17,659,303
24
2013-07-15T16:39:26Z
17,659,338
20
2013-07-15T16:41:27Z
[ "python" ]
I have seen it both ways, but which way is more Pythonic? ``` a = [1, 2, 3] # version 1 if not 4 in a: print 'is the not more pythonic?' # version 2 if 4 not in a: print 'this haz more engrish' ``` Which way would be considered better Python?
Most would agree that `4 not in a` is more Pythonic. Python was designed with the purpose of being easy to understand and intelligible, and `4 not in a` sounds more like how you would say it in English - chances are you don't need to know Python to understand what that means! Note that in terms of bytecode, the two w...
What is more 'pythonic' for 'not'
17,659,303
24
2013-07-15T16:39:26Z
17,659,369
7
2013-07-15T16:42:51Z
[ "python" ]
I have seen it both ways, but which way is more Pythonic? ``` a = [1, 2, 3] # version 1 if not 4 in a: print 'is the not more pythonic?' # version 2 if 4 not in a: print 'this haz more engrish' ``` Which way would be considered better Python?
I believe `not in` is more widely used. While the PEP 8 style guide doesn't explicitly discuss the topic, it does consider `not in` to be [its own comparison operator](http://www.python.org/dev/peps/pep-0008/#other-recommendations). Don't forget about [The Zen of Python](http://www.python.org/dev/peps/pep-0020/). One...
What is more 'pythonic' for 'not'
17,659,303
24
2013-07-15T16:39:26Z
17,659,400
36
2013-07-15T16:44:09Z
[ "python" ]
I have seen it both ways, but which way is more Pythonic? ``` a = [1, 2, 3] # version 1 if not 4 in a: print 'is the not more pythonic?' # version 2 if 4 not in a: print 'this haz more engrish' ``` Which way would be considered better Python?
The second option is more Pythonic for two reasons: * It is **one** operator, translating to one bytecode operand. The other line is really `not (4 in a)`; two operators. As it happens, [Python *optimizes* the latter case](http://hg.python.org/cpython/file/ed8b0ee1c531/Python/peephole.c#l407) and translates `not (x...
Python list of dictionaries projection, filter, or subset?
17,659,580
3
2013-07-15T16:53:36Z
17,659,631
14
2013-07-15T16:56:17Z
[ "python", "functional-programming", "functools" ]
I'm trying to create what I think is a 'projection' from a larger dictionary space onto a smaller dimension space. So, if I have: ``` mine = [ {"name": "Al", "age": 10}, {"name": "Bert", "age": 15}, {"name": "Charles", "age": 17} ] ``` I'm trying to find a functional expression to return only: ``` [ {"name": "Al"}, ...
Sounds like a job for list comprehensions, whether you like them or not. ``` >>> [{"name": d["name"]} for d in mine] [{'name': 'Al'}, {'name': 'Bert'}, {'name': 'Charles'}] ``` The solution without a list comprehension would require an additional function definition: ``` def project(key, d): return {k: d[k]} ma...
How to double all the values in a list
17,659,767
2
2013-07-15T17:04:58Z
17,659,811
7
2013-07-15T17:06:42Z
[ "python", "list", "for-loop" ]
``` n = [3, 5, 7] def double(lst): for x in lst: x *= 2 print x return lst print double(n) ``` Why doesn't this return `n = [6, 10, 14]`? There should also be a better solution that looks something like `[x *=2 for x in lst]` but it doesn't work either. Any other tips about for-loops and li...
> Why doesn't this return `n = [6, 10, 14]`? Because `n`, or `lst` as it is called inside `double`, is never modified. `x *= 2` is equivalent to `x = x * 2` for numbers `x`, and that only re-binds the *name* `x` without changing the object it references. To see this, modify `double` as follows: ``` def double(lst): ...
'CSV does not exist' - Pandas DataFrame
17,661,136
4
2013-07-15T18:22:45Z
17,661,212
10
2013-07-15T18:26:45Z
[ "python", "pandas" ]
I'm having difficulty reading a csv file into the pandas data frame. I am a total newcomer to pandas, and this is preventing me from progressing. I have read the documentation and searched for solutions, but I am unable to proceed. I have tried the following to no avail... ``` import pandas as pd import numpy as np pd...
"\r" usually is interpreted as a special character and means carriage return. Either add a 'r' prefix to your string literals which prevents this special sequence from being interpreted (e.g. `path = r"foo\rar"`), or, as already suggested, just use a normal slash as path delimiter. Python is intelligent enough for it t...
How to compare string and integer in python?
17,661,829
2
2013-07-15T19:00:39Z
17,661,830
11
2013-07-15T19:00:56Z
[ "python", "comparison" ]
I have this simple python program. I ran it and it prints `yes`, when in fact I expect it to not print anything because `14` is not greater than `14`. I saw this [related](http://stackoverflow.com/questions/3270680/how-does-python-compare-string-and-int) question, but it isn't very helpful. ``` #! /usr/bin/python im...
Convert the string to an integer with `int`: ``` hours = int("14") if (hours > 14): print "yes" ``` In CPython2, when comparing two non-numerical objects of different types, the comparison is performed by comparing the *names* of the types. Since `'int' < 'string'`, *any int is less than any string*. ``` In...
How to print out the full distribution of words in an LDA topic in gensim?
17,662,916
5
2013-07-15T20:06:08Z
17,663,094
7
2013-07-15T20:16:42Z
[ "python", "lda", "topic-modeling", "gensim" ]
The `lda.show_topics` module from the following code only prints the distribution of the top 10 words for each topic, how do i print out the full distribution of all the words in the corpus? ``` from gensim import corpora, models documents = ["Human machine interface for lab abc computer applications", "A survey of u...
There is a variable call `topn` in `show_topics()` where you can specify the number of top N words you require from the words distribution over each topic. see <http://radimrehurek.com/gensim/models/ldamodel.html> So instead of the default `lda.show_topics()`. You can use the `len(dictionary)` for the full word distri...
Django, creating a custom 500/404 error page
17,662,928
33
2013-07-15T20:07:02Z
17,663,045
15
2013-07-15T20:13:47Z
[ "python", "django", "django-templates", "http-status-code-404" ]
Following the tutorial found [here](https://docs.djangoproject.com/en/1.5/intro/tutorial03/) exactly, I cannot create a custom 500 or 404 error page. If I do type in a bad url, the page gives me the default error page. Is there anything I should be checking for that would prevent a custom page from showing up? File di...
From the page you referenced: > When you raise Http404 from within a view, Django will load a special view devoted to handling 404 errors. It finds it by looking for the variable handler404 in your root URLconf (and only in your root URLconf; setting handler404 anywhere else will have no effect), which is a string in ...
Django, creating a custom 500/404 error page
17,662,928
33
2013-07-15T20:07:02Z
24,725,091
35
2014-07-13T16:56:52Z
[ "python", "django", "django-templates", "http-status-code-404" ]
Following the tutorial found [here](https://docs.djangoproject.com/en/1.5/intro/tutorial03/) exactly, I cannot create a custom 500 or 404 error page. If I do type in a bad url, the page gives me the default error page. Is there anything I should be checking for that would prevent a custom page from showing up? File di...
Under your main `views.py` add your own custom implementation of the following two views, and just set up the templates **404.html** and **500.html** with what you want to display. With this solution, no custom code needs to be added to `urls.py` Here's the code: ``` from django.shortcuts import render_to_response f...
Django, creating a custom 500/404 error page
17,662,928
33
2013-07-15T20:07:02Z
33,342,977
12
2015-10-26T10:03:48Z
[ "python", "django", "django-templates", "http-status-code-404" ]
Following the tutorial found [here](https://docs.djangoproject.com/en/1.5/intro/tutorial03/) exactly, I cannot create a custom 500 or 404 error page. If I do type in a bad url, the page gives me the default error page. Is there anything I should be checking for that would prevent a custom page from showing up? File di...
Add these lines in urls.py # urls.py ``` from django.conf.urls import ( handler400, handler403, handler404, handler500 ) handler400 = 'my_app.views.bad_request' handler403 = 'my_app.views.permission_denied' handler404 = 'my_app.views.page_not_found' handler500 = 'my_app.views.server_error' # ... ``` and implement ...
how to determine whether a field exists?
17,663,820
7
2013-07-15T20:58:23Z
17,663,873
7
2013-07-15T21:02:10Z
[ "python", "mongodb", "cursor", "pymongo" ]
I'm connecting to my `mongodb` using `pymongo`: ``` client = MongoClient() mongo = MongoClient('localhost', 27017) mongo_db = mongo['test'] mongo_coll = mongo_db['test'] #Tweets database ``` I have a cursor and am looping through every record: ``` cursor = mongo_coll.find() for record in cursor: #for all the t...
Record is a dictionary in which the key "entities" links to another dictionary, so just check to see if "urls" is in that dictionary. ``` if "urls" in record["entities"]: ``` If you just want to proceed in any case, you can also use get. ``` msgurl = record["entities"].get("urls") ``` This will cause msgurl to equa...
one recv gets two or more send in python sockets
17,664,544
2
2013-07-15T21:47:51Z
17,664,559
9
2013-07-15T21:49:22Z
[ "python", "sockets" ]
this is a simple socket program which has a server and some clients. clients send their texts encrypted by a simple RSA cryptography then the server side decrypts the sentence and then sends the decrypted sentence back to the client. server: ``` import socket import sys from thread import * from math import * from ra...
This is an inherent part of TCP. Stream sockets are *byte* streams, not *message* streams. So, things are working exactly as they're supposed to. If you want to send a sequence of messages over a TCP stream, it's exactly the same problem as saving a sequence of objects to a file—you need some way of delimiting the m...
Call python3 code from python2 code
17,665,124
2
2013-07-15T22:40:12Z
17,665,156
9
2013-07-15T22:43:14Z
[ "python", "python-2.7", "python-3.x" ]
I am designing a GUI using the wxPython toolkit, which means it's being written in python2. However, I want to use python3 for the actual application code. How would I go about calling my python3 code from the GUI?
1. Talk over a pipe or socket 2. Enable such python 3 features as you can from `__future__` or use a library like `six` to write code which is compatible with both. 3. Don't do this. Finally, are you sure you can't use wxPython in Python 3? There's nothing in the online docs saying you can't.
Remove key from dictionary in Python returning new dictionary
17,665,809
5
2013-07-15T23:50:00Z
17,665,928
7
2013-07-16T00:04:30Z
[ "python", "methods", "dictionary" ]
I have a dictionary ``` d = {'a':1, 'b':2, 'c':3} ``` I need to remove a key, say **c** and return the dictionary without that key in one function call ``` {'a':1, 'b':2} ``` d.pop('c') will return the key value - 3 - instead of the dictionary. *I am going to need one function solution if it exists, as this will g...
How about this: ``` {i:d[i] for i in d if i!='c'} ``` or if you are using Python 2: ``` dict((i,d[i]) for i in d if i!='c') ```
python pandas groupby() result
17,666,075
9
2013-07-16T00:24:25Z
17,666,287
10
2013-07-16T00:48:48Z
[ "python", "group-by", "pandas" ]
I have the following python pandas data frame: ``` df = pd.DataFrame( { 'A': [1,1,1,1,2,2,2,3,3,4,4,4], 'B': [5,5,6,7,5,6,6,7,7,6,7,7], 'C': [1,1,1,1,1,1,1,1,1,1,1,1] } ); df A B C 0 1 5 1 1 1 5 1 2 1 6 1 3 1 7 1 4 2 5 1 5 2 6 1 6 2 6 1 7 3 7 1 8 3 7 1 9 4 6 ...
Here's one way (though it feels this should work in one go with an apply, I can't get it). ``` In [11]: g = df.groupby(['A', 'B']) In [12]: df1 = df.set_index(['A', 'B']) ``` The [`size`](http://pandas.pydata.org/pandas-docs/stable/groupby.html#aggregation) groupby function is the one you want, we have to match it t...
Finding N closest numbers
17,667,022
14
2013-07-16T02:26:06Z
17,667,109
11
2013-07-16T02:37:37Z
[ "python", "algorithm" ]
Have a 2-dimensional array, like - ``` a[0] = [ 0 , 4 , 9 ] a[1] = [ 2 , 6 , 11 ] a[2] = [ 3 , 8 , 13 ] a[3] = [ 7 , 12 ] ``` Need to select one element from each of the sub-array in a way that the resultant set of numbers are closest, that is the difference between the highest number and lowest number in the set is ...
collect all the values to create a single ordered sequence, with each element tagged with the array it came from: 0(0), 2(1), 3(2), 4(0), 6(1), ... 12(3), 13(2) then create a window across them, starting with the first (0(0)) and ending it at the first position that makes the window span all the arrays (0(0) -> 7(3)) ...
managing uWSGI with Upstart
17,667,239
6
2013-07-16T02:54:14Z
23,482,053
7
2014-05-05T21:16:36Z
[ "python", "uwsgi", "upstart" ]
I am trying to configure uWSGI with Upstart. I created the file `/etc/init/uwsgi-flask.conf`: ``` description "uwsgi for flask" start on runlevel [2345] stop on runlevel [06] exec /appdir/virtualenvdir/bin/uwsgi /appdir/virtualenvdir/uwsgi.ini --die-on-term ``` On reboot, it starts up correctly, but I am not able to...
You probably have `daemonize=some/log/file/path` in your ini file. That will make the process exit with a "normal" exit code, so Upstart will figure that you wanted the job stopped and terminate the job. Remove daemonize and upstart will track the process in the foreground.
How to sort list like this?
17,667,407
2
2013-07-16T03:14:21Z
17,667,451
9
2013-07-16T03:18:23Z
[ "python", "list", "sorting", "dictionary" ]
I have a list like this: ``` li = [ { 'name': 'Lee', 'age': 22 }, { 'name': 'Mike', 'age': 34 }, { 'name': 'John', 'age': 23 } ] ``` I want sort the list with `sorted` method, and sort by the the `age` key How to achieve it?
Use a [key function](http://docs.python.org/2/howto/sorting.html#key-functions): ``` li_sorted = sorted(li, key=lambda x: x['age']) ```