title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Python - Printing a dictionary as a horizontal table with headers
17,330,139
5
2013-06-26T20:45:56Z
17,330,263
20
2013-06-26T20:53:46Z
[ "python", "python-3.x", "dictionary" ]
I have a dictionary: ``` d = {1: ["Spices", math.floor(random.gauss(40, 5))], 2: ["Other stuff", math.floor(random.gauss(20, 5))], 3: ["Tea", math.floor(random.gauss(50, 5))], 10: ["Contraband", math.floor(random.gauss(1000, 5))], 5: ["Fruit", math.floor(random.gauss(10, 5))], 6: ["Textiles", math....
You can use [string formatting](http://docs.python.org/2/library/string.html#formatspec): ``` print "{:<8} {:<15} {:<10}".format('Key','Label','Number') for k, v in d.iteritems(): label, num = v print "{:<8} {:<15} {:<10}".format(k, label, num) ``` **Output:** ``` Key Label Number 1 ...
How does the @property decorator work?
17,330,160
352
2013-06-26T20:47:15Z
17,330,236
43
2013-06-26T20:52:51Z
[ "python", "properties", "decorator", "python-internals" ]
I would like to understand how the built-in function `property` works. What confuses me is that `property` can also be used as a decorator, but it only takes arguments when used as a built-in function and not when used as a decorator. This example is from the [documentation](http://docs.python.org/2/library/functions....
[Documentation says](http://docs.python.org/2/library/functions.html#property) it's just a shortcut for creating readonly properties. So ``` @property def x(self): return self._x ``` is equivalent to ``` def getx(self): return self._x x = property(getx) ```
How does the @property decorator work?
17,330,160
352
2013-06-26T20:47:15Z
17,330,245
39
2013-06-26T20:53:15Z
[ "python", "properties", "decorator", "python-internals" ]
I would like to understand how the built-in function `property` works. What confuses me is that `property` can also be used as a decorator, but it only takes arguments when used as a built-in function and not when used as a decorator. This example is from the [documentation](http://docs.python.org/2/library/functions....
The first part is simple: ``` @property def x(self): ... ``` is the same as ``` def x(self): ... x = property(x) ``` * which, in turn, is the simplified syntax for creating a `property` with just a getter. The next step would be to extend this property with a setter and a deleter. And this happens with the appropr...
How does the @property decorator work?
17,330,160
352
2013-06-26T20:47:15Z
17,330,273
452
2013-06-26T20:54:27Z
[ "python", "properties", "decorator", "python-internals" ]
I would like to understand how the built-in function `property` works. What confuses me is that `property` can also be used as a decorator, but it only takes arguments when used as a built-in function and not when used as a decorator. This example is from the [documentation](http://docs.python.org/2/library/functions....
The `property()` function returns a special [descriptor object](http://docs.python.org/2/howto/descriptor.html): ``` >>> property() <property object at 0x10ff07940> ``` It is this object that has *extra* methods: ``` >>> property().getter <built-in method getter of property object at 0x10ff07998> >>> property().sett...
How to check for palindrome using Python logic
17,331,290
23
2013-06-26T22:05:35Z
17,331,328
88
2013-06-26T22:08:00Z
[ "python", "palindrome" ]
I'm trying to check for a palindrome with Python. The code I have is very `for`-loop intensive. And it seems to me the biggest mistake people do when going from C to Python is trying to implement C logic using Python, which makes things run slowly, and it's just not making the most of the language. I see on [this](ht...
A pythonic way to determine if a given value is a palindrome: ``` str(n) == str(n)[::-1] ``` Explanation: * We're checking if the string representation of `n` equals the inverted string representation of `n` * The `[::-1]` slice takes care of inverting the string * After that, we compare for equality using `==`
How to check for palindrome using Python logic
17,331,290
23
2013-06-26T22:05:35Z
17,331,369
13
2013-06-26T22:11:16Z
[ "python", "palindrome" ]
I'm trying to check for a palindrome with Python. The code I have is very `for`-loop intensive. And it seems to me the biggest mistake people do when going from C to Python is trying to implement C logic using Python, which makes things run slowly, and it's just not making the most of the language. I see on [this](ht...
An alternative to the rather unintuitive `[::-1]` syntax is this: ``` >>> test = "abcba" >>> test == ''.join(reversed(test)) True ``` The `reversed` function returns a reversed sequence of the characters in `test`. `''.join()` joins those characters together again with nothing in between.
How do I remove extra parsing characters in a list?
17,331,482
3
2013-06-26T22:21:16Z
17,331,490
10
2013-06-26T22:22:14Z
[ "python", "list" ]
I have the following lists of lists: ``` animals = [('dog', 'cat'), ('mouse', 'bird')] ``` I would like to reduce it to: ``` animals = ['dog', 'cat', 'mouse', 'bird'] ``` is there a simpler way to have the result above than doing something like this: ``` animals = [('dog', 'cat'), ('mouse', 'bird')] final = [] fo...
You can use [`itertools.chain.from_iterable`](http://docs.python.org/2/library/itertools.html#itertools.chain.from_iterable): ``` >>> from itertools import chain >>> list(chain.from_iterable(animals)) ['dog', 'cat', 'mouse', 'bird'] ``` Or a nested `list comprehension`: ``` >>> [anim for item in animals for anim in ...
Passing data from Django view to D3
17,332,392
7
2013-06-26T23:58:27Z
17,332,440
7
2013-06-27T00:03:37Z
[ "python", "html", "django", "d3.js" ]
Complete newbie question: I have a Django app running in which I generate a view with data: ``` result = json.dumps(data) context = RequestContext(request, { 'result': result, }) return HttpResponse(template.render(context)) ``` Now I have a `map.js` file in which I render a heat map of the data using `d3.js`....
In your template use `{{ result }}` in between `<script></script>` tags to do your JavaScript magic. If `result` is a serialized JSON object you can just use `JSON.parse(result)` to convert the JSON string to a JavaScript object. Example: ``` <script type="text/javascript"> var data = JSON.parse("{{ result }}"); run...
Python __init__ return failure to create
17,332,929
6
2013-06-27T01:04:57Z
17,332,994
8
2013-06-27T01:13:43Z
[ "python", "return", "init" ]
First off, I know that the `__init__()` function of a class in Python cannot return a value, so sadly this option is unavailable. Due to the structure of my code, it makes sense to have data assertions (and prompts for the user to give information) inside the `__init__` function of the class. However, this means that ...
You could raise an exception when either assertio fail, or -, if you really don't want or can't work with exceptions, you can write the `__new__` method in your classes - in Python, `__init__` is technically an "initializer" method - and it should fill in he attributes and acquire some of the resources and others your ...
convert selected datetime to date in sqlalchemy
17,333,014
5
2013-06-27T01:17:00Z
17,334,055
8
2013-06-27T03:30:04Z
[ "python", "sqlalchemy" ]
I have a database of test records with one column 'test\_time' defined as datetime. I want to query how many distinct dates there are as I want to dump test results to csv according to dates. I now have the following: ``` distinct_dates = list(session.query(Test_Table.test_time).distinct()) ``` But this gives me a li...
That would be by using the "cast" expression: ``` distinct_dates = list(session.query(cast(Test_Table.test_time, DATE)).distinct()) ``` EDIT: Ok, let's give this a shot: ``` distinct_dates = list(session.query(func.DATE(Test_Table.test_time)).distinct()) ```
Gimp: python script not showing in menu
17,334,993
5
2013-06-27T05:13:51Z
17,345,604
8
2013-06-27T14:15:30Z
[ "python", "gimp", "python-fu", "gimpfu" ]
I followed [this](http://www.ibm.com/developerworks/library/os-autogimp/) tutorial and this is what I have come up so far: ``` #!/usr/bin/python # -*- coding: utf-8 -*- #http://www.ibm.com/developerworks/library/os-autogimp/ from gimpfu import* def plugin_main(timg, tdrawable, maxh=540, maxw=800): currentWidth ...
If your script has any syntax errors, it won't show up in the menu at all - the above code does have a syntax error on the very first line of code `from gimpfu import*` (missing a space before the `*`) One easy way to check for syntax errors is to try to run the script as a stand alone (it will fail when it can't find...
Getting a grid of a matrix via logical indexing in Numpy
17,335,993
6
2013-06-27T06:28:11Z
17,336,787
7
2013-06-27T07:10:22Z
[ "python", "matlab", "numpy", "matrix-indexing" ]
I'm trying to rewrite a function using numpy which is originally in MATLAB. There's a logical indexing part which is as follows in MATLAB: ``` X = reshape(1:16, 4, 4).'; idx = [true, false, false, true]; X(idx, idx) ans = 1 4 13 16 ``` When I try to make it in numpy, I can't get the correct indexing...
You could also write: ``` >>> X[np.ix_(idx,idx)] array([[ 1, 4], [13, 16]]) ```
Removing non numeric characters from a string
17,336,943
8
2013-06-27T07:19:03Z
17,336,991
9
2013-06-27T07:20:54Z
[ "python", "python-3.x", "python-3.3" ]
I have been given the task to remove all non numeric characters including spaces from a either text file or string and then print the new result next to the old characters for example: Before: ``` sd67637 8 ``` After: ``` sd67637 8 = 676378 ``` As i am a beginner i do not know where to start with this task. Please...
Loop over your string, char by char and only include digits: ``` new_string = ''.join(ch for ch in your_string if ch.isdigit()) ``` Or use a regex on your string (if at some point you wanted to treat non-contiguous groups separately)... ``` import re s = 'sd67637 8' new_string = ''.join(re.findall(r'\d+', s)) # 676...
Removing non numeric characters from a string
17,336,943
8
2013-06-27T07:19:03Z
17,337,613
14
2013-06-27T07:52:27Z
[ "python", "python-3.x", "python-3.3" ]
I have been given the task to remove all non numeric characters including spaces from a either text file or string and then print the new result next to the old characters for example: Before: ``` sd67637 8 ``` After: ``` sd67637 8 = 676378 ``` As i am a beginner i do not know where to start with this task. Please...
The easiest way is with a regexp ``` import re a = 'lkdfhisoe78347834 (())&/&745 ' result = re.sub('[^0-9]','', a) print result >>> '78347834745' ```
How to search if dictionary value contains certain string with Python
17,340,922
5
2013-06-27T10:38:25Z
17,341,041
16
2013-06-27T10:44:31Z
[ "python", "string", "dictionary", "key-value" ]
I have a dictionary with key-value pair. My value contains strings. How can I search if a specific string exists in the dictionary and return the key that correspond to the key that contains the value. Let's say I want to search if the string 'Mary' exists in the dictionary value and get the key that contains it. This...
You can do it like this: ``` #Just an example how the dictionary may look like myDict = {'age': ['12'], 'address': ['34 Main Street, 212 First Avenue'], 'firstName': ['Alan', 'Mary-Ann'], 'lastName': ['Stone', 'Lee']} def search(values, searchFor): for k in values: for v in values[k]: if...
Mininet Cannot find required executable controller
17,341,076
3
2013-06-27T10:46:34Z
17,763,632
7
2013-07-20T15:13:07Z
[ "python", "mininet" ]
Whenever I want to run sshd.py example in mininet or some custome code I have written myself I get ``` *** Creating network *** Adding controller *** Adding hosts: h1 h2 h3 h4 h5 *** Adding switches: s1 *** Adding links: (h1, s1) (h2, s1) (h3, s1) (h4, s1) (h5, s1) *** Configuring hosts h1 h2 h3 h4 h5 *** Starting...
Stumbled upon the same issue with mininet on Ubuntu. Try to explicitly specify the controller class when constructing a Mininet object, e.g. instead of ``` net = Mininet(topo) ``` do ``` from mininet.node import OVSController net = Mininet(topo = topo, controller = OVSController) ``` That solved the problem in my ...
Convert string from xmlcharrefreplace back to utf-8
17,341,601
7
2013-06-27T11:12:37Z
17,341,725
9
2013-06-27T11:18:53Z
[ "python", "utf-8", "encode", "unicode-string" ]
I've next part of code: ``` In [8]: st = u"опа" In [11]: st.encode("ascii", "xmlcharrefreplace") Out[11]: '&#1086;&#1087;&#1072;' In [14]: st1 = st.encode("ascii", "xmlcharrefreplace") In [15]: st1.decode("ascii", "xmlcharrefreplace") Out[15]: u'&#1086;&#1087;&#1072;' In [16]: st1.decode("utf-8", "xmlcharrefrep...
Using an instance of [`HTMLParser.HTMLParser()`](http://docs.python.org/2/library/htmlparser.html#HTMLParser.HTMLParser): ``` >>> from HTMLParser import HTMLParser >>> parser = HTMLParser() >>> parser.unescape('&#1086;&#1087;&#1072;') u'\u043e\u043f\u0430' >>> print parser.unescape('&#1086;&#1087;&#1072;') опа ```
Global variables in recursion. Python
17,341,993
6
2013-06-27T11:32:16Z
17,342,080
9
2013-06-27T11:35:58Z
[ "python", "variables", "recursion", "global" ]
OK, i'm using Python 2.7.3 and here is my code: ``` def lenRecur(s): count = 0 def isChar(c): c = c.lower() ans='' for s in c: if s in 'abcdefghijklmnopqrstuvwxyz': ans += s return ans def leng(s): global count if len(s)==0: ...
`count` in `lenRecur` is *not* a global. It is a scoped variable. You'll need to use Python 3 before you can make that work in this way; you are looking for the [`nonlocal` statement](http://docs.python.org/3/reference/simple_stmts.html#the-nonlocal-statement) added to Python 3. In Python 2, you can work around this ...
How to flush the printed statements in IPython
17,343,688
6
2013-06-27T12:51:41Z
17,343,760
10
2013-06-27T12:54:48Z
[ "python", "ipython" ]
I want to print some debug statements during a loop in my function and I use IPython to call the function. Let an example function be: ``` def test_print(): import time for i in range(5): time.sleep(2) print i, time.time() ``` The result is like follows: ``` 0 1372337149.84 1 1372337151.84 2...
I've never used IPython, but it should suffice to flush stdout after each `print` statement. Something like this ought to work... ``` def test_print(): import time import sys for i in range(5): time.sleep(2) print i, time.time() sys.stdout.flush() ```
why does python write to a file in gibberish characters
17,347,647
3
2013-06-27T15:48:08Z
17,347,794
11
2013-06-27T15:54:33Z
[ "python", "character-encoding" ]
I attempted [Problem 10](https://projecteuler.net/problem=10) at project euler and passed but I decided, *what if i wote all the prime numbers below 2 million to a text(.txt) file* and so I continued and so made some small adjustments to the main function which solved the problem so without just adding it to a variable...
This is a bug in Microsoft's Notepad program, not in your code. ``` >>> a = '‵‷ㄱㄠ″㜱ㄠ‹㌲㈠‹ㄳ㌠‷ㄴ㐠' >>> a.decode('UTF-8').encode('UTF-16LE') '5 7 11 13 17 19 23 29 31 37 41 4' ``` Oh hey, look, they're prime numbers (I assume 4 is just a truncated 43). You can work around the bug in Notepa...
List of objects with a unique attribute
17,347,678
11
2013-06-27T15:49:31Z
17,347,743
10
2013-06-27T15:52:14Z
[ "python" ]
I have a list of objects that each have a specific attribute. That attribute is not unique, and I would like to end up with a list of the objects that is a subset of the entire list such that all of the specific attributes is a unique set. For example, if I have four objects: ``` object1.thing = 1 object2.thing = 2 o...
You could create a dict whose key is the object's thing and values are the objects themselves. ``` d = {} for obj in object_list: d[obj.thing] = obj desired_list = d.values() ```
List of objects with a unique attribute
17,347,678
11
2013-06-27T15:49:31Z
17,347,744
8
2013-06-27T15:52:24Z
[ "python" ]
I have a list of objects that each have a specific attribute. That attribute is not unique, and I would like to end up with a list of the objects that is a subset of the entire list such that all of the specific attributes is a unique set. For example, if I have four objects: ``` object1.thing = 1 object2.thing = 2 o...
You can use a `list comprehension` and `set`: ``` >>> objects = (object1,object2,object3,object4) >>> seen = set() >>> unique = [obj if obj.thing not in seen and not seen.add(obj.thing) for obj in objects ] ``` The above code is equivalent to: ``` seen = set() uni...
Inserting and removing into/from sorted list in Python
17,348,332
3
2013-06-27T16:21:53Z
17,348,367
7
2013-06-27T16:23:43Z
[ "python", "list", "binary-search" ]
I have a sorted list of integers, L, and I have a value X that I wish to insert into the list such that L's order is maintained. Similarly, I wish to quickly find and remove the first instance of X. Questions: 1. How do I use the bisect module to do the first part, if possible? 2. Is L.remove(X) going to be the most ...
1. You use the [`bisect.insort()` function](http://docs.python.org/2/library/bisect.html#bisect.insort): ``` bisect.insort(L, X) ``` 2. `L.remove(X)` will scan the whole list until it finds `X`. Use `del L[bisect.bisect_left(L, X)]` instead (provided that `X` is indeed in `L`). Note that removing from the mi...
Python write string of bytes to file
17,349,918
7
2013-06-27T17:46:55Z
17,349,992
7
2013-06-27T17:50:33Z
[ "python", "string", "python-3.x", "byte" ]
How do I write a string of bytes to a file, in byte mode, using python? I have: ``` ['0x28', '0x0', '0x0', '0x0'] ``` How do I write 0x28, 0x0, 0x0, 0x0 to a file? I don't know how to transform this string to a valid byte and write it.
Map to a `bytearray()` or `bytes()` object, then write that to the file: ``` with open(outputfilename, 'wb') as output: output.write(bytearray(int(i, 16) for i in yoursequence)) ``` Another option is to use the [`binascii.unhexlify()` function](http://docs.python.org/3/library/binascii.html#binascii.unhexlify) to...
numpy.savetxt without hash mark at beginning of header line
17,352,244
12
2013-06-27T20:05:55Z
17,361,181
17
2013-06-28T09:13:06Z
[ "python", "numpy" ]
When I try to save a matrix with header, a hash mark and a space (# ) appear on the first line: input: ``` np.savetxt(filename,data, fmt='%i %i %i %i %s',delimiter='\t',header="a\tb\tc\td\te") ``` output: ``` # a b c d e 0 0 0 0 bla 0 0 0 0 bla 1 1 1 1 bla 1 1 1 1 bla ``` Any ...
it inserts the # because that line is a comment, and the default character for comments is the symbol #, as you can read in the documentation [here](http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html). If you want to get rid of it, pass `comments=''` as option to savetxt.
Django Test Client post() returns 302 despite error on view's post()
17,352,314
6
2013-06-27T20:11:22Z
17,354,504
10
2013-06-27T22:47:47Z
[ "python", "django", "testing", "post", "http-status-code-404" ]
I'm currently writing up some basic tests to ensure pages in a medium sized Django application are GETting and POSTing correctly. However, using django.test.client.Client isn't reliably failing when it should be. It returns a 302 response even when there's obviously placed errors in my code. in my app/urls.py: ``` ur...
It's not totally clear why you're getting a redirect, but if you want to follow it you need to tell `RequestClient` to follow redirects - per [the documentation](https://docs.djangoproject.com/en/1.8/topics/testing/tools/): > If you set `follow` to `True` the client will follow any redirects and a > `redirect_chain` a...
How can I build a model to distinguish tweets about Apple (Inc.) from tweets about apple (fruit)?
17,352,469
78
2013-06-27T20:20:59Z
17,352,583
33
2013-06-27T20:29:02Z
[ "java", "python", "machine-learning", "classification" ]
See below for 50 tweets about "apple." I have hand labeled the positive matches about Apple Inc. They are marked as 1 below. Here are a couple of lines: ``` 1|“@chrisgilmer: Apple targets big business with new iOS 7 features http://bit.ly/15F9JeF ”. Finally.. A corp iTunes account! 0|“@Zach_Paull: When did gree...
I would do it as follows: 1. Split the sentence into words, normalise them, build a dictionary 2. With each word, store how many times they occurred in tweets about the company, and how many times they appeared in tweets about the fruit - these tweets must be confirmed by a human 3. When a new tweet comes in, find eve...
How can I build a model to distinguish tweets about Apple (Inc.) from tweets about apple (fruit)?
17,352,469
78
2013-06-27T20:20:59Z
17,377,820
68
2013-06-29T07:25:37Z
[ "java", "python", "machine-learning", "classification" ]
See below for 50 tweets about "apple." I have hand labeled the positive matches about Apple Inc. They are marked as 1 below. Here are a couple of lines: ``` 1|“@chrisgilmer: Apple targets big business with new iOS 7 features http://bit.ly/15F9JeF ”. Finally.. A corp iTunes account! 0|“@Zach_Paull: When did gree...
What you are looking for is called [Named Entity Recognition](http://en.wikipedia.org/wiki/Named-entity_recognition). It is a statistical technique that (most commonly) uses [Conditional Random Fields](http://en.wikipedia.org/wiki/Conditional_random_field) to find named entities, based on having been trained to learn t...
How can I build a model to distinguish tweets about Apple (Inc.) from tweets about apple (fruit)?
17,352,469
78
2013-06-27T20:20:59Z
17,438,029
9
2013-07-03T00:43:56Z
[ "java", "python", "machine-learning", "classification" ]
See below for 50 tweets about "apple." I have hand labeled the positive matches about Apple Inc. They are marked as 1 below. Here are a couple of lines: ``` 1|“@chrisgilmer: Apple targets big business with new iOS 7 features http://bit.ly/15F9JeF ”. Finally.. A corp iTunes account! 0|“@Zach_Paull: When did gree...
If you don't have an issue using an outside library, I'd recommend [scikit-learn](http://scikit-learn.org/) since it can probably do this better & faster than anything you could code by yourself. I'd just do something like this: Build your corpus. I did the list comprehensions for clarity, but depending on how your da...
How can I build a model to distinguish tweets about Apple (Inc.) from tweets about apple (fruit)?
17,352,469
78
2013-06-27T20:20:59Z
17,468,347
10
2013-07-04T10:48:44Z
[ "java", "python", "machine-learning", "classification" ]
See below for 50 tweets about "apple." I have hand labeled the positive matches about Apple Inc. They are marked as 1 below. Here are a couple of lines: ``` 1|“@chrisgilmer: Apple targets big business with new iOS 7 features http://bit.ly/15F9JeF ”. Finally.. A corp iTunes account! 0|“@Zach_Paull: When did gree...
You can do the following: 1. Make a dict of words containing their count of occurrence in fruit and company related tweets. This can be achieved by feeding it some sample tweets whose inclination we know. 2. Using enough previous data, we can find out the probability of a word occurring in tweet about apple inc. 3. Mu...
How can I build a model to distinguish tweets about Apple (Inc.) from tweets about apple (fruit)?
17,352,469
78
2013-06-27T20:20:59Z
17,502,141
28
2013-07-06T10:43:34Z
[ "java", "python", "machine-learning", "classification" ]
See below for 50 tweets about "apple." I have hand labeled the positive matches about Apple Inc. They are marked as 1 below. Here are a couple of lines: ``` 1|“@chrisgilmer: Apple targets big business with new iOS 7 features http://bit.ly/15F9JeF ”. Finally.. A corp iTunes account! 0|“@Zach_Paull: When did gree...
I have a semi-working system that solves this problem, open sourced using scikit-learn, with a series of blog posts describing what I'm doing. The problem I'm tackling is word-sense disambiguation (choosing one of multiple [word sense](https://en.wikipedia.org/wiki/Word_sense) options), which is not the same as Named E...
Creating a Terminal Program with Python
17,352,630
17
2013-06-27T20:32:16Z
17,352,755
13
2013-06-27T20:40:24Z
[ "python", "command-line" ]
I recently started learning python. I have created some basic webapps with Django and wrote some simple scripts. After using VIM as a Python IDE I really fell I love with "Terminal programs" (is there an official term for this?). Right now I am capable of doing simple things like asking someones age and printing it to ...
A true command-line program is something in the vein of `ls` or `grep`; it is started from the command-line, but it's non-interactive and can be used in pipelines and combined with other programs. A typical command-line program has no interactive user experience, instead relying on shell's history and init file for cus...
Creating a Terminal Program with Python
17,352,630
17
2013-06-27T20:32:16Z
17,353,753
7
2013-06-27T21:45:21Z
[ "python", "command-line" ]
I recently started learning python. I have created some basic webapps with Django and wrote some simple scripts. After using VIM as a Python IDE I really fell I love with "Terminal programs" (is there an official term for this?). Right now I am capable of doing simple things like asking someones age and printing it to ...
You should take a look at the [cmd](http://docs.python.org/3/library/cmd.html) module. See the [Python Cookbook](http://code.activestate.com/recipes/langs/python/tags/meta%3arequires=cmd/) for examples of its use.
Creating a Terminal Program with Python
17,352,630
17
2013-06-27T20:32:16Z
24,477,227
13
2014-06-29T14:55:03Z
[ "python", "command-line" ]
I recently started learning python. I have created some basic webapps with Django and wrote some simple scripts. After using VIM as a Python IDE I really fell I love with "Terminal programs" (is there an official term for this?). Right now I am capable of doing simple things like asking someones age and printing it to ...
On a \*nix system (linux/unix), if you: ``` $ chmod 0744 your_file.py -rwxr--r-- your_file.py ``` and add the path to python as the first line of `your_file.py`: ``` #!/usr/bin/python ``` or (in my case): ``` #!/usr/local/bin/python ``` Once you do that, instead of running it like this: ``` $ python your_f...
Error importing request processor module Django
17,352,636
5
2013-06-27T20:32:51Z
17,352,651
10
2013-06-27T20:33:49Z
[ "python", "django" ]
While trying to configure the TEMPLATE\_CONTEXT PROCESSORS in Django settings.py I am getting the following error: ``` Exception Value: Error importing request processor module django.contrib.messages.context_processors.messagesdjango.core.context_processors: "No module named 'django.contrib...
You're missing a comma after your inclusion of `messages`, between these two lines: ``` "django.contrib.messages.context_processors.messages" "django.core.context_processors.request", ``` Should be: ``` "django.contrib.messages.context_processors.messages", "django.core.context_processors.request", ```
__init__ for unittest.TestCase
17,353,213
32
2013-06-27T21:08:51Z
17,353,262
44
2013-06-27T21:11:20Z
[ "python", "unit-testing" ]
I'd like to add a couple of things to what the `unittest.TestCase` class does upon being initialized but I can't figure out how to do it. Right now I'm doing: ``` #filename test.py class TestingClass(unittest.TestCase): def __init__(self): self.gen_stubs() def gen_stubs(self): # Create a co...
Try this: ``` class TestingClass(unittest.TestCase): def __init__(self, *args, **kwargs): super(TestingClass, self).__init__(*args, **kwargs) self.gen_stubs() ``` You are overriding the `TestCase`'s `__init__`, so you might want to let the base class handle the arguments for you.
Cleanest way to return a tuple containing a particular element?
17,354,355
3
2013-06-27T22:33:25Z
17,354,369
8
2013-06-27T22:34:57Z
[ "python", "tuples" ]
In python, if I have a tuple of tuples, like so: ``` ((1, 'foo'), (2, 'bar'), (3, 'baz')) ``` what is the most efficient/clean/pythonic way to return the 0th element of a tuple containing a particular 1st element. I'm assuming it can be done as a simple one-liner. In other words, how do I return 2 using 'bar'? --- ...
Use a list comprehension if you want all such values: ``` >>> lis = ((1, 'foo'), (2, 'bar'), (3, 'baz')) >>> [x[0] for x in lis if x[1]=='bar' ] [2] ``` If you want only one value: ``` >>> next((x[0] for x in lis if x[1]=='bar'), None) 2 ``` If you're doing this multiple times then convert that list of tuples into ...
Is there a scala equivalent to python's list comprehension
17,355,768
10
2013-06-28T01:16:28Z
17,355,900
15
2013-06-28T01:33:00Z
[ "python", "list", "scala" ]
I'm translating some of my python code to scala, and I was wondering if there's an equivalent to python's ``` [x for x in list if x!=somevalue] ``` Essentially I'm trying to remove certain elements from the list if it matches.
The closest analogue to a Python list comprehension would be `for (x <- list if x != somevalue) yield x` But since you're what you're doing is filtering, you might as well just use the `filter` method `list.filter(_ != somevalue)` or `list.filterNot(_ == somevalue)`
Python tkinter binding mousewheel to scrollbar
17,355,902
7
2013-06-28T01:33:11Z
17,457,843
18
2013-07-03T20:47:43Z
[ "python", "binding", "tkinter", "scrollbar", "mousewheel" ]
I have this scroll-able frame (frame inside canvas actually). ``` import Tkinter as tk class Scrollbarframe(): def __init__(self, parent,xsize,ysize,xcod,ycod): def ScrollAll(event): canvas1.configure(scrollregion=canvas1.bbox("all"),width=xsize,height=ysize,bg='white') self.parent=...
Perhaps the simplest solution is to make a global binding for the mousewheel. It will then fire no matter what widget is under the mouse or which widget has the keyboard focus. You can then unconditionally scroll the canvas, or you can be smart and figure out which of your windows should scroll. For example, on window...
how to use Google Shortener API with Python
17,357,351
6
2013-06-28T04:45:58Z
17,357,552
13
2013-06-28T05:04:29Z
[ "python", "google-api", "google-url-shortener" ]
I want to write an app to shorten url. This is my code: ``` import urllib, urllib2 import json def goo_shorten_url(url): post_url = 'https://www.googleapis.com/urlshortener/v1/url' postdata = urllib.urlencode({'longUrl':url}) headers = {'Content-Type':'application/json'} req = urllib2.Request( ...
I tried your code and couldn't make it work either, so I wrote it with [requests](http://docs.python-requests.org/en/latest/user/quickstart/#make-a-request): ``` import requests import json def goo_shorten_url(url): post_url = 'https://www.googleapis.com/urlshortener/v1/url' payload = {'longUrl': url} hea...
Implementing an algorithm to determine if a string has all unique characters
17,357,370
3
2013-06-28T04:47:53Z
17,357,428
15
2013-06-28T04:54:24Z
[ "python" ]
Context: I'm a CS n00b working my way through "Cracking the Coding Interview." The first problem asks to "implement an algorithm to determine if a string has all unique characters." My (likely naive) implementation is as follows: ``` def isUniqueChars2(string): uchars = [] for c in string: if c in uchars: ...
Here is how I would write this: ``` def unique(s): return len(set(s)) == len(s) ``` Strings are iterable so you can pass your argument directly to `set()` to get a set of the characters from the string (which by definition will not contain any duplicates). If the length of that set is the same as the length of th...
Download image with selenium python
17,361,742
11
2013-06-28T09:42:56Z
17,362,187
13
2013-06-28T10:06:39Z
[ "python", "firefox", "selenium", "selenium-webdriver" ]
I want get captcha image from browser. I have got a url of this picture, but the this picture changes each updated time (url is constant). Is there any solution to get picture from browser (like 'save picture as' button)? From the other hand, I think it should be work: 1. get screenshot of the browser 2. get positio...
Here's a complete example (using google's recaptcha as a target): ``` import urllib from selenium import webdriver driver = webdriver.Firefox() driver.get('http://www.google.com/recaptcha/demo/recaptcha') # get the image source img = driver.find_element_by_xpath('//div[@id="recaptcha_image"]/img') src = img.get_attr...
Celery Logs into file
17,366,579
6
2013-06-28T14:05:42Z
17,369,798
16
2013-06-28T16:49:15Z
[ "python", "celery" ]
Can some one pleas help how to get the celery task debug details to a log file .I have the requirement to have the details that a tasks does to be logged into a .log file Can you pleas give some suggestions on how this can be done without impacting the performance of the task
It's alway hard to answer with so little information in question, but I'll try. **Celery** have specific option `-f --logfile` which you can use: ``` -f LOGFILE, --logfile=LOGFILE Path to log file. If no logfile is specified, stderr is used. ``` To get information about other o...
Setuptools unable to use link from dependency_links
17,366,784
8
2013-06-28T14:16:49Z
17,442,663
13
2013-07-03T07:59:12Z
[ "python", "setuptools", "distribute" ]
I've been trying to install a package with the following setup configured: ``` setup( packages=find_packages(), include_package_data=True, install_requires=[ 'Django==1.5.1', 'xhtml2pdf', ], dependency_links=[ 'https://github.com/chrisglass/xhtml2pdf/zipball/28d12fcaafc4c47b...
Ok, so I solved (or hacked, depending on how you look at it) my own question. There were two issues with the code. The first issue was that the link was incorrect. Although I've seen it formatted like this elsewhere, it wouldn't work for me (whether using setuptools `mkvirtualenv mypackage` or distribute `mkvirtualen...
Python: Split list based on first character of word
17,366,788
4
2013-06-28T14:16:59Z
17,366,841
7
2013-06-28T14:18:51Z
[ "python", "list", "sorting", "split", "alphabetical" ]
Im kind of stuck on an issue and Ive gone round and round with it until ive confused myself. What I am trying to do is take a list of words: ``` ['About', 'Absolutely', 'After', 'Aint', 'Alabama', 'AlabamaBill', 'All', 'Also', 'Amos', 'And', 'Anyhow', 'Are', 'As', 'At', 'Aunt', 'Aw', 'Bedlam', 'Behind', 'Besides', 'B...
Use [`itertools.groupby()`](http://docs.python.org/2/library/itertools.html#itertools.groupby) to group your input by a specific key, such as the first letter: ``` from itertools import groupby from operator import itemgetter for letter, words in groupby(sorted(somelist), key=itemgetter(0)): print letter for ...
Why doesn't all() stop on the first False element?
17,366,817
3
2013-06-28T14:18:16Z
17,367,091
7
2013-06-28T14:29:17Z
[ "python" ]
From the [docs](http://docs.python.org/2/library/functions.html#all), `all` is equivalent to: ``` def all(iterable): for element in iterable: if not element: return False return True ``` Then why do I get this output: ``` # expecting: False $ python -c "print( all( (isinstance('foo', int...
One (fairly ugly) way to get the behaviour you want is via lambdas: ``` all(f() for f in (lambda: isinstance('foo', int), lambda: int('foo'))) ```
Plot a 3D surface from {x,y,z}-scatter data in python
17,367,558
11
2013-06-28T14:50:14Z
17,369,736
8
2013-06-28T16:46:10Z
[ "python", "3d", "matplotlib" ]
I'm trying to plot a 3D surface constructed to fit some {x,y,z} points in python -- ideally something like the Mathematica [`ListSurfacePlot3D`](http://reference.wolfram.com/mathematica/ref/ListSurfacePlot3D.html) function. Thus far I've tried `plot_surface` and `plot_wireframe` on my points to no avail. Only the axes...
`plot_surface` expects X,Y,Z values in the form of 2D arrays, as would be returned by `np.meshgrid`. When the inputs are regularly gridded in this way, the plot function implicitly knows which vertices in the surface are adjacent to one another and therefore should be joined with edges. In your example, however, you're...
trying to install pymssql on ubuntu 12.04 using pip
17,368,964
37
2013-06-28T16:02:13Z
17,378,879
84
2013-06-29T09:48:38Z
[ "python", "ubuntu", "ubuntu-12.04", "pip", "pymssql" ]
I am trying to install pymssql on ubuntu 12.04 using pip. This is the error I am getting. Any help would be greatly appreciated as I am completely lost! Tried googling this but unfortunately to no avail... ``` Downloading pymssql-2.0.0b1-dev-20130403.tar.gz (2.8Mb): 2.8Mb downloaded Running setup.py egg_info for ...
You need to install the FreeTDS development package (`freetds-dev`) before trying to install `pymssql` with pip: ``` $ sudo apt-get install freetds-dev ``` and then, in your *virtualenv* or wherever you wish to install it: ``` $ pip install pymssql ```
trying to install pymssql on ubuntu 12.04 using pip
17,368,964
37
2013-06-28T16:02:13Z
24,179,227
9
2014-06-12T07:57:46Z
[ "python", "ubuntu", "ubuntu-12.04", "pip", "pymssql" ]
I am trying to install pymssql on ubuntu 12.04 using pip. This is the error I am getting. Any help would be greatly appreciated as I am completely lost! Tried googling this but unfortunately to no avail... ``` Downloading pymssql-2.0.0b1-dev-20130403.tar.gz (2.8Mb): 2.8Mb downloaded Running setup.py egg_info for ...
Apart from freetds-dev, you need to install python-dev as well as follow. ``` sudo apt-get install python-dev ``` Or else, you will again face some error.
Python creating a smaller sub-array from a larger 2D NumPy array?
17,369,854
6
2013-06-28T16:52:48Z
17,370,240
7
2013-06-28T17:16:43Z
[ "python", "arrays", "numpy", "indexing" ]
So I have a large NumPy array that takes the following form: ``` data = [[2456447.64798471, 4, 15.717, 0.007, 5, 17.308, 0.019, 6, 13.965, 0.006], [2456447.6482855, 4, 15.768, 0.018, 5, 17.347, 0.024, 6, 14.001, 0.023], [2456447.648575, 4, 15.824, 0.02, 5, 17.383, 0.024, 6, 14.055, 0.023]] ``` I want ...
You could do this: ``` >>> data[:, [1, 2, 4, 5, 7, 8]] array([[ 4. , 15.717, 5. , 17.308, 6. , 13.965], [ 4. , 15.768, 5. , 17.347, 6. , 14.001], [ 4. , 15.824, 5. , 17.383, 6. , 14.055]]) ```
Python Slice Notation with Comma/List
17,370,820
9
2013-06-28T17:53:34Z
17,371,453
9
2013-06-28T18:37:19Z
[ "python", "list", "numpy", "slice" ]
I have come across some python code with slice notation that I am having trouble figuring out. It looks like slice notation but uses a comma and a list: ``` list[:, [1, 2, 3]] ``` Is this syntax valid? If so what does it do? **edit** looks like it is a 2D numpy array
Assuming that the object is really a `numpy` array, this is known as [advanced indexing](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing), and picks out the specified columns: ``` >>> import numpy as np >>> a = np.arange(12).reshape(3,4) >>> a array([[ 0, 1, 2, 3], [ 4, 5, ...
Appending an id to a list if not already present
17,370,984
7
2013-06-28T18:04:00Z
17,371,105
17
2013-06-28T18:11:45Z
[ "python" ]
I am trying to check if id is in a list and append the id only if its not in the list using the below code..however I see that the id is getting appended even though id is already present in the list.. can anyone provide inputs on what is wrong here? ``` list = ['350882 348521 350166\r\n'] id = 348521 if id...
What you are trying to do can almost certainly be achieved with a set. ``` >>> x = set([1,2,3]) >>> x.add(2) >>> x set([1, 2, 3]) >>> x.add(4) >>> x.add(4) >>> x set([1, 2, 3, 4]) >>> ``` using a set's add method you can build your unique set of ids very quickly. Or if you already have a list ``` unique_ids = set(id...
Tweepy (Twitter API) Not Returning all Search Results
17,371,652
4
2013-06-28T18:51:16Z
17,411,503
16
2013-07-01T18:47:16Z
[ "python", "search", "twitter", "tweepy" ]
I'm using the search feature with Tweepy for Twitter and for some reason the search results are limited to 15. Here is my code ``` results=api.search(q="Football",rpp=1000) for result in results: print "%s" %(clNormalizeString(result.text)) print len(results) ``` and only 15 results are returned. Does it have s...
The question is more about Twitter API instead of tweepy itself. According to the [documentation](https://dev.twitter.com/docs/api/1.1/get/search/tweets), `count` parameter defines: > The number of tweets to return per page, up to a maximum of 100. > Defaults to 15. This was formerly the "rpp" parameter in the old > ...
In Python why is [2] less than (1,)?
17,371,854
19
2013-06-28T19:03:37Z
17,371,877
23
2013-06-28T19:04:39Z
[ "python" ]
## BACKGROUND I've been trying to work out why my AI has been making some crazy moves and I traced the problem back to the following behaviour when using Python 2.7.2 ``` >>> print [2]>[1] True >>> print (2,)>(1,) True >>> print [2]>(1,) False (WHY?) >>> print [2]<[1] False >>> print (2,)<(1,) False ...
They're not the same type. > each element must compare equal and **the two sequences must be of the same type** and have the same length So the comparison is being performed based on type, not on actual data stored in the sequences. On python3.x, this comparison raises a `TypeError`: ``` Python 3.2 (r32:88445, May 1...
In Python why is [2] less than (1,)?
17,371,854
19
2013-06-28T19:03:37Z
17,371,885
26
2013-06-28T19:05:13Z
[ "python" ]
## BACKGROUND I've been trying to work out why my AI has been making some crazy moves and I traced the problem back to the following behaviour when using Python 2.7.2 ``` >>> print [2]>[1] True >>> print (2,)>(1,) True >>> print [2]>(1,) False (WHY?) >>> print [2]<[1] False >>> print (2,)<(1,) False ...
Sequences are not coerced when comparing, hence their type name is compared instead. ``` >>> 'list' < 'tuple' True ```
Python property getter and setter decorator not callable
17,372,152
2
2013-06-28T19:22:29Z
17,372,187
8
2013-06-28T19:24:29Z
[ "python" ]
I'm doing something similar to the following ``` class Parrot(object): def __init__(self): self.__voltage = 100000 @property def voltage(self): """Get the current voltage.""" return self.__voltage ``` However it sees the voltage property as an int so when I call like so ``` p = P...
The whole point of the getter is that it returns the value without being called. `p.voltage` returns the integer object, so running `p.voltage()` is equivalent to `100()` or something. There can still be cases where you want to call the value of a property, like if the value is itself a function. But you don't need it...
Regular expression in python is skipping first 2 characters of line
17,372,334
3
2013-06-28T19:34:24Z
17,372,411
7
2013-06-28T19:40:24Z
[ "python", "regex", "expression" ]
I have a text file that looks like this ``` Name #Variants #Cases #Controls CNGA3 5 5 0 GPR125 4 3 0 IGHMBP2 4 4 0 STK11IP 4 4 0 ACAD9 3 3 0 ANKRD17 3 3 0 ``` I want to parse through this file and return all of the gene names (the `name` column) to a list - `list_of_genes`, or some...
Your problem is here: ``` match=gene.match(line, re.IGNORECASE) ``` The [second parameter to a regex object's `match()` method](http://docs.python.org/2/library/re.html#re.RegexObject.match) is `pos`, meaning the starting position for the match operation. `re.IGNORECASE` happens to be `2`. You have already defined t...
Why is AssertionError not displayed?
17,372,957
2
2013-06-28T20:16:23Z
17,372,998
13
2013-06-28T20:18:58Z
[ "python" ]
As an experiment, I tried catching a failed assertion. ``` try: assert 1==2 except Exception as e: print e ``` Why is nothing displayed?
``` >>> try: assert 1==2 ... except Exception as e: print type(e) ... <type 'exceptions.AssertionError'> ``` or ``` >>> try: assert 1==2, "They Are Not Equal!!" ... except Exception as e: print e ... They Are Not Equal!! ``` as to why: it is calling the `__str__` method of the exception when you call `print`... sinc...
Read previous line in a file python
17,373,118
3
2013-06-28T20:28:09Z
17,373,385
7
2013-06-28T20:46:02Z
[ "python", "file", "loops" ]
I need to get the value of the previous line in a file and compare it with the current line as I'm iterating through the file. The file is HUGE so I can't read it whole or randomly accessing a line number with `linecache` because the library function still reads the whole file into memory anyway. **EDIT** I'm so sorry...
Just save the previous when you iterate to the next ``` prevLine = "" for line in file: # do some work here prevLine = line ``` This will store the previous line in `prevLine` while you are looping **edit** apparently OP needs to read this file backwards: aaand after like an hour of research I failed multip...
Using Curly Braces to Initialize Set
17,373,161
29
2013-06-28T20:31:24Z
17,373,237
32
2013-06-28T20:36:54Z
[ "python", "python-2.7" ]
I'm learning python, and I have a novice question about initializing sets. Through testing, I've discovered that a set can be initialized like so: ``` my_set = {'foo', 'bar', 'baz'} ``` Are there any disadvantages of doing it this way, as opposed to the standard way of: ``` my_set = set(['foo', 'bar', 'baz']) ``` o...
There are two obvious issues with the set literal syntax: ``` my_set = {'foo', 'bar', 'baz'} ``` 1. It's not available before Python 2.7 2. There's no way to express an empty set using that syntax (using `{}` creates an empty dict) Those may or may not be important to you. The section of the docs outlining this syn...
Using Curly Braces to Initialize Set
17,373,161
29
2013-06-28T20:31:24Z
17,373,286
13
2013-06-28T20:40:06Z
[ "python", "python-2.7" ]
I'm learning python, and I have a novice question about initializing sets. Through testing, I've discovered that a set can be initialized like so: ``` my_set = {'foo', 'bar', 'baz'} ``` Are there any disadvantages of doing it this way, as opposed to the standard way of: ``` my_set = set(['foo', 'bar', 'baz']) ``` o...
From [Python 3 documentation](http://docs.python.org/3/tutorial/datastructures.html#sets) (**the same holds for python 2.7**): > Curly braces or the set() function can be used to create sets. Note: > to create an empty set you have to use set(), not {}; the latter > creates an empty dictionary, a data structure that w...
Using Curly Braces to Initialize Set
17,373,161
29
2013-06-28T20:31:24Z
22,440,130
19
2014-03-16T17:17:53Z
[ "python", "python-2.7" ]
I'm learning python, and I have a novice question about initializing sets. Through testing, I've discovered that a set can be initialized like so: ``` my_set = {'foo', 'bar', 'baz'} ``` Are there any disadvantages of doing it this way, as opposed to the standard way of: ``` my_set = set(['foo', 'bar', 'baz']) ``` o...
Compare also the difference between `{}` and `set()` with a single word argument. ``` >>> a = set('aardvark') >>> a {'d', 'v', 'a', 'r', 'k'} >>> b = {'aardvark'} >>> b {'aardvark'} ``` but both `a` and `b` are sets of course.
pip/easy_install failure: failed to create process
17,373,265
19
2013-06-28T20:38:53Z
17,560,177
13
2013-07-09T23:47:15Z
[ "python", "pip", "easy-install" ]
After following this article: [How to install pip on windows?](http://stackoverflow.com/questions/4750806/how-to-install-pip-on-windows) on my Windows system using Enthought Canopy 64 Bit system, I cannot get pip or easy\_install to work due to error: ``` pip install requests failed to create process ``` I tried re-i...
When I encountered this, it was because I'd manually renamed the directory python was in. This meant that both setuptools and pip had to be reinstalled. Or, I had to manually rename the python directory to what it had been previously.
pip/easy_install failure: failed to create process
17,373,265
19
2013-06-28T20:38:53Z
19,248,259
8
2013-10-08T12:52:30Z
[ "python", "pip", "easy-install" ]
After following this article: [How to install pip on windows?](http://stackoverflow.com/questions/4750806/how-to-install-pip-on-windows) on my Windows system using Enthought Canopy 64 Bit system, I cannot get pip or easy\_install to work due to error: ``` pip install requests failed to create process ``` I tried re-i...
If you intentionally want to rename the folder where python.exe resides, you should also modify all python files in the Scripts folder. So a third solution would be to modify the python files as well: the first line in pip-2.7-script.py originally contain: ``` #!C:\OriginalPythonDir\python.exe ``` Modifying this path...
pip/easy_install failure: failed to create process
17,373,265
19
2013-06-28T20:38:53Z
30,832,759
9
2015-06-14T18:04:17Z
[ "python", "pip", "easy-install" ]
After following this article: [How to install pip on windows?](http://stackoverflow.com/questions/4750806/how-to-install-pip-on-windows) on my Windows system using Enthought Canopy 64 Bit system, I cannot get pip or easy\_install to work due to error: ``` pip install requests failed to create process ``` I tried re-i...
Just ran into this. Sort of. Pip worked for me, but after installing [pytest-watch](http://github.com/joeyespo/pytest-watch), running the `ptw` script was giving this error. For some reason, pip stopped quoting the #! in `ptw-script.py`: ``` #!C:\Program Files (x86)\Python\python.exe ``` It worked after I added quot...
searching for available python packages pip
17,373,473
17
2013-06-28T20:51:40Z
17,373,592
22
2013-06-28T21:00:16Z
[ "python", "pip", "easy-install", "package-managers" ]
Through the terminal I would like to be able to search for available python packages. Currently I am using `pip` and/or `easy_install`. I would like functionality similar to `apt-cache` in Ubuntu. Specifically that is: 1. Be able to search the python package index for packages given a term. Similar to `apt-cache searc...
To search for a package: `pip search [package-name]` should do the same.
How can i get list of only folders in amazon S3 using python boto
17,375,127
20
2013-06-28T23:34:02Z
19,434,162
34
2013-10-17T18:13:31Z
[ "python", "amazon-s3", "boto" ]
I am using boto and python and amazon s3. If i use `[key.name for key in list(self.bucket.list())]` then i get all the keys of all the files. ``` mybucket/files/pdf/abc.pdf mybucket/files/pdf/abc2.pdf mybucket/files/pdf/abc3.pdf mybucket/files/pdf/abc4.pdf mybucket/files/pdf/new/ mybucket/files/pdf/new/abc.pdf mybu...
building on sethwm's answer: To get the top level directories: ``` list(bucket.list("", "/")) ``` To get the subdirectories of `files`: ``` list(bucket.list("files/", "/") ``` and so on.
How can i get list of only folders in amazon S3 using python boto
17,375,127
20
2013-06-28T23:34:02Z
31,703,132
10
2015-07-29T14:16:59Z
[ "python", "amazon-s3", "boto" ]
I am using boto and python and amazon s3. If i use `[key.name for key in list(self.bucket.list())]` then i get all the keys of all the files. ``` mybucket/files/pdf/abc.pdf mybucket/files/pdf/abc2.pdf mybucket/files/pdf/abc3.pdf mybucket/files/pdf/abc4.pdf mybucket/files/pdf/new/ mybucket/files/pdf/new/abc.pdf mybu...
As pointed in one of the comments approach suggested by j1m returns a prefix object. If you are after a name/path you can use variable **name**. For example: ``` import boto import boto.s3 conn = boto.s3.connect_to_region('us-west-2') bucket = conn.get_bucket(your_bucket) folders = bucket.list("","/") for folder in ...
Testing code that requires a Flask app or request context
17,375,340
12
2013-06-29T00:03:15Z
17,377,101
21
2013-06-29T05:43:35Z
[ "python", "flask" ]
I am getting `working outside of request context` when trying to access `session` in a test. How can I set up a context when I'm testing something that requires one? ``` import unittest from flask import Flask, session app = Flask(__name__) @app.route('/') def hello_world(): t = Test() hello = t.hello() ...
If you want to make a request to your application, use the [`test_client`](http://flask.pocoo.org/docs/0.10/api/#flask.Flask.test_client). ``` c = app.test_client() response = c.get('/test/url') # test response ``` If you want to test code which uses an application context (`current_app`, `g`, `url_for`), push an [`a...
multidimensional numpy array -- reverse along a given axis
17,375,383
5
2013-06-29T00:10:34Z
17,375,648
7
2013-06-29T00:54:59Z
[ "python", "arrays", "numpy" ]
Let's say I have a multidimensional array with a shape that I don't know until runtime. How can I reverse it along a given axis k, also not known until runtime? The notation `somearray[:,:,::-1,:,:]` relies on static dimension references, [as in this other SO question](http://stackoverflow.com/questions/7416170/numpy...
I would use a tuple of `slice` objects for this: ``` def reversedim(M,k=0): idx = tuple((slice(None,None,-1) if ii == k else slice(None) for ii in xrange(M.ndim))) return M[idx] ```
multidimensional numpy array -- reverse along a given axis
17,375,383
5
2013-06-29T00:10:34Z
17,375,993
9
2013-06-29T02:07:20Z
[ "python", "arrays", "numpy" ]
Let's say I have a multidimensional array with a shape that I don't know until runtime. How can I reverse it along a given axis k, also not known until runtime? The notation `somearray[:,:,::-1,:,:]` relies on static dimension references, [as in this other SO question](http://stackoverflow.com/questions/7416170/numpy...
You can either construct a tuple of `slice` objects such as @ali\_m suggests, or do something like this: ``` reversed_arr = np.swapaxes(np.swapaxes(arr, 0, k)[::-1], 0, k) ``` This places the desired axis at the front of the shape tuple, then reverses that first axis, and then returns it to its original position. So...
Python requests urlencode not working?
17,375,624
3
2013-06-29T00:50:44Z
17,378,332
9
2013-06-29T08:38:05Z
[ "python", "facebook", "url", "facebook-fql", "python-requests" ]
EDIT: I figured out the problem. The # in #user\_sex is not being converting to %23 by python requests. Is there a way to force python requests to convert # to %23 or will I just have to hand code that part? I'm trying to make a facebook fql multiquery. When I use the fql\_url below ``` fql_url = ( 'https://graph...
The problem is, that `#` is indeed a valid character in an URL. It denotes the fragment part. As the fragment is always resolved by the useragent it is never sent to the server. You can try this: ``` >>> import urllib3 >>> urllib3.util.parse_url(fql_url) Url(scheme='https', auth=None, host='graph.facebook.com', port=N...
Decode JSON in Bash using python mjson.tool
17,375,940
2
2013-06-29T01:55:31Z
17,375,969
14
2013-06-29T02:01:46Z
[ "python", "json", "bash", "grep" ]
I need to get a `key` from JSON in standard bash, and found the following: ``` echo '{"first_key": "value", "second_key": "value2"}' | python -mjson.tool | grep 'first_key' ``` But this returns: ``` "first_key": "value", ``` How can I just return `value`, i.e. not the key, and remove the quotes and comma. Thanks.
``` $ echo '{"first_key": "value", "second_key": "value2"}' | python -c 'import sys, json; print json.load(sys.stdin)[sys.argv[1]]' first_key value ```
Remove common letters in strings
17,375,984
6
2013-06-29T02:05:02Z
17,376,030
7
2013-06-29T02:13:53Z
[ "python", "string" ]
So I have an interesting problem. I'm trying to write some word jumbles, and I need to know which letters I've used and which I haven't. So far I have the code below: ``` def remove_common(x,y): sort = sort = lambda x: "".join(c for c in sorted(x.lower()) if c.isalpha()) x,y = sort(x), sort(y) //some code t...
You can use `collections.Counter` objects, which can be subtracted from each other: ``` import collections def remove_common(x,y): count = lambda x: collections.Counter(c for c in x.lower() if c.isalpha()) cx, cy = count(x), count(y) diff = cx - cy rev_diff = cy - cx assert len(rev_diff) == 0, "%...
Django Inner Join Queryset
17,375,997
7
2013-06-29T02:08:27Z
17,376,278
11
2013-06-29T03:05:00Z
[ "python", "django", "inner-join", "django-queryset" ]
I'm working with Django and I need to do a queryset using two inner joins. I have three models A, B, and C and I want to do a query like the following in psql: `select DISTINCT a from A inner join B on B.a_id = A.id inner join C on C.b_id = B.id;` Models: (only included relevant fields) ``` class A(models.Model): ...
`A.objects.filter(b__c__isnull=False)` results a sql w/ same result: ``` SELECT DISTINCT a.* FROM a INNER JOIN b ON (a.id = b.a_id) INNER JOIN c ON (b.id=c.b_id) WHERE c.id IS NOT NULL; ``` P.S. Why do you use `IntegerField` instead of `AutoField` for ids?
Shared variable in python's multiprocessing
17,377,426
6
2013-06-29T06:30:38Z
17,393,879
7
2013-06-30T19:07:01Z
[ "python", "multiprocessing" ]
First question is what is the difference between Value and Manager().Value? Second, is it possible to share integer variable without using Value? Below is my sample code. What I want is getting a dict with a value of integer, not Value. What I did is just change it all after the process. Is there any easier way? ``` ...
When you use [`Value`](http://docs.python.org/2/library/multiprocessing.html#multiprocessing.Value) you get a [`ctypes`](http://docs.python.org/2/library/ctypes.html) object in shared memory that by default is synchronized using [`RLock`](http://docs.python.org/2/library/threading.html#threading.RLock). When you use [`...
Splat operators in JavaScript, equivalent to *args and **kwargs in Python?
17,380,315
36
2013-06-29T12:44:54Z
17,380,331
7
2013-06-29T12:46:17Z
[ "javascript", "python" ]
I use Python a lot, and I am just quickly learning JavaScript right now (or should I say re-learning). So, I wanted to ask, what is the equivalent of `*args` and `**kwargs` in JavaScript?
The nearest equivalent is the [`arguments` pseudo-array](http://javascriptweblog.wordpress.com/2011/01/18/javascripts-arguments-object-and-beyond/).
Splat operators in JavaScript, equivalent to *args and **kwargs in Python?
17,380,315
36
2013-06-29T12:44:54Z
17,381,144
30
2013-06-29T14:18:09Z
[ "javascript", "python" ]
I use Python a lot, and I am just quickly learning JavaScript right now (or should I say re-learning). So, I wanted to ask, what is the equivalent of `*args` and `**kwargs` in JavaScript?
The closest idiom for `*args` would be ``` function func (a, b /*, *args*/) { var star_args = Array.prototype.slice.call (arguments, func.length); /* now star_args[0] is the first undeclared argument */ } ``` taking advantage of the fact that `Function.length` is the number of arguments given in the function ...
Splat operators in JavaScript, equivalent to *args and **kwargs in Python?
17,380,315
36
2013-06-29T12:44:54Z
19,938,175
13
2013-11-12T19:28:36Z
[ "javascript", "python" ]
I use Python a lot, and I am just quickly learning JavaScript right now (or should I say re-learning). So, I wanted to ask, what is the equivalent of `*args` and `**kwargs` in JavaScript?
I found a good solution here: <http://readystate4.com/2008/08/17/javascript-argument-unpacking-converting-an-array-into-a-list-of-arguments/> Basically, use `function.apply(obj, [args])` instead of `function.call`. apply takes an array as the 2nd arg and 'splats' it for you.
Splat operators in JavaScript, equivalent to *args and **kwargs in Python?
17,380,315
36
2013-06-29T12:44:54Z
28,653,071
11
2015-02-22T00:24:09Z
[ "javascript", "python" ]
I use Python a lot, and I am just quickly learning JavaScript right now (or should I say re-learning). So, I wanted to ask, what is the equivalent of `*args` and `**kwargs` in JavaScript?
ES6 adds a spread operator to JavaScript. [Some browsers](http://kangax.github.io/compat-table/es6/) already have it implemented. The following code was tested on Firefox 35. ``` function choose(choice, ...availableChoices) { return availableChoices[choice]; } choose(2, "one", "two", "three", "four"); // returns ...
How to split a string using an empty separator in Python
17,380,592
11
2013-06-29T13:14:14Z
17,380,603
23
2013-06-29T13:15:16Z
[ "python", "string", "split" ]
What is a good way to do `some_string.split('')` in python? This syntax gives an error: ``` a = '1111' a.split('') ValueError: empty separator ``` I would like to obtain: ``` ['1', '1', '1', '1'] ```
Use [`list()`](http://docs.python.org/2/library/functions.html#list): ``` >>> list('1111') ['1', '1', '1', '1'] ``` Alternatively, you can use [`map()`](http://docs.python.org/2/library/functions.html#map): ``` >>> map(None, '1111') ['1', '1', '1', '1'] ``` Time differences: ``` $ python -m timeit "list('1111')" 1...
large graph visualization with python and networkx
17,381,006
14
2013-06-29T14:04:07Z
17,388,676
8
2013-06-30T08:44:32Z
[ "python", "visualization", "data-visualization", "networkx" ]
I am having trouble with large graph visualization in python and [networkx](http://networkx.github.io/). The graph is wish to visualize is directed, and has an edge and vertex set size of 215,000 From the documenation (which is linked at the top page) it is clear that networkx supports plotting with `matplotlib` and Gr...
``` from matplotlib import pylab import networkx as nx def save_graph(graph,file_name): #initialze Figure plt.figure(num=None, figsize=(20, 20), dpi=80) plt.axis('off') fig = plt.figure(1) pos = nx.spring_layout(graph) nx.draw_networkx_nodes(graph,pos) nx.draw_networkx_edges(graph,pos) ...
Python dir() equivalent in JavaScript?
17,381,178
4
2013-06-29T14:23:40Z
17,381,209
8
2013-06-29T14:27:36Z
[ "javascript", "python" ]
What I loved about Python was that if you wanted to know something about a particular module, you could just go something like this: ``` dir(django.auth.models) ``` and it would give you all the things inside of `models`, is there something similar to this in JavaScript?
You could use [`Object.keys()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys), e.g.: ``` > Object.keys(window) ["top", "window", "location", "external", "chrome", "Intl", "v8Intl", "document", "$", "jQuery", "MSIsPlayback", "i", "prepareEditor", "StackExchange", "scriptS...
Is there any method to using seperate scrapy pipeline for each spider?
17,381,237
2
2013-06-29T14:29:56Z
17,383,776
8
2013-06-29T19:05:39Z
[ "python", "web-scraping", "scrapy", "scrapy-spider" ]
I wanna to fetch web pages under different domain, that means I have to use different spider under the command "scrapy crawl myspider". However, I have to use different pipeline logic to put the data into database since the content of web pages are different. But for every spider, they have to go through all of the pip...
`ITEM_PIPELINES` setting is defined globally for all spiders in the project during the engine start. It cannot be changed per spider on the fly. Here are some options to consider: * Change the code of pipelines. Skip/continue processing items returned by spiders in the `process_item` method of your pipeline, e.g.: ...
If statement falsely triggered
17,381,435
2
2013-06-29T14:50:37Z
17,381,471
12
2013-06-29T14:54:25Z
[ "python", "if-statement" ]
I have a python script parse an incoming payload at set a variable named "confidence" and "id" then it will evaluate if the id is equal to sam@sam and that confidence is greater than or equal to 70. Now the id is equal sam@sam but confidence is not, it will still trigger! whats wrong with my code!!? ``` p = eg.event.p...
The problem is that "confidence" is a string and you are comparing it to a number. The result of comparing string to a number is consistent, but not necessarily the one you want. Fix: ``` confidence = int(p[1].strip()) ```
python pandas/numpy True/False to 1/0 mapping
17,383,094
17
2013-06-29T17:53:19Z
17,383,325
8
2013-06-29T18:17:18Z
[ "python", "numpy", "pandas" ]
I have a column in python pandas DataFrame that has boolean True/False values, but for further calculations I need 1/0 representation. Is there a quick pandas/numpy way to do that? EDIT: The answers below do not seem to hold in the case of numpy that, given an array with both integers and True/False values, returns `d...
You also can do this directly on Frames ``` In [104]: df = DataFrame(dict(A = True, B = False),index=range(3)) In [105]: df Out[105]: A B 0 True False 1 True False 2 True False In [106]: df.dtypes Out[106]: A bool B bool dtype: object In [107]: df.astype(int) Out[107]: A B 0 1 0 1 1...
python pandas/numpy True/False to 1/0 mapping
17,383,094
17
2013-06-29T17:53:19Z
27,362,540
19
2014-12-08T16:36:19Z
[ "python", "numpy", "pandas" ]
I have a column in python pandas DataFrame that has boolean True/False values, but for further calculations I need 1/0 representation. Is there a quick pandas/numpy way to do that? EDIT: The answers below do not seem to hold in the case of numpy that, given an array with both integers and True/False values, returns `d...
Just to very explicitly answer the question of how to convert a single column of boolean values to a column of integers 1 or 0: `df.somecolumn = df.somecolumn.astype(int)`
Argv - String into Integer
17,383,470
5
2013-06-29T18:32:32Z
17,383,481
7
2013-06-29T18:33:53Z
[ "python", "argv" ]
I'm pretty new at python and I've been playing with argv. I wrote this simple program here and getting an error that says : > TypeError: %d format: a number is required, not str ``` from sys import argv file_name, num1, num2 = argv int(argv[1]) int(argv[2]) def addfunc(num1, num2): print "This function adds %d a...
`sys.argv` is indeed a list of strings. Use the `int()` function to turn a string to a number, provided the string *can* be converted. You need to *assign* the result, however: ``` num1 = int(argv[1]) num2 = int(argv[2]) ``` or simply use: ``` num1, num2 = int(num1), int(num2) ``` You did call `int()` but ignored ...
Python: accessing attributes and methods of one class in another
17,383,716
7
2013-06-29T18:59:39Z
17,383,736
9
2013-06-29T19:01:28Z
[ "python", "oop" ]
Let's say I have two classes A and B: ``` Class A: # A's attributes and methods here Class B: # B's attributes and methods here ``` Now I can assess A's properties in object of B class as follows: ``` a_obj = A() b_obj = B(a_obj) ``` What I need is a two way access. How do I access A's properties in B and B's...
You need to create pointers either way: ``` class A(object): parent = None class B(object): def __init__(self, child): self.child = child child.parent = self ``` Now `A` can refer to `self.parent` (provided it is not `None`), and `B` can refer to `self.child`. If you try to make an instance ...
How to handle nested parentheses with regex?
17,384,479
4
2013-06-29T20:41:56Z
17,384,502
8
2013-06-29T20:44:02Z
[ "python", "regex" ]
I came up with a regex string that parses the given text into 3 categories: * in parentheses * in brackets * neither. Like this: ``` \[.+?\]|\(.+?\)|[\w+ ?]+ ``` My intention is to use the outermost operator only. So, given `a(b[c]d)e`, the split is going to be: ``` a || (b[c]d) || e ``` It works fine given paren...
Standard1 regular expressions are not sophisticated enough to match nested structures like that. The best way to approach this is probably to traverse the string and keep track of opening / closing bracket pairs. --- 1 I said *standard*, but not all regular expression engines are indeed standard. You might be able to...
Python: detect when a socket disconnects for any reason?
17,386,487
11
2013-06-30T02:13:37Z
21,802,953
11
2014-02-15T20:07:47Z
[ "python", "sockets" ]
I'm writing an app in Python 2.7.5 using the raw socket interface (`import socket`). I need to know if there's a way I can either register some sort of event, or easily test at a regular interval, if a TCP socket connection is still connected and established. Most of the advice I've found says things like "just try t...
Use `select` like this tutorial suggested <http://docs.python.org/2/howto/sockets.html#non-blocking-sockets> > If a socket is in the output readable list, you can be as-close-to-certain-as-we-ever-get-in-this-business that a recv on that socket will return something. Same idea for the writable list. You’ll be able t...
Does anaconda create a separate PYTHONPATH variable for each new environment?
17,386,880
17
2013-06-30T03:33:32Z
17,407,341
13
2013-07-01T14:49:53Z
[ "python", "scipy", "environment-variables", "anaconda" ]
I am starting to work with the Anaconda package from Continuum.io to do scipy work. I have been able to get anaconda up and running, but I cannot tell whether anaconda creates a new PYTHONPATH environment variable for each new environment it creates, or whether it relies on the common system PYTHONPATH? I could not fin...
No, the only thing that needs to be modified for an Anaconda environment is the PATH (so that it gets the right Python from the environment `bin/` directory, or `Scripts\` on Windows). The way Anaconda environments work is that they hard link everything that is installed into the environment. For all intents and purpo...
Does anaconda create a separate PYTHONPATH variable for each new environment?
17,386,880
17
2013-06-30T03:33:32Z
31,841,132
8
2015-08-05T19:24:28Z
[ "python", "scipy", "environment-variables", "anaconda" ]
I am starting to work with the Anaconda package from Continuum.io to do scipy work. I have been able to get anaconda up and running, but I cannot tell whether anaconda creates a new PYTHONPATH environment variable for each new environment it creates, or whether it relies on the common system PYTHONPATH? I could not fin...
Anaconda does not use the `PYTHONPATH`. One should however note that if the `PYTHONPATH` is set it could be used to load a library that is not in the anaconda environment. That is why before activating an environment it might be good to do a ``` unset PYTHONPATH ``` For instance this PYTHONPATH points to an incorrect...
Python string similarity with probability
17,388,213
51
2013-06-30T07:35:23Z
17,388,505
113
2013-06-30T08:18:52Z
[ "python", "probability" ]
How do i get the probability of a string being similar to another string in python? I want to get a decimal value like: `0.9 #means 90%` etc. preferably with standard python and library. e.g. : `similar("Apple","Appel") #would have a high prob.` `similar("Apple","Mango") #would have a lower prob.`
There is a built in. ``` from difflib import SequenceMatcher def similar(a, b): return SequenceMatcher(None, a, b).ratio() ``` Using it: ``` >>> similar("Apple","Appel") 0.8 >>> similar("Apple","Mango") 0.0 ```
Python string similarity with probability
17,388,213
51
2013-06-30T07:35:23Z
17,388,687
9
2013-06-30T08:45:51Z
[ "python", "probability" ]
How do i get the probability of a string being similar to another string in python? I want to get a decimal value like: `0.9 #means 90%` etc. preferably with standard python and library. e.g. : `similar("Apple","Appel") #would have a high prob.` `similar("Apple","Mango") #would have a lower prob.`
I think maybe you are looking for an algorithm describing the distance between strings. Here are some you may refer to: 1. [Hamming distance](http://en.wikipedia.org/wiki/Hamming_distance) 2. [Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance) 3. [Damerau–Levenshtein distance](http://en.wikiped...
Python functools partial efficiency
17,388,438
9
2013-06-30T08:09:20Z
17,388,981
8
2013-06-30T09:31:13Z
[ "python", "function", "partial", "functools" ]
I have been working with Python and I set up the following code situation: ``` import timeit setting = """ import functools def f(a,b,c): pass g = functools.partial(f,c=3) h = functools.partial(f,b=5,c=3) i = functools.partial(f,a=4,b=5,c=3) """ print timeit.timeit('f(4,5,3)', setup = setting, number=10...
> Why do the calls to the partial functions take longer? The code with `partial` takes about two times longer because of the additional function call. Function calls [are expensive:](http://wiki.python.org/moin/PythonSpeed/PerformanceTips) > Function call overhead in Python is relatively high, especially compared wit...
find whether the string starts and ends with the same word
17,389,109
4
2013-06-30T09:49:54Z
17,389,125
7
2013-06-30T09:52:28Z
[ "python", "regex" ]
I am trying to check whether the string starts and ends with the same word. eg`earth`. ``` s=raw_input(); m=re.search(r"^(earth).*(earth)$",s) if m is not None: print "found" ``` **my problem is when the string consists only of one word** eg: `earth` At present I have hard coded this case by ``` if m is not Non...
Use the [`str.startswith`](http://docs.python.org/2/library/stdtypes.html#str.startswith) and [`str.endswith`](http://docs.python.org/2/library/stdtypes.html#str.endswith) methods instead. ``` >>> 'earth'.startswith('earth') True >>> 'earth'.endswith('earth') True ``` You can simply combine them into a single functio...
How to speed up Pandas multilevel dataframe sum?
17,390,886
2
2013-06-30T13:35:25Z
17,394,064
9
2013-06-30T19:28:48Z
[ "python", "performance", "pandas", "cython" ]
I am trying to speed up the sum for several big multilevel dataframes. Here is a sample: ``` df1 = mul_df(5000,30,400) # mul_df to create a big multilevel dataframe #let df2, df3, df4 = df1, df1, df1 to minimize the memory usage, #they can also be mul_df(5000,30,400) df2, df3, df4 = df1, df1, df1 In [12]: timeit d...
method 1: On my machine not so bad (with `numexpr` disabled) ``` In [41]: from pandas.core import expressions as expr In [42]: expr.set_use_numexpr(False) In [43]: %timeit df1+df2+df3+df4 1 loops, best of 3: 349 ms per loop ``` method 2: Using `numexpr` (which is by default enabled if `numexpr` is installed) ``` I...
uwsgi + Flask + virtualenv ImportError: no module named site
17,391,605
15
2013-06-30T14:53:49Z
19,406,613
18
2013-10-16T14:49:11Z
[ "python", "flask", "virtualenv", "uwsgi" ]
(Other posts on SO are similar, but none have the specific combination of uwsgi + Flask + virtualenv) ([This one is closest](http://stackoverflow.com/questions/16605048/flasknginxuwsgi-importerror-no-module-named-site)) I installed uwsgi via apt-get. I also tried pip install wsgi. Both gave me the same issue. Test co...
**See the answer from @JRajan first.** If you're sure you just want to suppress the error, mouseover below. > Add `--no-site` to your command or `no-site=true` to your uwsgi.ini file.
uwsgi + Flask + virtualenv ImportError: no module named site
17,391,605
15
2013-06-30T14:53:49Z
28,923,037
15
2015-03-08T04:19:45Z
[ "python", "flask", "virtualenv", "uwsgi" ]
(Other posts on SO are similar, but none have the specific combination of uwsgi + Flask + virtualenv) ([This one is closest](http://stackoverflow.com/questions/16605048/flasknginxuwsgi-importerror-no-module-named-site)) I installed uwsgi via apt-get. I also tried pip install wsgi. Both gave me the same issue. Test co...
The path to your virtual environment is wrong. That's the reaon for this error. I'm using virtualenvwrapper and my virtual environments are set at ~/.virtualenvs. So in my case, the uwsgi call would look something like ``` sudo uwsgi -s /tmp/uwsgi.sock -w myapp:app -H ~/.virtualenvs/myapp ``` Hope this helps next ti...