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
matplotlib has no attribute 'pyplot'
14,812,342
9
2013-02-11T12:52:22Z
14,812,419
7
2013-02-11T12:56:38Z
[ "python", "matplotlib" ]
I can import matplotlib but when I try to run the following: ``` matplotlib.pyplot(x) ``` I get: ``` Traceback (most recent call last): File "<pyshell#31>", line 1, in <module> matplotlib.pyplot(x) AttributeError: 'module' object has no attribute 'pyplot' ```
Did you import it? Importing `matplotlib` is not enough. ``` >>> import matplotlib >>> matplotlib.pyplot Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute 'pyplot' ``` but ``` >>> import matplotlib.pyplot >>> matplotlib.pyplot ``` works. pyplo...
Keep pandas structure with numpy/scikit functions
14,813,289
8
2013-02-11T13:46:22Z
14,814,282
7
2013-02-11T14:37:44Z
[ "python", "pandas", "scikit-learn" ]
I'm using the excellent `read_csv()`function from pandas, which gives: ``` In [31]: data = pandas.read_csv("lala.csv", delimiter=",") In [32]: data Out[32]: <class 'pandas.core.frame.DataFrame'> Int64Index: 12083 entries, 0 to 12082 Columns: 569 entries, REGIONC to SCALEKER dtypes: float64(51), int64(518) ``` but w...
``` import pandas as pd pd.DataFrame(preprocessing.scale(data), index = data.index, columns = data.columns) ```
Python: An elegant way to delete empty lists from Python dictionary
14,813,396
4
2013-02-11T13:52:33Z
14,813,529
8
2013-02-11T13:59:24Z
[ "python", "list", "dictionary" ]
I have a dictionary as: ``` default = {'a': ['alpha'], 'b': ['beta','gamma'], 'g': []} ``` I wish to eliminate the empty values as: ``` default = {'a': ['alpha'], 'b': ['beta','gamma']} ``` I wrote a function (following an example found on the web) ``` def remove_empty_keys(d): for k in d.keys(): try: ...
To fix your function, change `del[k]` to `del d[k]`. There is no function to delete values in place from a dictionary. What you are doing is deleting the variable `k`, not changing the dictionary at all. This is why the original dictionary is always returned. Rewritten, your function might look like: ``` def remove_...
Can I serve multiple clients using just Flask app.run() as standalone?
14,814,201
66
2013-02-11T14:34:12Z
14,815,932
17
2013-02-11T16:03:07Z
[ "python", "flask" ]
I know I can link Flask with Apache or other web servers. But, I was thinking of running Flask as a standalone server serving multiple clients simultaneously. Is this possible? Do I have to handle spawning multiple threads and managing them?
Using the simple `app.run()` from within Flask creates a single synchronous server on a single thread capable of serving only one client at a time. It is intended for use in controlled environments with low demand (i.e. development, debugging) for exactly this reason. Spawning threads and managing them yourself is pro...
Can I serve multiple clients using just Flask app.run() as standalone?
14,814,201
66
2013-02-11T14:34:12Z
14,823,968
116
2013-02-12T01:20:58Z
[ "python", "flask" ]
I know I can link Flask with Apache or other web servers. But, I was thinking of running Flask as a standalone server serving multiple clients simultaneously. Is this possible? Do I have to handle spawning multiple threads and managing them?
[`flask.Flask.run`](http://flask.pocoo.org/docs/api/#flask.Flask.run) accepts additional keyword arguments (`**options`) that it forwards to [`werkzeug.serving.run_simple`](http://werkzeug.pocoo.org/docs/serving/#werkzeug.serving.run_simple) - two of those arguments are `threaded` (which you can set to `True` to enable...
Do Python for loops work by reference?
14,814,771
5
2013-02-11T15:03:30Z
14,814,847
9
2013-02-11T15:06:57Z
[ "python" ]
When using a `for` loop in Python to iterate over items in a list, will changing `item` (below) change the corresponding item in `items`? ``` for item in items: item += 1 ``` Will each item in items be incremented or remain the same as before the loop? [Note: I would be interested in Python 2.7 and 3.x]
No, variables in Python are *not* pointers. They refer to objects on a heap instead, and assigning to a variable doesn't change the referenced object, but the *variable*. Variables and objects are like labels tied to balloons; assignment reties the label to a different balloon instead. See this [previous answer of mi...
Convert text prediction script [Markov Chain] from javascript to python
14,816,100
4
2013-02-11T16:11:50Z
17,303,943
15
2013-06-25T17:38:18Z
[ "javascript", "python", "markov-chains" ]
i've been trying the last couple days to convert [this js script](http://blog.javascriptroom.com/2013/01/21/markov-chains/) to python code. My implementation (blindfull cp mostly, some minor fixes here and there) so far: ``` import random class markov: memory = {} separator = ' ' order = 2 def getIni...
Guy who wrote the article speaking. Glad you found it useful! Now, my first implementation of a Markov chain was actually in Python, so this answer will focus on how to write it in a more Pythonic way. I'll show how to go about making an order-2 Markov chain, since they're easy to talk about, but you can of course make...
Define a python dictionary with immutable keys but mutable values
14,816,341
8
2013-02-11T16:25:30Z
14,816,446
10
2013-02-11T16:31:19Z
[ "python", "dictionary", "key", "immutability" ]
Well, the question is in the title: how do I define a python dictionary with immutable keys but mutable values? I came up with this (in python 2.x): ``` class FixedDict(dict): """ A dictionary with a fixed set of keys """ def __init__(self, dictionary): dict.__init__(self) for key in d...
Consider proxying `dict` instead of subclassing it. That means that only the methods that you define will be allowed, instead of falling back to `dict`'s implementations. ``` class FixedDict(object): def __init__(self, dictionary): self._dictionary = dictionary def __setitem__(self, key, it...
Using buttons in Tkinter to navigate to different pages of the application?
14,817,210
9
2013-02-11T17:13:03Z
14,819,141
8
2013-02-11T19:10:24Z
[ "python", "user-interface", "tkinter" ]
I have quite a simple question here. In Tkinter (python), i was wondering who to use a button to go to different pages of my application, e.g a register page, and a login page. I am aware that GUI does not have 'pages' like websites do, ive seen a few different ways, but what is the best way to make links to different ...
Make each page a frame. Then, all your buttons need to do is hide whatever is visible, then make the desired frame visible. A simple method to do this is to stack the frames on top of each other (this is one time when `place` makes sense) and then ,`lift()` the frame you want to be visible. This technique works best w...
is there a way to capture misses on a list comprehension?
14,819,032
3
2013-02-11T19:02:31Z
14,819,134
7
2013-02-11T19:10:07Z
[ "python" ]
Based on a simple list comprehension : ``` yay = [ i for i in a if a[i] ] nay = [ i for i in a if not a[i] ] ``` I am wondering if there is a way to assign both the `yay` and `nay` values at once ( ie hits and misses on the conditional )? Something that would look like this ``` ( yay , nay ) = ... ``` I was curiou...
The usual solution here is not to get all hung up on the idea of using a list comprehension. Just use a `for` loop: ``` yay, nay = [], [] for i in a: if somecondition(i): yay.append(i) else: nay.append(i) ``` If you find yourself doing this a lot then simply move the code out into a function: ...
How do you use a regex in a list comprehension in Python?
14,819,164
5
2013-02-11T19:12:20Z
14,819,189
12
2013-02-11T19:13:55Z
[ "python", "regex" ]
I'm trying to locate all index positions of a string in a list of words and I want the values returned as a list. I would like to find the string if it is on its own, or if it is preceded or followed by punctuation, but not if it is a substring of a larger word. The following code only captures "cow" only and misses b...
You don't need to assign the result of `match` back to `x`. And your match should be on `x` rather than `list`. Also, you need to use `re.search` instead of `re.match`, since your the regex pattern `'\W*myString\W*'` will not match the first element. That's because `test;` is not matched by `\W*`. Actually, you only n...
Upload files using SFTP in Python, but create directories if path doesn't exist
14,819,681
9
2013-02-11T19:48:39Z
14,819,803
19
2013-02-11T19:57:29Z
[ "python", "ssh", "sftp", "paramiko" ]
I want to upload a file on a remote server with Python. I'd like to check beforehand if the remote path is really existing, and if it isn't, to create it. In pseudocode: ``` if(remote_path not exist): create_path(remote_path) upload_file(local_file, remote_path) ``` I was thinking about executing a command in Par...
SFTP supports the usual FTP commands (chdir, mkdir, etc...), so use those: ``` sftp = paramiko.SFTPClient.from_transport(transport) try: sftp.chdir(remote_path) # Test if remote_path exists except IOError: sftp.mkdir(remote_path) # Create remote_path sftp.chdir(remote_path) sftp.put(local_path, '.') #...
create lists of unique names in a for -loop in python
14,819,849
5
2013-02-11T20:01:28Z
14,819,883
11
2013-02-11T20:03:28Z
[ "python", "list", "for-loop", "unique" ]
I want to create a series of lists with unique names inside a for-loop and use the index to create the liste names. Here is what I want to do ``` x = [100,2,300,4,75] for i in x: list_i=[] ``` I want to create empty lists such as ``` lst_100 = [], lst_2 =[] lst_300 = [].. ``` any help?
Don't make dynamically named variables. It makes it hard to program with them. Instead, use a dict: ``` x = [100,2,300,4,75] dct = {} for i in x: dct['lst_%s' % i] = [] print(dct) # {'lst_300': [], 'lst_75': [], 'lst_100': [], 'lst_2': [], 'lst_4': []} ```
how do I .decode('string-escape') in Python3?
14,820,429
17
2013-02-11T20:37:59Z
14,820,462
17
2013-02-11T20:40:08Z
[ "python", "python-3.x", "escaping" ]
I have some escaped strings that need to be unescaped. I'd like to do this in Python. For example, in python2.7 I can do this: ``` >>> "\123omething special".decode('string-escape') 'Something special' >>> ``` How do I do it in Python3? This doesn't work: ``` >>> b"\123omething special".decode('string-escape') Trac...
You'll have to use `unicode_escape` instead: ``` >>> b"\\123omething special".decode('unicode_escape') ``` If you *start* with a `str` object instead (equivalent to the python 2.7 unicode) you'll need to encode to bytes first, then decode with `unicode_escape`. If you need bytes as end result, you'll have to encode ...
How do I install Socks / SocksIPy on Ubuntu?
14,820,453
8
2013-02-11T20:39:28Z
14,820,912
12
2013-02-11T21:10:25Z
[ "python", "ubuntu", "install", "socks" ]
I am new to python and would like to install `SocksIPy` on Ubuntu (running within a VirtualBox vm). The README says to place the `socks.py` file into my `lib/site-packages` directory. I do not know where to locate this directory. The Terminal command `python socks.py install` from the root runs, but does not install co...
The simplest way to install it - provided the VM has working Internect connectivity - would likely be to let `apt-get` do it for you. From a terminal: ``` sudo apt-get install python-socksipy ``` It's in the universe repository, which should be enabled by default. If not, you can [enable it yourself](http://askubuntu...
How do I install Socks / SocksIPy on Ubuntu?
14,820,453
8
2013-02-11T20:39:28Z
28,794,078
7
2015-03-01T13:29:52Z
[ "python", "ubuntu", "install", "socks" ]
I am new to python and would like to install `SocksIPy` on Ubuntu (running within a VirtualBox vm). The README says to place the `socks.py` file into my `lib/site-packages` directory. I do not know where to locate this directory. The Terminal command `python socks.py install` from the root runs, but does not install co...
[`PySocks`](https://github.com/Anorov/PySocks) is yet another `SocksiPy` fork: ``` $ pip install PySocks ``` It works on Python 2/3.
How to query directly the table created by Django for a ManyToMany relation?
14,820,579
12
2013-02-11T20:48:38Z
14,820,648
25
2013-02-11T20:53:17Z
[ "python", "django", "many-to-many" ]
I have a model `MyModel2` with a `ManyToManyField` related to another model `MyModel1`. How can I get the pairs `mymodel1.id, mymodel2.id`, as represented in the table Django create for this relation? Do I have to do a raw SQL query on this table or is it possible through the object managers of this models? ``` class...
This is the many to many field instance: ``` MyModel2.mymodel1 ``` This is the intermediary table model: ``` MyModel2.mymodel1.through ``` This is the intermediary model manager: ``` MyModel2.mymodel1.through.objects ``` This returns a queryset for all intermediary models: ``` MyModel2.mymodel1.through.objects.a...
invert colormap in mlab
14,820,665
3
2013-02-11T20:54:29Z
19,667,996
7
2013-10-29T20:03:14Z
[ "python", "mayavi", "mlab" ]
I simply want to know how to invert a colormap in mlab. I know in matplotlib you can simply add \_r to the name of the colormap to invert the color scheme. However it appears to be slightly different in mlab. Does anyone know how this can be achieved?
Using the script recording of the mayavi pipeline, I found : ``` s.module_manager.scalar_lut_manager.reverse_lut = True ```
Ubuntu Python shebang line not working
14,821,012
2
2013-02-11T21:17:48Z
14,821,303
8
2013-02-11T21:36:42Z
[ "python", "linux", "ubuntu", "python-2.7", "ubuntu-12.04" ]
Unable to get shebang line working in Ubuntu for python script. I only get a command not found error each time. test.py ``` #!/usr/bin/env python print ('!') ``` Ran ``` :which python /usr/bin/python ``` Played around with different locations for python in the shebang but no luck including what was provided by wh...
If you are trying to run the command as ``` $ test.py ``` the error may not have anything to do with the shebang. Rather, the directory that test.py resides in is not in your `PATH`. Try ``` $ ./test.py ``` to bypass `PATH` lookup. (This is in addition to making sure that the script itself is executable.)
SciPy build/install Mac Osx
14,821,297
27
2013-02-11T21:36:07Z
14,822,245
74
2013-02-11T22:37:41Z
[ "python", "osx", "python-2.7", "fortran", "scipy" ]
I successfully built/installed NumPy on my mac os x for python 2.7.3. Now I would like to build/install scipy as well. I downloaded it from git hub. Went into the directory. Ran python setup.py build and it seemed to be working until it came across this error: ``` customize Gnu95FCompiler Could not locate executable g...
Your problem is that you need to install a Fortran compiler to build `scipy`. Also, if you already have a `numpy` that's built with Fortran support disabled, you may have to replace it. Some of Apple's pre-installed Python versions have such a `numpy` build pre-installed. --- The easiest way to get Fortran is with [...
Is there a ceiling equivalent of // operator in Python?
14,822,184
32
2013-02-11T22:33:09Z
14,822,215
23
2013-02-11T22:35:29Z
[ "python", "python-3.x" ]
I found out about the `//` operator in Python which in Python 3 does division with floor. Is there an operator which divides with ceil instead? (I know about the `/` operator which in Python 3 does floating point division.)
There is no operator which divides with ceil. You need to `import math` and use `math.ceil`
Is there a ceiling equivalent of // operator in Python?
14,822,184
32
2013-02-11T22:33:09Z
14,822,585
7
2013-02-11T23:03:45Z
[ "python", "python-3.x" ]
I found out about the `//` operator in Python which in Python 3 does division with floor. Is there an operator which divides with ceil instead? (I know about the `/` operator which in Python 3 does floating point division.)
You can always just do it inline as well ``` ((foo - 1) // bar) + 1 ``` In python3, this is just shy of an order of magnitude faster than forcing the float division and calling ceil(), provided you care about the speed. Which you shouldn't, unless you've proven through usage that you need to. ``` >>> timeit.timeit("...
Is there a ceiling equivalent of // operator in Python?
14,822,184
32
2013-02-11T22:33:09Z
17,511,341
80
2013-07-07T10:30:02Z
[ "python", "python-3.x" ]
I found out about the `//` operator in Python which in Python 3 does division with floor. Is there an operator which divides with ceil instead? (I know about the `/` operator which in Python 3 does floating point division.)
You can just do upside-down floor division: ``` def ceildiv(a, b): return -(-a // b) ``` This works because [Python's division operator does floor division](http://python-history.blogspot.com/2010/08/why-pythons-integer-division-floors.html) (unlike in C, where integer division truncates the fractional part). Th...
Don't put html, head and body tags automatically, beautifulsoup
14,822,188
17
2013-02-11T22:33:22Z
14,822,344
25
2013-02-11T22:45:33Z
[ "python", "beautifulsoup", "html5lib" ]
using beautifulsoup with html5lib, it puts the html, head and body tags automatically: ``` BeautifulSoup('<h1>FOO</h1>', 'html5lib') # => <html><head></head><body><h1>FOO</h1></body></html> ``` is there any option that I can set, turn off this behavior ?
``` In [35]: import bs4 as bs In [36]: bs.BeautifulSoup('<h1>FOO</h1>', "html.parser") Out[36]: <h1>FOO</h1> ``` This [parses the HTML with Python's builtin HTML parser](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#differences-between-parsers). Quoting the docs: > Unlike html5lib, this parser makes no attem...
convert python dataframe to list
14,822,680
12
2013-02-11T23:11:37Z
14,822,703
26
2013-02-11T23:13:34Z
[ "python", "python-3.x", "python-2.7", "pandas" ]
I have a Python dataFrame with multiple columns. ``` LogBlk Page BayFail 0 0 [0, 1, 8, 9] 1 16 [0, 1, 4, 5, 6, 8, 9, 12, 13, 14] 2 32 [0, 1, 4, 5, 6, 8, 9, 12, 13, 14] 3 ...
`pandas.Series`, has a [`tolist` method](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tolist.html#numpy-ndarray-tolist): ``` In [10]: import pandas as pd In [11]: s = pd.Series([0,1,8,9], name = 'BayFail') In [12]: s.tolist() Out[12]: [0L, 1L, 8L, 9L] ``` --- Technical note: In my original ans...
why cant upstart run 'source bin/activate'?
14,823,001
25
2013-02-11T23:38:20Z
14,823,355
46
2013-02-12T00:11:45Z
[ "python", "virtualenv", "upstart" ]
upstart wont activate my virtualenv for some reason. This is how i run it ``` script # My startup script, plain old shell scripting here. cd path/to/env source bin/activate .... end script ``` the virtualenv runs fine when started manually Why does this not work?
So ive worked it out, for some reason upstart doesnt like using 'source' so i changed the line from: ``` source bin/activate ``` to ``` . bin/activate ``` and that works, dont know why though, so would be interested if someone could explain this
why cant upstart run 'source bin/activate'?
14,823,001
25
2013-02-11T23:38:20Z
17,958,737
31
2013-07-30T22:41:08Z
[ "python", "virtualenv", "upstart" ]
upstart wont activate my virtualenv for some reason. This is how i run it ``` script # My startup script, plain old shell scripting here. cd path/to/env source bin/activate .... end script ``` the virtualenv runs fine when started manually Why does this not work?
`source` is a bash built-in command but only a posix "special" command. Upstart runs `sh -e` when executing the script sections. sh shell doesn't understand `source`, only `.`
How to get the input from the Tkinter Text Box Widget?
14,824,163
21
2013-02-12T01:45:44Z
14,824,164
34
2013-02-12T01:45:44Z
[ "python", "tkinter" ]
How to get Tkinter input from the Text box in Python 2.7.3? **EDIT** I asked this question to help others with the same problem - *that* is the reason why there is no example code. This issue had been troubling me for hours and I used this question to teach others. *Please* do not rate it as if it was a real question...
To get Tkinter input from the text box, you must add a few more attributes to the normal `.get()` function. If we have a text box `myText_Box`, then this is the method for retrieving its input. ``` def retrieve_input(): input = self.myText_Box.get("1.0",END) ``` The first part, `"1.0"` means that the input should...
Edit the width of bars using dataframe.plot() function in matplotlib
14,824,456
16
2013-02-12T02:23:01Z
14,843,650
9
2013-02-12T23:14:31Z
[ "python", "matplotlib", "pandas", "histogram", "bar-chart" ]
I am making a stacked bar plot using: ``` DataFrame.plot(kind='bar',stacked=True) ``` I want to control width of bars so that the bars are connected to each other like a histogram. *I've looked through the documentation but to no avail - any suggestions? Is it possible to do it this way?*
If think you have to "postprocess" the barplot with matplotlib as pandas internally sets the width of the bars. The rectangles which form the bars are in container objects. So you have to iterate through these containers and set the width of the rectangles individually: ``` In [208]: df = pd.DataFrame(np.random.rando...
Edit the width of bars using dataframe.plot() function in matplotlib
14,824,456
16
2013-02-12T02:23:01Z
27,321,764
23
2014-12-05T17:46:24Z
[ "python", "matplotlib", "pandas", "histogram", "bar-chart" ]
I am making a stacked bar plot using: ``` DataFrame.plot(kind='bar',stacked=True) ``` I want to control width of bars so that the bars are connected to each other like a histogram. *I've looked through the documentation but to no avail - any suggestions? Is it possible to do it this way?*
For anyone coming across this question: Since pandas 0.14, plotting with bars has a 'width' command: <https://github.com/pydata/pandas/pull/6644> The example above can now be solved simply by using ``` df.plot(kind='bar', stacked=True, width=1) ```
Dynamically serving a matplotlib image to the web using python
14,824,522
15
2013-02-12T02:31:13Z
14,831,018
15
2013-02-12T11:03:13Z
[ "python", "matplotlib", "cgi" ]
This question has been asked in a similar way [here](http://stackoverflow.com/questions/5515278/plot-matplotlib-on-the-web) but the answer was way over my head (I'm super new to python and web development) so I'm hoping there's a simpler way or it could be explained differently. I'm trying to generate an image using m...
You should * first write to a cStringIO object * then write the HTTP header * then write the content of the cStringIO to stdout Thus, if an error in `savefig` occured, you could still return something else, even another header. Some errors won't be recognized earlier, e.g., some problems with texts, too large image d...
How to draw intersecting planes?
14,824,893
17
2013-02-12T03:26:03Z
14,825,951
16
2013-02-12T05:24:44Z
[ "python", "matplotlib" ]
I want to use matplotlib to draw more or less the figure I attached below, which includes the two intersecting planes with the right amount of transparency indicating their relative orientations, and the circles and vectors in the two planes projected in 2D. I'm not sure if there is an existing package for doing this,...
``` from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(111, projection='3d') dim = 10 X, Y = np.meshgrid([-dim, dim], [-dim, dim]) Z = np.zeros((2, 2)) angle = .5 X2, Y2 = np.meshgrid([-dim, dim], [0, dim]) Z2 = Y2 * angle X3, Y3 = np....
Getting multiple entities with get_by_id in ndb
14,825,361
6
2013-02-12T04:26:40Z
14,827,666
13
2013-02-12T07:38:25Z
[ "python", "google-app-engine", "app-engine-ndb" ]
With the old db, I could call `Model.get_by_id([1, 2, 3])` to get a list of entities. Ndb's `Model.get_by_id` doesn't support a list of ids as a parameter. What's the best way to replicate the old functionality?
You use the function get\_multi which takes a list of keys. ``` objects = ndb.get_multi([ndb.Key(Model, k) for k in ids]) ```
Flask: How to read a file in application root?
14,825,787
9
2013-02-12T05:10:29Z
14,826,195
27
2013-02-12T05:45:12Z
[ "python", "flask" ]
My Flask application structure looks like ``` application_top/ application/ static/ english_words.txt templates/ main.html urls.py views.py runserver.py ``` When I...
I think the issue is you put `/` in the path. Remove `/` because `static` is at the same level as `views.py`. I suggest making a `settings.py` the same level as `views.py` Or many Flask users prefer to use `__init__.py` but I don't. ``` application_top/ application/ static/ english_words.t...
Python os.path.join() on a list
14,826,888
32
2013-02-12T06:40:15Z
14,826,889
62
2013-02-12T06:40:15Z
[ "python", "python-2.7", "os.path" ]
I can do ``` >>> os.path.join("c:/","home","foo","bar","some.txt") 'c:/home\\foo\\bar\\some.txt' ``` But, when I do ``` >>> s = "c:/,home,foo,bar,some.txt".split(",") >>> os.path.join(s) ['c:/', 'home', 'foo', 'bar', 'some.txt'] ``` What am I missing here?
The problem is, `os.path.join` doesn't take a `list` as argument, it has to be separate arguments. This is where `*`, the 'splat' operator comes into play... I can do ``` >>> s = "c:/,home,foo,bar,some.txt".split(",") >>> os.path.join(*s) 'c:/home\\foo\\bar\\some.txt' ```
Python os.path.join() on a list
14,826,888
32
2013-02-12T06:40:15Z
14,830,552
11
2013-02-12T10:39:05Z
[ "python", "python-2.7", "os.path" ]
I can do ``` >>> os.path.join("c:/","home","foo","bar","some.txt") 'c:/home\\foo\\bar\\some.txt' ``` But, when I do ``` >>> s = "c:/,home,foo,bar,some.txt".split(",") >>> os.path.join(s) ['c:/', 'home', 'foo', 'bar', 'some.txt'] ``` What am I missing here?
Assuming `join` wasn't designed that way (which it is, as ATOzTOA pointed out), and it only took two parameters, you could still use the built-in `reduce`: ``` >>> reduce(os.path.join,["c:/","home","foo","bar","some.txt"]) 'c:/home\\foo\\bar\\some.txt' ``` Same output like: ``` >>> os.path.join(*["c:/","home","foo",...
How to run web2py project on Apache server?
14,827,559
2
2013-02-12T07:30:31Z
14,854,830
8
2013-02-13T13:36:21Z
[ "python", "apache", "web2py" ]
I want to develop my project with **web2py**. Before that I make it with **python cherrypy**. and now going to switch to web2py. But I would like use Apache server instead of WSGI and web2py server! Could you guide me how do this?
Into scripts folder(web2py/scripts) are some one-step setup scripts to deploy a web2py environment using apache for: * Fedora Linux: setup-web2py-fedora.sh * Ubuntu Linux: setup-web2py-ubuntu.sh If you have another OS you can check it in order to get a detailed step to step installation guide. As Calvin said, the de...
Using Amazon SWF To communicate between servers
14,829,562
9
2013-02-12T09:44:18Z
14,925,820
16
2013-02-17T20:40:30Z
[ "python", "linux", "amazon-web-services", "boto", "amazon-swf" ]
Use Amazon SWF to communicate messages between servers? 1. On server A I want to run a script A 2. When that is finished I want to send a message to server B to run a script B 3. If it completes successfully I want it to clear the job from the workflow queue I’m having a really hard time working out how I can use B...
I think you ask some very good questions which highlight how helpful SWF can be as a service. In short, you don't tell your servers to coordinate work between themselves. Your decider orchestrates all this for you, with the help of SWF service. The implementation of your workflow will go as follows: 1. Registering yo...
How to continue in nested loops in Python
14,829,640
22
2013-02-12T09:49:01Z
14,829,735
18
2013-02-12T09:53:48Z
[ "python" ]
How can you `continue` the parent loop of say two nested loops in Python? ``` for a in b: for c in d: for e in f: if somecondition: <continue the for a in b loop?> ``` I know you can avoid this in the majority of cases but can it be done in Python?
1. Break from the inner loop (if there's nothing else after it) 2. Put the outer loop's body in a function and return from the function 3. Raise an exception and catch it at the outer level 4. Set a flag, break from the inner loop and test it at an outer level. 5. Refactor the code so you no longer have to do this. I ...
How to continue in nested loops in Python
14,829,640
22
2013-02-12T09:49:01Z
14,829,934
10
2013-02-12T10:05:54Z
[ "python" ]
How can you `continue` the parent loop of say two nested loops in Python? ``` for a in b: for c in d: for e in f: if somecondition: <continue the for a in b loop?> ``` I know you can avoid this in the majority of cases but can it be done in Python?
Here's a bunch of hacky ways to do it: 1. Create a local function ``` for a in b: def doWork(): for c in d: for e in f: if somecondition: return # <continue the for a in b loop?> doWork() ``` A better option would be to mov...
Get particular value from dictionary
14,830,128
2
2013-02-12T10:16:13Z
14,830,142
9
2013-02-12T10:16:41Z
[ "python", "dictionary" ]
How to get a particular key from dictionary in python? I have a dictionary as : ``` dict = {'redorange':'1', 'blackhawak':'2', 'garlicbread':'3'} ``` I want to get value of that key which contains garlic in its key name. How I can achieve it?
Let's call your dictionary `d`: ``` print [v for k,v in d.iteritems() if 'garlic' in k] ``` prints a list of all corresponding values: ``` ['3'] ``` If you know you want a single value: ``` print next(v for k,v in d.iteritems() if 'garlic' in k) ``` prints ``` '3' ``` This raises `StopIterationError` if no such...
How to count no of rows in table from web apllication using selenium python webdriver
14,831,041
5
2013-02-12T11:04:41Z
14,836,860
12
2013-02-12T16:15:58Z
[ "python", "selenium-webdriver" ]
How to count the rows in the table from web application by using selenium python web driver. Here we can retrieve all data in the table from web application but couldn't count the rows and columns, please give me idea of how to do this.
Try some thing like this ``` int rowCount=driver.findElements(By.xpath("//table[@id='DataTable']/tbody/tr")).size(); int columnCount=driver.findElements(By.xpath("//table[@id='DataTable']/tbody/tr/td")).size(); ``` FYI : This is the implementation in java.
Convert a list of tuples to a list of lists
14,831,830
12
2013-02-12T11:47:02Z
14,831,861
20
2013-02-12T11:48:25Z
[ "python" ]
I've written this function to convert a list of tuples to a list of lists. Is there a more elegant / Pythonic way of doing this? ``` def get_list_of_lists(list_of_tuples): list_of_lists = [] for tuple in list_of_tuples: list_of_lists.append(list...
You can use [list comprehension](http://www.youtube.com/watch?v=pShL9DCSIUw): ``` >>> list_of_tuples = [(1, 2), (4, 5)] >>> list_of_lists = [list(elem) for elem in list_of_tuples] >>> list_of_lists [[1, 2], [4, 5]] ```
Convert a list of tuples to a list of lists
14,831,830
12
2013-02-12T11:47:02Z
14,831,908
14
2013-02-12T11:50:30Z
[ "python" ]
I've written this function to convert a list of tuples to a list of lists. Is there a more elegant / Pythonic way of doing this? ``` def get_list_of_lists(list_of_tuples): list_of_lists = [] for tuple in list_of_tuples: list_of_lists.append(list...
While the list comprehension is a totally valid answer, as you are just changing type, it might be worth considering the alternative, [the `map()` built-in](http://docs.python.org/3.3/library/functions.html#map): ``` >>> list_of_tuples = [(1, 2), (4, 5)] >>> map(list, list_of_tuples) [[1, 2], [4, 5]] ``` The `map()` ...
Get the last inserted id in django
14,832,115
3
2013-02-12T12:01:58Z
14,832,762
8
2013-02-12T12:38:10Z
[ "python", "django", "rawsql" ]
I am migrating some data from other databases , so i am using raw sql queries for inserting data into database . But i don't know how to get last inserted id from raw sql queries in django. I have tried this ``` affected_count1=cursor2.execute("table')") and SELECT IDENT_CURRENT(‘MyTable’) ``` but it gives me t...
You can get latest create obj like this: ``` obj = Foo.objects.latest('id') ``` more info [here](https://docs.djangoproject.com/en/dev/ref/models/querysets/#latest)
PyQt: clicking X doesn't trigger closeEvent
14,834,494
3
2013-02-12T14:11:38Z
14,835,059
7
2013-02-12T14:41:40Z
[ "python", "pyqt", "pyqt4" ]
I'm a total newbie in PyQt trying to develop simple application. I have designed simple ui with Qt-designer. I want extra confirmation if the user really want to exit application when clicking X or ,,Exit'' button or choosing Exit from menu. Here's the code: ``` import sys from PyQt4 import QtGui, QtCore, uic class ...
Note that you're doing: ``` self.ui = uic.loadUi('main_window.ui') self.ui.show() ``` Your *actual* window is an instance attribute (`ui`) *inside* `win`. Not the `win` itself. And it doesn't have `closeEvent` implemented. [`loadUi`](http://pyqt.sourceforge.net/Docs/PyQt4/designer.html#the-uic-module) can load the `...
Difference between class declarations
14,835,236
3
2013-02-12T14:50:14Z
14,835,276
7
2013-02-12T14:52:35Z
[ "python", "class" ]
I see some similar questions about this topic, but i wish to be sure, so i am asking... What is the difference between: ``` class MyClass: pass ``` and ``` class MyClass(): pass ``` Also, is there a difference between these two: ``` class MyClass(): pass class MyClass(object): pass ```
There is no difference between `class MyClass` and `class MyClass()`. The second question is dependent on your python version. On python3.x, there is no difference -- On python2.x, the latter (where you inherit from `object`) creates a [new-style class](http://www.python.org/doc/newstyle/) rather than an old-style clas...
Is there a standardized method to swap two variables in Python?
14,836,228
122
2013-02-12T15:43:55Z
14,836,239
53
2013-02-12T15:44:22Z
[ "python", "swap", "conventions" ]
In Python, I've seen two variable values swapped using this syntax: ``` left, right = right, left ``` Is this considered the standard way to swap two variable values or is there some other means by which two variables are by convention most usually swapped?
That is the standard way to swap two variables, yes.
Is there a standardized method to swap two variables in Python?
14,836,228
122
2013-02-12T15:43:55Z
14,836,456
151
2013-02-12T15:56:33Z
[ "python", "swap", "conventions" ]
In Python, I've seen two variable values swapped using this syntax: ``` left, right = right, left ``` Is this considered the standard way to swap two variable values or is there some other means by which two variables are by convention most usually swapped?
> Python evaluates expressions from left to right. Notice that while > evaluating an assignment, the right-hand side is evaluated before the > left-hand side. > > <http://docs.python.org/2/reference/expressions.html#evaluation-order> That means the following for the expression `a,b = b,a` : * the right-hand side `b,a...
Is there a standardized method to swap two variables in Python?
14,836,228
122
2013-02-12T15:43:55Z
34,644,888
9
2016-01-06T23:34:40Z
[ "python", "swap", "conventions" ]
In Python, I've seen two variable values swapped using this syntax: ``` left, right = right, left ``` Is this considered the standard way to swap two variable values or is there some other means by which two variables are by convention most usually swapped?
I know three ways to swap variables, but `a, b = b, a` is the simplest. There is ## XOR (for integers) ``` x = x ^ y y = y ^ x x = x ^ y ``` ## Temporary variable ``` w = x x = y y = w del w ``` ## Tuple swap ``` x, y = y, x ```
Is there a standardized method to swap two variables in Python?
14,836,228
122
2013-02-12T15:43:55Z
36,199,776
9
2016-03-24T12:05:22Z
[ "python", "swap", "conventions" ]
In Python, I've seen two variable values swapped using this syntax: ``` left, right = right, left ``` Is this considered the standard way to swap two variable values or is there some other means by which two variables are by convention most usually swapped?
This is standard way of swapping two variables, optimised in Python byte code. Consider following code snippet and analyze generated byte code: ``` import dis def f(): l, r = r, l dis.dis(f) ``` Output is: ``` 2 0 LOAD_FAST 0 (r) 3 LOAD_FAST 1 (l) ...
output the command line called by subprocess?
14,836,947
15
2013-02-12T16:19:56Z
14,837,250
22
2013-02-12T16:33:43Z
[ "python", "command-line", "subprocess", "popen" ]
I'm using the `subprocess.Popen` call, and in another question I found out that I had been misunderstanding how Python was generating arguments for the command line. **My Question** Is there a way to find out what the actual command line was? Example Code :- ``` proc = subprocess.popen(....) print "the commandline...
It depends on the version of Python you are using. [In the current version of Python3](http://hg.python.org/cpython/file/7727be7613f9/Lib/subprocess.py#l757), the arg is saved in `proc.args`: ``` proc = subprocess.Popen(....) print("the commandline is {}".format(proc.args)) ``` In Python2.7, [the `args` not saved](ht...
Arrow keys in Putty returning ^[[A ^[[D ^[[B instead of moving the cursor
14,837,248
27
2013-02-12T16:33:33Z
24,140,771
56
2014-06-10T12:16:53Z
[ "python", "putty", "arrow-keys" ]
Has anyone else ever had this error in PuTTy? For example, pressing the Up Key now produces: ``` >>> ^[[A ``` Google doesn't let you search for special characters so I'm stumped at finding existing version of this problem. --- EDIT: So this happened after I pasted in some unicode (when, I think, the translation w...
In my experience that's because "bash" is not running. Simply run "/bin/bash" to enjoy colors, history and more.
How are these strings represented internally in Python interpreter ? I don't understand
14,839,028
4
2013-02-12T18:14:10Z
14,839,118
8
2013-02-12T18:19:51Z
[ "python", "string", "unicode", "python-2.7" ]
``` # -*- coding: utf-8 -*- a = 'éáűőúöüó€' print type(a) # <type 'str'> print a # éáűőúöüó€ print ord(a[-1]) # 172 ``` Why is this working ? Shouldn't be this a `SyntaxError: Non-ASCII character '\xc3' in file ...` ? There are unicode literals in the string. When I prefix it with `u`...
> There are unicode literals in the string No, there are not. There are bytes in the string. Python simply goes with the bytes your editor saved to disk when you created the file. When you prefixed the string with a `u''`, you signalled to python that you are creating a `unicode` object instead. Python now pays atten...
Merge two objects in Python
14,839,528
16
2013-02-12T18:43:51Z
14,839,631
26
2013-02-12T18:50:02Z
[ "python", "object", "dictionary", "merge", "built-in" ]
Is there a good way to merge two objects in Python? Like a built-in method or fundamental library call? Right now I have this, but it seems like something that shouldn't have to be done manually: ``` def add_obj(obj, add_obj): for property in add_obj: obj[property] = add_obj[property] ``` Note: By "obje...
If `obj` is a dictionary, use its [`update`](http://docs.python.org/2/library/stdtypes.html#dict.update) function: ``` obj.update(add_obj) ```
Handling with multiple domains in Flask
14,839,618
9
2013-02-12T18:49:22Z
14,839,695
14
2013-02-12T18:54:11Z
[ "python", "routing", "flask" ]
I want to implement structure in Flask, which can handle multiple domains. So when I type in browser "<http://domain1.com/show/1>", it actually executes function with routing like ``` @app.route('<string:domain>/show/<int:id>') def show(domain = '', id = ''): return 'Domain is ' + domain + ', ID is ' + str(id) ```...
The `request` object already has a [`url_root`](http://flask.pocoo.org/docs/api/#flask.Request.url_root) parameter. Or you can use the `Host` header: ``` print request.url_root # prints "http://domain1.com/" print request.headers['Host'] # prints "domain1.com" ``` If you need to redirect within the application, `ur...
Is there a pythonic way to grab the total amount of variables within lists inside a dict?
14,841,037
2
2013-02-12T20:17:44Z
14,841,065
7
2013-02-12T20:19:20Z
[ "python", "list", "dictionary", "python-2.7" ]
I have a dictionary where each key has a list (vector) of items: ``` from collections import defaultdict dict = defaultdict(list) dict[133] = [2,4,64,312] dict[4] = [2,3,5,12,45,32] dict[54] = [12,2,443,223] def getTotalVectorItems(items): total = 0 for v in items.values(): total += len(v) return total pri...
You are looking for [the `sum()` built-in](http://docs.python.org/3/library/functions.html#sum) with a [generator expression](http://www.youtube.com/watch?v=pShL9DCSIUw): ``` sum(len(v) for v in items.values()) ``` The `sum()` function totals the values of the given iterator, and the generator expression yields the l...
is there a way to loop over two lists simultaneously in django?
14,841,165
11
2013-02-12T20:25:23Z
14,841,466
23
2013-02-12T20:44:51Z
[ "python", "django", "django-templates", "django-views" ]
I have two list objects of the same length with complementary data i want to render is there a way to render both at the same time ie. ``` {% for i,j in table, total %} {{ i }} {{ j }} {% endfor %} ``` or something similar?
If both lists are of the same length, you can return `zipped_data = zip(table, total)` as template context in your view, which produces a list of 2-valued tuples. Example: ``` >>> lst1 = ['a', 'b', 'c'] >>> lst2 = [1, 2, 3] >>> zip(lst1, lst2) [('a', 1), ('b', 2), ('c', 3)] ``` In your template, you can then write: ...
Rotate line around center point given two vertices
14,842,090
5
2013-02-12T21:22:55Z
14,842,362
15
2013-02-12T21:40:24Z
[ "python", "rotation", "trigonometry" ]
I've been trying to rotate a bunch of lines by 90 degrees (that together form a polyline). Each line contains two vertices, say (x1, y1) and (x2, y2). What I'm currently trying to do is rotate around the center point of the line, given center points |x1 - x2| and |y1 - y2|. For some reason (I'm not very mathematically ...
The coordinates of the center point of a line segment between points (x1,y1) and (x2,y2) is: ``` center_x = (x1 + x2) / 2 center_y = (y1 + y2) / 2 ``` In other words it's just the average, or arithmetic mean, of the pairs of x and y coordinate values. For a multi-segmented line, or polyline, the logical center point...
How to write python lambda with multiple lines?
14,843,777
2
2013-02-12T23:25:48Z
14,843,787
12
2013-02-12T23:26:34Z
[ "python", "lambda" ]
In python, how can you write a lambda function taking multiple lines. I tried ``` d = lambda x: if x: return 1 else return 2 ``` but I am getting errors...
Use `def` instead. ``` def d(x): if x: return 1 else: return 2 ``` All python functions are first order objects (they can be passed as arguments), `lambda` is just a convenient way to make short ones. In general, you are better off using a normal function definition if it becomes anything beyo...
python matplotlib blit to axes or sides of the figure?
14,844,223
4
2013-02-13T00:06:20Z
14,846,126
14
2013-02-13T03:54:33Z
[ "python", "user-interface", "matplotlib" ]
I'm trying to refresh some plots that I have within a gui everytime I go once through a fitting procedure. Also, these plots are within a framw which can be resized, so the axes and labels etc need to be redrawn after the resizing. So was wondering if anyone knew how to update the sides of a figure using something like...
All this can certainly be rather confusing at first! To begin with, if you're chaining the ticks, etc, there isn't much point in using blitting. Blitting is just a way to avoid re-drawing everything if only some things are changing. If everything is changing, there's no point in using blitting. Just re-draw the plot. ...
Invalid character in identifier
14,844,687
2
2013-02-13T00:54:09Z
14,844,830
13
2013-02-13T01:08:32Z
[ "python", "python-3.x" ]
I am working on the letter distribution problem from HP code wars 2012. I keep getting an error message that says invalid character in identifier. What does this mean and how can it be fixed. here is the page with the information. hpcodewars.org/past/cw15/problems/2012ProblemsFinalForPrinting.pdf here is the code ``` ...
The error `SyntaxError: invalid character in identifier` means you have some character in the middle of a variable name, function, etc. that's not a letter, number, or underscore. The actual error message will look something like this: ``` File "invalchar.py", line 23 values = list(analysis.values ()) ...
Dynamically constructing filters in SQLAlchemy
14,845,196
16
2013-02-13T01:52:19Z
14,876,320
26
2013-02-14T13:51:08Z
[ "python", "sqlalchemy" ]
I am looking for a way to dynamically construct filters using SQLAlchemy. That is, given the column, the operator name and the comparing value, construct the corresponding filter. I'll try to illustrate using an example (this would be used to build an API). Let's say we have the following model: ``` class Cat(Model):...
In case this is useful to someone, here is what I ended up doing: ``` from flask import request class Parser(object): sep = ';' # ... def filter_query(self, query): model_class = self._get_model_class(query) # returns the query's Model raw_filters = request.args.getlist('filter') for raw in raw_f...
Dynamically constructing filters in SQLAlchemy
14,845,196
16
2013-02-13T01:52:19Z
14,887,813
7
2013-02-15T03:23:28Z
[ "python", "sqlalchemy" ]
I am looking for a way to dynamically construct filters using SQLAlchemy. That is, given the column, the operator name and the comparing value, construct the corresponding filter. I'll try to illustrate using an example (this would be used to build an API). Let's say we have the following model: ``` class Cat(Model):...
One useful trick while building multiple expression filter: ``` filter_group = list(Column.in_('a','b'),Column.like('%a')) query = query.filter(and_(*filter_group)) ``` Using this approach will allow you to combine expressions with and/or logic. Also this will allow you to avoid recursion calls like in your answer.
Altering an Enum field using Alembic
14,845,203
15
2013-02-13T01:53:19Z
14,845,740
15
2013-02-13T03:04:03Z
[ "python", "sqlalchemy", "alembic" ]
How can I add an element to an Enum field in an alembic migration when using a version of PostgreSQL older than 9.1 (which adds the ALTER TYPE for enums)? [This](http://stackoverflow.com/questions/1771543/postgresql-updating-an-enum-type) SO question explains the direct process, but I'm not quite sure how best to trans...
I decided to try to follow the [postgres approach](http://stackoverflow.com/questions/1771543/postgresql-updating-an-enum-type) as directly as possible and came up with the following migration. ``` from alembic import op import sqlalchemy as sa old_options = ('nonexistent_executable', 'signal', 'success', 'timed_out'...
Emulating a Browser to download a file?
14,845,491
15
2013-02-13T02:31:06Z
15,027,466
19
2013-02-22T15:25:22Z
[ "python", "shell", "mechanize", "wget" ]
There is a flv file in the web, you can downloaded it directly in Chrome, the file is a CCTV television program,it is free for people to download (no copyright, CCTV is a non-profit TV, State-owned Company, chinese people--the tax payer have the right to download it freely, no copyright problem), I can get it in ...
First of all, if you are attempting any kind of scraping (yes this counts as scraping even though you are not necessarily parsing HTML), you have a certain amount of preliminary investigation to perform. If you don't already have [Firefox](http://www.mozilla.org/en-US/firefox/new/) and [Firebug](http://getfirebug.com/...
What is a better Tkinter geometry manager than .grid()
14,846,063
2
2013-02-13T03:46:18Z
14,846,130
11
2013-02-13T03:54:52Z
[ "python", "tkinter" ]
**My Complaint** I am currently delving deeper than "ever" before into the Tkinter GUI, and I have found the `.grid()` geometry manager to be inadequate for several reasons: 1. The plots are based on the largest widget within them - this relativity leads to inaccuracy. 2. In Windows 7, on Python 2.7.3, the program do...
There are 3 geometry managers that you have available to you -- `grid`, `pack` and `place`. The third is the most general, but also very difficult to use. I prefer `grid`. Note that you can place widgets inside of other widgets -- Or you can specify `columnspan`. So, if you want to get the following layout: ``` ----...
python - find index postion in list based of partial string
14,849,293
14
2013-02-13T08:27:02Z
14,849,322
32
2013-02-13T08:29:31Z
[ "python", "list" ]
``` mylist = ["aa123", "bb2322", "aa354", "cc332", "ab334", "333aa"] ``` I need the index position of all items that contain 'aa'. I'm having trouble combining enumerate() with partial string matching. I'm not even sure if I should be using enumerate. I just need to return the index positions: 0,2,5
``` indices = [i for i, s in enumerate(mylist) if 'aa' in s] ```
VRML to X3D Conversion
14,849,593
6
2013-02-13T08:48:37Z
14,938,641
7
2013-02-18T14:30:43Z
[ "python", "django", "vrml", "x3d", "x3dom" ]
I'm working on a web application that manages VRML files. I also want to let users see the uploaded files, without requiring a specific plug-in or player. X3DOM allows viewing X3D files without plug-ins on most browsers, so I'd like to use it. Alas, it works on X3D files, and not VRML files. I need to convert VRML fil...
[MeshLab](http://meshlab.sourceforge.net/)! There's an opensource project called [MeshLab](http://meshlab.sourceforge.net/) that does all sorts of processing on 3D meshes. It also has a command-line tool called MeshlabServer. Running `meshlabserver.exe -i <wrl file> -o <x3d file>` performs the conversion (very quickly...
Matplotlib: How to remove the vertical space when displaying circles on a grid?
14,849,815
4
2013-02-13T09:02:03Z
14,850,998
7
2013-02-13T10:08:51Z
[ "python", "matplotlib" ]
I need to draw a punchcard with matplotlib which seem to not have such a function.So I have coded the following one: ``` import matplotlib.pyplot as plt import numpy as np def draw_punchcard(infos, ax1=range(7), ax2=range(24), ax1_ticks=['Monday', 'Tuesday', 'Wednesday'...
I changed the vertical spacing of the circles based on the shape ratio of the data (`r = float(data.shape[1])/data.shape[0]`). Also, the canvas size is changed to fit the result, so that you're not left with a large white area in the default canvas size. Result: ![enter image description here](http://i.stack.imgur.co...
How to include third party Python libraries in Google App Engine?
14,850,853
25
2013-02-13T10:01:49Z
14,851,686
41
2013-02-13T10:44:17Z
[ "python", "google-app-engine" ]
How to add third party python libraries in Google App Engine, which are not provided by Google? I am trying to use BeautifulSoup in Google App Engine and unable to do so. But my question is for any library I want to use in Google App Engine.
Actually I think [this answer](http://stackoverflow.com/a/14648038/8418) fits better here. If you want to use 3rd party libraries that are not included in [this list](http://stackoverflow.com/a/14648038/8418), then you'll have to add them manually. In order to include manually any other library you have to have them ...
How to include third party Python libraries in Google App Engine?
14,850,853
25
2013-02-13T10:01:49Z
29,681,061
39
2015-04-16T16:41:48Z
[ "python", "google-app-engine" ]
How to add third party python libraries in Google App Engine, which are not provided by Google? I am trying to use BeautifulSoup in Google App Engine and unable to do so. But my question is for any library I want to use in Google App Engine.
Google has provided a documented way for included third-party libraries in your GAE project. See the ["Adding Third-party Packages to the Application" section of the Libraries in Python 2.7 docs](https://cloud.google.com/appengine/docs/python/tools/libraries27#vendoring). > If you want to include additional pure-pyth...
whitespaces in the path of windows filepath
14,852,140
4
2013-02-13T11:09:21Z
14,852,407
7
2013-02-13T11:23:12Z
[ "python", "file" ]
I am working on file operations using python. I have a filepath as : ``` filepath = "E:/ABC/SEM 2/testfiles/all.txt" ``` when I am opening the file using python, it says me : ``` IOError: No such file: ``` but, the file is present on the drive. It may be because windows cannnot take "SEM 2" properly as it contai...
There is no problem with whitespaces in the path since you're not using the "shell" to open the file. Here is a session from the windows console to prove the point. You're doing something else wrong ``` Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on wi 32 Type "help", "copyright", "credit...
Parsing XML with namespace in Python via 'ElementTree'
14,853,243
76
2013-02-13T12:08:37Z
14,853,417
119
2013-02-13T12:18:22Z
[ "python", "xml", "xml-parsing", "elementtree" ]
I have the following XML which I want to parse using Python's `ElementTree`: ``` <rdf:RDF xml:base="http://dbpedia.org/ontology/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:owl="http://www.w3.org/2002/07/owl#" xmlns:xsd="http://www.w3.org/2001/XMLSchema#" xmlns:rdfs="http://www.w3.or...
ElementTree is not too smart about namespaces. You need to give the `.find()`, `findall()` and `iterfind()` methods an explicit namespace dictionary. This is not documented very well: ``` namespaces = {'owl': 'http://www.w3.org/2002/07/owl#'} # add more as needed root.findall('owl:Class', namespaces) ``` Prefixes ar...
Parsing XML with namespace in Python via 'ElementTree'
14,853,243
76
2013-02-13T12:08:37Z
26,807,636
27
2014-11-07T18:22:52Z
[ "python", "xml", "xml-parsing", "elementtree" ]
I have the following XML which I want to parse using Python's `ElementTree`: ``` <rdf:RDF xml:base="http://dbpedia.org/ontology/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:owl="http://www.w3.org/2002/07/owl#" xmlns:xsd="http://www.w3.org/2001/XMLSchema#" xmlns:rdfs="http://www.w3.or...
Here's how to do this with lxml without having to hard-code the namespaces or scan the text for them (as Martijn Pieters mentions): ``` from lxml import etree tree = etree.parse("filename") root = tree.getroot() root.findall('owl:Class', root.nsmap) ```
python jsonify dictionary in utf-8
14,853,694
5
2013-02-13T12:33:58Z
14,853,985
7
2013-02-13T12:49:42Z
[ "python", "json", "utf-8", "flask" ]
I want to get json data into utf-8 I have a list `my_list = []` and then many appends unicode values to the list like this ``` my_list.append(u'ტესტ') return jsonify(result=my_list) ``` and it gets ``` { "result": [ "\u10e2\u10d4\u10e1\u10e2", "\u10e2\u10dd\u10db\u10d0\u10e8\u10d5\u10d8\u10da\u10d8" ] } `...
Use the standard-library [`json` module](http://docs.python.org/2/library/json.html) instead, and set the `ensure_ascii` keyword parameter to False when encoding: ``` >>> data = u'\u10e2\u10d4\u10e1\u10e2' >>> import json >>> json.dumps(data) '"\\u10e2\\u10d4\\u10e1\\u10e2"' >>> json.dumps(data, ensure_ascii=False) u'...
In Scipy how and why does curve_fit calculate the covariance of the parameter estimates
14,854,339
20
2013-02-13T13:08:42Z
14,857,441
14
2013-02-13T15:50:40Z
[ "python", "scipy", "curve" ]
I have been using scipy.optimize.leastsq to fit some data. I would like to get some confidence intervals on these estimates so I look into the cov\_x output but the documentation is very unclear as to what this is and how to get the covariance matrix for my parameters from this. First of all it says that it is a Jacob...
OK, I think I found the answer. First the solution: cov\_x\*s\_sq is simply the covariance of the parameters which is what you want. Taking sqrt of the diagonal elements will give you standard deviation (but be careful about covariances!). Residual variance = reduced chi square = s\_sq = sum[(f(x)-y)^2]/(N-n), where N...
Python: Why can't I unpack a tuple into a dictionary?
14,854,659
5
2013-02-13T13:27:39Z
14,854,674
13
2013-02-13T13:28:58Z
[ "python", "dictionary", "iterable-unpacking" ]
Why doesn't this work?: ``` d["a"], d["b"] = *("foo","bar") ``` Is there a better way to achieve what I'm trying to achieve?
It would work if you define a dictionary `d` before hand, and remove the `*` from there: ``` >>> d = {} >>> d["a"], d["b"] = ("foo","bar") ``` In fact, you don't need those parenthesis on the RHS, so this will also work: ``` >>> d['a'], d['b'] = 'foo', 'bar' ```
Python: Why can't I unpack a tuple into a dictionary?
14,854,659
5
2013-02-13T13:27:39Z
14,854,908
7
2013-02-13T13:40:33Z
[ "python", "dictionary", "iterable-unpacking" ]
Why doesn't this work?: ``` d["a"], d["b"] = *("foo","bar") ``` Is there a better way to achieve what I'm trying to achieve?
Others have showed how you can unpack into a dict. However, in answer to your question "is there a better way", I would argue that: ``` d.update(a='foo',b='bar') ``` much easier to parse. Admitedtly, this doesn't work if you have `a` and `b` which are *variables*, but then you could use: ``` d.update({a:'foo',b:'bar...
Importing Sets in python
14,855,110
2
2013-02-13T13:51:12Z
14,855,131
9
2013-02-13T13:52:25Z
[ "python", "python-2.7", "set" ]
When I am trying to use sets it's showing that there is nothing named set. ``` from sets import set > ImportError: cannot import name set ``` How do I fix it?
You don't *need* to import the [`sets` module](http://docs.python.org/2/library/sets.html); sets are built in now. Just use the built-in [`set()` type](http://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset) instead: ``` >>> set() set([]) ``` You can use the `{1, 2, 3}` set literal syntax too: ``` >>...
Disable points scaling in 3D scatter plots in Mayavi
14,855,422
3
2013-02-13T14:08:20Z
14,855,966
7
2013-02-13T14:38:12Z
[ "python", "data-visualization", "mayavi" ]
The `mayavi` module for Python has a 3D scatter plotting function. By default the size of the points are scaled with the data (as far as I could understand from going through their website). This is what a screencap of my data looks like: ![Mayavi Point Scatter](http://i.stack.imgur.com/9mpUP.png) The colormap indica...
The function `mayavi.mlab.points3d` has the `scale_mode` argument which can be set to `'none'`. For example: ``` In [23]: t = linspace(0, 4*numpy.pi, 20) In [24]: x = sin(2*t) In [25]: y = cos(t) In [26]: z = cos(2*t) In [27]: s = 2 + sin(t) In [28]: mlab.points3d(x, y, z, s, colormap="copper", scale_mode='none'...
Generate summed up ranges from a list
14,855,690
2
2013-02-13T14:23:41Z
14,855,725
9
2013-02-13T14:25:19Z
[ "python", "list", "range" ]
I have a list of integers: ``` list = [a,b,c,d] ``` I would like to convert it to these ranges: ``` 0..a a+1..a+b a+b+1..a+b+c a+b+c+1..a+b+c+d ``` Any ideas how to do this in python? Thanks
A simple generator will do: ``` def to_ranges(seq): iseq = iter(seq) x = next(iseq) yield range(0,x+1) start = x for x in iseq: stop = start+x yield range(start+1,stop+1) start = stop for x in to_ranges([1,2,3,4]): print x ``` This gives: ``` [0, 1] #0 .. a c...
HTTP 403 error retrieving robots.txt with mechanize
14,857,342
4
2013-02-13T15:46:28Z
14,858,689
7
2013-02-13T16:51:48Z
[ "python", "mechanize", "robots.txt", "http-status-code-403" ]
This shell command succeeds ``` $ curl -A "Mozilla/5.0 (X11; Linux x86_64; rv:18.0) Gecko/20100101 Firefox/18.0 (compatible;)" http://fifa-infinity.com/robots.txt ``` and prints robots.txt. Omitting the user-agent option results in a 403 error from the server. Inspecting the robots.txt file shows that content under <...
As verified by experiment, you need add an [Accept](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html) header to specify acceptable content types(any type will do, as long as "Accept" header exists). For example, it will work after changing: ``` br.addheaders = [('User-Agent', ua)] ``` to: ``` br.addheaders = [...
Disable PyYAML value conversion
14,857,512
7
2013-02-13T15:54:37Z
14,863,549
15
2013-02-13T21:32:51Z
[ "python", "python-2.7", "yaml", "pyyaml" ]
I have just started to use **PyYAML** to convert some data. I just use the `yaml.load` function and it was good enough for me until I noticed that it tries to convert all values to uni-coded string, int, dates and so on. This could be fatal in my application, is there a way to avoid this conversion? I would like to r...
Well, you could use `Loader=yaml.BaseLoader` to leave everything as a string: ``` >>> x = [[1,2,3], {1:2}] >>> s = yaml.dump(x) >>> s '- [1, 2, 3]\n- {1: 2}\n' >>> yaml.load(s) [[1, 2, 3], {1: 2}] >>> yaml.load(s, Loader=yaml.BaseLoader) [[u'1', u'2', u'3'], {u'1': u'2'}] ```
Python - Updating Variable in For Loop
14,858,364
2
2013-02-13T16:36:48Z
14,858,418
8
2013-02-13T16:39:15Z
[ "python" ]
So I decided to write Monopoly in Python, but I'm having some trouble updating the players location. I wrote a for loop that iterates through the players, rolls the dice for each one, and then updates their location. The problem is that the location variable isn't keeping the latest location, it keeps resetting back to...
You have function parameter with the same name as your target variable which you want to update. Due to which, any changes you make is made to the function parameter, and not to the global variable. That's because the `function` creates a local scope for the paremeter you are passing to the function. So, it overshadows...
numpy: using operator - with arrays containing None
14,858,647
6
2013-02-13T16:49:47Z
14,858,714
8
2013-02-13T16:53:14Z
[ "python", "numpy", "missing-data" ]
I have a list of numbers which I put into a numpy array: ``` >>> import numpy as np >>> v=np.array([10.0, 11.0]) ``` then I want to subtract a number from each value in the array. It can be done like this with numpy arrays: ``` >>> print v - 1.0 [ 9. 10.] ``` Unfortunately, my data often contains missing values, ...
My recommendation is to either use masked arrays: ``` v = np.ma.array([10., 11, 0],mask=[0, 0, 1]) print v - 10 >>> [0.0 1.0 --] ``` or NaNs ``` v = np.array([10.,11,np.nan]) print v - 10 >>> [ 0. 1. nan] ``` I actually prefer NaNs as missing data indicators.
True for all characters of a string
14,858,916
5
2013-02-13T17:03:57Z
14,858,929
13
2013-02-13T17:04:31Z
[ "python", "python-3.x" ]
In Python 3, what's the shortest way to check whether a predicate is true for all characters of a string?
``` all(predicate(x) for x in string) ```
How to check if all values in the columns of a numpy matrix are the same?
14,859,458
5
2013-02-13T17:33:03Z
14,860,884
14
2013-02-13T18:55:11Z
[ "python", "matrix", "numpy" ]
I want to check if all values in the columns of a numpy array/matrix are the same. I tried to use `reduce` of the [ufunc](http://docs.scipy.org/doc/numpy/reference/ufuncs.html) `equal`, but it doesn't seem to work in all cases: ``` In [55]: a = np.array([[1,1,0],[1,-1,0],[1,0,0],[1,1,0]]) In [56]: a Out[56]: array([...
``` In [45]: a Out[45]: array([[1, 1, 0], [1, 0, 0], [1, 0, 0], [1, 1, 0]]) ``` Compare each value to the corresponding value in the first row: ``` In [46]: a == a[0,:] Out[46]: array([[ True, True, True], [ True, False, True], [ True, False, True], [ True, True, True...
Not matching is not NoneType condition in Python
14,859,498
2
2013-02-13T17:35:03Z
14,859,531
7
2013-02-13T17:36:42Z
[ "python" ]
I m having problem with these piece of code. ``` if tdinst[0].string in features: nameval=tdinst[0].string value=tdinst[1].string print type(value) if type(value) is not None: print"it should not come here" value=value.replace("\n","") value=value....
There's a difference between `NoneType` and `None`. You need to be checking ``` if type(value) != NoneType: ``` or ``` if value is not None: ``` but perhaps the following is more straightforward: ``` if tdinst[0].string in features: nameval = tdinst[0].string value = tdinst[1].string if value: # this ...
Append several variables to a list in Python
14,860,460
11
2013-02-13T18:28:15Z
14,860,557
11
2013-02-13T18:34:57Z
[ "python", "list", "append" ]
I want to append several variables to a list. The number of variables varies. All variables start with "volume". I was thinking maybe a wildcard or something would do it. But I couldn't find anything like this. Any ideas how to solve this? Note in this example it is three variables, but it could also be five or six or ...
You can use `extend` to append any iterable to a list: ``` vol.extend((volumeA, volumeB, volumeC)) ``` Depending on the prefix of your variable names has a bad code smell to me, but you can do it. (The order in which values are appended is undefined.) ``` vol.extend(value for name, value in locals().items() if name....
Flask Database Issue
14,860,559
7
2013-02-13T18:35:01Z
14,863,868
14
2013-02-13T21:52:35Z
[ "python", "python-2.7", "flask", "flask-sqlalchemy", "sqlalchemy-migrate" ]
I am using this tutorial as a guideline. <http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iv-database> I want to have Categories that can heave multiple Products. Similar to how he has a User with multiple Posts. when I open up the python interpreter and try to create a category ``` >>>from app impo...
It's because you've got a collision. The error is: ``` `sqlalchemy.exc.ArgumentError: Error creating backref 'category' on relationship 'Category.products': property of that name exists on mapper 'Mapper|Product|product'` ``` You can see that you've created a relationship within `Category` to `Product` which is two w...
not able to understand behaviour of ** operator
14,861,094
3
2013-02-13T19:07:36Z
14,861,192
8
2013-02-13T19:13:32Z
[ "python" ]
I have suddenly came across this, I am not able to understand why this is happening! On python prompt, using the `**` operator on 3 onwards like below giving wrong result. i.e., ``` >>> 2**2**2 16 >>> 3**3**3 7625597484987L >>> 4**4**4 1340780792994259709957402499820584612747936582059239337772356144372176403007354697...
`**` is right-associative. Mathematically, this makes sense: 333 is equal to 327, not 273. [The documentation](http://docs.python.org/2/reference/expressions.html#the-power-operator) states that it is right-associative: > In an unparenthesized sequence of power and unary operators, the operators are evaluated from ri...
Why are some python builtin "functions" actually types?
14,861,572
12
2013-02-13T19:35:47Z
14,861,628
10
2013-02-13T19:39:00Z
[ "python" ]
Many iterator "functions" in the `__builtin__` module are actually implemented as types, even although the documentation talks about them as being "functions". Take for instance `enumerate`. The documentation says that it is equivalent to: ``` def enumerate(sequence, start=0): n = start for elem in sequence: ...
Yes, it has to do with the fact that built-ins are generally implemented in C. Really often C code will introduce new types instead of plain functions, as in the case of `enumerate`. Writing them in C provide finer control over them and often some performance improvements, and since there is no real downside it's a nat...
RuntimeWarning: invalid value encountered in divide
14,861,891
12
2013-02-13T19:54:53Z
23,116,937
19
2014-04-16T18:05:59Z
[ "python", "python-2.7", "matplotlib" ]
I have to make a program using Euler's method for the "ball in a spring" model ``` from pylab import* from math import* m=0.1 Lo=1 tt=30 k=200 t=20 g=9.81 dt=0.01 n=int((ceil(t/dt))) km=k/m r0=[-5,5*sqrt(3)] v0=[-5,5*sqrt(3)] a=zeros((n,2)) r=zeros((n,2)) v=zeros((n,2)) t=zeros((n,2)) r[1,:]=r0 v[1,:]=v0 for i in rang...
I think you code have some "divided by zero" or "Nan" appears. If you aware of that and don't want it to bother you, you can try ``` import numpy as np np.seterr(divide='ignore', invalid='ignore') ``` For more details <http://docs.scipy.org/doc/numpy/reference/generated/numpy.seterr.html>
sklearn logistic regression with unbalanced classes
14,863,125
11
2013-02-13T21:06:24Z
14,864,547
12
2013-02-13T22:34:53Z
[ "python", "scikit-learn", "classification" ]
I'm solving a classification problem with sklearn's logistic regression in python. My problem is a general/generic one. I have a dataset with two classes/result (positive/negative or 1/0), but the set is highly unbalanced. There are ~5% positives and ~95% negatives. I know there are a number of ways to deal with an u...
Have you tried to pass to your `class_weight="auto"` classifier? Not all classifiers in sklearn support this, but some do. Check the docstrings. Also you can rebalance your dataset by randomly dropping negative examples and / or over-sampling positive examples (+ potentially adding some slight gaussian feature noise).
Efficient reading of 800 GB XML file in Python 2.7
14,863,224
17
2013-02-13T21:11:27Z
14,863,321
11
2013-02-13T21:18:08Z
[ "python", "file", "text", "python-2.7", "io" ]
I am reading an 800 GB xml file in python 2.7 and parsing it with an etree iterative parser. Currently, I am just using `open('foo.txt')` with no buffering argument. I am a little confused whether this is the approach I should take or I should use a buffering argument or use something from io like io.BufferedReader or...
The standard [`open()` function](http://docs.python.org/2/library/functions.html#open) already, by default, returns a buffered file (if available on your platform). For file objects that is *usually* fully buffered. *Usually* here means that Python leaves this to the C stdlib implementation; it uses a [`fopen()` call]...
Iterate through Python dictionary by Keys in order
14,863,536
20
2013-02-13T21:31:53Z
14,863,575
28
2013-02-13T21:34:17Z
[ "python", "dictionary", "order", "loops" ]
If I have a dictionary in Python that looks like this: ``` D = {1:'a',5:'b',2:'a',7:'a'} ``` So that the values of the keys are mostly irrelevant is there are way to iterate through the dictionary by keys in numerical order. The keys are all integers. Instead of saying ``` for key in D: code.... ``...
You can use this: ``` for key in sorted(D.iterkeys()): .. code .. ``` In Python 3.x, use `D.keys()` (which is the same as `D.iterkeys()` in Python 2.x).
Iterate through Python dictionary by Keys in order
14,863,536
20
2013-02-13T21:31:53Z
14,863,715
7
2013-02-13T21:42:28Z
[ "python", "dictionary", "order", "loops" ]
If I have a dictionary in Python that looks like this: ``` D = {1:'a',5:'b',2:'a',7:'a'} ``` So that the values of the keys are mostly irrelevant is there are way to iterate through the dictionary by keys in numerical order. The keys are all integers. Instead of saying ``` for key in D: code.... ``...
Taking into account your stipulation that you don't want to sort, and assuming the keys are all integers, you can simply find the maximum and minimum values of the keys, then iterate over that range and check whether each is actually in the dictionary. ``` for key in xrange(min(D), max(D) + 1): if key in D: ...
Insert data into MySQL table from Python script
14,863,692
10
2013-02-13T21:41:05Z
14,865,152
18
2013-02-13T23:21:50Z
[ "python", "mysql" ]
I have a MySQL Table named TBLTEST with two columns ID and qSQL. Each qSQL has SQL queries in it. I have another table FACTRESTTBL. There are 10 rows in the table TBLTEST. For example, On TBLTEST lets take id =4 and qSQL ="select id, city, state from ABC". How can I insert into the FACTRESTTBL from TBLTEST using py...
You can use [MySQLdb for Python](http://www.tutorialspoint.com/python/python_database_access.htm). Sample code (you'll need to debug it as I have no way of running it here): ``` #!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # prepare a ...
is Python list comprehension with access to the index/enumerate possible?
14,864,922
29
2013-02-13T22:59:56Z
14,864,937
66
2013-02-13T23:01:37Z
[ "python", "list", "indexing", "list-comprehension" ]
consider the following Python code with which I add in a new list2 all the items with indices from 1 to 3 of list1: ``` for ind, obj in enumerate(list1): if 4> ind > 0: list2.append(obj) ``` how would you write this using python list comprehension, if I have no access to the indices through enumerate? something ...
``` list2 = [x for ind, x in enumerate(list1) if 4 > ind > 0] ```