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
ImportError: No Module Named bs4 (BeautifulSoup)
11,783,875
58
2012-08-02T18:47:00Z
31,221,231
11
2015-07-04T13:35:50Z
[ "python", "beautifulsoup", "flask", "importerror" ]
I'm working in Python and using Flask. When I run my main Python file on my computer, it works perfectly, but when I activate venv and run the Flask Python file in the terminal, it says that my main Python file has "No Module Named bs4." Any comments or advice is greatly appreciated.
For **python2.x**: ``` sudo pip install BeautifulSoup4 ``` For **python3**: ``` sudo apt-get install python3-bs4 ```
How to wait for 20 secs for user to press any key?
11,783,920
5
2012-08-02T18:51:29Z
11,784,277
7
2012-08-02T19:15:52Z
[ "python", "python-2.5" ]
How can I wait for user to press any key for 20 secs? I.e. I show the message and it counts 20 secs, the code continues execution either if 20 secs are passed OR if user pressed any key. How can I do it with python?
If you're on Windows: ``` def wait_for_user(secs): import msvcrt import time start = time.time() while True: if msvcrt.kbhit(): msvcrt.getch() break if time.time() - start > secs: break ```
Python memory usage of numpy arrays
11,784,329
51
2012-08-02T19:19:22Z
11,784,399
82
2012-08-02T19:24:14Z
[ "python", "numpy", "sys" ]
I'm using python to analyse some large files and I'm running into memory issues, so I've been using sys.getsizeof() to try and keep track of the usage, but it's behaviour with numpy arrays is bizarre. Here's an example involving a map of albedos that I'm having to open: ``` >>> import numpy as np >>> import struct >>>...
You can use `array.nbytes` for numpy arrays, for example: ``` >>> a = [0] * 1024 >>> b = np.array(a) >>> getsizeof(a) 8264 >>> b.nbytes 8192 ```
If elif else not working
11,784,436
3
2012-08-02T19:26:36Z
11,784,468
15
2012-08-02T19:28:23Z
[ "python" ]
I have the following python code for an if,elif,else statement: ``` if line_num == 151: if self.run_count == 1: print(values[self.run_count-1]) elif line_num == 129: if self.run_count == 2: print(values[self.run_count-1]) elif line_num == ...
Both `elif line_num == 129` statements will not get executed because they have the same condition. Instead, try something like this: ``` if line_num == 151: if self.run_count == 1: print(values[self.run_count-1]) elif line_num == 129: if self.run_count == 2: print(values...
Why does this python dictionary get created out of order using setdefault()?
11,784,860
3
2012-08-02T19:59:15Z
11,784,865
11
2012-08-02T19:59:39Z
[ "python", "dictionary", "for-loop", "setdefault" ]
I'm just starting to play around with Python (VBA background). Why does this dictionary get created out of order? Shouldn't it be a:1, b:2...etc.? ``` class Card: def county(self): c = 0 l = 0 groupL = {} # groupL for Loop for n in range(0,13): c += 1 l = chr(n+97) groupL.setde...
Dictionaries have no order in python. In other words, when you iterate over a dictionary, the order that the keys/items are "yielded" is not the order that you put them into the dictionary. (Try your code on a different version of python and you're likely to get differently ordered output). If you want a dictionary tha...
How does Python iterate a for loop?
11,785,490
6
2012-08-02T20:46:46Z
11,785,607
10
2012-08-02T20:54:18Z
[ "python", "loops", "for-loop" ]
I tried the following code on Python, and this is what I got: It seems like for many changes I try to make to the iterables by changing elem, it doesn't work. ``` lis = [1,2,3,4,5] for elem in lis: elem = 3 print lis [1, 2, 3, 4, 5] ``` However if the iterables are objects with its own methods (like a list), the...
The reason that this doesn't work is because you're misunderstanding what `elem` **is**. It's not the object itself, and it's not even correct to call it a "variable". It's a **name**, kind of like a label, that points to the object. If you just directly assign over it, you're just *overwriting* the name to point at s...
If list index exists, do X
11,786,157
35
2012-08-02T21:36:20Z
11,786,240
34
2012-08-02T21:42:43Z
[ "python", "python-2.7" ]
In my program, user inputs number `n`, and then inputs `n` number of strings, which get stored in a list. I need to code such that if a certain list index exists, then run a function. This is made more complicated by the fact that I have nested if statements about `len(my_list)`. Here's a simplified version of what ...
`I need to code such that if a certain list index exists, then run a function.` This is the perfect use for a [try block](http://docs.python.org/tutorial/errors.html#handling-exceptions): ``` ar=[1,2,3] try: t=ar[5] except IndexError: print 'sorry, no 5' ``` However, by definition, all items in a Python lis...
If list index exists, do X
11,786,157
35
2012-08-02T21:36:20Z
11,786,241
7
2012-08-02T21:42:45Z
[ "python", "python-2.7" ]
In my program, user inputs number `n`, and then inputs `n` number of strings, which get stored in a list. I need to code such that if a certain list index exists, then run a function. This is made more complicated by the fact that I have nested if statements about `len(my_list)`. Here's a simplified version of what ...
`len(nams)` should be equal to `n` in your code. All indexes `0 <= i < n` "exist".
If list index exists, do X
11,786,157
35
2012-08-02T21:36:20Z
11,786,282
45
2012-08-02T21:46:38Z
[ "python", "python-2.7" ]
In my program, user inputs number `n`, and then inputs `n` number of strings, which get stored in a list. I need to code such that if a certain list index exists, then run a function. This is made more complicated by the fact that I have nested if statements about `len(my_list)`. Here's a simplified version of what ...
Could it be more useful for you to use the length of the list `len(n)` to inform your decision rather than checking n[i] for each possible length?
Can python threads access variables in the namespace?
11,786,530
7
2012-08-02T22:07:00Z
11,786,875
9
2012-08-02T22:43:14Z
[ "python", "multithreading", "scope", "queue" ]
I have a script that creates a bunch of threads, runs a program to use the threads to run tasks from a queue, and returns something from each thread. I want to count how many of these returned successfully, so I set a variable "successful=0" and increment it every time the queue reports a task completed successfully. ...
``` successful+=1 ``` is not a thread-safe operation. With multiple threads trying to increment a shared global variable, collisions may happen and `successful` will not be incremented properly. To avoid this error, use a lock: ``` lock = threading.Lock() def foo(): global successful while True: ... ...
How to install MySQLdb on Mountain Lion
11,787,012
10
2012-08-02T22:59:10Z
11,788,327
19
2012-08-03T02:11:16Z
[ "python", "mysql", "installation" ]
I'm new to Python and I'm having trouble building MySQLdb, in an attempt to get Google AppEngine SDK running. I have just upgraded from Snow Leopard to Mountain Lion and have installed the latest XCode (4.4) I've downloaded <http://sourceforge.net/projects/mysql-python/> ``` python setup.py build ``` i get the follo...
It seems that the system is complaining about not be able to find `clang`, which is included in `Command Line Tools` of `Xcode`. Did you installed the tool as well? Can be installed via * Open `Xcode` * Preference (`Command` + `,`) * `Components` under the `Download` tab
beginner python on mac osx 10.8
11,787,182
5
2012-08-02T23:18:12Z
11,787,485
14
2012-08-02T23:57:32Z
[ "python", "osx", "osx-mountain-lion" ]
I'm learning programming and have been working with Ruby and ROR, but feel I like Python's language better for learning programming. Although I see the beauty of Ruby and Rails, I feel I need a language more easy to learn programming concepts, thus Python. However, I can't seem to find a community online or offline tha...
Mac OS X 10.8 comes bundled with Python 2.7.2 found at `/usr/bin/python`. Generally in the Python world your operating system is abstracted away, so there aren't that many OS-specific communities. Apple fully embraces Python, however, and you can even write fully native applications using Python. My suggestions to get...
Module function vs staticmethod vs classmethod vs no decorators: Which idiom is more pythonic?
11,788,195
27
2012-08-03T01:50:00Z
11,788,267
39
2012-08-03T02:01:32Z
[ "python", "static-methods" ]
I'm a Java developer who's toyed around with Python on and off. I recently stumbled upon [this article](http://dirtsimple.org/2004/12/python-is-not-java.html) which mentions common mistakes Java programmers make when they pick up Python. The first one caught my eye: > A static method in Java does not translate to a Py...
The most straightforward way to think about it is to think in terms of what type of object the method needs in order to do its work. If your method needs access to an instance, make it a regular method. If it needs access to the class, make it a classmethod. If it doesn't need access to the class or the instance, make ...
Module function vs staticmethod vs classmethod vs no decorators: Which idiom is more pythonic?
11,788,195
27
2012-08-03T01:50:00Z
16,079,946
11
2013-04-18T10:02:31Z
[ "python", "static-methods" ]
I'm a Java developer who's toyed around with Python on and off. I recently stumbled upon [this article](http://dirtsimple.org/2004/12/python-is-not-java.html) which mentions common mistakes Java programmers make when they pick up Python. The first one caught my eye: > A static method in Java does not translate to a Py...
Great answer by [BrenBarn](http://stackoverflow.com/users/1427416/brenbarn), but I would change *'If it doesn't need access to the class or the instance, make it a function'* to: 'If it doesn't need access to the class or the instance...but **is** thematically related to the class (typical example: helper functions an...
Module function vs staticmethod vs classmethod vs no decorators: Which idiom is more pythonic?
11,788,195
27
2012-08-03T01:50:00Z
16,378,764
9
2013-05-04T20:40:50Z
[ "python", "static-methods" ]
I'm a Java developer who's toyed around with Python on and off. I recently stumbled upon [this article](http://dirtsimple.org/2004/12/python-is-not-java.html) which mentions common mistakes Java programmers make when they pick up Python. The first one caught my eye: > A static method in Java does not translate to a Py...
This is not really an answer, but rather a lengthy comment: > Even more puzzling is that this code: > > ``` >   class A: > def foo(x): > print(x) > A.foo(5) > ``` > > Fails as expected in Python 2.7.3 but works fine in 3.2.3 (although > you can't call the method on an instanc...
Does Python has a similar variable interpolation like "string #{var}" in Ruby?
11,788,472
17
2012-08-03T02:33:39Z
11,788,514
24
2012-08-03T02:41:08Z
[ "python", "string-interpolation" ]
In Python, it is tedious to write: ``` print "foo is" + bar + '.' ``` Can I do something like this in python? `print "foo is #{bar}."`
Python doesn't do variable interpolation - it is explicit rather than implicit. However, you can use `str.format` to pass in variables: ``` # Rather than this: puts "foo is #{bar}" # You would do this: print "foo is {}".format(bar) # Or this: print "foo is {bar}".format(bar=bar) # Or this: print "foo is %s" % (bar...
Most pythonic (and efficient) way of nesting a list in pairs
11,788,565
5
2012-08-03T02:47:55Z
11,788,602
9
2012-08-03T02:55:05Z
[ "python", "list", "itertools", "list-comprehension" ]
my list is: ``` mylist=[1,2,3,4,5,6] ``` I would like to convert mylist into a list of pairs: ``` [[1,2],[3,4],[5,6]] ``` Is there a pythonic way of doing so? List comprehension? Itertools?
Yeppers, list comprehension is my usual way of doing it: ``` >>> groupsize = 2 >>> [mylist[x:x+groupsize] for x in range(0,len(mylist),groupsize)] [[1,2],[3,4],[5,6]] >>> groupsize = 3 >>> [mylist[x:x+groupsize] for x in range(0,len(mylist),groupsize)] [[1,2,3],[4,5,6]] ``` I use `range` for portability, if you are u...
Most pythonic (and efficient) way of nesting a list in pairs
11,788,565
5
2012-08-03T02:47:55Z
11,788,692
8
2012-08-03T03:06:22Z
[ "python", "list", "itertools", "list-comprehension" ]
my list is: ``` mylist=[1,2,3,4,5,6] ``` I would like to convert mylist into a list of pairs: ``` [[1,2],[3,4],[5,6]] ``` Is there a pythonic way of doing so? List comprehension? Itertools?
My preferred technique: ``` >>> mylist = [1, 2, 3, 4, 5, 6] >>> mylist = iter(mylist) >>> zip(mylist, mylist) [(1, 2), (3, 4), (5, 6)] ``` I usually use generators instead of lists anyway, so line 2 usually isn't required.
Best way to delete a django model instance after a certain date
11,788,821
7
2012-08-03T03:25:46Z
11,789,141
10
2012-08-03T04:08:32Z
[ "python", "django" ]
I am writing a little app where the user creates an event and specifies the date that event will occur. After the event date has past, I want to delete that event instance. My current attempt is throwing a function that checks if the event should expire in the event page view. I am not sure whether the expiration\_chec...
If you're hosting your application on a UNIX platform (GNU/Linux, OSX, *etc.*), it's probably best to make use of `cron`, the generic system utility for running things periodically. This requires implementing your expiry code as a [custom management command](https://docs.djangoproject.com/en/1.4/howto/custom-managemen...
ImportError: No module named statsmodels
11,788,900
9
2012-08-03T03:35:36Z
11,890,682
15
2012-08-09T19:34:41Z
[ "python", "import", "statsmodels" ]
Hi I downloaded the StatsModels source from <http://pypi.python.org/pypi/statsmodels#downloads> I then untarred to ``` /usr/local/lib/python2.7/dist-packages ``` and per the documentation at <http://statsmodels.sourceforge.net/devel/install.html> did this ``` sudo python setup.py install ``` It installed, but when ...
* you shouldn't untar it to /usr/local/lib/python2.7/dist-packages (you could use any temporary directory) * you might have used by mistake a different python executable e.g., /usr/bin/python instead of the one corresponding to /usr/local/lib/python2.7 You should use `pip` corresponding to a desired python version to ...
Extracting data from HTML table
11,790,535
13
2012-08-03T06:38:49Z
11,791,040
22
2012-08-03T07:15:55Z
[ "python", "linux", "perl", "bash" ]
I am looking for a way to get certain info from HTML in linux shell environment. This is bit that I'm interested in : ``` <table class="details" border="0" cellpadding="5" cellspacing="2" width="95%"> <tr valign="top"> <th>Tests</th> <th>Failures</th> <th>Success Rate</th> <th>Average Time</th> ...
A Python solution using [BeautifulSoup4](http://www.crummy.com/software/BeautifulSoup/bs4/doc/) (**Edit:** with proper skipping. **Edit3:** Using `class="details"` to select the `table`): ``` from bs4 import BeautifulSoup html = """ <table class="details" border="0" cellpadding="5" cellspacing="2" width="95%"> ...
What is the most pythonic way to exclude elements of a list that start with a specific character?
11,791,568
4
2012-08-03T07:54:51Z
11,791,601
17
2012-08-03T07:56:40Z
[ "python", "coding-style" ]
I have a list of strings. I want to get a new list that excludes elements starting with '#' while preserving the order. What is the most pythonic way to this? (preferably not using a loop?)
``` [x for x in my_list if not x.startswith('#')] ``` That's the most pythonic way of doing it. Any way of doing this will end up using a loop in either Python or C.
Lack Understanding of Multi-Variable Assignments Python
11,791,613
5
2012-08-03T07:57:31Z
11,791,761
8
2012-08-03T08:07:42Z
[ "python", "list", "tuples", "list-comprehension" ]
I'm new with Python (with Java as a basic). I read [Dive Into Python](http://www.diveintopython.net/) books, in the Chapter 3 I found about `Multi-Variable Assignment`. Maybe some of you can help me to understand what happen in this code bellow: ``` >>> params = {1:'a', 2:'b', 3:'c'} >>> params.items() # To display li...
The list comprehension you use there roughly translate as follows: ``` [a for b, a in params.items()] ``` becomes ``` result = [] for item in params.items(): b = item[0] a = item[1] result.append(a) ``` --- ``` [a for a, a in params.items()] ``` becomes ``` result = [] for item in params.items(): ...
Python thread starts running before calling Thread.start
11,792,629
6
2012-08-03T09:05:36Z
11,792,713
7
2012-08-03T09:10:43Z
[ "python", "multithreading", "python-multithreading" ]
``` t1=threading.Thread(target=self.read()) print "something" t2=threading.Thread(target=self.runChecks(), args=(self)) ``` self.read runs indefinitely, so the program won't ever reach the print line. How is this possible without calling t1.start()? (Even if I call that, it shold start running and go on to...
You're passing the *result* of self.read to the target argument of Thread. Thread expects to be passed a function to call, so just remove the parentheses and remember to start the Thread: ``` t1=threading.Thread(target=self.read) t1.start() print "something" ```
Generate all possible combinations from a int list under a limit
11,792,708
5
2012-08-03T09:10:19Z
11,793,060
8
2012-08-03T09:33:03Z
[ "python", "list", "optimization", "combinations" ]
I need to do this in Python. There is a given list l,may contain more than 5000 integer elements. There is a limit on sum of the numbers,20000 or may be high. The output should be all the possible sums of 2 numbers picked from list, Like, ``` l=[1,2,3,4,5,6,7,8,9] output 1+1,1+2,1+3,1+4,1+5,1+6........... 2+2,2+3,2+4...
Some old-fashioned optimization might get you faster code that's easier to grok than list comprehensions with multiple for loops: ``` def sums(lst, limit): # prevent global lookups by using a function res = set() # set membership testing is much faster than lists res_add = res.add # cache add me...
Continuous numbers in Objective-C array like range() in Python
11,792,883
6
2012-08-03T09:21:15Z
11,795,200
9
2012-08-03T11:51:47Z
[ "python", "objective-c", "ios", "osx", "cocoa" ]
Python can make a list with continuous numbers like this: ``` numbers=range(1,10); // >> [1,2,3,4,5,6,7,8,9] ``` How to implement this in Objective-c?
Reading your statement *" Just need an array with continuous numbers,I do not want to init it with a loop"* lets me ask: what is more important for you: to have an *`array`* or to have "*something*" that represents a continuous range of (natural) numbers. Have a look at `NSIndexSet` It may come close to what you want. ...
Custom django admin templates not working
11,793,890
13
2012-08-03T10:27:17Z
11,794,156
15
2012-08-03T10:45:29Z
[ "python", "django", "django-admin", "django-templates" ]
I've been trying to get custom templates for the admin page for Django working but have been unsuccessful. I've read the django documentation and several blogs which explain it as being such an easy step, which I assumed it was. As of right now the admin page works but my own rewrite of the CSS or templates is not wor...
Alright I fixed it, this was a stupid mistake but I was already playing with this for the past 2 hours. I had to declare my app before django.contrib.admin. It wouldn't accept it otherwise.
Custom django admin templates not working
11,793,890
13
2012-08-03T10:27:17Z
27,089,675
15
2014-11-23T13:52:56Z
[ "python", "django", "django-admin", "django-templates" ]
I've been trying to get custom templates for the admin page for Django working but have been unsuccessful. I've read the django documentation and several blogs which explain it as being such an easy step, which I assumed it was. As of right now the admin page works but my own rewrite of the CSS or templates is not wor...
One more mistake that one should resist making on this exercise. The exercise says to change this... ``` <h1 id="site-name"><a href="{% url 'admin:index' %}"> {{ site_header|default:_('Django administration') }} </a></h1> ``` to this... ``` <h1 id="site-name"><a href="{% url 'admin:index' %}">Polls Administration</a...
Pandas DataFrame Apply
11,794,935
6
2012-08-03T11:35:21Z
11,819,672
7
2012-08-05T20:07:32Z
[ "python", "pandas" ]
I have a Pandas DataFrame with four columns, `A, B, C, D`. It turns out that, sometimes, the values of `B` and `C` can be `0`. I therefore wish to obtain the following: ``` B[i] = B[i] if B[i] else min(A[i], D[i]) C[i] = C[i] if C[i] else max(A[i], D[i]) ``` where I have used `i` to indicate a run over all rows of th...
A combination of boolean indexing and apply can do the trick. Below an example on replacing zero element for column C. ``` In [22]: df Out[22]: A B C D 0 8 3 5 8 1 9 4 0 4 2 5 4 3 8 3 4 8 5 1 In [23]: bi = df.C==0 In [24]: df.ix[bi, 'C'] = df[bi][['A', 'D']].apply(max, axis=1) In [25]: df Out[...
start interactive mode on a specific script line
11,796,474
7
2012-08-03T13:14:55Z
11,796,515
9
2012-08-03T13:17:00Z
[ "python", "interactive" ]
I need to run my Python script as usual, but I want to stop execution on a specific line and start interactive mode. In other words, I want to be able to check the value of all my variables at that point, and continue myself from there on python's command line. How can I do this?
Use a debugger and add breakpoints. Do you use an IDE? All the major IDEs have debugger support. From the CLI, you can use `pdb`.
start interactive mode on a specific script line
11,796,474
7
2012-08-03T13:14:55Z
11,796,523
13
2012-08-03T13:17:08Z
[ "python", "interactive" ]
I need to run my Python script as usual, but I want to stop execution on a specific line and start interactive mode. In other words, I want to be able to check the value of all my variables at that point, and continue myself from there on python's command line. How can I do this?
This can be done with the `code` module. The easiest way is to call [`code.interact()`](http://docs.python.org/library/code.html#code.interact).
smtplib sends blank message if the message contain certain characters
11,796,664
8
2012-08-03T13:25:36Z
11,797,380
10
2012-08-03T14:08:53Z
[ "python", "email", "smtplib" ]
My current script allows me to send emails fine, but there are just some characters it doesn't like, particularly `':'` in this sample. ``` import smtplib, sys mensaje = sys.argv[1] def mailto(toaddrs, msg): fromaddr = 'myemailblabla' username = 'thisismyemail' password = '122344' server = smtplib.S...
The problem is that `smtplib` is not putting a blank line between the message header and the message body as shown by in the "Show Original" form of my test: ``` Return-Path: <me@gmail.com> Received: **REDACTED** Fri, 03 Aug 2012 06:56:20 -0700 (PDT) Message-ID: <501bd884.850c320b@mx.google.com> Date: Fri, 03 ...
Elasticsearch clients for python, no solution
11,797,035
8
2012-08-03T13:47:00Z
11,798,262
7
2012-08-03T15:01:53Z
[ "python", "elasticsearch", "pyes" ]
I am having a very bad week having chosen elasticsearch with graylog2. I am trying to run queries against the data in ES using Python. I have tried following clients. 1. ESClient - Very weird results, I think its not maintained, query\_body has no effect it returns all the results. 2. Pyes - Unreadable, undocumented....
Honestly, I've had the most luck with just CURLing everything. ES has so many different methods, filters, and queries that various "wrappers" have a hard time recreating all the functionality. In my view, it is similar to using an ORM for databases...what you gain in ease of use you lose in flexibility/raw power. Exce...
Elasticsearch clients for python, no solution
11,797,035
8
2012-08-03T13:47:00Z
12,361,233
8
2012-09-11T00:32:12Z
[ "python", "elasticsearch", "pyes" ]
I am having a very bad week having chosen elasticsearch with graylog2. I am trying to run queries against the data in ES using Python. I have tried following clients. 1. ESClient - Very weird results, I think its not maintained, query\_body has no effect it returns all the results. 2. Pyes - Unreadable, undocumented....
I have found rawes to be quite usable: <https://github.com/humangeo/rawes> It's a rather low-level interface but I have found it to be much less awkward to work with than the high-level ones. It also supports the Thrift RPC if you're into that.
Elasticsearch clients for python, no solution
11,797,035
8
2012-08-03T13:47:00Z
13,370,953
7
2012-11-13T23:54:53Z
[ "python", "elasticsearch", "pyes" ]
I am having a very bad week having chosen elasticsearch with graylog2. I am trying to run queries against the data in ES using Python. I have tried following clients. 1. ESClient - Very weird results, I think its not maintained, query\_body has no effect it returns all the results. 2. Pyes - Unreadable, undocumented....
Explicitly setting the host resolved that error for me: `basic_s = S()`**`.es(hosts=HOST, default_indexes=[INDEX])`**
django - int argument must be a string or a number, not 'Tuple'
11,797,597
5
2012-08-03T14:22:02Z
11,797,662
12
2012-08-03T14:26:25Z
[ "python", "django", "forms", "django-views", "tuples" ]
I've been looking at this for a couple hours and I can't seem to get a handle on why I'm getting this message... ``` int() argument must be a string or a number, not 'tuple' ``` on this line from my views.py (NOTE: Exception actually occurrs one level deeper inside django core, but this my line of code which eventual...
`get_or_create` returns a tuple, in the form of `(instance, created)`. The second parameter tells you whether it had to create it or not, obviously enough. Do the following instead: ``` client, created = Client.objects.get_or_create(name = name, email = email, site = url) ```
Matplotlib requirements with pip install in virtualenv
11,797,688
21
2012-08-03T14:28:14Z
11,864,171
21
2012-08-08T12:06:44Z
[ "python", "numpy", "matplotlib", "virtualenv", "pip" ]
I have a requirements.txt file like this: ``` numpy matplotlib ``` When I try `pip install -r requirements.txt` inside a new virtualvenv, I get this: ``` REQUIRED DEPENDENCIES numpy: no * You must install numpy 1.1 or later to build * matplotlib. ``` If I inst...
Matplotlib and pip don't seem to play together very well. So I don't think it is possible in this case. `pip` first downloads a package listed in your requirements file and than runs `setup.py`, but it doesn't really install it (I'm not quite sure about the internals of `pip`). After all packages are prepared in this ...
Matplotlib requirements with pip install in virtualenv
11,797,688
21
2012-08-03T14:28:14Z
13,464,592
10
2012-11-20T00:01:38Z
[ "python", "numpy", "matplotlib", "virtualenv", "pip" ]
I have a requirements.txt file like this: ``` numpy matplotlib ``` When I try `pip install -r requirements.txt` inside a new virtualvenv, I get this: ``` REQUIRED DEPENDENCIES numpy: no * You must install numpy 1.1 or later to build * matplotlib. ``` If I inst...
It's a known problem of the library and it's currently being discussed as a Matplotlib enhancement proposal: <https://github.com/matplotlib/matplotlib/wiki/MEP11>. Until it's fixed the only solution I can imagine is repackaging the library to remove the numpy check.
Mountain Lion update and mercurial libraries python
11,797,761
38
2012-08-03T14:32:22Z
11,824,215
14
2012-08-06T07:37:15Z
[ "python", "osx", "osx-mountain-lion" ]
I updated the mac to Mountain Lion (10.8) and now the project I developed with Python and Google App Engine does not work. GAE libraries are found, while standard Python libraries (are these Python libraries?) are missed (e.g. `cgi`, `logging`, `json`). When I open eclipse (which has PyDeV) I receive this alert: ```...
I just ran into the same problem, picked a new version (*mercurial-2.2.3+20120707-py2.7-macosx10.7*) from the [Mercurial website](http://mercurial.selenic.com/) and now it works again.
Mountain Lion update and mercurial libraries python
11,797,761
38
2012-08-03T14:32:22Z
12,780,859
44
2012-10-08T11:30:40Z
[ "python", "osx", "osx-mountain-lion" ]
I updated the mac to Mountain Lion (10.8) and now the project I developed with Python and Google App Engine does not work. GAE libraries are found, while standard Python libraries (are these Python libraries?) are missed (e.g. `cgi`, `logging`, `json`). When I open eclipse (which has PyDeV) I receive this alert: ```...
On OS X - 10.8.2 Installing mercurial through Python easy\_install tool solved the problem ``` easy_install -U mercurial ```
Mountain Lion update and mercurial libraries python
11,797,761
38
2012-08-03T14:32:22Z
19,544,932
11
2013-10-23T14:44:54Z
[ "python", "osx", "osx-mountain-lion" ]
I updated the mac to Mountain Lion (10.8) and now the project I developed with Python and Google App Engine does not work. GAE libraries are found, while standard Python libraries (are these Python libraries?) are missed (e.g. `cgi`, `logging`, `json`). When I open eclipse (which has PyDeV) I receive this alert: ```...
I had a similar problem to this last night after upgrading to **OX 10.9 Mavericks**. I had tried `brew install hg` and `brew update` but they didn't work, as everyone's systems are different if you're running homebrew I would recommend running `brew doctor` to see what your particular issue is, in my case I had the fol...
Is it possible to use a C library with python AppEngine?
11,798,698
5
2012-08-03T15:26:48Z
11,798,766
7
2012-08-03T15:30:25Z
[ "python", "c", "google-app-engine" ]
I am investigating into if I can use a library like [GHMM](http://sourceforge.net/projects/ghmm/) with my python web service in which runs on AppEngine.
Short answer: no <https://developers.google.com/appengine/kb/commontasks> **What third party libraries can I use in my application?** You can use any pure Python third party libraries in your Google App Engine application. In order to use a third party library, simply include the files in your application's director...
Reading a binary .dat file as an array
11,798,800
2
2012-08-03T15:32:41Z
11,798,898
10
2012-08-03T15:37:59Z
[ "python", "arrays", "numpy" ]
I have a code that goes through several iterations. In each iteration, the code generates a numpy based array. I append the numpy based array to an existing binary .dat file. I use the following code to generate the data: ``` WholeData = numpy.concatenate((Location,Data),axis=0) # Location & Data are two numpy array...
I think that numpy.fromfile is what you want here: ``` import numpy as np myarray = np.fromfile('BinaryData.dat',dtype=float) ``` Also note that according to the docs, this is not the best way to store data as "information on precision and endianness is lost". In other words, you need to make sure that the datatype p...
Get function callers' information in python
11,799,290
6
2012-08-03T16:02:56Z
11,799,376
7
2012-08-03T16:07:50Z
[ "python", "introspection", "callstack" ]
I want to get information about the callers of a specific function in python. For example: ``` class SomeClass(): def __init__(self, x): self.x = x def caller(self): return special_func(self.x) def special_func(x): print "My caller is the 'caller' function in an 'SomeClass' class." ``` Is...
Yes, the [`sys._getframe()`](http://docs.python.org/library/sys.html#sys._getframe) function let's you retrieve frames from the current execution stack, which you can then inspect with the methods and documentation found in the [`inspect` module](http://docs.python.org/library/inspect.html); you'll be looking for speci...
sys.stdin.readlines() hangs Python script
11,799,300
7
2012-08-03T16:03:35Z
11,799,368
12
2012-08-03T16:07:21Z
[ "python", "stdin", "hang", "readlines" ]
Everytime I'm executing my Python script, it appears to hang on this line: ``` lines = sys.stdin.readlines() ``` What should I do to fix/avoid this? **EDIT** Here's what I'm doing with `lines`: ``` lines = sys.stdin.readlines() updates = [line.split() for line in lines] ``` **EDIT 2** I'm running this script fro...
This depends a lot on what you are trying to accomplish. You might be able do: ``` for line in sys.stdin: #do something with line ``` Of course, with this idiom as well as the `readlines()` method you are using, you need to somehow send the EOF character to your script so that it knows that the file is ready to r...
is print a function in Python?
11,799,557
9
2012-08-03T16:20:24Z
11,799,590
20
2012-08-03T16:21:54Z
[ "python", "python-2.x" ]
In python everything is an object and you can pass it around easily. So I can do : ``` >> def b(): ....print "b" >> a = b >> a() b ``` But if I do ``` a = print ``` I get `SyntaxError` . Why so ?
In Python 2.x, print is a statement **not** a function. In 2.6+ you can enable it to be a function within a given module using `from __future__ import print_function`. In Python 3.x it is a function that can be passed around.
Fast(er) numpy fancy indexing and reduction?
11,800,075
9
2012-08-03T16:57:05Z
11,813,040
7
2012-08-05T00:27:59Z
[ "python", "optimization", "numpy", "scipy", "cython" ]
I'm trying to use and accelerate fancy indexing to "join" two arrays and sum over one of results' axis. Something like this: ``` $ ipython In [1]: import numpy as np In [2]: ne, ds = 12, 6 In [3]: i = np.random.randn(ne, ds).astype('float32') In [4]: t = np.random.randint(0, ds, size=(1e5, ne)).astype('uint8') In [5...
`numpy.take` is much faster than fancy indexing for some reason. The only trick is that it treats the array as flat. ``` In [1]: a = np.random.randn(12,6).astype(np.float32) In [2]: c = np.random.randint(0,6,size=(1e5,12)).astype(np.uint8) In [3]: r = np.arange(12) In [4]: %timeit a[r,c].sum(-1) 10 loops, best of 3...
List of strings to integers while keeping a format in python
11,800,522
5
2012-08-03T17:31:28Z
11,800,551
9
2012-08-03T17:32:46Z
[ "python", "list", "formatting", "integer" ]
So what I want to do seems relatively simple, but for the life of me, I just can't quite get it. I have a .txt file like ``` 4 2 6 5 1 9 4 5 ``` And I want its information to be available to me like so (i.e. I do not need to write a new .txt file unless it would be necessary.)... ``` 3 1 5 4 0 8 3 4 ``` or, `1` is ...
``` with open("original_filename") as original: for line in original: #if you just want the line as integers: integers = [ int(i) - 1 for i in line.split() ] #do something with integers here ... #if you want to write a new file, use the code below: #new_line = " ".join([ str...
Python Lists - Finding Number of Times a String Occurs
11,800,755
3
2012-08-03T17:47:54Z
11,800,782
12
2012-08-03T17:49:44Z
[ "python" ]
How would I find how many times each string appears in my list? Say I have the word: ``` "General Store" ``` that is in my list like 20 times. How would I find out that it appears 20 times in my list? I need to know this so I can display that number as a type of `"poll vote"` answer. E.g: ``` General Store - voted...
Use the `count` method. For example: ``` (x, mylist.count(x)) for x in set(mylist) ```
Calling app from subprocess.call with arguments
11,801,098
8
2012-08-03T18:12:41Z
11,801,126
14
2012-08-03T18:14:37Z
[ "python", "process", "python-2.6", "raspberry-pi" ]
I'm a beginner in Python, and I've been trying to call a command line app, but it fails: ``` >>> import subprocess as s >>> s.call("gpio -g read 17") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.6/subprocess.py", line 470, in call return Popen(*popenargs...
You're not using call right. Look at [the introduction](http://docs.python.org/library/subprocess.html#using-the-subprocess-module) or any of the examples in the docs. The first argument of call is "args", a sequence of arguments, where arg[0] is the program to run. So, when you do this: ``` s.call("gpio -g read 17")...
How to loop over files with Python?
11,801,309
39
2012-08-03T18:30:01Z
11,801,336
17
2012-08-03T18:32:00Z
[ "python" ]
I have a folder with ten files in it which I want to loop through. When I print out the name of the file my code works fine: ``` import os indir = '/home/des/test' for root, dirs, filenames in os.walk(indir): for f in filenames: print(f) ``` Which prints: ``` 1 2 3 4 5 6 7 8 9 10 ``` But if I try to ope...
Yes, you need the full path. ``` log = open(os.path.join(root, f), 'r') ``` Is the quick fix. As the comment pointed out, `os.walk` decends into subdirs so you do need to use the current directory root rather than `indir` as the base for the path join.
How to loop over files with Python?
11,801,309
39
2012-08-03T18:30:01Z
11,801,338
58
2012-08-03T18:32:13Z
[ "python" ]
I have a folder with ten files in it which I want to loop through. When I print out the name of the file my code works fine: ``` import os indir = '/home/des/test' for root, dirs, filenames in os.walk(indir): for f in filenames: print(f) ``` Which prints: ``` 1 2 3 4 5 6 7 8 9 10 ``` But if I try to ope...
If you are just looking for the files in a single directory (ie you are *not* trying to traverse a directory tree, which it doesn't look like), why not simply use [os.listdir()](http://docs.python.org/library/os.html?highlight=listdir#os.listdir): ``` import os for fn in os.listdir('.'): if os.path.isfile(fn): ...
How to create a commit and push into repo with GitHub API v3?
11,801,983
11
2012-08-03T19:18:18Z
16,412,503
7
2013-05-07T06:25:04Z
[ "python", "github", "github-api" ]
I want to create a repository and Commit a few files to it via any Python package. How do I do? I do not understand how to add files for commit.
You can see if the new update [GitHub CRUD API (May 2013)](https://github.com/blog/1498-file-crud-and-repository-statistics-now-available-in-the-api) can help > The [repository contents API](http://developer.github.com/v3/repos/contents/) has allowed reading files for a while. Now you can easily commit changes to sing...
nose2 vs py.test with isolated processes
11,802,316
4
2012-08-03T19:46:33Z
11,806,997
11
2012-08-04T08:08:10Z
[ "python", "nose", "py.test" ]
We have been using nosetest for running and collecting our unittests (which are all written as python unittests which we like). Things we like about nose: * uses standard python unit tests (we like the structure this imposes). * supports reporting coverage and test output in xml (for jenkins). What we are missing is ...
pytest has the [xdist plugin](http://pypi.python.org/pypi/pytest-xdist) which provides the `--boxed` option to run each test in a controlled subprocess. Here is a basic example:: ``` # content of test_module.py import pytest import os import time # run test function 50 times with different argument @pytest.mark.para...
Pythonic way of exchanging between lists?
11,802,436
3
2012-08-03T19:56:15Z
11,802,475
7
2012-08-03T19:59:17Z
[ "python", "list" ]
I want to have a list of cities and a list of postal codes, with the positions corresponding (if NYC is first in the city list, NYS's code will be first in the code list). Say I wanted to set `x` to NYC's zip code. I know it's possible to do this: ``` y = citylist.index('New York') x = postcodelist[y] xstring = str(x)...
If I understand correctly you have two parallel lists that you want to treat as essentially a list of keys and a list of values. If so, you can do something like the following: ``` >>> places = ['New York', 'Texas', 'California'] >>> zips = ['01010', '70707', '90909'] >>> place_zip_map = dict(zip(places, zips)) >>> pl...
Parsing HTML to get text inside an element
11,804,148
7
2012-08-03T22:31:15Z
11,804,617
18
2012-08-03T23:37:35Z
[ "python", "html", "python-2.x", "html-parser" ]
I need to get the text inside the two elements into a string: ``` source_code = """<span class="UserName"><a href="#">Martin Elias</a></span>""" >>> text 'Martin Elias' ``` How could I achieve this?
I searched "python parse html" and this was the first result: <http://docs.python.org/library/htmlparser.html> This code is taken from the python docs ``` from HTMLParser import HTMLParser # create a subclass and override the handler methods class MyHTMLParser(HTMLParser): def handle_starttag(self, t...
Parsing HTML to get text inside an element
11,804,148
7
2012-08-03T22:31:15Z
11,804,677
9
2012-08-03T23:46:52Z
[ "python", "html", "python-2.x", "html-parser" ]
I need to get the text inside the two elements into a string: ``` source_code = """<span class="UserName"><a href="#">Martin Elias</a></span>""" >>> text 'Martin Elias' ``` How could I achieve this?
I recommend using the Python [Beautiful Soup 4](http://www.crummy.com/software/BeautifulSoup/) library. ``` pip install beautifulsoup4 ``` It makes HTML parsing really easy. ``` from bs4 import BeautifulSoup source_code = """<span class="UserName"><a href="#">Martin Elias</a></span>""" soup = BeautifulSoup(source_co...
Python 3, Web-scraping, and Javascript [Oh My]
11,804,497
4
2012-08-03T23:20:25Z
11,804,541
10
2012-08-03T23:26:26Z
[ "javascript", "python", "python-3.x", "web-scraping" ]
I have come to the point of entering the melee on web-scraping webpages using Javascript, with Python3. I am well aware that my boot may be making contact with a dead horse, but I feel like drawing my six-shooter anyway. It's a spaghetti western; be my gray hat? **::Backstory::** I am using Python 3.2.3. I am intere...
When a page loads data via javascript, it has to make requests to the server to get that data via the XMLHttpRequest function (XHR). You can see what requests they are making, and then make them yourself, using wget! To find out which requests they are making, use the Web Inspector (Chrome and Safari) or Firebug (Fire...
Properly check if word is in string?
11,804,703
3
2012-08-03T23:51:39Z
11,804,715
10
2012-08-03T23:53:42Z
[ "python", "string" ]
Say, for example, I want to check if the word `test` is in a string. Normally, I'd just: ``` if 'test' in theString ``` But I want to make sure it's the actual word, not just the string. For example, `test` in "It was detestable" would yield a false positive. I could check to make sure it contains `(\s)test(\s)` (spa...
``` import re if re.search(r'\btest\b', theString): pass ``` This will look for word boundaries on either end of `test`. From [the docs](http://docs.python.org/library/re.html), `\b`: > Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of alphanumeric or undersc...
networkx add_node with specific position
11,804,730
8
2012-08-03T23:57:31Z
11,806,811
15
2012-08-04T07:35:04Z
[ "python", "networkx" ]
I am still a beginner with networkx I want to add multiple types of nodes in different position, I used the following code ``` pos = {0: (40, 20), 1: (20, 30), 2: (40, 30), 3: (30, 10)} X=nx.Graph() nx.draw_networkx_nodes(X,pos,node_size=3000,nodelist=[0,1,2,3],node_color='r') ``` but when I want to access the Graph...
I'm not completely sure on what you want to accomplish, but I interpret it as you want to add nodes to the graph, draw them in the wanted positions and still be able to access them in the graph object. Since you don't add the nodes to the graph, that would be a start: ``` X.add_nodes_from(pos.keys()) ``` Then you do...
networkx add_node with specific position
11,804,730
8
2012-08-03T23:57:31Z
11,809,184
17
2012-08-04T13:54:06Z
[ "python", "networkx" ]
I am still a beginner with networkx I want to add multiple types of nodes in different position, I used the following code ``` pos = {0: (40, 20), 1: (20, 30), 2: (40, 30), 3: (30, 10)} X=nx.Graph() nx.draw_networkx_nodes(X,pos,node_size=3000,nodelist=[0,1,2,3],node_color='r') ``` but when I want to access the Graph...
You can use the following approach to set individual node positions and then extract the "pos" dictionary to use when drawing. ``` In [1]: import networkx as nx In [2]: G=nx.Graph() In [3]: G.add_node(1,pos=(1,1)) In [4]: G.add_node(2,pos=(2,2)) In [5]: G.add_edge(1,2) In [6]: pos=nx.get_node_attributes(G,'pos') ...
Flask-Admin + (Flask-Login and/or Flask-Principal)
11,804,922
9
2012-08-04T00:30:54Z
11,805,239
11
2012-08-04T01:38:36Z
[ "python", "plugins", "import", "flask" ]
Authentication and authorization can be integrated into Flask via the *Flask-Login* and *Flask-Principal* plugins. (Or also potentially via the Flask-Security plugin.) HOWEVER: *Flask-Admin*--another plugin which provides a backend dashboard--is not a registered blueprint...and, I believe (insomuch as I can tell), the...
Flask-Admin provides another way of providing authentication - you simply subclass the `AdminIndex` and `BaseIndex` views (or views from `contrib` if you only need those) and implement the `is_accessible` method. See [the documentation](http://flask-admin.readthedocs.org/en/latest/quickstart/#authentication) for more d...
If string is equal to regex in Python?
11,805,159
4
2012-08-04T01:20:52Z
11,805,183
9
2012-08-04T01:23:48Z
[ "python", "regex" ]
Is there any way to check if a string is exactly equal to a regular expression in Python? For example, if the regex is `\d\s\d`, it should allow strings `1 5`, `8 2`, etc, but not `lorem 9 4 ipsum` or `a7 3`.
Strings and regex are different types. I think you're looking to check not whether a string is "exactly equal to" a regex, but that the regex matches the entire string. To do that, just use [start and end anchors (`^` and `$`, respectively)](http://docs.python.org/library/re.html#regular-expression-syntax) in the regex...
Transform comma separated string into a list but ignore comma in quotes
11,805,535
3
2012-08-04T02:52:04Z
11,805,565
9
2012-08-04T02:59:52Z
[ "python", "regex", "split", "delimiter" ]
How do I convert `"1,,2'3,4'"` into a list? Commas separate the individual items, unless they are within quotes. In that case, the comma is to be included in the item. This is the desired result: `['1', '', '2', '3,4']`. One regex I found on another thread to ignore the quotes is as follows: ``` re.compile(r'''((?:[^...
Instead of a regular expression, you might be better off using the [`csv`](http://docs.python.org/library/csv.html) module since what you are dealing with is a CSV string: ``` from cStringIO import StringIO from csv import reader file_like_object = StringIO("1,,2,'3,4'") csv_reader = reader(file_like_object, quotecha...
Tunneling httplib Through a Proxy
11,805,773
11
2012-08-04T03:52:35Z
11,806,449
13
2012-08-04T06:24:44Z
[ "python", "sockets", "proxy", "tunnel", "httplib" ]
I am trying to figure out how to send data to a server through a proxy. I was hoping this would be possible through tor but being as tor uses SOCKS it apparently isn't possible with httplib (correct me if I am wrong) This is what I have right now ``` import httplib con = httplib.HTTPConnection("google.com") con.set_t...
If you want to use http proxy, it should be like this: ``` import httplib conn = httplib.HTTPConnection(proxyHost, proxyPort) conn.request("POST", "http://www.google.com", params) ``` If you want to use SOCKS proxy, you can use SocksiPy as in this question: [How can I use a SOCKS 4/5 proxy with urllib2?](http://stack...
Removing first x characters from string?
11,806,559
42
2012-08-04T06:45:14Z
11,806,564
85
2012-08-04T06:45:57Z
[ "python", "string" ]
How might one remove the first x characters from a string? For example, if one had a string `lipsum`, how would they remove the first 3 characters and get a result of `sum`?
``` >>> 'lipsum'[3:] 'sum' ``` See the official documentation on [strings](http://docs.python.org/tutorial/introduction.html#strings) for more information and [this](http://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation) SO answer for a concise summary of the notation.
How do I generate a set of four specific characters?
11,807,034
2
2012-08-04T08:14:14Z
11,807,045
7
2012-08-04T08:15:25Z
[ "python", "string", "character", "generator" ]
New to coding, having fun with an adventure game. I want the character to be able to run away from a monster and in doing so, the game will generate a random character that must be one of the following four characters: N S W E I am having trouble doing so, currently I have ``` import random import string x=random.r...
Just use `random.choice('NSEW')`.
Simple example using BernoulliNB (naive bayes classifier) scikit-learn in python - cannot explain classification
11,807,649
7
2012-08-04T09:59:16Z
11,816,144
7
2012-08-05T11:49:14Z
[ "python", "machine-learning", "artificial-intelligence", "scikit-learn" ]
Using scikit-learn 0.10 Why does the following trivial code snippet: ``` from sklearn.naive_bayes import * import sklearn from sklearn.naive_bayes import * print sklearn.__version__ X = np.array([ [1, 1, 1, 1, 1], [0, 0, 0, 0, 0] ]) print "X: ", X Y = np.array([ 1, 2 ]) print "Y: ", Y clf = Bernou...
By default, alpha, the smoothing parameter is one. As msw said, your training set is very small. Due to the smoothing, no information is left. If you set alpha to a very small value, you should see the result you expected.
Cannot determine vowels from consonants
11,809,126
2
2012-08-04T13:43:24Z
11,809,154
8
2012-08-04T13:48:44Z
[ "python", "character" ]
With the code below, no matter what the first letter of the input is, it is always determined as a vowel: ``` original = raw_input("Please type in a word: ") firstLetter = original[0] print firstLetter if firstLetter == "a" or "e" or "i" or "o" or "u": print "vowel" else: print "consonant" ``` In fact, it do...
Python is not the English language. If you have a bunch of expressions with `or` or `and` between them, each one must make sense on its own. Note that on its own: ``` if "e": print("something") ``` will always print `something`, even if `letter` doesn't equal `"e"`. You need to do it like this: ``` if letter ==...
Python Mechanize.Browser.Open(url) Status Code
11,809,696
2
2012-08-04T15:17:32Z
11,809,850
7
2012-08-04T15:37:28Z
[ "python", "screen-scraping", "web-scraping", "mechanize", "mechanize-python" ]
I recently moved from perl to python and am updating some of my scripts which used perls WWW::Mechanize to use python mechanize module. All good so far but I cant get find the HTTP Status code anywhere? (200, 301, etc) I've googled and found this but isnt their a way to just view the code? [Getting and trapping HTTP...
Use `response.code` ``` from mechanize import Browser browser = Browser() response = browser.open('http://www.google.com') print response.code ```
How do bitwise operations work in Python?
11,810,113
5
2012-08-04T16:16:00Z
11,810,203
7
2012-08-04T16:29:57Z
[ "python", "bit-manipulation" ]
I have been learning about Bitwise operations today and I learned that Not (~) inverses all bits, e.g.: ``` 01010 to 10101 ``` which means ~10 should be -5 but instead I have seen that it is -11 (per the python command line) which is ``` 01010 to 11011 ``` only two of the bits have been inverted. Can anybody explai...
Assuming that values are 32 bits, 10 is ``` 00000000000000000000000000001010 ``` and if you invert all those bits, you get ``` 11111111111111111111111111110101 ``` or -11. Because it's a [2's complement system](http://en.wikipedia.org/wiki/Two%27s_complement)!
Change operator precedence in Python
11,811,051
6
2012-08-04T18:27:01Z
11,811,077
7
2012-08-04T18:32:26Z
[ "python", "operator-precedence" ]
I have overloaded some Python operators, arithmetic and boolean. The Python precedence rules remain in effect, which is unnatural for the overloaded operators, leading to lots of parentheses in expressions. Is there a way to "overload" Python's precedences?
No. It's part of the python language itself. Thats how the language parses. Official quote: [Evaluation order](http://docs.python.org/reference/expressions.html#evaluation-order) > Python evaluates expressions from left to right. Notice that while > evaluating an assignment, the right-hand side is evaluated before th...
How to generate a list from a pandas Data Frame with the column name and column values?
11,811,392
15
2012-08-04T19:25:34Z
11,811,425
32
2012-08-04T19:31:03Z
[ "python", "pandas" ]
I have a pandas dataframe object that looks like this: ``` one two three four five 0 1 2 3 4 5 1 1 1 1 1 1 ``` I'd like to generate a list of lists objects where the first item is the column label and the remaining list values are the column data values: ``` nested_list =...
Simplest way is probably `list(dt.T.itertuples())` (where `dt` is your dataframe). This generates a list of tuples.
How to generate a list from a pandas Data Frame with the column name and column values?
11,811,392
15
2012-08-04T19:25:34Z
20,566,408
9
2013-12-13T12:21:02Z
[ "python", "pandas" ]
I have a pandas dataframe object that looks like this: ``` one two three four five 0 1 2 3 4 5 1 1 1 1 1 1 ``` I'd like to generate a list of lists objects where the first item is the column label and the remaining list values are the column data values: ``` nested_list =...
@BrenBarn answer above yields a list of tuples not a list of list as asked in question. I specifically needed a list of lists to be able to write the dataframe into spreadsheed using DataNitro. Adapted the above example with list comprehension: ``` [list(x) for x in dt.T.itertuples()] ``` This yields the result as ne...
Login dialog PyQt
11,812,000
4
2012-08-04T21:04:35Z
11,812,578
17
2012-08-04T22:53:42Z
[ "python", "qt", "login", "dialog", "pyqt" ]
I nearly finished my application, when the customer asked if I could implement some kind of login form on application startup. So far I have designed the UI, and tinkered about the actual execution. Username and password are irrelevant for now. ``` class Login(QtGui.QDialog): def __init__(self,parent=None): ...
A `QDialog` has its own event loop, so it can be run separately from the main application. So you just need to check the dialog's return code to decide whether the main application should be run or not. Example code: ``` from PyQt4 import QtGui # from mainwindow import Ui_MainWindow class Login(QtGui.QDialog): ...
Insert variable into global namespace from within a function?
11,813,287
14
2012-08-05T01:31:34Z
11,813,291
12
2012-08-05T01:32:31Z
[ "python", "namespaces" ]
Is it possible to write a function which inserts an object into the global namespace and binds it to a variable? E.g.: ``` >>> 'var' in dir() False >>> def insert_into_global_namespace(): ... var = "an object" ... inject var >>> insert_into_global_namespace() >>> var "an object" ```
Yes, just use the `global` statement. ``` def func(): global var var = "stuff" ```
Insert variable into global namespace from within a function?
11,813,287
14
2012-08-05T01:31:34Z
14,298,025
14
2013-01-12T21:15:48Z
[ "python", "namespaces" ]
Is it possible to write a function which inserts an object into the global namespace and binds it to a variable? E.g.: ``` >>> 'var' in dir() False >>> def insert_into_global_namespace(): ... var = "an object" ... inject var >>> insert_into_global_namespace() >>> var "an object" ```
But be aware that assigning function variables declared global only injects into the module namespace. You cannot use these variables globally after an import: ``` from that_module import call_that_function call_that_function() print(use_var_declared_global) ``` and you get ``` NameError: global name 'use_var_declar...
Insert variable into global namespace from within a function?
11,813,287
14
2012-08-05T01:31:34Z
27,642,440
13
2014-12-24T21:47:51Z
[ "python", "namespaces" ]
Is it possible to write a function which inserts an object into the global namespace and binds it to a variable? E.g.: ``` >>> 'var' in dir() False >>> def insert_into_global_namespace(): ... var = "an object" ... inject var >>> insert_into_global_namespace() >>> var "an object" ```
It seems to be as simple as ``` globals()['var'] = "an object" ``` and/or ``` def insert_into_namespace(name_space, name, value=None): name_space[name] = value insert_into_namespace(globals(), "var", "an object") ``` Remark that `globals` is a built-in keyword, that is, `'globals' in __builtins__.__dict__` eva...
I'm trying to use python in powershell
11,813,435
24
2012-08-05T02:05:32Z
11,813,499
26
2012-08-05T02:22:46Z
[ "python", "powershell", "python-2.7" ]
I'm trying to follow Zed Shaw's guide for Learning Python the Hard Way. I need to use python in Powershell. I have Python 2.7.3 installed in `C:\Python27`. Whenever I type python into Powershell, I get an error that says the term 'python' is not recognized as the name of a cmdlet, function, script file, or operable pro...
Try setting the path this way: ``` $env:path="$env:Path;C:\Python27" ```
I'm trying to use python in powershell
11,813,435
24
2012-08-05T02:05:32Z
11,814,706
14
2012-08-05T07:31:55Z
[ "python", "powershell", "python-2.7" ]
I'm trying to follow Zed Shaw's guide for Learning Python the Hard Way. I need to use python in Powershell. I have Python 2.7.3 installed in `C:\Python27`. Whenever I type python into Powershell, I get an error that says the term 'python' is not recognized as the name of a cmdlet, function, script file, or operable pro...
`$env:path="$env:Path;C:\Python27"` will only set it for the current session. Next time you open Powershell, you will have to do the same thing again. The `[Environment]::SetEnvironmentVariable()` is the right way, and it would have set your PATH environment variable permanently. You just have to start Powershell agai...
I'm trying to use python in powershell
11,813,435
24
2012-08-05T02:05:32Z
21,990,462
10
2014-02-24T14:22:13Z
[ "python", "powershell", "python-2.7" ]
I'm trying to follow Zed Shaw's guide for Learning Python the Hard Way. I need to use python in Powershell. I have Python 2.7.3 installed in `C:\Python27`. Whenever I type python into Powershell, I get an error that says the term 'python' is not recognized as the name of a cmdlet, function, script file, or operable pro...
For what's worth, this command did it for me (Python3.3) : ``` [System.Environment]::SetEnvironmentVariable("PATH", $Env:Path + ";C:\Python33", "Machine") ``` I just had to restart the Powershell after that.
python: pass multiple arguments from one function to another
11,813,548
4
2012-08-05T02:35:29Z
11,813,558
7
2012-08-05T02:38:13Z
[ "python", "function", "argument-passing" ]
I'm trying to learn python (with my VBA background) buy building a black-jack game as a pedagogical exercise. I've done some searches about passing multiple arguments but I really don't understand what i'm finding in the way of explanations. Looking at the last function called 'hand' i'm trying to make use of three s...
try `print hand(*deal(shuffle(load_deck())))` The `*` tells python to do [argument unpacking](http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists).
How do I create a simple pdf file in python?
11,813,555
20
2012-08-05T02:36:58Z
11,813,607
10
2012-08-05T02:52:37Z
[ "python", "pdf" ]
I'm looking for a way to output a VERY simple pdf file from Python. Basically it will consist of two columns of words, one in Russian (so utf-8 characters) and the other in English. I've been googling for about an hour, and the packages I've found are either massive overkill (and still don't provide useful examples) s...
You may use [wkhtmltopdf](http://wkhtmltopdf.org/). It is a command line utility that uses Webkit to convert html to pdf. You can generate your data as html and style it with css if you want, then, use wkhtmltopdf to generate the pdf file.
What do `ns` and `us` stand for in `timeit` result?
11,813,999
10
2012-08-05T04:35:38Z
11,814,004
7
2012-08-05T04:36:59Z
[ "python", "timeit" ]
I was trying to compare performance of two statements with `timeit`, and the results are something like: ``` 100 loops, best of 3: 100 ns per loop 100 loops, best of 3: 1.96 us per loop ``` But I don't know what these `ns` and `us` stands for, so I don't know which one is faster.
Nanoseconds and microseconds... 10-9 and 10-6 respectively.
What do `ns` and `us` stand for in `timeit` result?
11,813,999
10
2012-08-05T04:35:38Z
11,814,007
18
2012-08-05T04:37:15Z
[ "python", "timeit" ]
I was trying to compare performance of two statements with `timeit`, and the results are something like: ``` 100 loops, best of 3: 100 ns per loop 100 loops, best of 3: 1.96 us per loop ``` But I don't know what these `ns` and `us` stands for, so I don't know which one is faster.
*ns* stands for nanoseconds. *n* is the regular [SI prefix](http://en.wikipedia.org/wiki/Metric_prefix) meaning 10-9. *us* means microseconds. In SI that would be *µs* (10-6 seconds) - the *u* is used because there's not a *µ* in ASCII, but it does look pretty similar. In your case, that means you're comparing 100×1...
Site matching query does not exist
11,814,059
37
2012-08-05T04:51:41Z
11,814,271
98
2012-08-05T05:45:18Z
[ "python", "django" ]
Python noob, as in this is my first project, so excuse my unfamiliarity. The site was working very well until I clicked "log out" on my app. After that, the website would give me this error: DoesNotExist at /login/ Site matching query does not exist. I searched everywhere and the only solution I get relates to settin...
If you don't have a site defined in your database and django wants to reference it, you will need to create one. From a `python manage.py shell` : ``` from django.contrib.sites.models import Site new_site = Site.objects.create(domain='foo.com', name='foo.com') print new_site.id ``` Now set that site ID in your setti...
Site matching query does not exist
11,814,059
37
2012-08-05T04:51:41Z
14,388,746
12
2013-01-17T21:49:05Z
[ "python", "django" ]
Python noob, as in this is my first project, so excuse my unfamiliarity. The site was working very well until I clicked "log out" on my app. After that, the website would give me this error: DoesNotExist at /login/ Site matching query does not exist. I searched everywhere and the only solution I get relates to settin...
Table `django_site` must contain a row with the same value of `id` (by default equals to `1`), as `SITE_ID` is set to (inside your `settings.py`).
how to import matplotlib in python
11,815,538
5
2012-08-05T10:04:13Z
11,830,055
10
2012-08-06T14:14:36Z
[ "python", "module", "matplotlib", "graph-theory" ]
I am new to python and I am working on a graph problem and I want to draw this graph to have a better understanding of it. I learnt that matplotlib module is supposed to be imported for this but I dont know how to add it to the project.(I am a java developer and It is pretty much like adding jar to your classpath) Whe...
**module: `new`** As David Robinson points out in a comment on another answer you may have posted an incomplete error message, in which case it is possible that the inbuilt module `new` is being shadowed by `new.py` in the `gis` module. - if that is the case the [suggested fix](http://stackoverflow.com/questions/10790...
int object is unscriptable Python
11,815,754
3
2012-08-05T10:41:13Z
11,815,829
8
2012-08-05T10:53:57Z
[ "python", "list", "error-handling" ]
I'm trying to make Battleship for practice, and single player was a success...when there was only one player and one set of ships and a board :P Any idea why this is giving me an 'int object is unscriptable' error??? Here is the Board class. Well, some of it anyway: ``` class Board: 'Game Board' topMarkers =...
You have two (overlapping) contradictory definitions for `p`: ``` p = [p1,p2] ``` and ``` playersCheck = [0,1] for p in playersCheck: ``` `p[i][0][1].showGrid()` works with the first definition, but fails when `p` is assigned an integer value from the second definition.
memoization library for python 2.7
11,815,873
39
2012-08-05T11:03:06Z
11,861,795
25
2012-08-08T09:43:01Z
[ "python", "python-2.7", "memoization" ]
I see that python 3.2 has memoization as a decorator in functools library. <http://docs.python.org/py3k/library/functools.html#functools.lru_cache> Unfortunately it is not yet backported to 2.7. Is there any specific reason as why it is not available in 2.7? Is there any 3rd party library providing the same feature or...
> Is there any specific reason as why it is not available in 2.7? [@Nirk](http://stackoverflow.com/a/11854956/63011) has already provided the reason: unfortunately, the 2.x line only receive bugfixes, and new features are developed for 3.x only. > Is there any 3rd party library providing the same feature? [`repoze.l...
memoization library for python 2.7
11,815,873
39
2012-08-05T11:03:06Z
12,562,777
19
2012-09-24T10:04:27Z
[ "python", "python-2.7", "memoization" ]
I see that python 3.2 has memoization as a decorator in functools library. <http://docs.python.org/py3k/library/functools.html#functools.lru_cache> Unfortunately it is not yet backported to 2.7. Is there any specific reason as why it is not available in 2.7? Is there any 3rd party library providing the same feature or...
There is a backport of the `functools` module from *Python 3.2.3* for use with *Python 2.7* and *PyPy*: [functools32](http://pypi.python.org/pypi/functools32). It includes the `lru_cache` decorator.
memoization library for python 2.7
11,815,873
39
2012-08-05T11:03:06Z
18,723,434
13
2013-09-10T15:46:19Z
[ "python", "python-2.7", "memoization" ]
I see that python 3.2 has memoization as a decorator in functools library. <http://docs.python.org/py3k/library/functools.html#functools.lru_cache> Unfortunately it is not yet backported to 2.7. Is there any specific reason as why it is not available in 2.7? Is there any 3rd party library providing the same feature or...
I was in the same situation and was forced to implement it by myself. There were also a few other issues with the python 3.x implementation: * The main issues is not enabling a separate cache for each instance (in case the function being cached is an instance method). Meaning that if I set a maxsize of 100 to the cach...
Cannot kill Python script with Ctrl-C
11,815,947
74
2012-08-05T11:16:13Z
11,816,038
112
2012-08-05T11:30:20Z
[ "python", "linux" ]
I am testing Python threading with the following script: ``` import threading class FirstThread (threading.Thread): def run (self): while True: print 'first' class SecondThread (threading.Thread): def run (self): while True: ...
`Ctrl`+`C` terminates the main thread, but because your threads aren't in daemon mode, they keep running, and that keeps the process alive. We can make them daemons: ``` f = FirstThread() f.daemon = True f.start() s = SecondThread() s.daemon = True s.start() ``` But then there's another problem - once the main thread...
Passing no arguments while calling function through dict
11,816,099
14
2012-08-05T11:42:00Z
11,816,119
17
2012-08-05T11:45:08Z
[ "python" ]
I have made a Python script which calls functions based on user's input. Until now I was calling argument-less functions simply through a dict ``` options = { 0 : func0, 1 : func1, 2 : func2, } options[choice]() ``` Now I am in a situation where I need to call a few functions with a...
Use a lists of arguments: ``` options = { 0 : (func0, []), 1 : (func1, []), 2 : (func2, [foo1]), 3 : (func3, [foo2]), } options[choice][0](*options[choice][1]) # or func, args = options[choice] func(*args) ``` If you want to be able to specify named arguments as well, you...
Passing no arguments while calling function through dict
11,816,099
14
2012-08-05T11:42:00Z
11,816,126
25
2012-08-05T11:46:06Z
[ "python" ]
I have made a Python script which calls functions based on user's input. Until now I was calling argument-less functions simply through a dict ``` options = { 0 : func0, 1 : func1, 2 : func2, } options[choice]() ``` Now I am in a situation where I need to call a few functions with a...
`None` is still a value, and passing it to a function that is not expecting arguments will not work. Instead consider using [`partial`](http://docs.python.org/library/functools.html#functools.partial) here ``` from functools import partial options = { 0: func0, 1: func1, 2: partial(func2, foo1...
pycharm convert tabs to spaces automatically
11,816,147
32
2012-08-05T11:49:35Z
11,816,221
37
2012-08-05T11:58:41Z
[ "python", "pycharm" ]
I am using pycharm IDE for python development it works perfectly fine for django code so suspected that converting tabs to spaces is default behaviour, however in python IDE is giving errors everywhere because it can't convert tabs to spaces automatically is there a way to achieve this.
Change the code style to use spaces instead of tabs: ![spaces](http://i.stack.imgur.com/g3RS7.png) Then select a folder you want to convert in the Project View and use `Code` | **Reformat Code**.
pycharm convert tabs to spaces automatically
11,816,147
32
2012-08-05T11:49:35Z
20,491,867
21
2013-12-10T10:24:46Z
[ "python", "pycharm" ]
I am using pycharm IDE for python development it works perfectly fine for django code so suspected that converting tabs to spaces is default behaviour, however in python IDE is giving errors everywhere because it can't convert tabs to spaces automatically is there a way to achieve this.
For selections, you can also convert the selection using the "To spaces" function. I usually just use it via the ctrl-shift-A then find "To Spaces" from there.
How to rename all folders?
11,816,315
4
2012-08-05T12:14:08Z
11,816,333
8
2012-08-05T12:16:24Z
[ "python", "rename", "python-2.5" ]
I have the code like below: ``` temp = os.walk(sys.argv[1]) for root, dirs, files in temp: for i in dirs: dir = os.path.join(root,i) os.rename(dir, dir+"!") ``` It works almost ok. But once parent folder is renamed, it can not rename subfolders. How can I avoid that?
Walk the tree with `topdown` set to False instead: ``` temp = os.walk(sys.argv[1], topdown=False) for root, dirs, files in temp: for i in dirs: dir = os.path.join(root,i) os.rename(dir, dir+"!") ``` From the [documentation](http://docs.python.org/library/os.html#os.walk): > If optional argument *...
What's the equivalent of PHP's "$my_array[]" in Python?
11,816,583
2
2012-08-05T12:52:24Z
11,816,592
8
2012-08-05T12:53:37Z
[ "php", "python" ]
What's the equivalent of PHP's "append to array" (`$my_array[] = "abc";`) in Python, which I have recently started learning? Let's say that I've a dictionary like this: ``` my_dict = {'fruits':['orange', 'pear']} ``` And now I want to add another fruit to `my_dict['fruits']`: `apple`
[`.append()`](http://docs.python.org/library/stdtypes.html#mutable-sequence-types) adds new elements: ``` my_dict = {'fruits':['orange', 'pear']} my_dict['fruits'].append('apple') ```
"object of type 'NoneType' has no len()" error
11,816,844
7
2012-08-05T13:30:22Z
11,816,864
11
2012-08-05T13:33:01Z
[ "python", "web2py" ]
I'm seeing weird behavior on this code: ``` images = dict(cover=[],second_row=[],additional_rows=[]) for pic in pictures: if len(images['cover']) == 0: images['cover'] = pic.path_thumb_l elif len(images['second_row']) < 3: images['second_row'].append(pic.path_thumb_m) else: images[...
You assign something new to `images['cover']`: ``` images['cover'] = pic.path_thumb_l ``` where `pic.path_thumb_l` is `None` at some point in your code. You probably meant to append instead: ``` images['cover'].append(pic.path_thumb_l) ```