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
Running python script inside ipython
11,744,181
53
2012-07-31T15:55:55Z
11,746,437
9
2012-07-31T18:13:42Z
[ "python", "path", "ipython" ]
Is it possible to run a python script (not module) from inside ipython without indicating its path? I tried to set PYTHONPATH but it seems to work only for modules. I would like to execute ``` %run my_script.py ``` without being in the directory containing the file.
The `%run` magic has a parameter `file_finder` that it uses to get the full path to the file to execute (see [here](https://github.com/ipython/ipython/blob/master/IPython/core/magics/execution.py#L322)); as you note, it just looks in the current directory, appending ".py" if necessary. There doesn't seem to be a way t...
Running python script inside ipython
11,744,181
53
2012-07-31T15:55:55Z
28,462,540
8
2015-02-11T19:12:42Z
[ "python", "path", "ipython" ]
Is it possible to run a python script (not module) from inside ipython without indicating its path? I tried to set PYTHONPATH but it seems to work only for modules. I would like to execute ``` %run my_script.py ``` without being in the directory containing the file.
### - How to run a script in Ipython -### ``` import os filepath='C:\\Users\\User\\FinalWrittenSoftwares' os.chdir(filepath) %run pyFileInFilePathDirec.py ``` That should do it
Running python script inside ipython
11,744,181
53
2012-07-31T15:55:55Z
29,015,555
12
2015-03-12T16:44:31Z
[ "python", "path", "ipython" ]
Is it possible to run a python script (not module) from inside ipython without indicating its path? I tried to set PYTHONPATH but it seems to work only for modules. I would like to execute ``` %run my_script.py ``` without being in the directory containing the file.
from within the directory of "my\_script.py" you can simply do: ``` %run ./my_script.py ```
How to set 'auto' for upper limit, but keep a fixed lower limit with matplotlib.pyplot
11,744,990
31
2012-07-31T16:41:06Z
11,745,291
33
2012-07-31T16:58:23Z
[ "python", "matplotlib", "limits" ]
I want to set the upper limit of the y-axis to 'auto', but I want to keep the lower limit of the y-axis to always be zero. I tried 'auto' and 'autorange', but those don't seem to work. Thank you in advance. Here is my code: ``` import matplotlib.pyplot as plt def plot(results_plt,title,filename): ##############...
You can pass just `left` or `right` to `set_xlim`: ``` plt.gca().set_xlim(left=0) ``` For the y axis, use `bottom` or `top`: ``` plt.gca().set_ylim(bottom=0) ```
How to set 'auto' for upper limit, but keep a fixed lower limit with matplotlib.pyplot
11,744,990
31
2012-07-31T16:41:06Z
32,634,026
8
2015-09-17T15:16:03Z
[ "python", "matplotlib", "limits" ]
I want to set the upper limit of the y-axis to 'auto', but I want to keep the lower limit of the y-axis to always be zero. I tried 'auto' and 'autorange', but those don't seem to work. Thank you in advance. Here is my code: ``` import matplotlib.pyplot as plt def plot(results_plt,title,filename): ##############...
Just set `xlim` for one of the limits: ``` plt.xlim(xmin=0) ```
Any way to reset a mocked method to its original state? - Python Mock - mock 1.0b1
11,746,431
13
2012-07-31T18:13:19Z
11,792,325
19
2012-08-03T08:45:45Z
[ "python", "mocking", "python-mock" ]
I have the following simplified class I'm mocking: ``` class myClass(object): @staticmethod def A(): #... def check(self): #code... value = self.A() #more code... ``` In my first test I mock only the method A ``` from django.test import TestCase from mock import MagicMock...
You can use `mock.patch` as a decorator or a context manager: ``` from mock import patch, MagicMock @patch('myClass.A', MagicMock(return_value='CPU')) def test(self): pass ``` or: ``` def test(self): with patch('myClass.A', MagicMock(return_value='CPU')): pass ``` If you don't supply a mock object ...
How to update dictionary from a tuple (or list of 2)
11,746,668
3
2012-07-31T18:29:28Z
11,746,698
8
2012-07-31T18:31:24Z
[ "python", "dictionary" ]
I thought it would be possible to update an existing dictionary as follows: ``` nameValuePair = 'myKey=myValue' d.update(nameValuePair.split('=')) ``` However I get this error: ``` Traceback (most recent call last): File "<pyshell#98>", line 1, in <module> d2.update(item.split('=')) ValueError: dictionary upda...
The error message already gives you a hint: Each item in the sequence you pass must have a length of 2, meaning it has to consist of a key and a value. Therefore you have to pass a tuple (list, sequence,...) of 2-tuples (-lists, -sequences,...): ``` // the value passed will be ((myKey, myValue), ) d.update((nameValue...
Flood Fill Algorithm Python
11,746,766
6
2012-07-31T18:37:17Z
11,747,550
7
2012-07-31T19:26:52Z
[ "python" ]
So I'm trying to create a flood fill algorithm and I keep getting a recursion error with this. The algorithm seems to have infinite recursion and I cannot pinpoint why. I have looked all over the internet and I cannot find a solution as it seems like my program is correct according to most sources. There seems to be so...
Python has a tendency to throw a `maximum recursion depth exceeded` error, even if the algorithm doesn't recurse infinitely and would eventually halt on its own. There are two solutions to this: increase the recursion limit, or switch to an iterative algorithm. You can raise your recursion limit with `sys.setrecursion...
Python numpy: Convert string in to numpy array
11,747,125
5
2012-07-31T19:01:23Z
11,747,162
9
2012-07-31T19:03:40Z
[ "python", "vector", "numpy", "cosine" ]
I have following String that I have put together: ``` v1fColor = '2,4,14,5,0,0,0,0,0,0,0,0,0,0,12,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,15,6,0,0,0,0,1,0,0,0,0,0,0,0,0,0,20,9,0,0,0,2,2,0,0,0,0,0,0,0,0,0,13,6,0,0,0,1,0,0,0,0,0,0,0,0,0,0,10,8,0,0,0,1,2,0,0,0,0,0,0,0,0,0,17,17,0,0,0,3,6,0,0,0,0,0,0,0,0,0,7,5,0,0,0,2,0,0,0,0,0,0,0...
You have to split the string by its commas first: ``` NP.array(v1fColor.split(","), dtype=NP.uint8) ```
Python Brute Force algorithm
11,747,254
8
2012-07-31T19:09:48Z
11,747,381
8
2012-07-31T19:17:14Z
[ "python", "algorithm", "brute-force" ]
I need to generate every possible combination from a given charset to a given range. Like, ``` charset=list(map(str,"abcdefghijklmnopqrstuvwxyz")) range=10 ``` And the out put should be, ``` [a,b,c,d..................,zzzzzzzzzy,zzzzzzzzzz] ``` I know I can do this using already in use libraries.But I need to know ...
If you REALLY want to brute force it, try this, but it will take you a ridiculous amount of time: ``` your_list = 'abcdefghijklmnopqrstuvwxyz' complete_list = [] for current in xrange(10): a = [i for i in your_list] for y in xrange(current): a = [x+i for i in your_list for x in a] complete_list = c...
Python Brute Force algorithm
11,747,254
8
2012-07-31T19:09:48Z
11,747,419
24
2012-07-31T19:19:34Z
[ "python", "algorithm", "brute-force" ]
I need to generate every possible combination from a given charset to a given range. Like, ``` charset=list(map(str,"abcdefghijklmnopqrstuvwxyz")) range=10 ``` And the out put should be, ``` [a,b,c,d..................,zzzzzzzzzy,zzzzzzzzzz] ``` I know I can do this using already in use libraries.But I need to know ...
Use [`itertools.product`](http://docs.python.org/library/itertools.html#itertools.product), combined with [`itertools.chain`](http://docs.python.org/library/itertools.html#itertools.chain) to put the various lengths together: ``` import itertools def bruteforce(charset, maxlength): return (''.join(candidate) ...
How to connect Javascript to Python sharing data with JSON format in both ways?
11,747,527
7
2012-07-31T19:25:25Z
11,749,466
8
2012-07-31T21:45:26Z
[ "javascript", "python", "json", "web-services", "sqlite" ]
I'm trying to find out how to create a local connection between a Python server and a Javascript client using the JSON format for the data to be retrieved. Particularly, I need to make some queries on the HTML client side, send these queries to the server on JSON format and run them on the Python server side to search ...
Here's a "hello world" example of [a flask web-application](http://flask.pocoo.org/) that can serve static html and javascript files, search database using parameter from a javascript request, and return results to javascript as json: ``` import sqlite3 from flask import Flask, jsonify, g, redirect, request, url_for ...
Passing arguments during Class Initialization
11,748,205
2
2012-07-31T20:12:27Z
11,748,275
9
2012-07-31T20:15:56Z
[ "python" ]
I am scratching my head on what is going in the following code. ``` class foo(object): def __init__(self,*args): print type(args) print args j_dict = {'rmaNumber':1111, 'caseNo':2222} print type(j_dict) p = foo(j_dict) ``` it yields : ``` <type 'dict'> <type 'tuple'> ({'rmaNumber': 1111, 'caseN...
Actually it's because `args` is a `tuple` to hold a variable length argument list. `args[0]` is still your `dict` - no conversion has taken place. See [this tutorial](http://basicpython.com/understanding-arguments-args-and-kwargs-in-python/) for further information about `args` and `kwargs` (the keyword version of arg...
Check whether the JSON (object property exists) & print it as unicode decoded
11,748,234
5
2012-07-31T20:13:30Z
11,748,645
13
2012-07-31T20:39:49Z
[ "python", "json", "unicode", "simplejson" ]
I get the following data from the [Instagram API](http://instagram.com/developer/endpoints/users/), I m trying to get the text `property` from the `caption` using the following code: ``` data = simplejson.load(info) # info is retrieved using the urllib2 for post in data['data']: if post['caption'] is not...
You don't need the intricate tests on wether 'text' is present for the post caption. This code works well with the JSON string you posted: ``` for post in data['data']: if post.get('caption'): print post['caption'].get('text', 0) ``` Furthermore, you could be more defensive and refer to `data.get('data', ...
Having Trouble Getting SimpleHTTPRequestHandler to respond to AJAX
11,748,372
8
2012-07-31T20:22:05Z
11,769,969
9
2012-08-02T01:49:07Z
[ "javascript", "jquery", "python", "ajax", "simplehttpserver" ]
I recently tried implementing the SimpleHTTPRequestHandler to accept AJAX requests according to [this](http://stackoverflow.com/questions/336866/how-to-implement-a-minimal-server-for-ajax-in-python). Although everything seems to work as far as receiving the request from the client, I cannot send anything back to the c...
Make sure your response has a **send\_header()** with a content type. I have seen AJAX requests get confused without this. You can also try switching your POST to a GET for debugging and make sure the browser can see the content. Here is a simple HTTP example for returning XML if you point your query or browser to **1...
Negative form of isinstance() in Python
11,748,671
2
2012-07-31T20:41:49Z
11,748,702
10
2012-07-31T20:43:42Z
[ "python", "negate", "negation", "isinstance" ]
How would I use a negative form of Python's isinstance()? Normally negation would work something like ``` x != 1 if x not in y if not a ``` I just haven't seen an example with isinstance(), so I'd like to know if there's a correct way to used negation with isinstance().
Just use `not`. `isinstance` just returns a `bool`, which you can `not` like any other.
Django: Disabled Dropdown doesn't send information back to POST
11,748,971
9
2012-07-31T21:03:27Z
11,749,254
15
2012-07-31T21:27:14Z
[ "python", "django" ]
I have a dropdown in a modelform and the user should not be able to change the selected value. I found that a `disabled` does exactly do what I need. However there is an oddness to this: The first time when the form opens (GET) the value is selected and the user can't change the value. which is great: ![enter image d...
Its not a django thing, its an HTML thing. Disabled form elements are not sent by the form. > [The Element] cannot receive user input nor will its value be submitted with the form. <http://www.w3.org/TR/html401/interact/forms.html#h-17.12.1> & <http://www.w3schools.com/tags/att_input_disabled.asp> you could use `rea...
deploying IronPython script or static building an application
11,750,213
4
2012-07-31T22:56:13Z
11,750,214
10
2012-07-31T22:56:13Z
[ ".net", "python", "windows", "ironpython", "ironpython-studio" ]
I created an IronPython script that imports from Python libraries, such as `os`, `sys`, etc. as well as .NET libraries. It runs perfectly fine from my Visual Studio IronPython solution but I need to deploy this so other people who don't have IronPython or Python installed can run it. How would I do that?
Requirements: * `ipy.exe` in `C:\Program Files (x86)\IronPython 2.7.1\` * `pyc.py` in `C:\Program Files (x86)\IronPython 2.7.1\Tools\Scripts\` * `MyProgram.py` would be your program. 1. Inside your project folder (where `MyProgram.py` is), create a folder called "deploy." 2. Run `cd deploy` in the command prompt....
Python count of items in a dictionary of lists
11,751,081
5
2012-08-01T00:44:29Z
11,751,134
15
2012-08-01T00:52:50Z
[ "python", "list", "dictionary" ]
I have a dictionary of lists for which I want to add a value to a particular list... I have the following dictionary of lists. ``` d = {'a': [4,'Adam', 2], 'b': [3,'John', 4], 'c': [4,'Adam', 3], 'd': [4,'Bill' 3], 'e': [4,'Bob'], 'f': [4, 'Joe'], 'g': [4, 'Bill']} ``` I want to essentially count out the number of na...
[`collections.Counter`](http://docs.python.org/library/collections.html#counter-objects) is always good for counting things. ``` >>> from collections import Counter >>> d = {'a': [4,'Adam', 2], 'b': [3,'John', 4], 'c': [4,'Adam', 3], 'd': [4,'Bill', 3], 'e': [4,'Bob'], 'f': [4, 'Joe'], 'g': [4, 'Bill']} >>> # create a...
New to flask and Flask-Login - ImportError: No module named login
11,751,972
12
2012-08-01T02:58:06Z
11,753,075
20
2012-08-01T05:34:58Z
[ "python", "flask" ]
It appears that installation of flask-login has issues. Despite a successful install using the below ``` pip install flask-login ``` My app.py file: ``` from flaskext.login import LoginManager lm = LoginManager() ``` I get this error : ``` ImportError: No module named login ``` So how do I resolve
There was a transition of the flask extension import way: > Instead we now recommend naming packages `flask_foo` instead of the now deprecated `flaskext.foo`. Flask 0.8 introduces a redirect import system that lets uses import from `flask.ext.foo` and it will try `flask_foo` first and if that fails `flaskext.foo`. > >...
How to get tkinter working with Ubuntu's default Python 2.7 install?
11,752,174
2
2012-08-01T03:26:42Z
11,799,470
10
2012-08-03T16:14:17Z
[ "python", "ubuntu", "tkinter" ]
I'm using Ubuntu 11.10, which came pre-installed with Python 2.7.3. I installed the python3 package, and the python3-tk package, via apt-get install, and they worked together "out of the box". But though I've installed the python-tk package, I can't figure out how to get Python2.7 to see it. I get the error message b...
I figured it out after way too much time spent on this problem, so hopefully I can save someone else the hassle. I found this old bug report deemed invalid that mentioned the exact problem I was having, I had Tkinter.py, but it couldn't find the module \_tkinter: <http://bugs.python.org/issue8555> I installed the tk-...
Check if node exists in h5py
11,753,418
8
2012-08-01T06:05:28Z
11,754,741
15
2012-08-01T07:45:16Z
[ "python", "h5py" ]
Wondering if there's a simple way to check if a node exists within an HDF5 file using h5py. I couldn't find anything in the docs, so right now I'm using exceptions, which is ugly. ``` # check if node exists # first assume it exists e = True try: h5File["/some/path"] except KeyError: e = False # now we know it doe...
``` e = "/some/path" in h5File ``` does it. This is very briefly mentioned in [the `Group` documentation](http://docs.h5py.org/en/latest/high/group.html#Group.__contains__).
Sorting Python dictionary based on nested dictionary values
11,753,660
11
2012-08-01T06:25:34Z
11,753,731
11
2012-08-01T06:31:10Z
[ "python", "sorting", "dictionary" ]
How do you sort a Python dictionary based on the inner value of a nested dictionary? For example, sort `mydict` below based on the value of `context`: ``` mydict = { 'age': {'context': 2}, 'address': {'context': 4}, 'name': {'context': 1} } ``` The result should be like this: ``` { 'name': {'context...
``` >>> from collections import OrderedDict >>> mydict = { 'age': {'context': 2}, 'address': {'context': 4}, 'name': {'context': 1} } >>> OrderedDict(sorted(mydict.iteritems(), key=lambda x: x[1]['context'])) OrderedDict([('name', {'context': 1}), ('age', {'context': 2}), ('address', {'context':...
How to remove ^M from a text file and replace it with the next line
11,755,208
2
2012-08-01T08:15:24Z
11,755,403
7
2012-08-01T08:28:36Z
[ "python", "replace" ]
So suppose I have a text file of the following contents: ``` Hello what is up. ^M ^M What are you doing? ``` I want to remove the `^M` and replace it with the line that follows. So my output would look like: ``` Hello what is up. What are you doing? ``` How do I do the above in Python? Or if there's any way to do t...
``` ''.join(somestring.split(r'\r')) ``` or ``` somestring.replace(r'\r','') ``` This assumes you have carriage return characters in your string, and not the literal "^M". If it is the literal string "^M" then substiture r'\r' with "^M" If you want the newlines gone then use r'\r\n' This is very basic string manip...
Path to a file without basename
11,757,520
7
2012-08-01T10:42:25Z
11,757,548
23
2012-08-01T10:44:18Z
[ "python" ]
How can I get the path of a file without the file basename ? Something like `/a/path/to/my/file.txt` --> `/a/path/to/my/` Tried with .split() without success
Use `os.path.dirname(filename)`.
Get the __file__ of the function one level up in the stack
11,757,801
6
2012-08-01T10:58:36Z
11,758,034
8
2012-08-01T11:14:03Z
[ "python", "stack", "filepath" ]
I've found that I'm using this pattern a lot : ``` os.path.join(os.path.dirname(__file__), file_path) ``` so I've decided to put in a function in a file that has many such small utilities: ``` def filepath_in_cwd(file_path): return os.path.join(os.path.dirname(__file__), file_path) ``` The thing is, `__file__`...
This should do it: ``` inspect.getfile(sys._getframe(1)) ``` [`sys._getframe(1)`](http://docs.python.org/library/sys.html#sys._getframe) gets the caller frame, [`inspect.getfile(...)`](http://docs.python.org/library/inspect.html#inspect.getfile) retrieves the filename.
Python JSON loads/dumps break Unicode?
11,759,070
12
2012-08-01T12:19:46Z
11,759,156
24
2012-08-01T12:24:34Z
[ "python", "json", "unicode" ]
When I print a JSON string from Google, it prints Unicode (foreign characters) correctly. However, if I do json.loads and json.dumps, it prints ABC\ub098\ub178\ud14, which is clearly not what the original JSON string from Google looked like. ``` def get_google_place(request, keyword): request_url = 'https://maps...
Call [`json.dumps`](http://docs.python.org/library/json.html#json.dumps) with `ensure_ascii=False`: ``` json_string = json.dumps(json_dict, ensure_ascii=False) ``` On Python 2, the return value will be `unicode` instead of `str`, so you might want to `encode` it before doing anything else with it.
Calling static method in python
11,759,269
18
2012-08-01T12:31:21Z
11,759,291
51
2012-08-01T12:32:43Z
[ "python", "static-methods" ]
I have a class `Person` and a static method in that class called `call_person`: ``` class Person: def call_person(): print "hello person" ``` In the python console I import the class Person and call `Person.call_person()`. But it is giving me error that says `'module' object has no attribute 'call_person'...
You need to do something like: ``` class Person(object): #always inherit from object. It's just a good idea... @staticmethod def call_person(): print "hello person" #Calling static methods works on classes as well as instances of that class Person.call_person() #calling on class p = Person() p.call_...
Calling static method in python
11,759,269
18
2012-08-01T12:31:21Z
11,759,427
9
2012-08-01T12:38:32Z
[ "python", "static-methods" ]
I have a class `Person` and a static method in that class called `call_person`: ``` class Person: def call_person(): print "hello person" ``` In the python console I import the class Person and call `Person.call_person()`. But it is giving me error that says `'module' object has no attribute 'call_person'...
Everybody has already explained why this isn't a static method but I will explain why you aren't finding it. You are looking for the method in the module and not in the class so something like this would find it properly. ``` import person_module person_module.Person.call_person() # Accessing the class from the module...
convert binary string to numpy array
11,760,095
14
2012-08-01T13:14:37Z
11,760,170
20
2012-08-01T13:19:31Z
[ "python", "numpy", "binary-data" ]
Assume I have the string: ``` my_data = '\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@' ``` Where I got it is irrelevant, but for the sake of having something concrete, assume I read it from a binary file. I know my string is the binary representation of 4 (4-byte) floats. I would like to get those floats as a n...
``` >>> np.fromstring(b'\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@', dtype='<f4') # or dtype=np.dtype('<f4'), or np.float32 on a little-endian system (which most computers are these days) array([ 1., 2., 3., 4.], dtype=float32) ``` Or, if you want big-endian: ``` >>> np.fromstring(b'\x00\x00\x80?\x00\x00\x0...
argparse arguments nesting
11,760,578
13
2012-08-01T13:41:18Z
11,760,682
19
2012-08-01T13:46:55Z
[ "python", "argparse" ]
I have a following code in python: ``` parser = argparse.ArgumentParser(description='Deployment tool') group = parser.add_mutually_exclusive_group() group.add_argument('-a', '--add', dest='name_to_add', help='Add a new group or a role to existing group') group.add_argument('-u', '--upgrade', dest='name_to_upgrade', he...
Instead of having `-a` and `-u` be options, you may want to make them subcommands. Then, make `--web-port` an option of the `add` subcommand: ``` python my_script.py add name --web_port=XXXX python my_script.py upgrade name ``` Something like: ``` parser = argparse.ArgumentParser(description='Deployment tool') subpa...
Get Image File Size From Base64 String
11,761,889
5
2012-08-01T14:53:02Z
11,761,906
15
2012-08-01T14:54:05Z
[ "python", "image" ]
I'm working on a python web service. It calls another web service to change the picture of a profile. It connects to another web service. This web service can only accept pictures that are 4 MB or smaller. I will put the checking in the first web service. It uses PIL to check if the base64 string is a valid image. Ho...
Multiply the length of the data by 3/4, since encoding turns 6 bytes into 8. If the result is within a few bytes of 4MB then you'll need to count the number of `=` at the end.
simplify a loop in python
11,762,521
3
2012-08-01T15:27:15Z
11,762,554
8
2012-08-01T15:28:56Z
[ "python", "performance", "for-loop" ]
I am using this loop in my python code: ``` final_fun=[] for i_base in xrange(n_base): final_fun.append(sum(fun[:,i_base])/n_ci) ``` and I would want to know how I can simplify this loop? If I simplify this loop will my program be faster? In general I know how to simplify this but here I am blocked by the append!
Use list comprehensions. It's faster and cleaner. The interpreter can be slowed down a lot by the for loop, and there's nothing to lose by simply rearranging the syntax. See [this explanation](http://wiki.python.org/moin/PythonSpeed/PerformanceTips#Loops) for more details. ``` final_fun = [sum(fun[:,i_base])/n_ci for...
Pass information from javascript to django app and back
11,762,629
8
2012-08-01T15:32:20Z
11,763,954
24
2012-08-01T16:52:34Z
[ "javascript", "python", "ajax", "django" ]
So I'm trying to basically set up a webpage where a user chooses an id, the webpage then sends the id information to python, where python uses the id to query a database, and then returns the result to the webpage for display. I'm not quite sure how to do this. I know how to use an ajax call to call the data generated...
You're talking about AJAX. AJAX always requires 3 pieces (technically, just two: Javascript does double-duty). 1. Client (Javascript in this case) makes request 2. Server (Django view in this case) handles request and returns response 3. Client (again, Javascript) receives response and does something with it You have...
How to resample a python pandas TimeSeries containing dytpe Decimal values?
11,762,815
6
2012-08-01T15:41:19Z
11,767,878
7
2012-08-01T21:31:04Z
[ "python", "decimal", "pandas", "series" ]
I'm having a pandas Series object filled with decimal numbers of dtype Decimal. I'd like to use the new pandas 0.8 function to resample the decimal time series like this: ``` resampled = ts.resample('D', how = 'mean') ``` When trying this i get an "GroupByError: No numeric types to aggregate" error. I assume the prob...
I found the answer by myself. It is possible to provide a function to the 'how' argument of resample: ``` f = lambda x: Decimal(np.mean(x)) ts.resample('D', how = f) ```
Python 3 - urllib, HTTP Error 407: Proxy Authentication Required
11,763,028
11
2012-08-01T15:53:41Z
11,763,340
17
2012-08-01T16:12:22Z
[ "python", "authentication", "proxy", "urllib" ]
I'm trying to open a website (I am behind a corporate proxy) using urllib.request.urlopen() but I am getting the error: ``` urllib.error.HTTPError: HTTP Error 407: Proxy Authentication Required ``` I can find the proxy in urllib.request.getproxies(), but how do I specify a username and password to use for it? I could...
``` import urllib.request as req proxy = req.ProxyHandler({'http': r'http://username:password@url:port'}) auth = req.HTTPBasicAuthHandler() opener = req.build_opener(proxy, auth, req.HTTPHandler) req.install_opener(opener) conn = req.urlopen('http://google.com') return_str = conn.read() ```
Multiple format options in Python
11,763,480
3
2012-08-01T16:20:42Z
11,763,513
8
2012-08-01T16:23:04Z
[ "python" ]
In Python, how can I do multiple formats at once: So I want to make a number have no decimal places and have a thousands separator: num = 80000.00 I want it to be 80,000 I know I can do these two things serepatly, but how would I combine them: ``` "{:,}".format(num) # this will give me the thousands separator "{0:...
You can combine the two format strings. The comma goes first after the colon: ``` >>> "{:,.0f}".format(80000.0) '80,000' ``` Note that you can also use the free `format()` function instead of the method `str.format()` when formatting only a single value: ``` >>> format(80000.0, ",.0f") '80,000' ``` **Edit**: The `,...
Python List of Ngrams with frequencies
11,763,613
10
2012-08-01T16:29:20Z
11,766,018
10
2012-08-01T19:18:17Z
[ "python", "nltk", "scikit-learn" ]
I need to get most popular ngrams from text. Ngrams length must be from 1 to 5 words. I know how to get bigrams and trigrams. For example: ``` bigram_measures = nltk.collocations.BigramAssocMeasures() finder = nltk.collocations.BigramCollocationFinder.from_words(words) finder.apply_freq_filter(3) finder.apply_word_fi...
**update** Since scikit-learn 0.14 the format has changed to: ``` n_grams = CountVectorizer(ngram_range=(1, 5)) ``` **old answer** `WordNGramAnalyzer` is indeed deprecated since scikit-learn 0.11. Creating n-grams and getting term frequencies is now combined in [sklearn.feature\_extraction.text.CountVectorizer](htt...
Python List of Ngrams with frequencies
11,763,613
10
2012-08-01T16:29:20Z
11,834,518
7
2012-08-06T19:21:20Z
[ "python", "nltk", "scikit-learn" ]
I need to get most popular ngrams from text. Ngrams length must be from 1 to 5 words. I know how to get bigrams and trigrams. For example: ``` bigram_measures = nltk.collocations.BigramAssocMeasures() finder = nltk.collocations.BigramCollocationFinder.from_words(words) finder.apply_freq_filter(3) finder.apply_word_fi...
If you want to generate the raw ngrams (and count them yourself, perhaps), there's also `nltk.util.ngrams(sequence, n)`. It will generate a sequence of ngrams for any value of *n*. It has options for padding, see the documentation.
Python http.client json request and response. How?
11,763,976
6
2012-08-01T16:54:39Z
11,764,225
13
2012-08-01T17:12:03Z
[ "python", "python-3.x" ]
I have the following code that I'd like to update to Python 3.x The required libraries would change to http.client and json. I can't seem to understand how to do it. Can you please help? ``` import urllib2 import json data = {"text": "Hello world github/linguist#1 **cool**, and #1!"} json_data = json.dumps(data) r...
``` import http.client import json connection = http.client.HTTPSConnection('api.github.com') headers = {'Content-type': 'application/json'} foo = {'text': 'Hello world github/linguist#1 **cool**, and #1!'} json_foo = json.dumps(foo) connection.request('POST', '/markdown', json_foo, headers) response = connection....
Python for loop access two elements at a time
11,764,010
6
2012-08-01T16:56:29Z
11,764,083
12
2012-08-01T17:02:04Z
[ "python", "for-loop" ]
I'm adding into the value section of a dictionary a name and the value of properties of an item: ``` value+=child.get('name') + '\t' + child.text + '\t' ``` Each piece of text is separated by a tab. So then when I process this value string later, I split on the tabs and have a for loop to iterate over the list. How ...
You can iterate over the list with step size 2, and get the name and tag each over each iteration... ``` for i in range(0,len(list1),2): name = list1[i] tag = list1[i+1] print '<tag name="%s">%s</tag>' % (name, tag) ```
Launch Fab File inside a python script
11,764,203
4
2012-08-01T17:10:34Z
11,764,419
13
2012-08-01T17:26:27Z
[ "python", "fab" ]
I have a `fab` script, it works fine. To start it, I execute: ``` fab -H 192.168.xx.xx deployFiles deployConfiguration:'master',7 ``` `deployFiles` and `deployConfiguration` are both functions in my `fabfile.py`. `'master'` and `7` are my parameters for `deployConfiguration` I have another Python script and I want t...
You just import them, and call them. Using either the settings context manager or setting the relevant settings on fabric.api.env ``` from fabric.context_managers import settings from fabfile import deployFiles, deployConfiguration with settings(host_string='user@192.168.xx.xx'): deployFiles() deployConfigura...
How to find the minimum value in a numpy matrix?
11,764,260
6
2012-08-01T17:14:13Z
11,764,285
13
2012-08-01T17:15:57Z
[ "python", "arrays", "matrix", "numpy", "minimum" ]
Hey this is a quick and easy question... How would i find the minimum value of this matrix, excluding 0? As in, 8 ``` arr = numpy.array([[ 0., 56., 20., 44.], [ 68., 0., 56., 8.], [ 32., 56., 0., 44.], [ 68., 20., 56., 0.]]) ```
As you're using `numpy`, you could use ``` arr[arr>0].min() ``` for the case you posted. but if your array could have negative values, then you should use ``` arr[arr != 0].min() ```
How to nest records in an Avro schema?
11,764,287
18
2012-08-01T17:16:06Z
11,765,060
22
2012-08-01T18:10:18Z
[ "python", "avro" ]
I'm trying to get Python to parse Avro schemas such as the following... ``` from avro import schema mySchema = """ { "name": "person", "type": "record", "fields": [ {"name": "firstname", "type": "string"}, {"name": "lastname", "type": "string"}, { "name": "address", ...
According to other sources on the web I would rewrite your second address definition: ``` mySchema = """ { "name": "person", "type": "record", "fields": [ {"name": "firstname", "type": "string"}, {"name": "lastname", "type": "string"}, { "name": "address", "t...
Why python-cgi fails on unicode?
11,764,408
8
2012-08-01T17:25:01Z
11,767,629
8
2012-08-01T21:09:40Z
[ "python", "unicode", "cgi" ]
If run this code in console - it works well (it is in Russian), but if run it like cgi on Apache2 server - it fails: `<type 'exceptions.UnicodeEncodeError'>: 'ascii' codec can't encode characters in position 8-9: ordinal not in range(128)`. The code is: ``` #!/usr/bin/env python # -*- coding: UTF-8 -*- import cgitb c...
When running from the console Python can detect the encoding of the console and implicitly converts Unicode printed to the console to that encoding. It can still fail if that encoding doesn't support the characters you are trying to print. UTF-8 can support all Unicode characters, but other common console encodings lik...
Can you add parameters to Django custom admin actions?
11,764,709
11
2012-08-01T17:46:30Z
11,764,815
9
2012-08-01T17:53:39Z
[ "python", "django", "admin", "models" ]
For example (not the case, but just to illustrate) if I wanted to add an action to set a specific field in the selected items to X. Is it possible to add an action to allow X to be entered as opposed to hard coded?
See: [Actions that Provide Intermediate Pages](https://docs.djangoproject.com/en/dev/ref/contrib/admin/actions/#actions-that-provide-intermediate-pages) You can't do it right from the changelist page, but on your intermediate page, you could have a form that would allow the user to enter a value, and then use that val...
Why do integers in database row tuple have an 'L' suffix?
11,764,713
22
2012-08-01T17:46:48Z
11,764,758
10
2012-08-01T17:50:34Z
[ "python", "mysql" ]
My question is why do a MySQL row's integer values have an 'L' suffix? Here are the details: The following dictionary -- artificially formatted here for ease of display -- ``` {'estimated': '', 'suffix': '', 'typeofread': 'g', 'acct_no': 901001000L, 'counter': 0, 'time_billed': datetime.datetime(2012, 5,...
`L` is for the `long` data type. For example, ``` age = 24 # int bankBalance = 20000005L # long ```
Why do integers in database row tuple have an 'L' suffix?
11,764,713
22
2012-08-01T17:46:48Z
11,764,774
24
2012-08-01T17:51:30Z
[ "python", "mysql" ]
My question is why do a MySQL row's integer values have an 'L' suffix? Here are the details: The following dictionary -- artificially formatted here for ease of display -- ``` {'estimated': '', 'suffix': '', 'typeofread': 'g', 'acct_no': 901001000L, 'counter': 0, 'time_billed': datetime.datetime(2012, 5,...
Because in versions of Python before Python 3, long integer literals were indicated with an `l` or `L` suffix. In Python 3, `int`s and `long`s have been merged into just `int`, which functions pretty much like `long` used to. Do note that, technically, Python( 2)'s `int` was equivalent to C's `long`, while Python's `l...
Using locals() and format() method for strings: are there any caveats?
11,764,900
26
2012-08-01T17:59:39Z
11,765,023
21
2012-08-01T18:07:47Z
[ "python", "string-formatting", "local-variables", "locals" ]
Are there any disadvantages, caveats or bad practice warnings about using the following pattern? ``` def buildString(user, name = 'john', age=22): userId = user.getUserId() return "Name: {name}, age: {age}, userid:{userId}".format(**locals()) ``` I had a very repetitive string generation code to write and was...
If the format string is not user-supplied, this usage is okay. `format` is preferred over using the old `%` for string substitution. [`locals`](http://docs.python.org/library/functions.html#locals) is built-in to Python and its behavior will be reliable. I think `locals` does exactly what you need. Just don't mod...
Using locals() and format() method for strings: are there any caveats?
11,764,900
26
2012-08-01T17:59:39Z
11,765,189
8
2012-08-01T18:19:43Z
[ "python", "string-formatting", "local-variables", "locals" ]
Are there any disadvantages, caveats or bad practice warnings about using the following pattern? ``` def buildString(user, name = 'john', age=22): userId = user.getUserId() return "Name: {name}, age: {age}, userid:{userId}".format(**locals()) ``` I had a very repetitive string generation code to write and was...
I do this sort of thing regularly. The only problem I've had is that [PyFlakes will complain about unused variables](https://bugs.launchpad.net/pyflakes/+bug/872503) when I do it.
Better way to shuffle two related lists
11,765,061
16
2012-08-01T18:10:21Z
11,765,138
21
2012-08-01T18:15:54Z
[ "python", "list", "shuffle" ]
Is there better ways to randomly shuffle two related lists without breaking their correspondence in the other list? I've found related questions in `numpy.array` and `c#` but not exactly the same one. As a first try, a simple `zip` trick will do: ``` import random a = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] b = [2,...
Given the relationship demonstrated in the question, I'm going to assume the lists are the same length and that `list1[i]` corresponds to `list2[i]` for any index `i`. With that assumption in place, shuffling the lists is as simple as shuffling the indices: ``` from random import shuffle # Given list1 and list2 list1_...
matplotlib - 3d surface from a rectangular array of heights
11,766,536
9
2012-08-01T19:51:42Z
11,776,477
23
2012-08-02T11:28:08Z
[ "python", "matplotlib", "3d", "hdf5", "geometry-surface" ]
I am trying to plot some HDF data in matplotlib. After importing them using h5py, the data is stored in a form of array, like this: ``` array([[151, 176, 178], [121, 137, 130], [120, 125, 126]) ``` In this case, x and y values are just the indexes of the array's fields, while z value is the value of spe...
If you want a 3-d surface plot, you have to create the `meshgrid` first. You can try: ``` from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np X = np.arange(1, 10) Y = np.arange(1, 10) X, Y = np.meshgrid(X, Y) R = np.sqrt(X**2 + Y**2) Z = np.sin(R) fig = plt.figure() ax = fig.gca...
Export a Python List to Excel
11,766,833
5
2012-08-01T20:10:02Z
11,778,645
8
2012-08-02T13:38:26Z
[ "python", "excel", "com" ]
I am trying to export a list to excel via the Win32COM client whihc i have imported at the header. The object i created is coded as below, but I cant seem to get it to export each value to its own row in the spreadsheet. If I can get a good pointer (other than give up python!! :D), I would appreciate it. ``` class Xce...
Since you seemed to like my answer/comment, here's an answer proper: [Python Excel](http://www.python-excel.org/) has just about everything you'd ever need. If you want something more integrated but seems limited, there is [IronSpread](http://www.ironspread.com/index.html). XLRD and XLWT are great packages, but they d...
adding script to build.gradle
11,767,713
10
2012-08-01T21:16:59Z
11,767,966
20
2012-08-01T21:39:13Z
[ "python", "groovy", "build", "gradle" ]
I have a build.gradle file. I have add a code such that it executes a python script which i have writtetn. Can anyone tell me how to do it. build.gradle is written in groovy . So please ask more questions if you feel my question is not sufficient
Take a look at the [Exec](http://gradle.org/docs/current/dsl/org.gradle.api.tasks.Exec.html) task. It can be used for running command line processes. You could create a task like: ``` task runPython(type:Exec) { workingDir 'path_to_script' commandLine 'python', 'my_script.py' } ```
Greater than less than, python
11,767,867
8
2012-08-01T21:29:54Z
11,767,888
19
2012-08-01T21:32:14Z
[ "python", "if-statement" ]
I am doing a ranking type thing, what happens is I compare the score to the current score and if the score is lower then the current then the player has got a high score, but when using this code here ``` print "Score = " + str(score) + ", Compared to = " + str(array[x]) if score < array[x]: ...
Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x. ``` >>> 2 < "2" True >>> 2 > "2" False >>> 2 == "2" False ``` Edit Further explanation: [How does Python compare string and int?](http://stackoverflow....
How to use nose's assert_raises?
11,767,938
33
2012-08-01T21:36:44Z
11,768,202
45
2012-08-01T21:57:59Z
[ "python", "nosetests" ]
I've searched for documentation, but couldn't find any. There were a couple that didn't explain much. Can someone explain to me Nose's ``` assert_raises(what should I put here?) ``` function and how to use it?
The `assert_raises()` function tests to make sure a function call raises a specified exception when presented with certain parameters. For example, if you had a function `add` that adds two numbers, it should probably raise a `TypeError` when you pass it, say, an integer and a string. So: ``` from nose.tools import a...
How to use nose's assert_raises?
11,767,938
33
2012-08-01T21:36:44Z
19,310,416
61
2013-10-11T04:45:10Z
[ "python", "nosetests" ]
I've searched for documentation, but couldn't find any. There were a couple that didn't explain much. Can someone explain to me Nose's ``` assert_raises(what should I put here?) ``` function and how to use it?
While the accepted answer is correct, I think there is a better use to `assert_raises` method. If you simply want to assert that an exception occurs, it's probably simpler and cleaner to use `@raises` syntax. ``` @raises(HTTPError) def test_exception_is_raised: call_your_method(p1, p2) ``` However, assume you wa...
Transform URL string into normal string in python (%20 to space etc)
11,768,070
9
2012-08-01T21:48:46Z
11,768,102
16
2012-08-01T21:51:39Z
[ "python", "string" ]
Is there any way in python to transfrom this-> %CE%B1%CE%BB%20 into this: "αλ " which is its real representation? Thanks in advance!
``` >>> import urllib2 >>> print urllib2.unquote("%CE%B1%CE%BB%20") αλ ```
Why map(print, a_list) doesn't work?
11,768,095
14
2012-08-01T21:51:16Z
11,768,129
17
2012-08-01T21:53:23Z
[ "python", "python-2.7", "map-function" ]
For a normal function, `map` works well: ``` def increment(n): return n+1 l = [1, 2, 3, 4, 5] l = map(increment, l) print l >>> [2, 3, 4, 5, 6] ``` However, if it's `print` being put inside the `map` function: ``` l = [1, 2, 3, 4, 5] l = map(print, l) print l ``` python will complain: ``` l = map(print, l) ...
In Python 2.x, `print` is a statement, not a function. If you try this in Python 3.x it will work. In Python 2.x, you can say `print(x)` and it is not a syntax error, but it isn't actually a function call. Just as `1 + (3)` is the same as `1 + 3`, `print(x)` is the same as `print x` in Python 2.x. In Python 2.x you c...
Why map(print, a_list) doesn't work?
11,768,095
14
2012-08-01T21:51:16Z
11,768,208
7
2012-08-01T21:58:49Z
[ "python", "python-2.7", "map-function" ]
For a normal function, `map` works well: ``` def increment(n): return n+1 l = [1, 2, 3, 4, 5] l = map(increment, l) print l >>> [2, 3, 4, 5, 6] ``` However, if it's `print` being put inside the `map` function: ``` l = [1, 2, 3, 4, 5] l = map(print, l) print l ``` python will complain: ``` l = map(print, l) ...
A better way to map print in 2.x would be to do ``` from __future__ import print_function ```
Heroku Can't find Django Templates
11,768,143
2
2012-08-01T21:54:24Z
11,768,200
9
2012-08-01T21:57:54Z
[ "python", "django", "heroku" ]
Im getting a templatedoesnot exist error on Heroku when it looks for my html files. The files all sync up on the development server. The template dirs in settings are set to: '/Users/jonathanschen/Python/projects/skeleton/myportfolio/templates', But when trying to load the page the herokuapp page i get the following ...
You'll need to update your TEMPLATE\_DIRS setting to point to something Heroku can find - the path that you have it set to right now will work locally, but Heroku has no idea where `/Users/jonathanschen/` is (because it doesn't have that folder). You might want to try making your TEMPLATE\_DIRS setting use a relative p...
Python: download a file over an FTP server
11,768,214
18
2012-08-01T21:59:40Z
11,768,443
22
2012-08-01T22:22:07Z
[ "python", "ftp", "download" ]
I'm trying to download some public data files. I screenscrape to get the links to the files, which all look something like this: ``` ftp://ftp.cdc.gov/pub/Health_Statistics/NCHS/nhanes/2001-2002/L28POC_B.xpt ``` I can't find any documentation on the Requests library website.[1](http://docs.python-requests.org/en/late...
`requests` library doesn't support ftp links. To download a file from FTP server you could: ``` import urllib urllib.urlretrieve('ftp://server/path/to/file', 'file') # if you need to pass credentials: # urllib.urlretrieve('ftp://username:password@server/path/to/file', 'file') ``` Or: ``` import shutil import ur...
Python: download a file over an FTP server
11,768,214
18
2012-08-01T21:59:40Z
12,424,311
26
2012-09-14T12:12:19Z
[ "python", "ftp", "download" ]
I'm trying to download some public data files. I screenscrape to get the links to the files, which all look something like this: ``` ftp://ftp.cdc.gov/pub/Health_Statistics/NCHS/nhanes/2001-2002/L28POC_B.xpt ``` I can't find any documentation on the Requests library website.[1](http://docs.python-requests.org/en/late...
You Can Try this ``` import ftplib path = 'pub/Health_Statistics/NCHS/nhanes/2001-2002/' filename = 'L28POC_B.xpt' ftp = ftplib.FTP("Server IP") ftp.login("UserName", "Password") ftp.cwd(path) ftp.retrbinary("RETR " + filename ,open(filename, 'wb').write) ftp.quit() ```
Can the staticmethod and classmethod decoraters be implemented in pure Python?
11,768,752
8
2012-08-01T22:54:49Z
11,768,768
8
2012-08-01T22:57:36Z
[ "python", "decorator", "static-methods", "class-method" ]
This is an academic question, more than a practical one. I'm trying to delve into the foundations of Python, and I wonder: could I implement the `staticmethod` and `classmethod` decorators in pure Python if I wanted to? For `staticmethod` maybe I could keep a reference to the original function and call it omitting the...
There are examples in [the docs](http://docs.python.org/howto/descriptor.html#static-methods-and-class-methods): ``` class StaticMethod(object): "Emulate PyStaticMethod_Type() in Objects/funcobject.c" def __init__(self, f): self.f = f def __get__(self, obj, objtype=None): return self.f ``...
Why is SQLAlchemy insert with sqlite 25 times slower than using sqlite3 directly?
11,769,366
50
2012-08-02T00:14:06Z
11,769,768
137
2012-08-02T01:17:27Z
[ "python", "sqlite", "orm", "sqlite3", "sqlalchemy" ]
Why is this simple test case inserting 100,000 rows 25 times slower with SQLAlchemy than it is using the sqlite3 driver directly? I have seen similar slowdowns in real-world applications. Am I doing something wrong? ``` #!/usr/bin/env python # Why is SQLAlchemy with SQLite so slow? # Output from this program: # SqlAlc...
The SQLAlchemy ORM uses the [unit of work](http://martinfowler.com/eaaCatalog/unitOfWork.html) pattern when synchronizing changes to the database. This pattern goes far beyond simple "inserts" of data. It includes that attributes which are assigned on objects are received using an attribute instrumentation system which...
Why is SQLAlchemy insert with sqlite 25 times slower than using sqlite3 directly?
11,769,366
50
2012-08-02T00:14:06Z
21,968,239
14
2014-02-23T12:33:13Z
[ "python", "sqlite", "orm", "sqlite3", "sqlalchemy" ]
Why is this simple test case inserting 100,000 rows 25 times slower with SQLAlchemy than it is using the sqlite3 driver directly? I have seen similar slowdowns in real-world applications. Am I doing something wrong? ``` #!/usr/bin/env python # Why is SQLAlchemy with SQLite so slow? # Output from this program: # SqlAlc...
Excellent answer from @zzzeek. For those wondering about the same stats for queries I've modified @zzzeek code slightly to query those same records right after inserting them then convert those records to a list of dicts. Here's the results ``` SqlAlchemy ORM: Total time for 100000 records 11.9210000038 secs SqlAlche...
How can I login to django using tastypie
11,770,501
23
2012-08-02T03:06:51Z
11,770,751
69
2012-08-02T03:42:31Z
[ "python", "django", "tastypie" ]
I'm trying to override is\_authenticated in my custom authentication. I have something simple (to start with) like this: ``` class MyAuthentication(BasicAuthentication): def __init__(self, *args, **kwargs): super(MyAuthentication, self).__init__(*args, **kwargs) def is_authenticated(self, request, **k...
Your approach will try to create a new user with the username that you are authenticating with. This will bubble up at the DB layer, as you've noticed, that such a user already exists. What you want is to create a `UserResource`, add a method on it that users can post to and login with data passing in username/passwor...
Using SL4A (Python) and bluetooth
11,770,594
3
2012-08-02T03:21:07Z
12,065,268
7
2012-08-22T01:36:29Z
[ "android", "python", "bluetooth", "sl4a" ]
Looking for some pointers to get me started. In my left hand I have a SGS2 running ICS. I've got SL4A up and running and have installed Python 2.6.2 In my right hand I've got a generic chinese bluetooth RFID reader. It works, it reads tags (it has a display) and it's paired with the phone. I'd like them to play nice...
it seems that what you need is the bluetooth facade. Here are some commands pertaining to bluetooth that might be helpful to you: ``` bluetoothAccept bluetoothActiveConnections bluetoothConnect bluetoothDiscoveryCancel bluetoothDiscoveryStart bluetoothGetConnectedDeviceName bluetoothGetLocalAddress bluetoothGetLocalNa...
List comprehensions for side effects - idiomatically correct or an abomination?
11,771,109
3
2012-08-02T04:35:47Z
11,771,188
10
2012-08-02T04:44:26Z
[ "python", "idiomatic" ]
I have a list of `cheese` objects. `Cheese` has a method that does a bunch of stuff with the db and whatnot, called `out_of_stock()`. So: ``` [cheese.out_of_stock() for cheese in cheeses] ``` It feels sloppy to me. Like I'm doing something (creating a list) for a bunch of side effects (zeroing inventory). Am I bein...
List comprehensions are for creating a list. That's not what you're doing here, so I'd avoid it.
PyQt dialog - How to make it quit after pressing a button?
11,772,624
4
2012-08-02T07:08:43Z
11,772,721
17
2012-08-02T07:15:53Z
[ "python", "dialog", "pyqt" ]
Well, I'm writing a small PyQt4 app, it's just a single Yes/No dialog which has to execute an external command (e.g. 'eject /dev/sr0') and quit. The app runs, it executes the command after pressing the "Yes" button, but I cannot make the dialog itself exit when executing the command. ``` #!/usr/bin/python # -*- codin...
``` btn.clicked.connect(self.close) ``` That would be my suggestion
Error - urlopen error [Errno 8] _ssl.c:504: EOF occurred in violation of protocol , help needed
11,772,847
18
2012-08-02T07:26:09Z
24,175,862
18
2014-06-12T03:06:48Z
[ "python", "proxy", "mechanize", "urllib2" ]
My aim is to extract the html from all the links in the first page after entering the google search term. I work behind a proxy so this is my approach. 1.I first used mechanize to enter the search term in the form , ive set the proxies and robots correctly. 2.After extracting the links , Ive used an opener using urll...
Instead of copying and editing Python library modules, you can monkey-patch ssl.wrap\_socket() in the ssl module by overriding the ssl\_version keyword parameter. The following code can be used as-is. Put this at the start of your program before making any requests. ``` import ssl from functools import wraps def sslwr...
Python Flask, how to set content type
11,773,348
77
2012-08-02T08:03:16Z
11,774,026
103
2012-08-02T08:49:39Z
[ "python", "flask" ]
I am using Flask and I return an XML file from a get request. How do I set the content type? e.g. ``` @app.route('/ajax_ddl') def ajax_ddl(): xml = 'foo' header("Content-type: text/xml") return xml ```
Try like this: ``` from flask import Response @app.route('/ajax_ddl') def ajax_ddl(): xml = 'foo' return Response(xml, mimetype='text/xml') ``` The actual Content-Type is based on the mimetype parameter and the charset (defaults to UTF-8). Response (and request) objects are documented here: <http://werkzeug....
Python Flask, how to set content type
11,773,348
77
2012-08-02T08:03:16Z
18,501,318
24
2013-08-29T02:21:47Z
[ "python", "flask" ]
I am using Flask and I return an XML file from a get request. How do I set the content type? e.g. ``` @app.route('/ajax_ddl') def ajax_ddl(): xml = 'foo' header("Content-type: text/xml") return xml ```
I like and upvoted @Simon Sapin's answer. I ended up taking a slightly different tack, however, and created my own decorator: ``` from flask import Response from functools import wraps def returns_xml(f): @wraps(f) def decorated_function(*args, **kwargs): r = f(*args, **kwargs) return Response...
Python Flask, how to set content type
11,773,348
77
2012-08-02T08:03:16Z
24,852,564
55
2014-07-20T16:33:41Z
[ "python", "flask" ]
I am using Flask and I return an XML file from a get request. How do I set the content type? e.g. ``` @app.route('/ajax_ddl') def ajax_ddl(): xml = 'foo' header("Content-type: text/xml") return xml ```
As simple as this ``` x = "some data you want to return" return x, 200, {'Content-Type': 'text/css; charset=utf-8'} ``` Hope it helps
Python Flask, how to set content type
11,773,348
77
2012-08-02T08:03:16Z
31,751,634
7
2015-07-31T17:11:43Z
[ "python", "flask" ]
I am using Flask and I return an XML file from a get request. How do I set the content type? e.g. ``` @app.route('/ajax_ddl') def ajax_ddl(): xml = 'foo' header("Content-type: text/xml") return xml ```
Use the [make\_response method](http://flask.pocoo.org/docs/0.10/api/#flask.Flask.make_response) to get a response with your data. Then set the [mimetype attribute](http://flask.pocoo.org/docs/0.10/api/#flask.Response.mimetype). Finally return this response: ``` @app.route('/ajax_ddl') def ajax_ddl(): xml = 'foo' ...
flask - how do you get a query string from flask
11,774,265
116
2012-08-02T09:04:40Z
11,774,434
231
2012-08-02T09:14:53Z
[ "python", "flask", "query-string" ]
Not obvious from the flask documention on how to get the query string. I am new, looked at the docs, could not find! So ``` @app.route('/') @app.route('/data') def data(): query_string=?????? return render_template("data.html") ```
``` from flask import request @app.route('/data') def data(): # here we want to get the value of user (i.e. ?user=some-value) user = request.args.get('user') ```
flask - how do you get a query string from flask
11,774,265
116
2012-08-02T09:04:40Z
11,781,872
91
2012-08-02T16:29:15Z
[ "python", "flask", "query-string" ]
Not obvious from the flask documention on how to get the query string. I am new, looked at the docs, could not find! So ``` @app.route('/') @app.route('/data') def data(): query_string=?????? return render_template("data.html") ```
The full URL is available as `request.url`, and the query string is available as `request.query_string`. Here's an example: ``` from flask import request @app.route('/adhoc_test/') def adhoc_test(): return request.query_string ``` To access an individual known param passed in the query string, you can use `req...
flask - how do you get a query string from flask
11,774,265
116
2012-08-02T09:04:40Z
11,792,690
7
2012-08-03T09:08:44Z
[ "python", "flask", "query-string" ]
Not obvious from the flask documention on how to get the query string. I am new, looked at the docs, could not find! So ``` @app.route('/') @app.route('/data') def data(): query_string=?????? return render_template("data.html") ```
Werkzeug/Flask as already parsed everything for you. No need to do the same work again with urlparse: ``` from flask import request @app.route('/') @app.route('/data') def data(): query_string = request.query_string ## There is it return render_template("data.html") ``` The full documentation for the reques...
Python list difference with number of ocurrences
11,774,751
3
2012-08-02T09:35:22Z
11,774,824
8
2012-08-02T09:39:28Z
[ "python", "list", "comparison" ]
Is there a list subtraction / list diff function built in with python? I know how to write such a function, so no need to explain that. But since it's a common thing to do, I would like to know if there is already such a function built in. I have two sorted lists, each may contain multiple copies of identical elements...
Maybe you can just use the [Counter](http://docs.python.org/library/collections.html#counter-objects) class. --- **Example:** ``` l1 = [1,1,2,3,5,6] l2 = [1,2,8,9] from collections import Counter print Counter(l1) - Counter(l2) print Counter(l2) - Counter(l1) ``` **Result:** > Counter({1: 1, 3: 1, 5: 1, 6: 1}) ...
How to run a python file using cron jobs
11,774,925
25
2012-08-02T09:45:24Z
11,775,112
32
2012-08-02T09:57:49Z
[ "python", "shell", "cron" ]
Hi I have created a python file for example as `file_example.py` The file will output the sensex value Suppose the path of the file on linux system is `/Desktop/downloads/file_example.py` and I normally will run the file like `python file_example.py` But I want to set a cron job to run the python file every 2 min w...
Assuming you are using a unix OS, you would do the following. edit the crontab file using the command ``` crontab -e ``` add a line that resembles the one below ``` */2 * * * * /Desktop/downloads/file_example.py ``` this can be used to run other scripts simply use the path to the script needed i.e. ``` */2 * * * ...
How to run a python file using cron jobs
11,774,925
25
2012-08-02T09:45:24Z
26,897,450
14
2014-11-12T21:59:46Z
[ "python", "shell", "cron" ]
Hi I have created a python file for example as `file_example.py` The file will output the sensex value Suppose the path of the file on linux system is `/Desktop/downloads/file_example.py` and I normally will run the file like `python file_example.py` But I want to set a cron job to run the python file every 2 min w...
You can use python-crontab module. <https://pypi.python.org/pypi/python-crontab> To create a new cron job is as simple as follows: ``` from crontab import CronTab #init cron cron = CronTab() #add new cron job job = cron.new(command='/usr/bin/echo') #job settings job.hour.every(4) ```
How can I display a np.array with pylab.imshow()
11,775,354
7
2012-08-02T10:11:34Z
11,775,935
14
2012-08-02T10:52:13Z
[ "python", "matplotlib" ]
the np.array that results from this loop has 4383 lines and 6 columns. I have tried without success to use pylab.imshow () from matplotlib(pylab) to display the array. The objective is to creat an image of the array, in wich the colors gradient represent the magnitude of the array values. Each row of the array represen...
You can use `imshow` as follows: ``` import pylab as plt import numpy as np Z=np.array(((1,2,3,4,5),(4,5,6,7,8),(7,8,9,10,11))) im = plt.imshow(Z, cmap='hot') plt.colorbar(im, orientation='horizontal') plt.show() ``` ![enter image description here](http://i.stack.imgur.com/c6olN.png) In your case can you check the...
Why is the main() function not defined inside the if '__main__'?
11,775,494
6
2012-08-02T10:20:13Z
11,775,531
11
2012-08-02T10:22:51Z
[ "python", "main" ]
You can often see this (variation a): ``` def main(): do_something() do_sth_else() if __name__ == '__main__': main() ``` And I am now wondering why *not* this (variation b): ``` if __name__ == '__main__': do_something() do_sth_else() ``` Or *at least* this (variation c): ``` if __name__ == '__main...
Why limit your `main()` function to command line usage only? By defining a `main()` function at module scope, you can now wrap your script and alter how it is called. Perhaps you want to set default arguments in sys.argv, perhaps you want to reuse the code in another script.
Find nearest link with BeautifullSoup (python)
11,776,157
6
2012-08-02T11:06:06Z
11,808,510
12
2012-08-04T12:02:49Z
[ "python", "beautifulsoup", "lxml" ]
I am doing a small project where I extract occurences of political leaders in newspapers. Sometimes a politician will be mentioned, and there is neither a parent or child with a link. (due I guess to semantically bad markup). So I want to create a function that can find the nearest link, and then extract that. In the ...
Someone will probably come up with a solution that works with copy&paste and you will think that this solves your problem. Your problem isn't the code, though! It's your strategy. There is a software design principle called "divide and conquer" which you should apply in a redesign to your code: Seperate the code that i...
What does the following Python code do? It's like a list comprehension with parentheses.
11,776,241
2
2012-08-02T11:12:12Z
11,776,307
9
2012-08-02T11:16:58Z
[ "python", "web-crawler" ]
I'm researching web crawlers made in Python, and I've stumbled across a pretty simple one. But, I don't understand the last few lines, highlighted in the following code: ``` import sys import re import urllib2 import urlparse tocrawl = [sys.argv[1]] crawled = [] keywordregex = re.compile('<meta\sname=["\']keywords["...
It's a [generator expression](http://docs.python.org/tutorial/classes.html#generator-expressions) and it simply empties the list `links` as you iterate over it. They could have replaced this part ``` a = (links.pop(0) for _ in range(len(links))) //What does this do? for link in a: ``` With this: ``` while links: ...
Plotting a 2D array with matplotlib.imshow
11,776,663
3
2012-08-02T11:40:38Z
12,850,466
7
2012-10-12T00:09:30Z
[ "python", "matplotlib", "2d" ]
The `np.array` that results from this loop has 4383 rows and 6 columns. I have tried without success to use `pylab.imshow()` from matplotlib(pylab) to display the array. The objective is to creat an image of the array, in wich the colors gradient represent the magnitude of the array values. Each row of the array repres...
You **can** use `imshow` if you just set the aspect when you call it. As follows: ``` im = plt.imshow(tem, cmap='hot', aspect=aspect_ratio*(cols/rows)) ``` where `aspect_ratio` here would set the actual aspect ratio you want and `cols/rows` just normalizes the original aspect ratio to 1. `cols` and `rows` are the num...
Invert an axis in a matplotlib grafic
11,777,381
10
2012-08-02T12:25:35Z
11,779,370
28
2012-08-02T14:17:30Z
[ "python", "matplotlib" ]
How can I invert the y\_axis? Z is a np.array.Thank you ``` Z=TempLake X,Y=np.meshgrid(range(Z.shape[0]+1),range(Z.shape[1]+1)) im = plt.pcolormesh(X,Y,Z.transpose(), cmap='hot') plt.colorbar(im, orientation='horizontal') plt.show() ``` I have this: ![enter image description here](http://i.stack.imgur.com/dWZOW...
As @Chris said, this can be done with: ``` ax = plt.gca() ax.invert_yaxis() ``` Before the 'plt.show()'.
Python OpenCV Box2D
11,779,100
4
2012-08-02T14:03:06Z
11,799,667
9
2012-08-03T16:26:40Z
[ "python", "image-processing", "opencv" ]
I am trying to call OpenCV function MinAreaRect2 from within python. I use OpenCV 2.4.2 with python 2.7 and numpy 1.6. I went this far : ``` import cv def nda2ipl(arr, dtype=None): return cv.fromarray(np.ascontiguousarray(arr, dtype=dtype)) def min_area_rect2(points): storage = cv.CreateMemStorage() cv_p...
OpenCV Python wrapper documentation is kept along with the normal documentation in same site, www.docs.opencv.org Earlier Python module used was `cv` interface, which used native data types from original C++ interface like cvMat, cvSeq etc. Later it was shifted to more better, advanced and simpler module `cv2` interf...
run a python script from c#
11,779,143
40
2012-08-02T14:05:09Z
11,779,234
42
2012-08-02T14:10:39Z
[ "c#", "python", ".net", "ironpython", "python.net" ]
This sort of question has been asked before in varying degrees, but I feel it has not been answered in a concise way and so I ask it again. I want to run a script in Python, let's say it's this: ``` if __name__ == '__main__': f = open(sys.argv[1], 'r') s = f.read() f.close() print s ``` Which gets a ...
The reason it isn't working is because you have `UseShellExecute = false`. If you don't use the shell, you will have to supply the complete path to the python executable as `FileName`, and build the `Arguments` string to supply both your script and the file you want to read. Also note, that you can't `RedirectStandar...
run a python script from c#
11,779,143
40
2012-08-02T14:05:09Z
11,780,190
23
2012-08-02T14:54:12Z
[ "c#", "python", ".net", "ironpython", "python.net" ]
This sort of question has been asked before in varying degrees, but I feel it has not been answered in a concise way and so I ask it again. I want to run a script in Python, let's say it's this: ``` if __name__ == '__main__': f = open(sys.argv[1], 'r') s = f.read() f.close() print s ``` Which gets a ...
If you're willing to use IronPython, you can execute scripts directly in C#: ``` using IronPython.Hosting; using Microsoft.Scripting.Hosting; private static void doPython() { ScriptEngine engine = Python.CreateEngine(); engine.ExecuteFile(@"test.py"); } ``` [Get IronPython here.](http://ironpython.net/)
How to show a PDF file in a Django view
11,779,246
8
2012-08-02T14:11:19Z
11,780,055
16
2012-08-02T14:49:04Z
[ "python", "django", "model-view-controller", "pdf" ]
Is it possible to show a PDF file *in* the Django view, rather than making the user have to download it to see it? And if it is possible, how would it be done? This is what I have so far - ``` @login_required def resume(request, applicant_id): #Get the applicant's resume resume = File.objects.get(applicant=appl...
Simplistically, if you have a PDF file and you want to output it through a Django view, all you need to do is dump the file contents into the response and send it with the appropriate mimetype. ``` def pdf_view(request): with open('/path/to/my/file.pdf', 'r') as pdf: response = HttpResponse(pdf.read(), mim...
What is the cause of mysqldb's Warning: Truncated incorrect DOUBLE value error?
11,780,770
5
2012-08-02T15:22:39Z
11,781,913
10
2012-08-02T16:31:09Z
[ "python", "mysql-python" ]
I am getting many warnings of the same kind -- ``` Warning: Truncated incorrect DOUBLE value: '512121500B' ``` -- but cannot figure out why. The MySQL table dr\_snapshot looks like this: ``` PremiseID char(10) Primary Key cycle SMALLINT(6) last_read DATETIME reading INTEGER DeviceID INTEGER ``` I want to delete ma...
Look at this line `"where PremiseID = " + str(premiseID) + " ; "])"`. The comparison is happening on different types and when MySQL compares different datatypes they are cast to DOUBLE internally before comparison. So you can try putting single quote around or cast around to solve the issue. So it's not try catch but t...
Forcing json to dump a json object even when list is empty
11,781,148
9
2012-08-02T15:45:00Z
11,781,201
13
2012-08-02T15:48:09Z
[ "python", "json" ]
I have a list, which may be empty or non-empty. I want to create a new file which contains that list in a format that is human-readable and easy for my next script to parse. In the case where the list is non-empty, this works fine and my next script reads in the json file. But when the list is empty, I get "ValueError...
Modify your reader script to this: ``` with open('favoriteColor.json') as inFile: try: colors = json.load(inFile) except ValueError: colors = [] ``` This attempts to load the file as a json. If it fails due to a value error, we know that this is because the json is empty. Therefore we can ...
Why are textwrap.wrap() and textwrap.fill() so slow?
11,781,261
2
2012-08-02T15:51:49Z
11,781,870
7
2012-08-02T16:29:05Z
[ "python" ]
Why are [`textwrap.wrap()`](http://docs.python.org/library/textwrap.html#textwrap.wrap) and [`textwrap.fill()`](http://docs.python.org/library/textwrap.html#textwrap.fill) so slow? For example, to wrap a string of 10000 characters on my laptop takes nearly two and a half seconds. ``` $ python -m timeit -n 10 -s 's = "...
Profiling the code reveals that the time is taken up by the regular expression intended to split the input into words. A stripped down version of it that exhibits the same issue is: ``` import re s = "A" * 10000 wordsep_re = re.compile( r'\w+[^\W]-' ) wordsep_re.split(s) ``` I believe Python uses recursive ba...
Python using getattr to call function with variable parameters
11,781,265
5
2012-08-02T15:51:55Z
11,781,292
13
2012-08-02T15:53:47Z
[ "python", "function", "variables", "parameters", "getattr" ]
I'm using getattr to call different functions depending on a variable. Im doing something like that: ``` getattr(foo, bar) () ``` That works, calling functions like foo.bar() My problem is that I have 'bar' functions and I want to call it with different parameters. For example: ``` def f1() : pass def f2(param1...
You could try something like: ``` getattr(foo, bar)(*params) ``` This works if `params` is a list or a tuple. The elements from `params` will be unpacked in order: ``` params=(1, 2) foo(*params) ``` is equivalent to: ``` params=(1, 2) foo(params[0], params[1]) ``` If there are keyword arguments, you can do that t...
Python OpenCV Contour tree hierarchy
11,782,147
5
2012-08-02T16:48:18Z
11,807,675
7
2012-08-04T10:03:26Z
[ "python", "opencv" ]
I am trying to implement the algorithm found [here](http://www.m.cs.osakafu-u.ac.jp/cbdar2007/proceedings/papers/O1-1.pdf) in python with OpenCV. I am new to OpenCV so bare with me. I am trying to implement the part of the algorithm that remove irrelevant edge boundaries based on the number of interior boundaries that...
The main confusion here is probably the fact that the hierarchy returned is a numpy array with more dimensions than necessary. On top of that, it looks like the Python FindContours function returns a tuple that is a LIST of contours, and and NDARRAY of the hierarchy... You can get a sensible array of hierarchy informa...
Can I execute ipython scripts?
11,782,744
6
2012-08-02T17:29:59Z
11,783,567
12
2012-08-02T18:26:52Z
[ "python", "ipython" ]
Is there a way to execute ipython scripts? I don't mean python scripts, but with simplified syntax as it would be entered into the ipython shell
sure, just run them with IPython as you with Python for a plain Python script: ``` $> echo '%time print "hello, world"' > script.ipy $> ipython script.ipy hello, world CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s Wall time: 0.00 s ```
Is there an easy way to make sessions timeout in flask?
11,783,025
34
2012-08-02T17:49:19Z
11,785,722
53
2012-08-02T21:01:53Z
[ "python", "session", "timeout", "flask" ]
I'm building a website with flask where users have accounts and are able to login. I'm using flask-principal for the loging in part and the role management. Is there a way of making the user's session expire after say 5 minutes or 10 minutes? I was not able to find that in flask documentation or, flask-principal's docu...
flask sessions expire once you close the browser unless you have a permanent session. You can possibly try the following: ``` from datetime import timedelta from flask import session, app @app.before_request def make_session_permanent(): session.permanent = True app.permanent_session_lifetime = timedelta(minu...
python httplib/urllib get filename
11,783,269
8
2012-08-02T18:05:51Z
11,783,319
20
2012-08-02T18:09:32Z
[ "python", "urllib", "httplib" ]
is there a possibillity to get the filename ``` e.g. xyz.com/blafoo/showall.html ``` if you work with urllib or httplib? so that i can save the file under the filename on the server? if you go to sites like ``` xyz.com/blafoo/ ``` you cant see the filename. Thank you
To get filename from response http headers: ``` import cgi response = urllib2.urlopen(URL) _, params = cgi.parse_header(response.headers.get('Content-Disposition', '')) filename = params['filename'] ``` To get filename from the URL: ``` import posixpath import urlparse path = urlparse.urlsplit(URL).path filename ...
ImportError: No Module Named bs4 (BeautifulSoup)
11,783,875
58
2012-08-02T18:47:00Z
11,784,778
93
2012-08-02T19:52:18Z
[ "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.
Activate the virtualenv, and then install BeautifulSoup4: ``` $ pip install BeautifulSoup4 ``` When you installed `bs4` with `easy_install`, you installed it system-wide. So your system python can import it, but not your virtualenv python. If you do not need `bs4` to be installed in your system python path, uninstall...