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
Catching a 500 server error in Flask
14,993,318
24
2013-02-21T01:54:52Z
15,004,612
20
2013-02-21T14:22:19Z
[ "python", "flask" ]
I love Flask's error catching. It's beautifully simple: ``` @app.errorhandler(404) def pageNotFound(error): return "page not found" ``` works like charm. But it doesn't work for the 500 error code. I want to catch Python errors when something goes wrong an exception is raised in the code. Is that possible? I sho...
What you have described is, by default, how Flask works. My assumption is that you are running in debug mode, and therefore exceptions are being shown to you in the debug screen. Make sure debug mode is off, then try again. Here is a [comment directly from the code itself:](https://github.com/mitsuhiko/flask/blob/2ab91...
Catching a 500 server error in Flask
14,993,318
24
2013-02-21T01:54:52Z
28,738,343
9
2015-02-26T09:13:01Z
[ "python", "flask" ]
I love Flask's error catching. It's beautifully simple: ``` @app.errorhandler(404) def pageNotFound(error): return "page not found" ``` works like charm. But it doesn't work for the 500 error code. I want to catch Python errors when something goes wrong an exception is raised in the code. Is that possible? I sho...
here is my code snippt ``` @app.route('/') def index(): raise Exception("Can't connect to database") @app.errorhandler(Exception) def exception_handler(error): return "!!!!" + repr(error) ```
How to deserialize the datetime in a json object in python?
14,995,743
2
2013-02-21T06:14:33Z
14,996,040
7
2013-02-21T06:37:07Z
[ "python", "json", "datetime" ]
My original dictionary is ``` A = { 'date': datetime.date(2013, 1, 1), 'price': 100 } ``` Since `datetime.date` is not serializable, I add a default function to deal with that: ``` B = json.dumps(A, default=lamb...
``` from datetime import datetime def load_with_datetime(pairs, format='%Y-%m-%d'): """Load with dates""" d = {} for k, v in pairs: if isinstance(v, basestring): try: d[k] = datetime.strptime(v, format).date() except ValueError: d[k] = v ...
Python libraries to calculate human readable filesize from bytes?
14,996,453
6
2013-02-21T07:08:06Z
14,996,816
18
2013-02-21T07:31:45Z
[ "python", "python-module" ]
I find `hurry.filesize` very useful but it doesn't give output in decimal? For example: ``` print size(4026, system=alternative) gives 3 KB. ``` But later when I add all the values I don't get the exact sum. For example if the output of `hurry.filesize` is in 4 variable and each value is 3. If I add them all, I get ...
This isn't really hard to implement yourself: ``` suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'] def humansize(nbytes): if nbytes == 0: return '0 B' i = 0 while nbytes >= 1024 and i < len(suffixes)-1: nbytes /= 1024. i += 1 f = ('%.2f' % nbytes).rstrip('0').rstrip('.') return '%s %s...
How to make eclipse/pydev happy to see flask extensions on windows?
14,997,336
8
2013-02-21T08:07:16Z
21,783,469
23
2014-02-14T15:39:20Z
[ "python", "eclipse", "flask", "pydev", "flask-extensions" ]
I stumbled upon [this article](http://blog.jasongiedymin.com/post/3855004203/make-eclipse-pydev-happy-to-see-flask-flask-extensions) and followed all steps. But pyDev won't see my flask extensions and that's really annoying. There's only one thing (and I think this is the key): `Touch /site-packages/flaskext/__init__....
The Eclipse uses static analysis of modules by default. `flask.ext` builds import list dynamically. To force dynamic analysis using Python shell add `flask.ext` to forced builtins list. Go to `Preferences -> PyDev -> Interpreters -> Python Interpreter`. Select your interpreter, go to `Forced Builtins` tab. Click `New....
Advanced square detection (with connected region)
14,997,733
7
2013-02-21T08:34:53Z
15,004,457
9
2013-02-21T14:14:59Z
[ "python", "opencv", "image-processing", "computer-vision", "object-detection" ]
if the squares has connected region in image, how can I detect them. I have tested the method mentioned in [OpenCV C++/Obj-C: Advanced square detection](http://stackoverflow.com/questions/10533233/opencv-c-obj-c-advanced-square-detection) It did not work well. Any good ideas ? ![squares that has Connected region](h...
Applying a Watershed Transform based on the Distance Transform will separate the objects: ![enter image description here](http://i.stack.imgur.com/3MT86.png) Handling objects at the border is always problematic, and often discarded, so that pink rectangle at top left not separated is not a problem at all. Given a bi...
Python: How to insert return inside if __name__ == main?
15,000,883
2
2013-02-21T11:17:23Z
15,000,927
13
2013-02-21T11:19:50Z
[ "python", "function", "return" ]
This gives error: ``` if __name__=="__main__": box = Myfunc() box.do(1) if box.loop() <> Drh.DrhOk: return else: ... ... ``` SyntaxError: 'return' outside function How do I return `if __name__=="__main__":` block?
You don't. Your `__main__` block should always read: ``` if __name__ == "__main__": main() ``` Putting your code inside a `main()` function ensures that it is testable.
why does my colorbar have lines in it?
15,003,353
27
2013-02-21T13:22:29Z
15,021,541
18
2013-02-22T10:06:01Z
[ "python", "matplotlib", "matplotlib-basemap" ]
**Edit**: Since this seems to be a popular post, here's the solution that seems to be working well for me. Thanks @gazzar and @mfra. ``` cbar.solids.set_rasterized(True) cbar.solids.set_edgecolor("face") ``` --- Does anyone know why my colorbar has what appear to be lines in it? Or rather why is the color transition...
In case you create vector graphics, have you tried this (taken from <http://matplotlib.org/api/pyplot_api.html?highlight=colorbar#matplotlib.pyplot.colorbar>): "It is known that some vector graphics viewer (svg and pdf) renders white gaps between segments of the colorbar. This is due to bugs in the viewers not matplot...
why does my colorbar have lines in it?
15,003,353
27
2013-02-21T13:22:29Z
25,329,113
7
2014-08-15T15:17:00Z
[ "python", "matplotlib", "matplotlib-basemap" ]
**Edit**: Since this seems to be a popular post, here's the solution that seems to be working well for me. Thanks @gazzar and @mfra. ``` cbar.solids.set_rasterized(True) cbar.solids.set_edgecolor("face") ``` --- Does anyone know why my colorbar has what appear to be lines in it? Or rather why is the color transition...
I generally prefer to rasterize the colorbar contents to avoid this issue using Eric Firing's advice [here](http://matplotlib.1069221.n5.nabble.com/rasterized-colorbar-td39582.html) by adding the following line. ``` cbar.solids.set_rasterized(True) ``` This workaround supposedly fails for images with transparency, bu...
What is the difference between chain and chain.from_iterable in itertools?
15,004,772
34
2013-02-21T14:29:14Z
15,004,794
38
2013-02-21T14:30:20Z
[ "python", "iterator", "itertools" ]
I could not find any valid example on the internet where I can see the difference between them and why to choose one over the other.
The first takes a list of iterables, the second one takes the sequence from another iterable: ``` itertools.chain(list1, list2, list3) iterables = [list1, list2, list3] itertools.chain.from_iterable(iterables) ``` but `iterables` can be any iterator that yields the iterables. ``` def generate_iterables(): for i...
What is the most pythonic way of logging for multiple modules and multiple handlers with specified encoding?
15,005,478
3
2013-02-21T15:03:18Z
15,011,351
8
2013-02-21T20:13:23Z
[ "python", "logging", "character-encoding", "module" ]
I'm looking for concrete advice about how the multiple module and multiple handler logging should be done. I have added my simplified code here, but I don't want to bias the answers - tell me what the best practice is. I would like to log everything to a file, and warn and above to console. This is my `level0.py` whi...
For modules consisting of many parts, I use the method recommended in the [documentation](http://docs.python.org/2/howto/logging.html#logging-advanced-tutorial), which just has one line per module, `logger = logging.getLogger(__name__)`. As you point out, the module shouldn't know or care how or where its messages are ...
Dynamically rethrowing self-defined C++ exceptions as Python exceptions using SWIG
15,006,048
21
2013-02-21T15:30:35Z
15,025,798
8
2013-02-22T13:54:45Z
[ "c++", "python", "exception", "reflection", "swig" ]
**Situation** I want to create a Python language binding for a C++ API using SWIG. Some of the API functions may throw exceptions. The C++ application has a hierarchy of self-defined exceptions, like this example: ``` std::exception -> API::Exception -> API::NetworkException -> API::TimeoutException ...
It looks like someone has answered your basic question over on the swig-user list... ``` %exception { try { $action } catch (MyException &_e) { SWIG_Python_Raise(SWIG_NewPointerObj( (new MyException(static_cast<const MyException& >(_e))), SWIGTYPE_p_MyException,SWIG_POINTER_OWN), ...
How to preview a part of a large pandas DataFrame?
15,006,298
21
2013-02-21T15:42:05Z
15,006,495
25
2013-02-21T15:50:02Z
[ "python", "pandas", "dataframe", "ipython", "ipython-notebook" ]
I am just getting started with pandas in the IPython Notebook and encountering the following problem: When a `DataFrame` read from a CSV file is small, the IPython Notebook displays it in a nice table view. When the `DataFrame` is large, something like this is ouput: ``` In [27]: evaluation = readCSV("evaluation_MO_w...
In this case, where the `DataFrame` is long but not too wide, you can simply slice it: ``` >>> df = pd.DataFrame({"A": range(1000), "B": range(1000)}) >>> df <class 'pandas.core.frame.DataFrame'> Int64Index: 1000 entries, 0 to 999 Data columns: A 1000 non-null values B 1000 non-null values dtypes: int64(2) >>>...
How to preview a part of a large pandas DataFrame?
15,006,298
21
2013-02-21T15:42:05Z
15,786,557
13
2013-04-03T11:49:52Z
[ "python", "pandas", "dataframe", "ipython", "ipython-notebook" ]
I am just getting started with pandas in the IPython Notebook and encountering the following problem: When a `DataFrame` read from a CSV file is small, the IPython Notebook displays it in a nice table view. When the `DataFrame` is large, something like this is ouput: ``` In [27]: evaluation = readCSV("evaluation_MO_w...
I write a method to show the four corners of the data and monkey-patch to dataframe to do so: ``` def _sw(df, up_rows=10, down_rows=5, left_cols=4, right_cols=3, return_df=False): ''' display df data at four corners A,B (up_pt) C,D (down_pt) parameters : up_rows=10, down_rows=5, left_cols=4...
How to preview a part of a large pandas DataFrame?
15,006,298
21
2013-02-21T15:42:05Z
25,959,539
18
2014-09-21T13:09:56Z
[ "python", "pandas", "dataframe", "ipython", "ipython-notebook" ]
I am just getting started with pandas in the IPython Notebook and encountering the following problem: When a `DataFrame` read from a CSV file is small, the IPython Notebook displays it in a nice table view. When the `DataFrame` is large, something like this is ouput: ``` In [27]: evaluation = readCSV("evaluation_MO_w...
``` # Say you have a df object containing your dataframe df.head(5) # will print out the first 5 rows df.tail(5) # will print out the 5 last rows # Note: it is similar to R ```
chr for non-ASCII characters in Python
15,006,771
6
2013-02-21T16:02:20Z
15,006,993
13
2013-02-21T16:12:03Z
[ "python", "unicode" ]
I'm trying to implement a search through a list of strings, in a context where there's no way to use something like `str.startswith` (If you're curious about it, I'm querying the app engine datastore.) I'd like to look for every string that has a certain prefix, let's say 'py'. I have comparison operators at my dispos...
Perhaps use [unichr()](https://docs.python.org/2/library/functions.html#unichr), this function will be worked
Deleting carriage returns caused by line reading
15,007,637
7
2013-02-21T16:41:40Z
15,007,662
10
2013-02-21T16:42:32Z
[ "python", "python-2.7" ]
I have a list: ``` Cat Dog Monkey Pig ``` I have a script: ``` import sys input_file = open('list.txt', 'r') for line in input_file: sys.stdout.write('"' + line + '",') ``` The output is: ``` "Cat ","Dog ","Monkey ","Pig", ``` I'd like: ``` "Cat","Dog","Monkey","Pig", ``` I can't get rid of the carriage ret...
[str.rstrip](http://docs.python.org/2/library/stdtypes.html#str.rstrip) or simply [str.strip](http://docs.python.org/2/library/stdtypes.html#str.strip) is the right tool to split carriage return (newline) from the data read from the file. Note str.strip will strip of whitespaces from either end. If you are only interes...
parsing boolean values with argparse
15,008,758
153
2013-02-21T17:37:16Z
15,008,806
239
2013-02-21T17:40:24Z
[ "python", "boolean", "argparse", "command-line-parsing" ]
I would like to use argparse to parse boolean command-line arguments written as "--foo True" or "--foo False". For example: ``` my_program --my_boolean_flag False ``` However, the following test code does not do what I would like: ``` import argparse parser = argparse.ArgumentParser(description="My parser") parser.a...
I think a more canonical way to do this is via: ``` command --feature ``` and ``` command --no-feature ``` `argparse` supports this version nicely: ``` parser.add_argument('--feature', dest='feature', action='store_true') parser.add_argument('--no-feature', dest='feature', action='store_false') parser.set_defaults...
parsing boolean values with argparse
15,008,758
153
2013-02-21T17:37:16Z
19,227,287
12
2013-10-07T14:20:38Z
[ "python", "boolean", "argparse", "command-line-parsing" ]
I would like to use argparse to parse boolean command-line arguments written as "--foo True" or "--foo False". For example: ``` my_program --my_boolean_flag False ``` However, the following test code does not do what I would like: ``` import argparse parser = argparse.ArgumentParser(description="My parser") parser.a...
I was looking for the same issue, and imho the pretty solution is : ``` def str2bool(v): return v.lower() in ("yes", "true", "t", "1") ``` and using that to parse the string to boolean as suggested above.
parsing boolean values with argparse
15,008,758
153
2013-02-21T17:37:16Z
19,233,287
20
2013-10-07T19:45:21Z
[ "python", "boolean", "argparse", "command-line-parsing" ]
I would like to use argparse to parse boolean command-line arguments written as "--foo True" or "--foo False". For example: ``` my_program --my_boolean_flag False ``` However, the following test code does not do what I would like: ``` import argparse parser = argparse.ArgumentParser(description="My parser") parser.a...
There seems to be some confusion as to what `type=bool` and `type='bool'` might mean. Should one (or both) mean 'run the function `bool()`, or 'return a boolean'? As it stands `type='bool'` means nothing. `add_argument` gives a `'bool' is not callable` error, same as if you used `type='foobar'`, or `type='int'`. But `...
parsing boolean values with argparse
15,008,758
153
2013-02-21T17:37:16Z
22,704,123
9
2014-03-28T04:20:17Z
[ "python", "boolean", "argparse", "command-line-parsing" ]
I would like to use argparse to parse boolean command-line arguments written as "--foo True" or "--foo False". For example: ``` my_program --my_boolean_flag False ``` However, the following test code does not do what I would like: ``` import argparse parser = argparse.ArgumentParser(description="My parser") parser.a...
In addition to what @mgilson said, it should be noted that there's also a [`ArgumentParser.add_mutually_exclusive_group(required=False)`](http://docs.python.org/dev/library/argparse.html#mutual-exclusion) method that would make it trivial to enforce that `--flag` and `--no-flag` aren't used at the same time.
parsing boolean values with argparse
15,008,758
153
2013-02-21T17:37:16Z
31,347,222
40
2015-07-10T17:52:29Z
[ "python", "boolean", "argparse", "command-line-parsing" ]
I would like to use argparse to parse boolean command-line arguments written as "--foo True" or "--foo False". For example: ``` my_program --my_boolean_flag False ``` However, the following test code does not do what I would like: ``` import argparse parser = argparse.ArgumentParser(description="My parser") parser.a...
I recommend mgilson's answer but with a mutally exclusive group so that you cannot use `--feature` and `--no-feature` at the same time. ``` command --feature ``` and ``` command --no-feature ``` but not ``` command --feature --no-feature ``` Script: ``` feature_parser = parser.add_mutually_exclusive_group(requ...
How to have image + text in one button in Tkinter
15,009,117
6
2013-02-21T17:58:02Z
15,009,738
14
2013-02-21T18:33:02Z
[ "python", "image", "button", "text", "tkinter" ]
I´m trying to create a button, which will include an image aligned to the left and text aligned to the right. I just want to change text by parameter "text", not by modifying whole image. Is this possible somehow? Here´s a simple example, what I mean. <http://img651.imageshack.us/img651/3776/previewrv.png> Hope I ...
Look at the `compound` option to the label. It lets you specify the relationship of the label to the text (top, bottom, left, right, none). For example: ``` import Tkinter as tk class View(tk.Frame): def __init__(self, *args, **kwargs): tk.Frame.__init__(self, *args, **kwargs) self.image = tk.Pho...
How to use NLTK to generate sentences from an induced grammar?
15,009,656
10
2013-02-21T18:27:37Z
15,617,664
10
2013-03-25T14:39:05Z
[ "python", "nlp", "nltk" ]
I have a (large) list of parsed sentences (which were parsed using the Stanford parser), for example, the sentence "Now you can be entertained" has the following tree: ``` (ROOT (S (ADVP (RB Now)) (, ,) (NP (PRP you)) (VP (MD can) (VP (VB be) (VP (VBN entertained)))) (. .))) ``` I ...
In NLTK 2.0 you can use nltk.parse.generate to generate *all* possible sentences for a given grammar (<http://nltk.org/_modules/nltk/parse/generate.html>). This code defines a function which should generate a single sentence based on the production rules in a (P)CFG. ``` # This example uses choice to choose from poss...
parsing json array in python
15,010,418
6
2013-02-21T19:14:35Z
15,010,485
8
2013-02-21T19:19:32Z
[ "python", "json" ]
I'm trying to parse some data in python I have some json: ``` { "data sources": [ "http://www.gcmap.com/" ], "metros": [ { "code": "SCL", "continent": "South America", "coordinates": { "S": 33, "W": 71 }, ...
If you always get the same keys, you can use `**` to easily construct your instances. Making the `Metro` a `namedtuple` will simplify your life if you are using it simply to hold values: ``` from collections import namedtuple Metro = namedtuple('Metro', 'code, name, country, continent, timezone, coordinates, populatio...
Python Module Import: Single-line vs Multi-line
15,011,367
12
2013-02-21T20:14:38Z
15,011,456
23
2013-02-21T20:20:09Z
[ "python", "module" ]
So this is just a simple question. In python when importing modules, what is the difference between this: ``` from module import a, b, c, d ``` and this ``` from module import a from module import b from module import c from module import d ``` To me it makes sense always to condense code and use the first example,...
There is no difference at all. They both function exactly the same. However, from a stylistic perspective, one might be more preferable than the other. And on that note, the [PEP-8 for imports](http://www.python.org/dev/peps/pep-0008/#imports) says that you should compress `from module import name1, name2` onto a sing...
Splitting on last delimiter in Python string?
15,012,228
43
2013-02-21T21:06:15Z
15,012,237
80
2013-02-21T21:06:55Z
[ "python", "string", "list", "parsing", "split" ]
What's the recommended Python idiom for splitting a string on the *last* occurrence of the delimiter in the string? example: ``` # instead of regular split >> s = "a,b,c,d" >> s.split(",") >> ['a', 'b', 'c', 'd'] # ..split only on last occurrence of ',' in string: >>> s.mysplit(s, -1) >>> ['a,b,c', 'd'] ``` `mysplit...
Use [`.rsplit()`](http://docs.python.org/2/library/stdtypes.html#str.rsplit) instead: ``` s.rsplit(',', 1) ``` Demo: ``` >>> s = "a,b,c,d" >>> s.rsplit(',', 1) ['a,b,c', 'd'] >>> s.rsplit(',', 2) ['a,b', 'c', 'd'] ``` This method starts splitting from the right-hand-side of the string; by giving it a maximum, you g...
Close pre-existing figures in matplotlib when running from eclipse
15,012,309
27
2013-02-21T21:11:10Z
15,012,716
37
2013-02-21T21:39:02Z
[ "python", "numpy", "matplotlib", "pydev", "matlab-figure" ]
My question is simple: I have a python script that generates figures using matplotlib. Every time i run it it generates new windows with figures. How can I have the script close windows that were opened the previous time it ran? the analogous command in matlab is to put 'close all' at the beginning of your matlab scri...
You can close a figure by calling `matplotlib.pyplot.close`, for example: ``` from numpy import * import matplotlib.pyplot as plt from scipy import * t = linspace(0, 0.1,1000) w = 60*2*pi fig = plt.figure() plt.plot(t,cos(w*t)) plt.plot(t,cos(w*t-2*pi/3)) plt.plot(t,cos(w*t-4*pi/3)) plt.show() plt.close(fig) ``` Y...
mongoengine - query how to filter by ListField size
15,013,438
7
2013-02-21T22:26:44Z
21,073,860
7
2014-01-12T11:02:35Z
[ "python", "mongodb", "mongoengine", "mongodb-query" ]
I have the following model: ``` class Like(EmbeddedDocument): user = ReferenceField(User,dbref=False) date = DateTimeField(default=datetime.utcnow,required=True) meta = {'allow_inheritance': False} class Post(Document): name = StringField(max_length=120, required=True) likes = ListField(EmbeddedDocu...
Far from being the perfect solution, but you can do with a raw mongo query and the [$where](http://docs.mongodb.org/manual/reference/operator/query/where/#op._S_where) operator, for example: ``` posts = Post.objects.filter(__raw__={'$where': 'this.likes.length > 20'}) ``` Another option, which should work faster, but...
Python: Sum values in a dictionary based on condition
15,014,276
4
2013-02-21T23:33:33Z
15,014,319
8
2013-02-21T23:38:22Z
[ "python", "python-3.x" ]
I have a dictionary that has `Key:Values.` The values are integers. I would like to get a sum of the values based on a condition...say all values > 0 (i.e). I've tried few variations, but nothing seems to work unfortunately.
Try using the `values` method on the dictionary (which returns a generator in Python 3.x), iterating through each value and summing if it is greater than 0 (or whatever your condition is): ``` In [1]: d = {'one': 1, 'two': 2, 'twenty': 20, 'negative 4': -4} In [2]: sum(v for v in d.values() if v > 0) Out[2]: 23 ```
Why is there no xrange function in Python3?
15,014,310
97
2013-02-21T23:36:54Z
15,014,361
7
2013-02-21T23:42:07Z
[ "python", "python-3.x", "pep", "xrange" ]
Recently I started using Python3 and it's lack of xrange hurts. Simple example: **1)** Python2: ``` from time import time as t def count(): st = t() [x for x in xrange(10000000) if x%4 == 0] et = t() print et-st count() ``` **2)** Python3: ``` from time import time as t def xrange(x): return iter(ran...
Python 3's `range` type works just like Python 2's `xrange`. I'm not sure why you're seeing a slowdown, since the iterator returned by your `xrange` function is exactly what you'd get if you iterated over `range` directly. I'm not able to reproduce the slowdown on my system. Here's how I tested: Python 2, with `xrang...
Why is there no xrange function in Python3?
15,014,310
97
2013-02-21T23:36:54Z
15,014,576
78
2013-02-22T00:03:10Z
[ "python", "python-3.x", "pep", "xrange" ]
Recently I started using Python3 and it's lack of xrange hurts. Simple example: **1)** Python2: ``` from time import time as t def count(): st = t() [x for x in xrange(10000000) if x%4 == 0] et = t() print et-st count() ``` **2)** Python3: ``` from time import time as t def xrange(x): return iter(ran...
Some performance measurements, using `timeit` instead of trying to do it manually with `time`. First, Apple 2.7.2 64-bit: ``` In [37]: %timeit collections.deque((x for x in xrange(10000000) if x%4 == 0), maxlen=0) 1 loops, best of 3: 1.05 s per loop ``` Now, python.org 3.3.0 64-bit: ``` In [83]: %timeit collections...
Why is there no xrange function in Python3?
15,014,310
97
2013-02-21T23:36:54Z
15,015,199
56
2013-02-22T01:09:29Z
[ "python", "python-3.x", "pep", "xrange" ]
Recently I started using Python3 and it's lack of xrange hurts. Simple example: **1)** Python2: ``` from time import time as t def count(): st = t() [x for x in xrange(10000000) if x%4 == 0] et = t() print et-st count() ``` **2)** Python3: ``` from time import time as t def xrange(x): return iter(ran...
Python3's range *is* Python2's xrange. There's no need to wrap an iter around it. To get an actual list in Python3, you need to use `list(range(...))` If you want something that works with Python2 and Python3, try this ``` try: xrange except NameError: xrange = range ```
django - model unicode() show foreignkey object attribute
15,015,253
9
2013-02-22T01:15:45Z
15,015,491
8
2013-02-22T01:41:47Z
[ "python", "django", "django-models", "python-2.7", "django-admin" ]
I'm new to Django and have an Application model and a Environment model. The Environment has the Application as a foreignkey. I know that I need to write a **unicode**() method for a human-readable representation of the model, but is there a way to get an attribute from the foreignkey object to display as part of the s...
You can indeed, by referring to the attribute using the 'dot' syntax. Here is what you want: ``` def __unicode__(self): return '%s %s' % (self.app_id.app_name, self.environ_name) ```
Is there any single function to print iterables values
15,015,452
2
2013-02-22T01:36:14Z
15,015,470
7
2013-02-22T01:38:40Z
[ "python" ]
Suppose i have the any iterable `var = "ABCDEF"` I get the iterable like this `it = itertools.combinations(var,2)` is there any single function to print all values of iterables like `printall(it)` rather than using the for loop
This rather depends what you want, if you want to print out all the values, you need to compute them - an iterable doesn't guarantee the values are computed until after they are all requested, so the easiest way to achieve this is to [make a list](http://docs.python.org/3/library/functions.html#func-list): ``` print(l...
How to print the LDA topics models from gensim? Python
15,016,025
10
2013-02-22T02:47:42Z
15,016,117
10
2013-02-22T03:00:39Z
[ "python", "nlp", "lda", "topic-modeling", "gensim" ]
Using `gensim` I was able to extract topics from a set of documents in LSA but how do I access the topics generated from the LDA models? When printing the `lda.print_topics(10)` the code gave the following error because `print_topics()` return a `NoneType`: ``` Traceback (most recent call last): File "/home/alvas/w...
After some messing around, it seems like `print_topics(numoftopics)` for the `ldamodel` has some bug. So my workaround is to use `print_topic(topicid)`: ``` >>> print lda.print_topics() None >>> for i in range(0, lda.num_topics-1): >>> print lda.print_topic(i) 0.083*response + 0.083*interface + 0.083*time + 0.083*hum...
running imagemagick convert (console application) from python
15,016,974
2
2013-02-22T04:42:41Z
15,017,247
7
2013-02-22T05:07:09Z
[ "python", "python-3.x", "imagemagick", "subprocess", "imagemagick-convert" ]
I am trying to rasterize some fonts using imagemagick with this command which works fine from a terminal: ``` convert -size 30x40 xc:white -fill white -fill black -font "fonts\Helvetica Regular.ttf" -pointsize 40 -gravity South -draw "text 0,0 'O'" draw_text.gif ``` Running the same command using subprocess to automa...
I figured it out: It turns out that **windows has its own `convert.exe` program in `PATH`**. The following code prints `b'C:\\Windows\\System32\\convert.exe\r\n'`: ``` try: print(subprocess.check_output(["where",'convert'],stderr=subprocess.STDOUT,shell=True)) except CalledProcessError as e: print(e) prin...
pandas read_csv and filter columns with usecols
15,017,072
29
2013-02-22T04:50:55Z
15,030,455
7
2013-02-22T18:04:28Z
[ "python", "pandas" ]
I have a csv file which isn't coming in correctly with `pandas.read_csv` when I filter the columns with `usecols` and use multiple indexes. ``` import pandas as pd csv = r"""dummy,date,loc,x bar,20090101,a,1 bar,20090102,a,3 bar,20090103,a,5 bar,20090101,b,1 bar,20090102,b,3 bar,20090103,b,5""" f = open('foo.csv', 'w'...
This code achieves what you want --- also its weird and certainly buggy: I observed that it works when: a) you specify the `index_col` rel. to the number of columns you really use -- so its three columns in this example, not four (you drop `dummy` and start counting from then onwards) b) same for `parse_dates` c) n...
pandas read_csv and filter columns with usecols
15,017,072
29
2013-02-22T04:50:55Z
15,100,193
7
2013-02-26T22:01:28Z
[ "python", "pandas" ]
I have a csv file which isn't coming in correctly with `pandas.read_csv` when I filter the columns with `usecols` and use multiple indexes. ``` import pandas as pd csv = r"""dummy,date,loc,x bar,20090101,a,1 bar,20090102,a,3 bar,20090103,a,5 bar,20090101,b,1 bar,20090102,b,3 bar,20090103,b,5""" f = open('foo.csv', 'w'...
If your csv file contains extra data, columns can be [deleted](http://pandas.pydata.org/pandas-docs/dev/dsintro.html#column-selection-addition-deletion) from the DataFrame after import. ``` import pandas as pd from StringIO import StringIO csv = r"""dummy,date,loc,x bar,20090101,a,1 bar,20090102,a,3 bar,20090103,a,5 ...
pandas read_csv and filter columns with usecols
15,017,072
29
2013-02-22T04:50:55Z
27,791,362
20
2015-01-06T02:47:26Z
[ "python", "pandas" ]
I have a csv file which isn't coming in correctly with `pandas.read_csv` when I filter the columns with `usecols` and use multiple indexes. ``` import pandas as pd csv = r"""dummy,date,loc,x bar,20090101,a,1 bar,20090102,a,3 bar,20090103,a,5 bar,20090101,b,1 bar,20090102,b,3 bar,20090103,b,5""" f = open('foo.csv', 'w'...
The answer by @chip completely misses the point of two keyword arguments. * **names** is only necessary when there is no header and you want to specify other arguments using column names rather than integer indices. * **usecols** is supposed to provide a filter before reading the whole DataFrame into memory; if used p...
Using static methods in python - best practice
15,017,734
9
2013-02-22T05:49:46Z
15,017,939
8
2013-02-22T06:08:28Z
[ "python", "coding-style", "static-methods" ]
When and how are static methods suppose to be used in python? We have already established using a class method as factory method to create an instance of an object should be avoided when possible. In other words, it is not best practice to use class methods as an alternate constructor (See [Factory method for python ob...
The answer to the linked question specifically says this: > A @classmethod is the idiomatic way to do an "alternate constructor"—there are examples all over the stdlib—itertools.chain.from\_iterable, datetime.datetime.fromordinal, etc. So I don't know how you got the idea that using a classmethod is inherently ba...
Using static methods in python - best practice
15,017,734
9
2013-02-22T05:49:46Z
15,031,999
10
2013-02-22T19:42:24Z
[ "python", "coding-style", "static-methods" ]
When and how are static methods suppose to be used in python? We have already established using a class method as factory method to create an instance of an object should be avoided when possible. In other words, it is not best practice to use class methods as an alternate constructor (See [Factory method for python ob...
> When and how are static methods suppose to be used in python? The glib answer is: Not very often. The even glibber but not quite as useless answer is: When they make your code more readable. --- First, let's take a detour to [the docs](http://docs.python.org/2/library/functions.html#staticmethod): > Static metho...
How to take partial screenshot with Selenium WebDriver in python?
15,018,372
21
2013-02-22T06:41:47Z
15,870,708
49
2013-04-08T03:16:37Z
[ "python", "selenium" ]
I have searched a lot for this but couldn't find a solution. Here's [a similar question](http://stackoverflow.com/questions/10848900/how-to-take-partial-screenshot-frame-with-selenium-webdriver) with a possible solution in java. Is there a similar solution in Python?
This question seems to have gone a long time without an answer, but having just worked on it I thought I would pass on some of the things I've learned Note: Other than Selenium this example also requires the PIL Imaging library. Sometimes this is put in as one of the standard libraries and sometimes it's not, but if y...
Python timeout context manager with threads
15,018,519
7
2013-02-22T06:54:18Z
15,190,306
7
2013-03-03T20:12:09Z
[ "python", "timeout", "contextmanager", "time-limiting" ]
I have `timeout` context manager that works perfectly with signals but it raises error in multithread mode because signals work only in main thread. ``` def timeout_handler(signum, frame): raise TimeoutException() @contextmanager def timeout(seconds): old_handler = signal.signal(signal.SIGALRM, timeout_handle...
If the code guarded by the context manager is loop-based, consider handling this the way people handle thread killing. Killing another thread is generally unsafe, so the standard approach is to have the controlling thread set a flag that's visible to the worker thread. The worker thread periodically checks that flag an...
Check if object is a number or boolean
15,019,830
14
2013-02-22T08:28:31Z
15,019,884
22
2013-02-22T08:33:49Z
[ "python", "python-2.7" ]
> Design a logical expression equivalent to the following statement: > > `x` is a list of three or five elements, the second element of which is > the string `'Hip'` and the first of which is not a number or Boolean. What I have: ``` x = ['Head', 'Hip', 10] print x[1] is 'Hip' ``` My question: How do you check for w...
To answer the specific question: ``` isinstance(x[0], (int, float)) ``` This checks if `x[0]` is an instance of any of the types in the tuple `(int, float)`. You can add `bool` in there, too, but it's not necessary, because `bool` is itself a subclass of `int`. Doc reference: * [`isinstance()`](http://docs.python....
Check if object is a number or boolean
15,019,830
14
2013-02-22T08:28:31Z
34,613,329
8
2016-01-05T13:51:47Z
[ "python", "python-2.7" ]
> Design a logical expression equivalent to the following statement: > > `x` is a list of three or five elements, the second element of which is > the string `'Hip'` and the first of which is not a number or Boolean. What I have: ``` x = ['Head', 'Hip', 10] print x[1] is 'Hip' ``` My question: How do you check for w...
Easiest i would say: ``` type(x) == type(True) ```
Python: split list of integers based on step between them
15,019,889
5
2013-02-22T08:34:06Z
15,019,976
7
2013-02-22T08:40:35Z
[ "python", "list", "split", "integer", "indices" ]
I have the following problem. Having a list of integers, I want to split it, into a list of lists, whenever the step between two elements of the original input list is not 1. For example: input = [0, 1, 3, 5, 6, 7], output = [[0, 1], [3], [5, 6, 7]] I wrote the following function, but it's uggly as hell, and I was won...
This works with any iterable ``` >>> from itertools import groupby, count >>> inp = [0, 1, 3, 5, 6, 7] >>> [list(g) for k, g in groupby(inp, key=lambda i,j=count(): i-next(j))] [[0, 1], [3], [5, 6, 7]] ```
Configuring Flask-SQLAlchemy to use multiple databases with Flask-Restless
15,021,292
8
2013-02-22T09:52:14Z
15,027,619
9
2013-02-22T15:32:49Z
[ "python", "flask", "flask-sqlalchemy" ]
I have a Flask app that uses Flask-SQLAlchemy and I'm trying to configure it to use multiple databases with the Flask-Restless package. According to the docs (<http://pythonhosted.org/Flask-SQLAlchemy/binds.html>), configuring your models to use multiple databases with `__bind_key__` seems pretty straightforward. How...
This was not working because of a simple typo: ``` __bind_key = 'db1' ``` Should have been ``` __bind_key__ = 'db1' ``` I've updated the original question and fixed the typo as an example of how this can work for others.
How to encode a categorical variable in sklearn?
15,021,521
10
2013-02-22T10:05:17Z
15,038,477
13
2013-02-23T08:02:11Z
[ "python", "machine-learning", "scikit-learn" ]
I'm trying to use the car evaluation dataset from the UCI repository and I wonder whether there is a convenient way to binarize categorical variables in sklearn. One approach would be to use the DictVectorizer of LabelBinarizer but here I'm getting k different features whereas you should have just k-1 in order to avoid...
DictVectorizer is the recommended way to generate a one-hot encoding of categorical variables; you can use the `sparse` argument to create a sparse CSR matrix instead of a dense numpy array. I usually don't care about multicollinearity and I haven't noticed a problem with the approaches that I tend to use (i.e. LinearS...
How to encode a categorical variable in sklearn?
15,021,521
10
2013-02-22T10:05:17Z
18,078,977
15
2013-08-06T11:29:38Z
[ "python", "machine-learning", "scikit-learn" ]
I'm trying to use the car evaluation dataset from the UCI repository and I wonder whether there is a convenient way to binarize categorical variables in sklearn. One approach would be to use the DictVectorizer of LabelBinarizer but here I'm getting k different features whereas you should have just k-1 in order to avoid...
The basic method is ``` import numpy as np import pandas as pd, os from sklearn.feature_extraction import DictVectorizer def one_hot_dataframe(data, cols, replace=False): vec = DictVectorizer() mkdict = lambda row: dict((col, row[col]) for col in cols) vecData = pd.DataFrame(vec.fit_transform(data[cols].a...
How to encode a categorical variable in sklearn?
15,021,521
10
2013-02-22T10:05:17Z
22,130,844
28
2014-03-02T17:27:59Z
[ "python", "machine-learning", "scikit-learn" ]
I'm trying to use the car evaluation dataset from the UCI repository and I wonder whether there is a convenient way to binarize categorical variables in sklearn. One approach would be to use the DictVectorizer of LabelBinarizer but here I'm getting k different features whereas you should have just k-1 in order to avoid...
if your data is a pandas DataFrame, then you can simply call get\_dummies. Assume that your data frame is df, and you want to have one binary variable per level of variable 'key'. You can simply call: ``` pd.get_dummies(df['key']) ``` and then delete one of the dummy variables, to avoid the multi-colinearity problem....
Pycharm: Code completion not giving recommendations
15,022,804
4
2013-02-22T11:10:02Z
15,022,934
12
2013-02-22T11:16:56Z
[ "python", "pycharm" ]
Say I'm working with the 'requests' python library. ``` req = requests.get("http://google.com") ``` Now after this, if I type `req.`, I'm supposed to get a list of all methods I can access. But for some reason I don't, even if I manually press ctrl-space. If I try this in ipython, I get autocomplete recommendations....
As Python is a dynamically typed language, you need to ensure it can work out what type things are, and inspect on the libraries on your system correctly. Try to make sure it's obvious what type the object is in your code. One good way recently added (2.7) is to enable runtime type detection - PyCharm hooks into your ...
Get the directory path of absolute file path in Python
15,022,854
17
2013-02-22T11:13:02Z
15,022,906
29
2013-02-22T11:15:09Z
[ "python", "path" ]
I want to get the directory where the file resides. For example the full path is: ``` fullpath = "/absolute/path/to/file" # something like: os.getdir(fullpath) # if this existed and behaved like I wanted, it would return "/absolute/path/to" ``` I could do it like this: ``` dir = '/'.join(fullpath.split('/')[:-1]) ``...
You are looking for this: ``` >>> import os.path >>> fullpath = '/absolute/path/to/file' >>> os.path.dirname(fullpath) '/absolute/path/to' ``` Related functions: ``` >>> os.path.basename(fullpath) 'file' >>> os.path.split(fullpath) ('/absolute/path/to','file') ```
How are import statements in plpython handled?
15,023,080
10
2013-02-22T11:24:46Z
15,025,425
15
2013-02-22T13:32:05Z
[ "python", "json", "postgresql", "postgresql-9.1", "plpython" ]
I have a plypython function which does some json magic. For this it obviously imports the json library. Is the import called on every call to the function? Are there any performance implication I have to be aware of?
The `import` is executed on every function call. This is the same behavior you would get if you wrote a normal Python module with the `import` statement inside a function body as oppposed to at the module level. Yes, this will affect performance. You can work around this by caching your imports like this: ``` CREATE...
Looping through big files takes hours in Python
15,025,919
3
2013-02-22T14:01:42Z
15,025,991
9
2013-02-22T14:06:00Z
[ "python", "performance", "glob" ]
This is my second day working in Python .I worked on this in C++ for a while, but decided to try Python. My program works as expected. However, when I process one file at a time without the glob loop, it takes about a half hour per file. When I include the glob, the loop takes about 12 hours to process 8 files. My que...
Here: ``` for line in f.readlines(): ``` You should just do this: ``` for line in f: ``` The former reads the entire file into a list of lines, then iterates over that list. The latter does it incrementally, which should drastically reduce the total memory allocated and later freed by your program.
Pure Python faster than Numpy? can I make this numpy code faster?
15,026,519
4
2013-02-22T14:33:50Z
15,026,878
10
2013-02-22T14:54:47Z
[ "python", "numpy" ]
I need to compute the min, max, and mean from a specific list of faces/vertices. I tried to optimize this computing with the use of Numpy but without success. Here is my test case: ``` #!/usr/bin/python # -*- coding: iso-8859-15 -*- ''' Module Started 22 févr. 2013 @note: test case comparaison numpy vs python @autho...
The reason your `Fnumpy` is slower is that it contains an additional step not done by `Fpython`: the creation of a numpy array in memory. If you move the line `np_verticies=np.array(verticies)` outside of `Fnumpy` and the timed section your results will be very different: ``` >>NUMPY >>([1.1000000000452519, 2.20000000...
How to make separator in read_csv more flexible wrt whitespace?
15,026,698
17
2013-02-22T14:43:51Z
15,026,839
30
2013-02-22T14:51:51Z
[ "python", "csv", "pandas", "dataframe", "whitespace" ]
I need to created a data frame using data stored in a file. For that I want to use `read_csv` method. However, the separator is not very regular. Some columns are separated by tabs (`\t`), other are separated by spaces. Moreover, some columns can be separated by 2 or 3 or more spaces or even by a combination of spaces ...
From the [documentation](http://pandas.pydata.org/pandas-docs/stable/io.html), you can use either a regex or `delim_whitespace`: ``` >>> import pandas as pd >>> for line in open("whitespace.csv"): ... print repr(line) ... 'a\t b\tc 1 2\n' 'd\t e\tf 3 4\n' >>> pd.read_csv("whitespace.csv", header=None, delim...
Python module for searching patent databases, ie USPTO or EPO
15,028,166
6
2013-02-22T15:59:14Z
20,133,916
11
2013-11-21T23:15:31Z
[ "python", "python-2.7", "search" ]
For my work i have to find potential customers in biomedical research and industry. I wrote some pretty handy programs using the module biopython, which has a nice interface for searching NCBI. I have also used the clinical\_trials module, to search clinicaltrials.gov. I now want to search patent databases, like EPO ...
You can parse at least the USPTO using any XML parsing tool such as the lxml python module. There is a great paper on doing just this by Gabe Fierro, available here: [Extracting and Formatting Patent Data from USPTO XML](http://funginstitute.berkeley.edu/wp-content/uploads/2013/06/Extracting_and_Formatting.pdf) (no pa...
Is it acceptable & safe to run pip install under sudo?
15,028,648
38
2013-02-22T16:21:22Z
15,028,735
48
2013-02-22T16:25:43Z
[ "python", "osx", "pip", "sudo" ]
I've started to use my mac to install python packages in the same way I do with my Windows PC at work, however on my mac I've come across frequent `permission denied` errors writing log files & sometimes writing to site-packages. Therefore I thought about running `pip install <package>` under `sudo` but is that a safe...
Use a [virtual environment](http://www.virtualenv.org): ``` $ virtualenv myenv .. some output .. $ source myenv/bin/activate (myenv) $ pip install what-i-want ``` You only use `sudo` or elevated permissions when you want to install stuff for the global, system-wide Python installation. It is best to use a virtual en...
Generate functions without closures in python
15,028,782
6
2013-02-22T16:27:56Z
15,028,838
8
2013-02-22T16:31:21Z
[ "python", "function", "closures", "pickle" ]
right now I'm using closures to generate functions like in this simplified example: ``` def constant_function(constant): def dummyfunction(t): return constant return dummyfunction ``` These generated functions are then passed to the init-method of a custom class which stores them as instance attribute...
You could use a callable class: ``` class ConstantFunction(object): def __init__(self, constant): self.constant = constant def __call__(self, t): return self.constant def constant_function(constant): return ConstantFunction(constant) ``` The closure state of your function is then transfer...
How do I find information about a function in python?
15,029,495
5
2013-02-22T17:05:21Z
15,029,505
8
2013-02-22T17:05:47Z
[ "python" ]
I know in R you can just type ?"function\_name". How do you do this in python? Specifically, I am trying to find information about `set_position` in the `pyplot` library.
``` help(function) ``` should do the trick. Demo: ``` def func(): """ I am a function who doesn't do anything, I just sit in your namespace and crowd it up. If you call me expecting anything I'll just return to you the singleton None """ pass help(func) ```
Exporting items from a model to CSV Django / Python
15,029,666
5
2013-02-22T17:13:13Z
15,029,693
10
2013-02-22T17:14:33Z
[ "python", "django", "django-models", "python-3.x" ]
I'm fairly new to django and Python and want to be able to export a list of items in my model i.e products. I'm looking at the documentation here - <https://docs.djangoproject.com/en/dev/howto/outputting-csv/> I'm persuming I need will need to create a variable that stores all the data that I want. But not sure where ...
Have a look at the [python csv module](http://docs.python.org/2/library/csv.html). You'll probably want to get the models fields with ``` def get_model_fields(model): return model._meta.fields ``` Then use ``` getattr(instance, field.name) ``` to get the field values (as in [this](http://stackoverflow.com/ques...
Exporting items from a model to CSV Django / Python
15,029,666
5
2013-02-22T17:13:13Z
16,657,792
10
2013-05-20T20:27:17Z
[ "python", "django", "django-models", "python-3.x" ]
I'm fairly new to django and Python and want to be able to export a list of items in my model i.e products. I'm looking at the documentation here - <https://docs.djangoproject.com/en/dev/howto/outputting-csv/> I'm persuming I need will need to create a variable that stores all the data that I want. But not sure where ...
Depending on the scenario - you may want to have a CSV of your model. If you have access to the Django Admin site, you can plug in a generic action for any model displayed as a list (google: django admin actions) <http://djangosnippets.org/snippets/790/> If you're operating with a console (`python manage.py ...`), yo...
How to convert co-occurrence matrix to sparse matrix
15,030,047
3
2013-02-22T17:36:49Z
15,030,394
7
2013-02-22T18:00:39Z
[ "python", "scipy", "sparse-matrix" ]
I am starting dealing with sparse matrices so I'm not really proficient on this topic. My problem is, I have a simple coo-occurrences matrix from a word list, just a 2-dimensional co-occurrence matrix word by word counting how many times a word occurs in same context. The matrix is quite sparse since the corpus is not ...
Here's how you construct a document-term matrix `A` from a set of documents in SciPy's COO format, which is a good tradeoff between ease of use and efficiency(\*): ``` vocabulary = {} # map terms to column indices data = [] # values (maybe weights) row = [] # row (document) indices col = [] # c...
Installing Python packages from local file system folder with pip
15,031,694
88
2013-02-22T19:21:34Z
15,031,843
40
2013-02-22T19:32:09Z
[ "python", "pip" ]
Is it possible to install packages using pip from the local filesystem? I have run `python setup.py sdist` for my package, which has created the appropriate tar.gz file. This file is stored on my system at `/srv/pkg/mypackage/mypackage-0.1.0.tar.gz`. Now in a virtual environment I would like to install packages eithe...
I am pretty sure that what you are looking for is called `--find-links` option. Though you might need to generate a dummy `index.html` for your local package index which lists the links to all packages. This tool helps: <https://github.com/wolever/pip2pi>
Installing Python packages from local file system folder with pip
15,031,694
88
2013-02-22T19:21:34Z
20,043,907
174
2013-11-18T09:10:41Z
[ "python", "pip" ]
Is it possible to install packages using pip from the local filesystem? I have run `python setup.py sdist` for my package, which has created the appropriate tar.gz file. This file is stored on my system at `/srv/pkg/mypackage/mypackage-0.1.0.tar.gz`. Now in a virtual environment I would like to install packages eithe...
What about:: ``` pip install --help ... -e, --editable <path/url> Install a project in editable mode (i.e. setuptools "develop mode") from a local project path or a VCS url. ``` eg, `pip install -e /srv/pkg` where /srv/pkg is the top-level directory where 'setup.py' can be found.
Installing Python packages from local file system folder with pip
15,031,694
88
2013-02-22T19:21:34Z
26,393,695
11
2014-10-15T23:17:08Z
[ "python", "pip" ]
Is it possible to install packages using pip from the local filesystem? I have run `python setup.py sdist` for my package, which has created the appropriate tar.gz file. This file is stored on my system at `/srv/pkg/mypackage/mypackage-0.1.0.tar.gz`. Now in a virtual environment I would like to install packages eithe...
This is the solution that I ended up using: ``` import pip def install(package): # Debugging # pip.main(["install", "--pre", "--upgrade", "--no-index", # "--find-links=.", package, "--log-file", "log.txt", "-vv"]) pip.main(["install", "--upgrade", "--no-index", "--find-links=.", package]) i...
Installing Python packages from local file system folder with pip
15,031,694
88
2013-02-22T19:21:34Z
32,330,650
8
2015-09-01T11:38:43Z
[ "python", "pip" ]
Is it possible to install packages using pip from the local filesystem? I have run `python setup.py sdist` for my package, which has created the appropriate tar.gz file. This file is stored on my system at `/srv/pkg/mypackage/mypackage-0.1.0.tar.gz`. Now in a virtual environment I would like to install packages eithe...
I am installing pyfuzzy. It's not in PyPI, "No matching distribution found for pyfuzzy". However, I try the accepted answer ``` pip install --no-index --find-links=file:///Users/victor/Downloads/pyfuzzy-0.1.0 pyfuzzy ``` It cannot work as well. The result is: > Ignoring indexes: <https://pypi.python.org/simple> > C...
Python's "open()" throws different errors for "file not found" - how to handle both exceptions?
15,032,108
28
2013-02-22T19:48:31Z
15,032,444
37
2013-02-22T20:11:48Z
[ "python", "python-3.x", "filenotfoundexception", "ioerror" ]
I have a script where a user is prompted to type a filename (of a file that is to be opened), and if the file doesn't exist in the current directory, the user is prompted again. Here is the short version: ``` file = input("Type filename: ") ... try: fileContent = open(filename, "r") ... except FileNotFoundErr...
In 3.3, [`IOError` became an alias for `OSError`](http://docs.python.org/3.3/library/exceptions.html#IOError), and `FileNotFoundError` is a subclass of `OSError`. So you might try ``` except (OSError, IOError) as e: ... ``` This will cast a pretty wide net, and you can't assume that the exception is "file not foun...
Compute a confidence interval from sample data
15,033,511
31
2013-02-22T21:29:50Z
15,034,143
57
2013-02-22T22:18:58Z
[ "python", "numpy", "statistics" ]
I have sample data which I would like to compute a confidence interval for, assuming a normal distribution. I have found and installed the numpy and scipy packages and have gotten numpy to return a mean and standard deviation (numpy.mean(data) with data being a list). Any advice on getting a sample confidence interval...
``` import numpy as np import scipy as sp import scipy.stats def mean_confidence_interval(data, confidence=0.95): a = 1.0*np.array(data) n = len(a) m, se = np.mean(a), scipy.stats.sem(a) h = se * sp.stats.t._ppf((1+confidence)/2., n-1) return m, m-h, m+h ``` you can calculate like this way.
Compute a confidence interval from sample data
15,033,511
31
2013-02-22T21:29:50Z
34,474,255
11
2015-12-26T18:56:16Z
[ "python", "numpy", "statistics" ]
I have sample data which I would like to compute a confidence interval for, assuming a normal distribution. I have found and installed the numpy and scipy packages and have gotten numpy to return a mean and standard deviation (numpy.mean(data) with data being a list). Any advice on getting a sample confidence interval...
Here a shortened version of shasan's code, calculating the 95% confidence interval of the mean of array `a`: ``` import numpy as np, scipy.stats as st st.t.interval(0.95, len(a)-1, loc=np.mean(a), scale=st.sem(a)) ``` But using StatsModels' [tconfint\_mean](http://www.statsmodels.org/stable/generated/statsmodels.sta...
Copy directory contents into a directory with python
15,034,151
23
2013-02-22T22:19:17Z
15,034,373
41
2013-02-22T22:36:45Z
[ "python", "shutil", "copytree" ]
I have a directory /a/b/c that has files and subdirectories. I need to copy the /a/b/c/\* in the /x/y/z directory. What python methods can I use? I tried shutil.copytree("a/b/c", "/x/y/z"), but python tries to create /x/y/z and raises an error "Directory exists".
I found this code working. ``` from distutils.dir_util import copy_tree # copy subdirectory example fromDirectory = "/a/b/c" toDirectory = "/x/y/z" copy_tree(fromDirectory, toDirectory) ``` * Reference - <https://docs.python.org/2/distutils/apiref.html#distutils.dir_util.copy_tree>
Is there a Scala equivalent of the Python list unpack (a.k.a. "*") operator?
15,034,565
10
2013-02-22T22:54:08Z
15,034,725
13
2013-02-22T23:09:05Z
[ "python", "scala", "argument-passing" ]
In Python, we have the star (or "\*" or "unpack") operator, that allows us to unpack a list for convenient use in passing positional arguments. For example: ``` range(3, 6) args = [3, 6] # invokes range(3, 6) range(*args) ``` In this particular example, it doesn't save much typing, since `range` only takes two argume...
There is no direct equivalent in scala. The closest thing you will find is the usage of `_*`, which works on vararg methods only. By example, here is an example of a vararg method: ``` def hello( names: String*) { println( "Hello " + names.mkString(" and " ) ) } ``` which can be used with any number of arguments: ...
Training a sklearn LogisticRegression classifier without all possible labels
15,034,664
3
2013-02-22T23:03:30Z
15,039,953
7
2013-02-23T11:21:31Z
[ "python", "machine-learning", "scikit-learn" ]
I am trying to use scikit-learn 0.12.1 to: 1. train a LogisticRegression classifier 2. evaluate the classifer on held out validation data 3. feed new data to this classifier and retrieve the 5 most probable labels for each observation Sklearn makes all of this very easy except for one peculiarity. There is no guarant...
Here's a workaround. Make sure you have a list of all classes called `all_classes`. Then, if `clf` is your `LogisticRegression` classifier, ``` from itertools import repeat # determine the classes that were not present in the training set; # the ones that were are listed in clf.classes_. classes_not_trained = set(clf...
What command to use instead of urllib.request.urlretrieve?
15,035,123
10
2013-02-22T23:42:28Z
15,035,466
12
2013-02-23T00:22:12Z
[ "python", "urllib", "replace", "python-3.3" ]
I'm currently writing a script that takes an image url and downloads it to a pre-named file. Here is the relevant part of my code: ``` import urllib.request urllib.request.urlretrieve(image['url'],p) ``` It takes 'url' and saves it as 'p'. According to the python documentation, the [urllib.request.urlretrieve](htt...
*Deprecated* is one thing, *might become deprecated at some point in the future* is another. If it suits your needs, I'd continuing using `urlretrieve`. That said, you can do without it: ``` from urllib.request import urlopen from shutil import copyfileobj with urlopen(image['url']) as in_stream, open(p, 'wb') as o...
Building Python in Sublime Text
15,035,538
3
2013-02-23T00:31:57Z
15,846,455
8
2013-04-06T02:45:40Z
[ "python", "build", "sublimetext2", "build-error" ]
I am unable to get a Python system to build on a friend's computer which runs Windows XP SP3 using Sublime Text 2. We reinstalled Python 2.7.3 and also Sublime Text 2 and still are having trouble with this. Our `Python.sublime-build` field says: ``` { "cmd": ["C:\\Python27\\python.exe", "-u", "$(FULL_CURRENT_PATH)...
I fixed this by saving my file as a .py file. I opened up a new file, added some code, and tried to build it, which gave me that error. After saving as a .py file, I was able to build and run fine.
numpy covariance matrix
15,036,205
9
2013-02-23T02:05:32Z
15,036,271
7
2013-02-23T02:15:52Z
[ "python", "numpy", "covariance" ]
Suppose I have two vectors of length 25, and I want to compute their covariance matrix. I try doing this with numpy.cov, but always end up with a 2x2 matrix. ``` >>> import numpy as np >>> x=np.random.normal(size=25) >>> y=np.random.normal(size=25) >>> np.cov(x,y) array([[ 0.77568388, 0.15568432], [ 0.15568432...
You have two vectors, not 25. The computer I'm on doesn't have python so I can't test this, but try: ``` z = zip(x,y) np.cov(z) ``` Of course.... really what you want is probably more like: ``` n=100 # number of points in each vector num_vects=25 vals=[] for _ in range(num_vects): vals.append(np.random.normal(si...
numpy covariance matrix
15,036,205
9
2013-02-23T02:05:32Z
15,068,615
8
2013-02-25T13:55:43Z
[ "python", "numpy", "covariance" ]
Suppose I have two vectors of length 25, and I want to compute their covariance matrix. I try doing this with numpy.cov, but always end up with a 2x2 matrix. ``` >>> import numpy as np >>> x=np.random.normal(size=25) >>> y=np.random.normal(size=25) >>> np.cov(x,y) array([[ 0.77568388, 0.15568432], [ 0.15568432...
Try this: ``` import numpy as np x=np.random.normal(size=25) y=np.random.normal(size=25) z = np.vstack((x, y)) c = np.cov(z.T) ```
Python 3.3 TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
15,036,594
3
2013-02-23T03:10:01Z
15,036,603
9
2013-02-23T03:10:58Z
[ "python", "string", "input", "typeerror" ]
New to programming and am unsure why I am getting this error ``` count=int(input ("How many donuts do you have?")) if count <= 10: print ("number of donuts: " ) +str(count) else: print ("Number of donuts: many") ```
In python3, `print` is a *function* that returns `None`. So, the line: ``` print ("number of donuts: " ) +str(count) ``` you have `None + str(count)`. What you probably want is to use string formatting: ``` print ("Number of donuts: {}".format(count)) ```
Batch gradient descent with scikit learn (sklearn)
15,036,630
6
2013-02-23T03:13:41Z
15,040,070
17
2013-02-23T11:32:37Z
[ "python", "machine-learning", "scikit-learn" ]
I'm playing with a one-vs-all Logistic Regression classifier using Scikit-Learn (sklearn). I have a large dataset that is too slow to run all at one go; also I would like to study the learning curve as the training proceeds. I would like to use batch gradient descent to train my classifier in batches of, say, 500 samp...
What you want is not batch gradient descent, but stochastic gradient descent; batch learning means learning on the entire training set in one go, while what you describe is properly called minibatch learning. That's implemented in `sklearn.linear_model.SGDClassifier`, which fits a logistic regression model if you give ...
Python on the AWS Beanstalk. How to snapshot custom logs?
15,038,135
7
2013-02-23T07:12:42Z
23,790,037
13
2014-05-21T17:25:03Z
[ "python", "logging", "elastic-beanstalk" ]
I'm developing python application which works on aws beanstalk environment. For error handling and debugging proposes I write logs to custom lof file on the directory /var/logs/. What should I do in order to have ability snapshot logs from Elastic beanstalk management console?
Expanding on Vadim911 (and my own comment), I solved the problem using a config file in [.ebextensions](http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customize-containers-ec2.html). Here is the python code: ``` import logging logging.basicConfig(filename='/opt/python/log/my.log', level=logging.DEBUG) ``` Here...
Topological sort python
15,038,876
6
2013-02-23T09:06:00Z
15,039,202
7
2013-02-23T09:52:39Z
[ "python", "algorithm", "graph" ]
I coded a solution for DFS non-recursive, but i can't modify it to make a topological sort: ``` def dfs(graph,start): path = [] stack = [start] while stack != []: v = stack.pop() if v not in path: path.append(v) for w in reversed(graph[v]): if w not in path and not...
You recursive solution doesn't seem to be producing topologically sorted output. For example with this input: ``` graph = { 1: [2,11], 2: [3], 11: [12], 12: [13] } 1 /\ / 11 / \ 2 12 / \ 3 13 ``` we should get `13` prior to `2`. But the output o...
Finding intersection/difference between python lists
15,039,006
4
2013-02-23T09:25:41Z
15,039,054
7
2013-02-23T09:30:49Z
[ "python", "list", "numpy" ]
I have two python lists: ``` a = [('when', 3), ('why', 4), ('throw', 9), ('send', 15), ('you', 1)] b = ['the', 'when', 'send', 'we', 'us'] ``` I need to filter out all the elements from a that are similar to those in b. Like in this case, I should get: ``` c = [('why', 4), ('throw', 9), ('you', 1)] ``` What should...
A list comprehension will work. ``` a = [('when', 3), ('why', 4), ('throw', 9), ('send', 15), ('you', 1)] b = ['the', 'when', 'send', 'we', 'us'] filtered = [i for i in a if not i[0] in b] >>>print(filtered) [('why', 4), ('throw', 9), ('you', 1)] ```
If RAM isn't a concern, is reading line by line faster or reading everything into RAM and access it? - Python
15,039,380
14
2013-02-23T10:16:46Z
15,039,509
8
2013-02-23T10:32:21Z
[ "python", "performance", "file-io", "unicode", "ram" ]
If RAM isn't a concern (I have close to 200GB on the server), is reading line by line faster or reading everything into RAM and access it? Each line will be a string of around 200-500 unicode characters. There are close to 2 million lines for each file. **Line-by-line** ``` import codecs for i in codecs.open('unicode...
Nothing stops you from testing this on your machine. I created a file with 1M lines each and the results, timed as ``` time python something.py > /dev/null ``` were: Line-by-Line: ``` real 0m4.878s user 0m4.860s sys 0m0.008s ``` Reading into RAM: ``` real 0m0.981s user 0m0.828s sys 0m0.148s ``...
If RAM isn't a concern, is reading line by line faster or reading everything into RAM and access it? - Python
15,039,380
14
2013-02-23T10:16:46Z
15,039,682
15
2013-02-23T10:52:20Z
[ "python", "performance", "file-io", "unicode", "ram" ]
If RAM isn't a concern (I have close to 200GB on the server), is reading line by line faster or reading everything into RAM and access it? Each line will be a string of around 200-500 unicode characters. There are close to 2 million lines for each file. **Line-by-line** ``` import codecs for i in codecs.open('unicode...
I used cProfile on a ~1MB dictionary words file. I read the same file 3 times. The first reads tho whole file in just to even the playing field in terms of it being stored in cache. Here is the simple code: ``` def first_read(): codecs.open(file, 'r', 'utf8').readlines() def line_by_line(): for i in codecs.op...
what is the difference between os.open and os.fdopen in python
15,039,528
18
2013-02-23T10:34:31Z
15,039,662
31
2013-02-23T10:49:43Z
[ "python" ]
I am really confused when to use `os.open` and when to use `os.fdopen` I was doing all my work with `os.open` and it worked without any problem but I am not able to understand under what conditions we need `file descriptors` and all other functions like `dup` and `fsync` Is the `file object` different from `file desc...
You are confusing the built-in `open()` function with `os.open()` provided by the `os` module. They qre quite different; `os.open(filename, "w")` is not valid Python (`os.open` accepts integer flags as its second argument), `open(filename, "w")` is. In short, `open()` creates new file objects, `os.open()` creates OS-l...
Streaming file upload using bottle (or flask or similar)
15,040,706
9
2013-02-23T12:49:20Z
16,018,673
14
2013-04-15T15:09:41Z
[ "python", "rest", "file-upload", "bottle" ]
I have a REST frontend written using Python/Bottle which handles file uploads, usually large ones. The API is wirtten in such a way that: The client sends PUT with the file as a payload. Among other things, it sends Date and Authorization headers. This is a security measure against replay attacks -- the request is sin...
I recommend splitting the incoming file into smaller-sized chunks on the frontend. I'm doing this to implement a pause/resume function for large file uploads in a Flask application. Using [Sebastian Tschan's jquery plugin](https://github.com/blueimp/jQuery-File-Upload/wiki), you can implement chunking by specifying a ...
How to continuously display python output in a webpage?
15,041,620
7
2013-02-23T14:32:20Z
15,042,327
11
2013-02-23T15:45:58Z
[ "python", "python-2.7", "flask", "jinja2" ]
I want to be able to visit a webpage and it will run a python function and display the progress in the webpage. So when you visit the webpage you can see the output of the script as if you ran it from the command line and see the output in the command line. What do I need to do in the function? What do I need to do ...
Here is a very simple app that streams a process' output with normal HTTP: ``` import flask import time app = flask.Flask(__name__) @app.route('/yield') def index(): def inner(): for x in range(100): time.sleep(1) yield '%s<br/>\n' % x return flask.Response(inner(), mimetype='...
Pythonically inserting multiple values to a list
15,041,834
3
2013-02-23T14:55:33Z
15,041,878
12
2013-02-23T14:59:28Z
[ "python", "list", "insert", "idiomatic" ]
I want to turn this list: ``` l=["Three","Four","Five","Six"] ``` into this one: ``` ['Three', 3, 'Four', 4, 'Five', 5, 'Six', 6] ``` and I used this code (which works well) to do it: ``` for i,j in zip(range(1,len(l)*2,2),range(3,7)*2): l.insert(i,j) ``` But I guess Python would not be proud of it. Is there ...
I might do something like this: ``` >>> a = ["Three","Four","Five","Six"] >>> b = range(3,7) >>> zip(a,b) [('Three', 3), ('Four', 4), ('Five', 5), ('Six', 6)] >>> [term for pair in zip(a,b) for term in pair] ['Three', 3, 'Four', 4, 'Five', 5, 'Six', 6] ``` or, using `itertools.chain`: ``` >>> from itertools import c...
How do I unit testing my GUI program with Python and PyQt?
15,044,447
7
2013-02-23T19:09:05Z
15,044,564
12
2013-02-23T19:20:29Z
[ "python", "qt", "unit-testing" ]
I heard Unit Testing is a great method to keep the code work correctly. The unit testing usually puts an simple input to an function, and check its simple output. But how do I test an UI? My program is written in PyQt. should I choose PyUnit, or Qt's built-in QTest?
There's a good tutorial about using Python's unit testing framework with QTest [here](http://www.voom.net/pyqt-qtest-example). **It isn't about choosing one or the other. Instead, it's about using them together.** The purpose of QTest is only to simulate keystrokes, mouse clicks, and mouse movement. Python's unit test...
Javascript or Python - How do I figure out if it's night or day?
15,044,521
19
2013-02-23T19:15:20Z
15,044,612
10
2013-02-23T19:25:17Z
[ "javascript", "python", "geolocation", "timezone" ]
**any idea how I figure out if it's currently night/day or sunrise/dawn based on time and location of the user?** I haven't found anything useful that I could use within either the client or backend. What makes it tricky is the hour doesn't necessarily define if it is night and day, this depends pretty much on the ye...
You can do as I did and use this public domain [Sun.py](http://kortis.to/radix/python/code/Sun.py) module to compute the position of the sun relative to positions on the Earth. It's pretty old, but has worked well for me for many years. I made a few superficial modifications to it to be more up-to-date with Python 2.7,...
Javascript or Python - How do I figure out if it's night or day?
15,044,521
19
2013-02-23T19:15:20Z
15,044,683
11
2013-02-23T19:31:47Z
[ "javascript", "python", "geolocation", "timezone" ]
**any idea how I figure out if it's currently night/day or sunrise/dawn based on time and location of the user?** I haven't found anything useful that I could use within either the client or backend. What makes it tricky is the hour doesn't necessarily define if it is night and day, this depends pretty much on the ye...
A concise description of an algorithm to calculate the sunrise and sunset is provided by the United States Naval Observatory, available here: <http://williams.best.vwh.net/sunrise_sunset_algorithm.htm> In addition to providing the date and location, you also need to select a Zenith angle (at which the sun will be con...
Javascript or Python - How do I figure out if it's night or day?
15,044,521
19
2013-02-23T19:15:20Z
16,405,311
7
2013-05-06T18:56:24Z
[ "javascript", "python", "geolocation", "timezone" ]
**any idea how I figure out if it's currently night/day or sunrise/dawn based on time and location of the user?** I haven't found anything useful that I could use within either the client or backend. What makes it tricky is the hour doesn't necessarily define if it is night and day, this depends pretty much on the ye...
**[PyEphem](http://rhodesmill.org/pyephem/index.html)** can be used to calculate the time to the next sunrise and sunset. Building upon [a blog post I found](http://scienceoss.com/calculate-sunrise-and-sunset-with-pyephem/) and [the documentation of rise-set](http://rhodesmill.org/pyephem/rise-set.html), your problem c...
how to get User id from auth_user table in django?
15,044,778
2
2013-02-23T19:41:51Z
15,044,805
8
2013-02-23T19:44:07Z
[ "python", "django" ]
how to get User id from `auth_user` table in django. Suppose username is availlable to me.
Assuming the user exists: ``` from django.contrib.auth.models import User User.objects.get(username=the_username).pk ```
How to sort the letters in a string alphabetically in Python
15,046,242
49
2013-02-23T22:00:04Z
15,046,263
97
2013-02-23T22:02:27Z
[ "python", "string" ]
Is there an easy way to sort the letters in a string alphabetically in Python? So for: ``` a = 'ZENOVW' ``` I would like to return: ``` 'ENOVWZ' ```
You can do: ``` >>> a = 'ZENOVW' >>> ''.join(sorted(a)) 'ENOVWZ' ```
How to sort the letters in a string alphabetically in Python
15,046,242
49
2013-02-23T22:00:04Z
15,046,311
43
2013-02-23T22:07:54Z
[ "python", "string" ]
Is there an easy way to sort the letters in a string alphabetically in Python? So for: ``` a = 'ZENOVW' ``` I would like to return: ``` 'ENOVWZ' ```
``` >>> a = 'ZENOVW' >>> b = sorted(a) >>> print b ['E', 'N', 'O', 'V', 'W', 'Z'] ``` `sorted` returns a list, so you can make it a string again using `join`: ``` >>> c = ''.join(b) ``` which joins the items of `b` together with an empty string `''` in between each item. ``` >>> print c 'ENOVWZ' ```
Toplevel in Tkinter: Prevent Two Windows from Opening
15,046,498
5
2013-02-23T22:29:26Z
15,046,539
7
2013-02-23T22:35:28Z
[ "python", "tkinter" ]
Say I have some simple code, like this: ``` from Tkinter import * root = Tk() app = Toplevel(root) app.mainloop() ``` This opens two windows: the `Toplevel(root)` window and the `Tk()` window. Is it possible to avoid the `Tk()` window (`root`) from opening? If so, how? I only want the toplevel. I want this to happen...
The [`withdraw()`](http://effbot.org/tkinterbook/wm.htm#Tkinter.Wm.withdraw-method) method removes the window from the screen. The [`iconify()`](http://effbot.org/tkinterbook/wm.htm#Tkinter.Wm.iconify-method) method minimizes the window, or turns it into an icon. The [`deiconify()`](http://effbot.org/tkinterbook/wm...
a iterative algorithm for fibonacci numbers
15,047,116
8
2013-02-23T23:53:01Z
15,047,141
31
2013-02-23T23:56:53Z
[ "python", "algorithm", "fibonacci" ]
I am interested in a iterative algorithm for Fibonacci numbers, so I found the formula on wiki...it looks straight forward so I tried it in Python...it doesn't have a problem compiling and formula looks right...not sure why its giving the wrong output...did I not implement it right ? ``` def fib (n): if( n == 0):...
The problem is that your `return y` is within the loop of your function. So after the first iteration, it will already stop and return the first value: 1. Except when `n` is 0, in which case the function is made to return `0` itself, and in case `n` is 1, when the for loop will not iterate even once, and no `return` is...
"Protected" access in Python - how?
15,049,333
4
2013-02-24T06:39:30Z
15,049,373
8
2013-02-24T06:46:14Z
[ "python", "inheritance", "python-3.x", "protected" ]
I would like to set up a class hierarchy in Python 3.2 with 'protected' access: Members of the base class would be in scope only for derived classes, but not 'public'. A double underscore makes a member 'private', a single underscore indicates a warning but the member remains 'public'. What (if any...) is the correct ...
Member access allowance in Python works by "negotiation" and "treaties", not by force. In other words, the user of your class is supposed to leave their hands off things which are not their business, but you cannot enforce that other than my using `_xxx` identifiers making absolutely clear that their access is (normal...
How to upload and save a file using bottle framework
15,050,064
8
2013-02-24T08:40:22Z
17,134,909
19
2013-06-16T15:36:40Z
[ "python", "python-2.7", "bottle" ]
HTML: ``` <form action="/upload" method="post" enctype="multipart/form-data"> Category: <input type="text" name="category" /> Select a file: <input type="file" name="upload" /> <input type="submit" value="Start upload" /> </form> ``` View: ``` @route('/upload', method='POST') def do_login(): category ...
Starting from **bottle-0.12** the **[FileUpload](http://bottlepy.org/docs/dev/api.html?highlight=fileupload#bottle.FileUpload)** class was implemented with its **upload.save()** functionality. Here is example for the **Bottle-0.12**: ``` import os from bottle import route, request, static_file, run @rout...