title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
python pass list as function parameter
9,765,843
3
2012-03-19T06:23:03Z
9,765,854
12
2012-03-19T06:24:27Z
[ "python", "list", "function" ]
folks, The result of the following code is [] Why is it not ['0','1','2']? If I want to make psswd equal to number in the function foo, what should I do? ``` number = ['0','1','2'] def foo(psswd): psswd = number[:] if __name__ == '__main__': psswd = [] foo(psswd) print psswd ```
You need to mutate instead of rebinding, with [slice-assigning](http://stackoverflow.com/a/4081587/20862). ``` psswd[:] = number[:] ```
How do I redirect to the www. version of my Flask site on Heroku?
9,766,134
5
2012-03-19T06:55:15Z
10,964,868
11
2012-06-09T21:55:42Z
[ "python", "heroku", "flask" ]
I've got a Python Flask app running on Heroku (Cedar stack) with two custom domains (one with and one without the www subdomain). I'd like to redirect all incoming requests to the www. version of the resource requested (the inverse of [this question](http://stackoverflow.com/questions/9350141/how-do-i-redirect-all-requ...
An easier solution than to create a separate Heroku app would be a `before_request` function. ``` from urlparse import urlparse, urlunparse @app.before_request def redirect_nonwww(): """Redirect non-www requests to www.""" urlparts = urlparse(request.url) if urlparts.netloc == 'example.com': urlpa...
Different behaviour for list.__iadd__ and list.__add__
9,766,387
8
2012-03-19T07:22:18Z
9,766,428
18
2012-03-19T07:25:59Z
[ "python", "list" ]
consider the following code: ``` >>> x = y = [1, 2, 3, 4] >>> x += [4] >>> x [1, 2, 3, 4, 4] >>> y [1, 2, 3, 4, 4] ``` and then consider this: ``` >>> x = y = [1, 2, 3, 4] >>> x = x + [4] >>> x [1, 2, 3, 4, 4] >>> y [1, 2, 3, 4] ``` Why is there a difference these two? (And yes, I tried searching for this).
`__iadd__` mutates the list, whereas `__add__` returns a *new* list, as demonstrated. An expression of `x += y` first tries to call `__iadd__` and, failing that, calls `__add__` followed an assignment (see Sven's comment for a minor correction). Since `list` has `__iadd__` then it does this little bit 'o mutation magi...
zipWith analogue in Python?
9,766,608
35
2012-03-19T07:48:12Z
9,766,642
9
2012-03-19T07:52:00Z
[ "python", "haskell" ]
What is the analogue of Haskell's [zipWith](http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v%3azipWith) function in Python? ``` zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] ```
You can use map: ``` >>> x = [1,2,3,4] >>> y = [4,3,2,1] >>> map(lambda a, b: a**b, x, y) [1, 8, 9, 4] ```
zipWith analogue in Python?
9,766,608
35
2012-03-19T07:48:12Z
9,766,647
29
2012-03-19T07:52:13Z
[ "python", "haskell" ]
What is the analogue of Haskell's [zipWith](http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v%3azipWith) function in Python? ``` zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] ```
You can create yours, if you wish, but in Python we mostly do ``` list_c = [ f(a,b) for (a,b) in zip(list_a,list_b) ] ``` as Python is not inherently functional. It just happens to support a few convenience idioms.
zipWith analogue in Python?
9,766,608
35
2012-03-19T07:48:12Z
9,766,650
36
2012-03-19T07:52:19Z
[ "python", "haskell" ]
What is the analogue of Haskell's [zipWith](http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v%3azipWith) function in Python? ``` zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] ```
`map()` ``` map(operator.add, [1, 2, 3], [3, 2, 1]) ``` Although a LC with `zip()` is usually used. ``` [x + y for (x, y) in zip([1, 2, 3], [3, 2, 1])] ```
How to create an SQL View with SQLAlchemy?
9,766,940
27
2012-03-19T08:22:50Z
9,769,411
42
2012-03-19T11:34:32Z
[ "python", "postgresql", "sqlalchemy" ]
Everything is in the title. Is there a "Pythonic" way (I mean, no "pure SQL" query) to define an SQL view with SQLAlchemy ? Thanks for your help,
**Update:** See also the SQLAlchemy usage recipe [here](https://bitbucket.org/zzzeek/sqlalchemy/wiki/UsageRecipes/Views) Creating a (read-only non-materialized) view is not supported out of the box as far as I know. But adding this functionality in SQLAlchemy 0.7 is straightforward (similar to the example I gave [here...
How to set value in with Beautiful Soup in some HTML element if I know id of that element or class?
9,766,966
4
2012-03-19T08:25:52Z
9,767,324
9
2012-03-19T08:58:55Z
[ "python", "beautifulsoup" ]
How to set value with Beautiful Soup in some element if I know id of that HTML element or class ? For example I have `<td id="test"></td`> and I want to set text RESTORE... like `<td id="test">RESTORE...</td>`.
Find the tag you want to modify using a `find()` search for `id=test`. Then: [BeautifulSoup Documentation - "Modifying the tree"](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#modifying-the-tree) > **Modifying .string** > > If you set a tag’s .string attribute, the tag’s contents are replaced with the str...
Setting a relative frequency in a matplotlib histogram
9,767,241
13
2012-03-19T08:52:54Z
9,768,339
20
2012-03-19T10:13:16Z
[ "python", "matplotlib", "histogram", "frequency" ]
I have data as a list of floats and I want to plot it as a histogram. Hist() function does the job perfectly for plotting the absolute histogram. However, I cannot figure out how to represent it in a relative frequency format - I would like to have it as a fraction or ideally as a percentage on the y-axis. Here is the...
Because normed option of hist returns the density of points, e.g dN/dx What you need is something like that: ``` # assuming that mydata is an numpy array ax.hist(mydata, weights=np.zeros_like(data) + 1. / data.size) # this will give you fractions ```
TypeError: 'int' object is not callable
9,767,391
13
2012-03-19T09:05:32Z
9,767,422
50
2012-03-19T09:08:18Z
[ "python", "python-2.7" ]
Given the following integers and calculation ``` from __future__ import division a = 23 b = 45 c = 16 round((a/b)*0.9*c) ``` This results in: ``` TypeError: 'int' object is not callable. ``` How can I round the output to an integer?
Somewhere else in your code you have something that looks like this: ``` round = 42 ``` Then when you write ``` round((a/b)*0.9*c) ``` that is interpreted as meaning a function call on the object bound to `round`, which is an `int`. And that fails. The problem is whatever code binds an `int` to the name `round`. F...
Insert static files literally into Jinja templates without parsing them
9,767,585
14
2012-03-19T09:20:20Z
9,769,454
13
2012-03-19T11:37:58Z
[ "python", "jinja2" ]
I'm trying to insert file into a page using Jinja 2.6 using the `include` tag. This worked fine until I started using characters in the file that are reminiscent of the Jinja syntax, at which point it realized it couldn't parse them and bombed. Short of going though the file and escaping all characters, what can I do ...
You can define a function to load the text file and render it in the template: ``` import jinja2 def include_file(name): return jinja2.Markup(loader.get_source(env, name)[0]) loader = jinja2.PackageLoader(__name__, 'templates') env = jinja2.Environment(loader=loader) env.globals['include_file'] = include_file d...
Insert static files literally into Jinja templates without parsing them
9,767,585
14
2012-03-19T09:20:20Z
23,271,480
7
2014-04-24T14:13:15Z
[ "python", "jinja2" ]
I'm trying to insert file into a page using Jinja 2.6 using the `include` tag. This worked fine until I started using characters in the file that are reminiscent of the Jinja syntax, at which point it realized it couldn't parse them and bombed. Short of going though the file and escaping all characters, what can I do ...
If you are using Flask it can be written like this: ``` from jinja2 import Markup ... app.jinja_env.globals['include_raw'] = lambda filename : Markup(app.jinja_loader.get_source(app.jinja_env, filename)[0]) ``` And used like this: ``` {{ include_raw('js-inline/modernizr.min.js') }} ``` Path of the included file i...
Calculating SimRank using NetworkX?
9,767,773
5
2012-03-19T09:33:30Z
11,251,578
7
2012-06-28T19:30:12Z
[ "python", "graph-algorithm", "networkx" ]
I was wondering how can we can use the python module `networkX` to implement [SimRank](http://en.wikipedia.org/wiki/SimRank) to compare the similarity of 2 nodes? I understand that `networkX` provides methods for looking at neighbors, and link analysis algorithms such as PageRank and HITS, but is there one for SimRank?...
**Update** I implemented an networkx\_addon library. SimRank is included in the library. Check out: <https://github.com/hhchen1105/networkx_addon> for details. Sample Usage: ``` >>> import networkx >>> import networkx_addon >>> G = networkx.Graph() >>> G.add_edges_from([('a','b'), ('b','c'), ('a','c')...
PEP8: conflict between W292 and W391
9,768,139
20
2012-03-19T09:58:00Z
9,768,190
24
2012-03-19T10:02:05Z
[ "python", "pep8" ]
As far as I know in unix it's a good practice to always have blank line at the end of file - or to put it in other words: every line should end with `\n`. While checking my python code with PEP8 I noticed that it also states that there should be `\n` at end of file: ``` W292 no newline at end of file JCR: The las...
W391 is a **blank** line, that is, *two consecutive* `\n`s. There is no conflict.
PEP8: conflict between W292 and W391
9,768,139
20
2012-03-19T09:58:00Z
9,769,111
11
2012-03-19T11:12:13Z
[ "python", "pep8" ]
As far as I know in unix it's a good practice to always have blank line at the end of file - or to put it in other words: every line should end with `\n`. While checking my python code with PEP8 I noticed that it also states that there should be `\n` at end of file: ``` W292 no newline at end of file JCR: The las...
This is what W391 is talking about: ``` print 'last line' ``` This is wrong according to W292: ``` print 'last line' ``` What is correct is: ``` print 'last line' ```
What does '~' at the end of file name mean in Python MVC
9,768,843
2
2012-03-19T10:52:36Z
9,768,866
11
2012-03-19T10:54:22Z
[ "python" ]
Im having a very odd problem. Im trying to install a Python program. Im using `python setup.py install` The setup.py file states: ``` install_requires=[ "Pylons==0.9.7", ``` The setup.py~ file states: ``` install_requires=[ "Pylons==0.10", ``` This is causing an issue when Im trying to install as the prog...
It's a backup file -- many editors save the previous version of your file under the same name with a `~` appended.
Python NoneType object is not callable (beginner)
9,768,865
15
2012-03-19T10:54:18Z
9,768,888
24
2012-03-19T10:56:23Z
[ "python", "nonetype" ]
I tells me line 1 and line 5 (new to debugging/programming, not sure if that helps) ``` def hi(): print 'hi' def loop(f, n): #f repeats n times if n<=0: return else: f() loop(f, n-1) loop(hi(), 5) hi TypeError: 'NoneType' object is not callable ``` W...
You want to pass the function *object* `hi` to your `loop()` function, not the result of a *call* to `hi()` (which is `None` since `hi()` doesn't return anything). So try this: ``` >>> loop(hi, 5) hi hi hi hi hi ``` Perhaps this will help you understand better: ``` >>> print hi() hi None >>> print hi <function hi a...
Celery Received unregistered task of type (run example)
9,769,496
43
2012-03-19T11:40:50Z
9,769,705
24
2012-03-19T11:55:40Z
[ "python", "celery" ]
I'm trying to run [example](http://ask.github.com/celery/getting-started/first-steps-with-celery.html#id3) from Celery documentation. I run: `celeryd --loglevel=INFO` ``` /usr/local/lib/python2.7/dist-packages/celery/loaders/default.py:64: NotConfigured: No 'celeryconfig' module found! Please make sure it exists and ...
You can see the current list of registered tasks in the `celery.registry.TaskRegistry` class. Could be that your celeryconfig (in the current directory) is not in `PYTHONPATH` so celery can't find it and falls back to defaults. Simply specify it explicitly when starting celery. ``` celeryd --loglevel=INFO --settings=c...
Celery Received unregistered task of type (run example)
9,769,496
43
2012-03-19T11:40:50Z
9,946,243
25
2012-03-30T15:43:20Z
[ "python", "celery" ]
I'm trying to run [example](http://ask.github.com/celery/getting-started/first-steps-with-celery.html#id3) from Celery documentation. I run: `celeryd --loglevel=INFO` ``` /usr/local/lib/python2.7/dist-packages/celery/loaders/default.py:64: NotConfigured: No 'celeryconfig' module found! Please make sure it exists and ...
I think you need to restart the worker server. I meet the same problem and solve it by restarting.
Celery Received unregistered task of type (run example)
9,769,496
43
2012-03-19T11:40:50Z
11,295,754
37
2012-07-02T14:33:15Z
[ "python", "celery" ]
I'm trying to run [example](http://ask.github.com/celery/getting-started/first-steps-with-celery.html#id3) from Celery documentation. I run: `celeryd --loglevel=INFO` ``` /usr/local/lib/python2.7/dist-packages/celery/loaders/default.py:64: NotConfigured: No 'celeryconfig' module found! Please make sure it exists and ...
I had the same problem: The reason of `"Received unregistered task of type.."` was that celeryd service didn't find and register the tasks on service start (btw their list is visible when you start `./manage.py celeryd --loglevel=info` ). These tasks should be declared in `CELERY_IMPORTS = ("tasks", )` in settings fil...
Celery Received unregistered task of type (run example)
9,769,496
43
2012-03-19T11:40:50Z
12,109,542
11
2012-08-24T12:37:44Z
[ "python", "celery" ]
I'm trying to run [example](http://ask.github.com/celery/getting-started/first-steps-with-celery.html#id3) from Celery documentation. I run: `celeryd --loglevel=INFO` ``` /usr/local/lib/python2.7/dist-packages/celery/loaders/default.py:64: NotConfigured: No 'celeryconfig' module found! Please make sure it exists and ...
I also had the same problem; I added ``` CELERY_IMPORTS=("mytasks") ``` in my `celeryconfig.py` file to solve it.
Celery Received unregistered task of type (run example)
9,769,496
43
2012-03-19T11:40:50Z
22,243,943
7
2014-03-07T07:20:43Z
[ "python", "celery" ]
I'm trying to run [example](http://ask.github.com/celery/getting-started/first-steps-with-celery.html#id3) from Celery documentation. I run: `celeryd --loglevel=INFO` ``` /usr/local/lib/python2.7/dist-packages/celery/loaders/default.py:64: NotConfigured: No 'celeryconfig' module found! Please make sure it exists and ...
Whether you use `CELERY_IMPORTS` or `autodiscover_tasks`, the important point is the tasks are able to be found and the name of the tasks registered in Celery should match the names the workers try to fetch. When you launch the Celery, say `celery worker -A project --loglevel=DEBUG`, you should see the name of the tas...
openerp schedule server action
9,771,171
4
2012-03-17T17:03:02Z
9,784,730
8
2012-03-20T10:09:40Z
[ "python", "openerp" ]
In OpenERP 6.0.1, I've created a server action to send a confirmation email after an invoice is confirmed, and linked it to appropriately to the invoice workflow. now normally when an invoice is confirmed, an email is automatically sent. is there a way to set a date for when the email should be sent instead of being ...
There is a one object `ir.cron` which will run on specific time period. There you can specify the time when you want to sent the mail. This object will call the function which you given in `Method` attribute. In this function you have to search for those invoices which are in `created` state. Then check the date when ...
How to join MongoDB collections in Python?
9,771,330
4
2012-03-19T13:44:23Z
9,779,263
9
2012-03-19T23:07:20Z
[ "python", "mongodb", "mapreduce", "pymongo" ]
How to join ( in a sense of INNER JOIN from SQL ) two MongoDB collections in Python ? Do I need to use native map/reduce javascript code or to do this in PyMongo ? How to solve this with less code ?
Mongo stores data differently than in a traditional relational database, and does not support table joins as one might be used to in a SQL database. There is a note on this in the "Database References" documentation. <http://www.mongodb.org/display/DOCS/Database+References> If possible, it is preferable to store all d...
feedparser with timeout
9,772,691
5
2012-03-19T15:12:17Z
9,772,871
9
2012-03-19T15:22:26Z
[ "python", "feedparser" ]
My code got stuck on this function call: ``` feedparser.parse("http://...") ``` This worked before. The url is even not possible to open in the browser. How would you cure this case? Is there a timeout possibility? I'd like to continue as if nothing would happen (only with printing some message or log this issue)
You can specify timeout globally using `socket.setdefaulttimeout()`. The timeout may limit how long an individual socket operation may last -- `feedparser.parse()` may perform many socket operations and therefore the total time spent on dns, establishing the tcp connection, sending/receiving data may be much longer. S...
Problems of **arg in Python
9,772,938
2
2012-03-19T15:26:05Z
9,773,040
11
2012-03-19T15:31:46Z
[ "python" ]
I'll post my code first, and then ask questions. ``` def menu(**arg): if len(arg) == 0: name = raw_input("Enter your name: ") location = raw_input("Enter your name: ") else: for i,j in arg.items(): globals()[i] = j print "Name: %s | Location: %s" % (name, location) ``` ...
First of all, don't modify `globals` -- that's unnecessary and overly complex. If `len(args) == 0`, just create a dictionary called `args` with a `name` and a `location` value. The actual problem with the code, however, is that once you define `location` and `name` *anywhere* in the function -- even in an `if` clause ...
Removing u in list
9,773,121
11
2012-03-19T15:36:59Z
9,773,151
14
2012-03-19T15:38:39Z
[ "python", "google-app-engine" ]
I have read up on remove the character 'u' in a list but I am using google app engine and it does not seem to work! ``` def get(self): players = db.GqlQuery("SELECT * FROM Player") print players playerInfo = {} test = [] for player in players: email = player.email gem = str(pla...
That 'u' is part of the external representation of the string, meaning it's a Unicode string as opposed to a byte string. It's not in the string, it's part of the type. As an example, you can create a new Unicode string literal by using the same synax. For instance: ``` >>> sandwich = u"smörgås" >>> sandwich u'sm\x...
Python/SQLite3: cannot commit - no transaction is active
9,773,200
13
2012-03-19T15:41:24Z
9,781,882
10
2012-03-20T05:44:37Z
[ "python", "sqlite", "transactions", "sqlite3", "commit" ]
I'm trying to code a [book indexer](http://pastebin.com/YeBgbBAV) using Python (traditional, 2.7) and SQLite (3). The code boils down to this sequence of SQL statements: ``` 'select count(*) from tag_dict' () /* [(30,)] */ 'select count(*) from file_meta' () /* [(63613,)] */ 'begin transaction' () 'select id from arc...
Well, as it often happens I found the solution just a minutes after posing the question. The solution was [found here](http://www.velocityreviews.com/forums/t326247-pysql-lite-transactions-question.html) and consists of the only idea: ## Never use BEGIN/COMMIT in non-autocommit mode in Python application - use db.com...
How to load a pickle file containing a dictionary with unicode characters?
9,773,817
8
2012-03-19T16:18:57Z
9,773,891
8
2012-03-19T16:23:38Z
[ "python", "unicode", "dictionary", "pickle" ]
I have a dictionary: ``` mydict={'öö':1,'ää':2} ``` I have written it to a pickle file: ``` a=codecs.open(r'mydict.pkl', 'wb', 'utf-8') pickle.dump(mydict, a) ``` If I try to load it: ``` m=codecs.open(r'mydict.pkl', 'rb', 'utf-8') mydict = pickle.load(m) ``` I get an error: ``` KeyError: u"S'\\xe4\\xe4'\np1...
pickle is a binary format, using codec translations before writing will break it. Try to just write to a file and loading it back: ``` >>> mydict={'öö':1,'ää':2} >>> mydict {'\xc3\xb6\xc3\xb6': 1, '\xc3\xa4\xc3\xa4': 2} >>> pickle.dump(mydict, open('/tmp/test.pkl', 'wb')) >>> pickle.load(open('/tmp/test.pkl', 'rb'...
Append a NumPy array to a NumPy array
9,775,297
34
2012-03-19T17:55:24Z
9,775,350
20
2012-03-19T17:59:36Z
[ "python", "numpy" ]
I have a numpy\_array. Something like `[ a b c ]`. And then I want to append it into another NumPy array (just like we create a list of lists). How do we create an array of NumPy arrays containing NumPy arrays? I tried to do the following without any luck ``` >>> M = np.array([]) >>> M array([], dtype=float64) >>> M...
Well, the error message says it all: NumPy arrays do not have an `append()` method. There's a free function [`numpy.append()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.append.html) however: ``` numpy.append(M, a) ``` This will create a new array instead of mutating `M` in place. Note that using `nump...
Append a NumPy array to a NumPy array
9,775,297
34
2012-03-19T17:55:24Z
9,775,378
50
2012-03-19T18:01:37Z
[ "python", "numpy" ]
I have a numpy\_array. Something like `[ a b c ]`. And then I want to append it into another NumPy array (just like we create a list of lists). How do we create an array of NumPy arrays containing NumPy arrays? I tried to do the following without any luck ``` >>> M = np.array([]) >>> M array([], dtype=float64) >>> M...
``` In [1]: import numpy as np In [2]: a = np.array([[1, 2, 3], [4, 5, 6]]) In [3]: b = np.array([[9, 8, 7], [6, 5, 4]]) In [4]: np.concatenate((a, b)) Out[4]: array([[1, 2, 3], [4, 5, 6], [9, 8, 7], [6, 5, 4]]) ``` or this: ``` In [1]: a = np.array([1, 2, 3]) In [2]: b = np.array([4, 5, 6])...
Clamping floating numbers in Python?
9,775,731
15
2012-03-19T18:25:28Z
9,775,761
16
2012-03-19T18:26:51Z
[ "python", "math", "clamp" ]
Is there a built-in function for this in Python 2.6? Something like: ``` clamp(myValue, min, max) ```
There's no such function, but ``` max(min(my_value, max_value), min_value) ``` will do the trick.
Clamping floating numbers in Python?
9,775,731
15
2012-03-19T18:25:28Z
13,232,356
18
2012-11-05T12:41:41Z
[ "python", "math", "clamp" ]
Is there a built-in function for this in Python 2.6? Something like: ``` clamp(myValue, min, max) ```
Numpy's [`clip`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.clip.html) function will do this. ``` >>> import numpy >>> numpy.clip(10,0,3) 3 >>> numpy.clip(-4,0,3) 0 >>> numpy.clip(2,0,3) 2 ```
How do I stop tkinter after function?
9,776,718
4
2012-03-19T19:38:23Z
9,776,771
9
2012-03-19T19:42:55Z
[ "python", "button", "loops", "tkinter" ]
I'm having a problem stopping the 'feed'; the cancel argument doesn't seem to have any impact on the after method. Although "feed stopped" is printed to the console. I'm attempting to have one button that will start the feed and another that will stop the feed. ``` from Tkinter import Tk, Button import random de...
When you call `root.after(...)`, it will return an identifier. You should keep track of that identifier (e.g., store it in an instance variable), and then you can later call `root.after_cancel(after_id)` to cancel it.
How do I stop tkinter after function?
9,776,718
4
2012-03-19T19:38:23Z
9,777,453
8
2012-03-19T20:28:57Z
[ "python", "button", "loops", "tkinter" ]
I'm having a problem stopping the 'feed'; the cancel argument doesn't seem to have any impact on the after method. Although "feed stopped" is printed to the console. I'm attempting to have one button that will start the feed and another that will stop the feed. ``` from Tkinter import Tk, Button import random de...
The problem is that, even though you're calling `print_sleep` with `True` to stop the cycle, there's already a pending job waiting to fire. Pressing the stop button won't cause a new job to fire but the old job is still there, and when it calls itself, it passes in False which causes the loop to continue. You need to ...
Why does '.sort()' cause the list to be 'None' in Python?
9,777,122
7
2012-03-19T20:08:42Z
9,777,176
14
2012-03-19T20:11:29Z
[ "python", "list", "sorting" ]
I am attempting to sort a Python list of `int`s and then use the `.pop()` function to return the highest one. I have tried a writing the method in different ways: ``` def LongestPath(T): paths = [Ancestors(T,x) for x in OrdLeaves(T)] #^ Creating a lists of lists of ints, this part works result =[len(y)...
Simply remove the assignment from ``` result = result.sort() ``` leaving just ``` result.sort() ``` The `sort` method works in-place (it modifies the existing list), so no assignment is necessary, and it returns `None`. When you assign its result to the name of the list, you're assigning `None`. It can easily (and...
Why does '.sort()' cause the list to be 'None' in Python?
9,777,122
7
2012-03-19T20:08:42Z
9,777,440
8
2012-03-19T20:28:06Z
[ "python", "list", "sorting" ]
I am attempting to sort a Python list of `int`s and then use the `.pop()` function to return the highest one. I have tried a writing the method in different ways: ``` def LongestPath(T): paths = [Ancestors(T,x) for x in OrdLeaves(T)] #^ Creating a lists of lists of ints, this part works result =[len(y)...
This ``` result = result.sort() ``` should be this ``` result.sort() ``` It is a convention in Python that methods that mutate sequences return `None`. Consider: ``` >>> a_list = [3, 2, 1] >>> print a_list.sort() None >>> a_list [1, 2, 3] >>> a_dict = {} >>> print a_dict.__setitem__('a', 1) None >>> a_dict {'a':...
slicing numpy array into two parts
9,777,384
2
2012-03-19T20:24:26Z
9,777,447
7
2012-03-19T20:28:40Z
[ "python", "numpy" ]
I have a 2d numpy array Something like this: ``` [[ 1 2 3 4], [4,5,6,7].. ...... ] ] ``` Now I want to divide this into two parts. lets say the first numpy array has the first two elements. and the second numpy array has rest of the elements something like this ``` B = [[1 2 3 4], [4 5 6 7]] C = [[ rest...
This is covered in the [Indexing, Slicing, and Iterating](http://www.scipy.org/Tentative_NumPy_Tutorial#head-864862d3f2bb4c32f04260fac61eb4ef34788c4c) portion of the tutorial: ``` >>> import numpy as np >>> A = np.array([[1,2,3,4],[4,5,6,7],[7,8,9,10]]) >>> B = A[:2] >>> C = A[2:] >>> B array([[1, 2, 3, 4], [4,...
Suppress Scientific Notation in Numpy When Creating Array From Nested List
9,777,783
28
2012-03-19T20:54:15Z
10,854,323
57
2012-06-01T16:46:21Z
[ "python", "numpy" ]
I have a nested list that looks like the following: ``` my_list = [[3.74, 5162, 13683628846.64, 12783387559.86, 1.81], [9.55, 116, 189688622.37, 260332262.0, 1.97], [2.2, 768, 6004865.13, 5759960.98, 1.21], [3.74, 4062, 3263822121.39, 3066869087.9, 1.93], [1.91, 474, 44555062.72, 44555062.72, 0.41], [5.8, 5006, 8...
I guess what you need is `np.set_printoptions(suppress=True)`, for details see here: <http://pythonquirks.blogspot.fr/2009/10/controlling-printing-in-numpy.html>
Suppress Scientific Notation in Numpy When Creating Array From Nested List
9,777,783
28
2012-03-19T20:54:15Z
11,528,796
9
2012-07-17T18:40:47Z
[ "python", "numpy" ]
I have a nested list that looks like the following: ``` my_list = [[3.74, 5162, 13683628846.64, 12783387559.86, 1.81], [9.55, 116, 189688622.37, 260332262.0, 1.97], [2.2, 768, 6004865.13, 5759960.98, 1.21], [3.74, 4062, 3263822121.39, 3066869087.9, 1.93], [1.91, 474, 44555062.72, 44555062.72, 0.41], [5.8, 5006, 8...
for 1D and 2D arrays you can use np.savetxt to print using a specific format string: ``` >>> import sys >>> x = numpy.arange(20).reshape((4,5)) >>> numpy.savetxt(sys.stdout, x, '%5.2f') 0.00 1.00 2.00 3.00 4.00 5.00 6.00 7.00 8.00 9.00 10.00 11.00 12.00 13.00 14.00 15.00 16.00 17.00 18.00 19.00 ``` Your opt...
QtSql vs MySQLdb vs SQLAlchemy
9,778,602
4
2012-03-19T22:01:11Z
9,779,083
14
2012-03-19T22:49:08Z
[ "python", "mysql", "pyqt" ]
I'm developing a PyQt program that will soon switch from an xml type backend to one hosted on a local MySQL server. I've been trying to read around about each of the three options, but thought it might be best to ask ye SO gods. My current experience in MySQL execution with MySQLdb at the moment and have been using th...
I'm not a SO god, but I do have some input. My main experience with SQL in Python is with Django. The solution matters on what you're willing to commit to. If you want to stick with using the Qt libraries and just the PyQt libraries, then go with QtSql. If you want to just build your application quickly but pull in a ...
Is writing a daemon in Python a good idea?
9,779,200
18
2012-03-19T23:00:15Z
9,779,293
14
2012-03-19T23:10:54Z
[ "python", "daemon" ]
I have to write a daemon program that constantly runs in the background and performs some simple tasks. The logic is not complicated at all, however it has to run for extended periods of time and be stable. I think C++ would be a good choice for writing this kind of application, however I'm also considering Python sin...
I've written a number of daemons in Python for my last company. The short answer is, it works just fine. As long as the code itself doesn't have some huge memory bomb, I've never seen any gradual degradation or memory hogging. Be mindful of anything in the global or class scopes, because they'll live on, so use `del` m...
bash: pip: command not found
9,780,717
111
2012-03-20T02:43:07Z
9,780,772
20
2012-03-20T02:51:21Z
[ "python", "osx", "pip", "python-2.6" ]
I downloaded pip and ran `python setup.py install` and everything worked just fine. The very next step in the tutorial is to run `pip install <lib you want>` but before it even tries to find anything online I get an error "bash: pip: command not found". This is on Mac OS X, which I'm new too, so I'm assuming there's s...
pip would install itself into the bin of your python installation location. It also should create a symlink to some more common location like `/usr/local/bin/pip` You can either edit your `~/.profile` and update your PATH to include `/Library/Frameworks/Python.framework/Versions/2.6/bin`, or you could create a symlink...
bash: pip: command not found
9,780,717
111
2012-03-20T02:43:07Z
9,781,267
8
2012-03-20T04:14:58Z
[ "python", "osx", "pip", "python-2.6" ]
I downloaded pip and ran `python setup.py install` and everything worked just fine. The very next step in the tutorial is to run `pip install <lib you want>` but before it even tries to find anything online I get an error "bash: pip: command not found". This is on Mac OS X, which I'm new too, so I'm assuming there's s...
To solve: 1. Add this line to ~/.bash\_profile export PATH="/usr/local/bin:$PATH" 2. In a terminal window, run source ~/.bash\_profile
bash: pip: command not found
9,780,717
111
2012-03-20T02:43:07Z
9,781,752
173
2012-03-20T05:27:45Z
[ "python", "osx", "pip", "python-2.6" ]
I downloaded pip and ran `python setup.py install` and everything worked just fine. The very next step in the tutorial is to run `pip install <lib you want>` but before it even tries to find anything online I get an error "bash: pip: command not found". This is on Mac OS X, which I'm new too, so I'm assuming there's s...
Why not just do `sudo easy_install pip` or if this is for python 2.6 `sudo easy_install-2.6 pip`? This installs pip using the default python package installer system and saves you the hassle of manual set-up all at the same time. This will allow you to then run the `pip` command for python package installation as it ...
bash: pip: command not found
9,780,717
111
2012-03-20T02:43:07Z
18,166,102
84
2013-08-10T20:34:16Z
[ "python", "osx", "pip", "python-2.6" ]
I downloaded pip and ran `python setup.py install` and everything worked just fine. The very next step in the tutorial is to run `pip install <lib you want>` but before it even tries to find anything online I get an error "bash: pip: command not found". This is on Mac OS X, which I'm new too, so I'm assuming there's s...
Use setuptools to install `pip`: ``` sudo easy_install pip ``` (I know the above part of my answer is redundant with klobucar's, but I can't add comments yet), so here's an answer with a solution to `sudo: easy_install: command not found` on Debian/Ubuntu: ``` sudo apt-get install python-setuptools ``` Also, for py...
bash: pip: command not found
9,780,717
111
2012-03-20T02:43:07Z
26,688,123
13
2014-11-01T10:05:05Z
[ "python", "osx", "pip", "python-2.6" ]
I downloaded pip and ran `python setup.py install` and everything worked just fine. The very next step in the tutorial is to run `pip install <lib you want>` but before it even tries to find anything online I get an error "bash: pip: command not found". This is on Mac OS X, which I'm new too, so I'm assuming there's s...
I have to admit to being absolutely new to python, which I only need for one thing: awscli. I encountered this problem having downloaded python 3.x.x - pip: command not found Whilst following the instructions for downloading the AWS cli I changed ``` pip install awscli ``` to ``` pip3 install awscli ``` which ran ...
python member variable of instance works like member variable, and some works like static variable
9,781,334
8
2012-03-20T04:26:20Z
9,781,361
14
2012-03-20T04:30:29Z
[ "python" ]
i'm python newbie, and member variable of class works weird in my python code. some works like normal variable, but some works like static variable! ``` class Chaos: list_value = [] value = "default" def set_value(self, word): self.list_value.append(word) self.value = word def show(s...
Those are, in fact, class variables. To create instance variables, initialize them in the `__init__` function: ``` class Chaos: def __init__(self): self.list_value = [] self.value = "default" ``` The reason `value` is behaving like instance variables is because you're setting it using `self.value`...
Find all tables in html using BeautifulSoup
9,783,579
4
2012-03-20T08:38:04Z
9,783,625
11
2012-03-20T08:41:38Z
[ "python", "screen-scraping", "beautifulsoup" ]
I want to find all tables in html using BeautifulSoup. Inner tables should be included in outer tables. I have created some code which works and it gives expected output. But, I don't like this solution, because it destroys 'soup' object. Do you know how to do it in more elegant way ? ``` from BeautifulSoup import B...
use `soup.findAll("table")` instead of `find()` and `decompose()` : ``` tables = soup.findAll("table") for table in tables: if table.findParent("table") is None: print str(table) ``` output : ``` <table>table1<table>inner11<table>inner12</table></table></table> <table>table2<table>inner2</table></tabl...
Dynamically importing Python modules
9,783,691
7
2012-03-20T08:47:29Z
9,783,770
9
2012-03-20T08:53:13Z
[ "python", "import" ]
I am trying to import the members of a module whose name is not known. Instead of ``` import foo ``` I am using: ``` __import__("foo") ``` How can I achieve a similar thing for the `from foo import bar` case instead of resorting to an "eval"? **Update:** It seems `fromlist` did the trick. Is there a way to emulate...
``` __import__("foo", fromlist=["bar"]) ``` for more information `help(__import__)`
Dynamically importing Python modules
9,783,691
7
2012-03-20T08:47:29Z
9,784,370
9
2012-03-20T09:42:40Z
[ "python", "import" ]
I am trying to import the members of a module whose name is not known. Instead of ``` import foo ``` I am using: ``` __import__("foo") ``` How can I achieve a similar thing for the `from foo import bar` case instead of resorting to an "eval"? **Update:** It seems `fromlist` did the trick. Is there a way to emulate...
To emulate `from foo import *` you could use `dir` to get the attributes of the imported module: ``` foo = __import__('foo') for attr in dir(foo): if not attr.startswith('_'): globals()[attr] = getattr(foo, attr) ``` Using `from foo import *` is generally frowned upon, and emulating it even more so, I'd i...
lxml in python, parse from url
9,783,875
4
2012-03-20T09:03:34Z
9,784,281
7
2012-03-20T09:35:43Z
[ "python", "lxml", "python-2.7" ]
I am novice to lxml. I want to download the web page and get interested data from, my code is: ``` import urllib2 from lxml import etree url = "http://www.example.com/" html = urllib2.urlopen(url) root = etree.parse(html) # the problem is here ``` can anyone explain me why it is wrong? error is: ``` Traceback (m...
The key here is the exception: ``` IOError: Error reading file '<!DOCTYPE html PUBLIC ... ``` Youre passing the content of a file to a function that expects a path to a file. Same reason `doc = lxml.html.parse(url)` works, a url "is a" filepath. Does the following work better? ``` doc = lxml.html.fromstring(res.co...
Nested, infinite dictionary in python
9,783,983
2
2012-03-20T09:12:05Z
9,784,191
10
2012-03-20T09:28:50Z
[ "python", "dictionary" ]
I want set the keys and values ​​in the dictionary. Here is an example of what I do. ``` class NestedDict(dict): def __getitem__(self, key): if key in self: return self.get(key) return self.setdefault(key, NestedDict()) >>> c = NestedDict() >>> c {} >>> c['a']['b'] = 'test' >>> c['a']['c'] = 2...
Since `d` is non existent in `c['a']`, what kind of behaviour do you expect when you try to add `1` to it? It will first call `__getitem__`, not find the key and then return a `NestedDict` which doesn't support in place addition with an `int`. On a side note, It looks to me as though you're trying to implement a dicti...
Does Django send the signal pre_init/post_init when instances are loaded by a QuerySet?
9,784,422
2
2012-03-20T09:46:02Z
9,785,177
8
2012-03-20T10:39:08Z
[ "python", "django", "django-queryset" ]
I need to call an instance method on each instance loaded by a queryset. Can I use the pre\_init/post\_init signals for that?
Yes, pre\_init/post\_init is sent even when instances are created from querysets. Don't take my word for it, try it e.g.: ``` def pre_init_callback(sender, **kwargs): print 'pre_init', sender, kwargs pre_init.connect(pre_init_callback) def post_init_callback(sender, **kwargs): print 'post_init', sender, kwar...
numpy ndarray hashability
9,785,514
11
2012-03-20T11:03:30Z
9,786,043
7
2012-03-20T11:38:39Z
[ "python", "numpy" ]
I have some problems understanding how numpy objects hashability is managed. ``` >>> import numpy as np >>> class Vector(np.ndarray): ... pass >>> nparray = np.array([0.]) >>> vector = Vector(shape=(1,), buffer=nparray) >>> ndarray = np.ndarray(shape=(1,), buffer=nparray) >>> nparray array([ 0.]) >>> ndarray array...
I get the same results in Python 2.6.6 and numpy 1.3.0. According to [the Python glossary](http://docs.python.org/glossary.html#term-hashable), an object should be hashable if `__hash__` is defined (and is not `None`), and either `__eq__` or `__cmp__` is defined. `ndarray.__eq__` and `ndarray.__hash__` are both defined...
Module Object is Not Callable
9,785,651
2
2012-03-20T11:12:05Z
9,786,152
16
2012-03-20T11:46:26Z
[ "python", "object", "module" ]
For some reason I'm getting a module object is not callable error on this code. I don't really get why? Whats going on and how do I fix it? :( ``` import time start_time = time.time() name = raw_input('What is your name') end_time = time.time() total_time=end_time-start_time print total_time ``` and the traceback: `...
Don't call your own script file `time.py` ... it's importing itself!
how do I parallelize a simple python loop?
9,786,102
71
2012-03-20T11:42:42Z
9,786,225
65
2012-03-20T11:52:58Z
[ "python", "parallel-processing" ]
this is probably a trivial question, but how do I parallelize the following loop in python? ``` # setup output lists output1 = list() output2 = list() output3 = list() for j in range(0, 10): # calc individual parameter value parameter = j * offset # call the calculation out1, out2, out3 = calc_stuff(p...
Using multiple threads on CPython won't give you better performance for pure-Python code due to the global interpreter lock (GIL). I suggest using the [`multiprocessing`](http://docs.python.org/library/multiprocessing.html) module instead: ``` pool = multiprocessing.Pool(4) out1, out2, out3 = zip(*pool.map(calc_stuff,...
how do I parallelize a simple python loop?
9,786,102
71
2012-03-20T11:42:42Z
32,637,397
8
2015-09-17T18:20:37Z
[ "python", "parallel-processing" ]
this is probably a trivial question, but how do I parallelize the following loop in python? ``` # setup output lists output1 = list() output2 = list() output3 = list() for j in range(0, 10): # calc individual parameter value parameter = j * offset # call the calculation out1, out2, out3 = calc_stuff(p...
To parallelize a simple for loop, [joblib](https://pythonhosted.org/joblib/parallel.html) brings a lot of value to raw use of multiprocessing. Not only the short syntax, but also things like transparent bunching of iterations when they are very fast (to remove the overhead) or capturing of the traceback of the child pr...
How to build pgmagick under pythonbrew on OS X?
9,786,515
7
2012-03-20T12:12:52Z
9,879,782
8
2012-03-26T20:59:43Z
[ "python", "osx", "pythonbrew" ]
I'm not having much success when attempting building `pgmagick` on OS X Lion with XCode 4.3.1. I've installed both ImageMagick and GraphicsMagick, along side boost, using the following commands (via homebrew): ``` $ brew install graphicsmagick --with-magick-plus-plus $ brew install imagemagick --with-magick-plus-plus...
According to my own reproduction of this issue in brew 0.9 and OSX 10.6.8, the problem is `--with-thread-unsafe` isn't being honored by the current brew formula file. You can verify this by checking the formula with `brew edit boost` and seeing if the option appears within the contents of the formula. Because of this,...
TypeError: expected a character buffer object - while trying to save integer to textfile
9,786,941
34
2012-03-20T12:40:27Z
9,787,008
49
2012-03-20T12:45:29Z
[ "python", "file", "parsing" ]
I'm trying to make a *very* simple 'counter' that is supposed to keep track of how many times my program has been executed. First, I have a textfile that only includes one character: `0` Then I open the file, parse it as an `int`, add `1` to the value, and then try to return it to the textfile: ``` f = open('testfil...
Have you checked the docstring of `write()`? It says: > write(str) -> None. Write string str to file. > > Note that due to buffering, flush() or close() may be needed before > the file on disk reflects the data written. So you need to convert `y` to `str` first. Also note that the string will be written at the curre...
TypeError: expected a character buffer object - while trying to save integer to textfile
9,786,941
34
2012-03-20T12:40:27Z
9,787,166
7
2012-03-20T12:54:53Z
[ "python", "file", "parsing" ]
I'm trying to make a *very* simple 'counter' that is supposed to keep track of how many times my program has been executed. First, I have a textfile that only includes one character: `0` Then I open the file, parse it as an `int`, add `1` to the value, and then try to return it to the textfile: ``` f = open('testfil...
``` from __future__ import with_statement with open('file.txt','r+') as f: counter = str(int(f.read().strip())+1) f.seek(0) f.write(counter) ```
join or merge with overwrite in pandas
9,787,853
12
2012-03-20T13:36:09Z
9,794,891
13
2012-03-20T21:02:32Z
[ "python", "pandas" ]
I want to perform a join/merge/append operation on a dataframe with datetime index. Let's say I have `df1` and I want to add `df2` to it. `df2` can have fewer or more columns, and overlapping indexes. For all rows where the indexes match, if `df2` has the same column as `df1`, I want the values of `df1` be overwritten...
How about: `df2.combine_first(df1)`? ``` In [33]: df2 Out[33]: A B C D 2000-01-03 0.638998 1.277361 0.193649 0.345063 2000-01-04 -0.816756 -1.711666 -1.155077 -0.678726 2000-01-05 0.435507 -0.025162 -1.112890 0.324111 2000-01-06 -0.210756 -1.027164 0.036664 0.884715 ...
Assign class boolean value in Python
9,787,890
8
2012-03-20T13:38:00Z
9,787,942
17
2012-03-20T13:41:01Z
[ "python", "class", "condition" ]
If statements in Python allow you to do something like: ``` if not x: print "X is false." ``` This works if you're using an empty list, an empty dictionary, None, 0, etc, but what if you have your own custom class? Can you assign a false value for that class so that in the same style of conditional, it will...
You need to implement the [`__nonzero__`](http://docs.python.org/reference/datamodel.html#object.__nonzero__) method on your class. This should return True or False to determine the truth value: ``` class MyClass(object): def __init__(self, val): self.val = val def __nonzero__(self): return sel...
How to get the most recent file
9,788,119
4
2012-03-20T13:50:25Z
9,788,258
8
2012-03-20T13:57:45Z
[ "python", "file" ]
i am newbie in Python language and i need write a code that list directory that contains files with random names, for example: > JuniperAccessLog-standalone-FCL\_VPN-20120319-1110.gz > JuniperAccessLog-standalone-FCL\_VPN-20120321-1110.gz I need get the more recent file I try this, but without success. ``` import...
If you want the most recent file, you could take advantage of the fact that they appear to sort into date time order: ``` import os logdir='.' # path to your log directory logfiles = sorted([ f for f in os.listdir(logdir) if f.startswith('JuniperAccessLog-standalone-FCL_VPN')]) print "Most recent file = %s" % (logf...
Numpy accumulating one array in another using index array
9,790,436
10
2012-03-20T16:04:33Z
9,790,857
14
2012-03-20T16:28:38Z
[ "python", "arrays", "numpy" ]
My question is about a specific array operation that I want to express using numpy. I have an array of floats `w` and an array of indices `idx` of the same length as `w` and I want to sum up all `w` with the same `idx` value and collect them in an array `v`. As a loop, this looks like this: ``` for i, x in enumerate(...
`numpy.bincount` was introduced for this purpose: ``` tmp = np.bincount(idx, w) v[:len(tmp)] += tmp ``` I think as of 1.6 you can also pass a minlength to `bincount`.
Why is getattr() so much slower than self.__dict__.get()?
9,790,991
10
2012-03-20T16:35:24Z
9,791,053
12
2012-03-20T16:38:12Z
[ "python", "python-2.7", "getattr" ]
The example below is from a REST database driver on Python 2.7. In the `__setattr__` method below, if I use the commented out `getattr()` line, it reduces the object instantiation performance from 600 rps to 230. Why is `getattr()` so much slower than `self.__dict__.get()` in this case? ``` class Element(object): ...
In short: because `getattr(foo,bar)` [does the same thing as `foo.bar`](http://docs.python.org/library/functions.html#getattr), which is not the same thing as just accessing the `__dict__` property (for a start, `getattr` has to select the right `__dict__`, but there's a whole lot more going on). Details contained in,...
removing `u` character in python output
9,791,055
2
2012-03-20T16:38:23Z
9,791,207
8
2012-03-20T16:46:40Z
[ "javascript", "python", "google-app-engine", "angularjs" ]
I create a form and when I click the submit button, I assign the 3 value into a javascript dict and send it over to a python script to process however My web browser tell me a error! from Json error: {u'food': 90, u'cargo': 70, u'fuel': 50} SyntaxError controller.js ``` function customiseCtrl($xhr){ var self = this;...
Printing a Python dict will in many cases not generate valid JSON. You want the `json` module: ``` import json # ... snip ... self.response.out.write(json.dumps(info)) # or json.dump(info, self.response.out) ```
How do I refresh the values on an object in Django?
9,791,947
20
2012-03-20T17:30:40Z
9,836,636
11
2012-03-23T09:20:18Z
[ "python", "django", "django-models" ]
I have a model object in Django. One of the methods on the object uses row-level locking to ensure values are accurate, like so: ``` class Foo(model.Model): counter = models.IntegerField() @transaction.commit_on_success def increment(self): x = Foo.objects.raw("SELECT * from fooapp_foo WHERE id = ...
I assume you must need to do this from within the class itself, or you would just do something like: ``` def refresh(obj): """ Reload an object from the database """ return obj.__class__._default_manager.get(pk=obj.pk) ``` But doing that internally and replacing `self` gets ugly...
How do I refresh the values on an object in Django?
9,791,947
20
2012-03-20T17:30:40Z
27,582,098
33
2014-12-20T16:24:10Z
[ "python", "django", "django-models" ]
I have a model object in Django. One of the methods on the object uses row-level locking to ensure values are accurate, like so: ``` class Foo(model.Model): counter = models.IntegerField() @transaction.commit_on_success def increment(self): x = Foo.objects.raw("SELECT * from fooapp_foo WHERE id = ...
Finally, in **Django 1.8**, we have a specific method to do this. It's called [refresh\_from\_db](https://docs.djangoproject.com/en/dev/ref/models/instances/#refreshing-objects-from-database) and it's a new method of the class `django.db.models.Model`. An example of usage: ``` def update_result(self): obj = MyMod...
Set changes element order?
9,792,664
21
2012-03-20T18:19:39Z
9,792,680
29
2012-03-20T18:21:25Z
[ "python", "set" ]
Recently I noticed that when I am converting list to set the order or elements is changed and is sorted by character. Consider this example: ``` x=[1,2,20,6,210] print x # [1, 2, 20, 6, 210] # the order is same as initial order set(x) # set([1, 2, 20, 210, 6]) # in the set(x) output order is sorted ``` My question...
1. A `set` is an unordered data structure. 2. Don't use a `set`, but rather `collections.OrderedDict`: ``` >>> a = collections.OrderedDict.fromkeys([1, 2, 20, 6, 210]) >>> b = collections.OrderedDict.fromkeys([6, 20, 1]) >>> collections.OrderedDict.fromkeys(x for x in a if x not in b) OrderedDict([(2, N...
Set changes element order?
9,792,664
21
2012-03-20T18:19:39Z
9,793,068
8
2012-03-20T18:49:39Z
[ "python", "set" ]
Recently I noticed that when I am converting list to set the order or elements is changed and is sorted by character. Consider this example: ``` x=[1,2,20,6,210] print x # [1, 2, 20, 6, 210] # the order is same as initial order set(x) # set([1, 2, 20, 210, 6]) # in the set(x) output order is sorted ``` My question...
Answering your first question, set is a data structure optimized for set operations, and like a mathematical set, it does not enforce/maintain any particular order of the elements. The abstract concept of set does no enforce order, so does not the implementation. When you create a set from a list, python takes the libe...
How to create Dict from array in python
9,793,603
3
2012-03-20T19:30:17Z
9,793,627
11
2012-03-20T19:32:53Z
[ "python", "dictionary" ]
Have: ``` keys = ['a', 'b','c','d'] ``` numpy array.... ``` array = numpy.array([[1, 2, 3, 5], [6, 7, 8, 10], [11, 12, 13, 15]]) ``` want ``` my_dict = {'a': [1,6,11], 'b': [2,7,12], 'c': [3,7,13], 'd': [5,10,15]} ```
Transpose the array, `zip()` the keys with the result and convert to a `dict`: ``` dict(zip(keys, zip(*array))) ``` Since `array` is a NumPy array, you can also use ``` dict(zip(keys, array.T))) ```
Creating a relative symlink in python without using os.chdir()
9,793,631
4
2012-03-20T19:33:26Z
9,793,699
10
2012-03-20T19:37:54Z
[ "python", "multithreading", "symlink" ]
Say I have a path to a file: ``` /path/to/some/directory/file.ext ``` In python, I'd like to create a symlink in the same directory as the file, that points to the file. I'd like to end up with this: ``` /path/to/some/directory/symlink -> file.ext ``` I can do this fairly easily using os.chdir() to cd into the dire...
You could just set the second argument to the destination, like: ``` import os os.symlink('file.ext', '/path/to/some/directory/symlink') ```
Creating a relative symlink in python without using os.chdir()
9,793,631
4
2012-03-20T19:33:26Z
13,353,846
10
2012-11-13T00:22:10Z
[ "python", "multithreading", "symlink" ]
Say I have a path to a file: ``` /path/to/some/directory/file.ext ``` In python, I'd like to create a symlink in the same directory as the file, that points to the file. I'd like to end up with this: ``` /path/to/some/directory/symlink -> file.ext ``` I can do this fairly easily using os.chdir() to cd into the dire...
You can also use `os.path.relpath()` so that you can use symlinks with relative paths. Say your script is in a directory `foo/` and this directory has subdirectories `src/` and `dst/`, and you want to create relative symlinks in `dst/` to point to the files in `src/`. To do so, you can do: ``` import os from glob impo...
how to replace every n-th value of an array in python most efficiently?
9,793,731
4
2012-03-20T19:40:33Z
9,793,759
19
2012-03-20T19:42:50Z
[ "python", "numpy" ]
I was wondering whether there is a more pythonic (and efficient) way of doing the following: ``` MAX_SIZE = 100 nbr_elements = 10000 y = np.random.randint(1, MAX_SIZE, nbr_elements) REPLACE_EVERY_Nth = 100 REPLACE_WITH = 120 c = 0 for index, item in enumerate(y): c += 1 if (c % REPLACE_EVERY_Nth == 0): ...
Use a slicing with `REPLACE_EVERY_Nth` as step value: ``` y[::REPLACE_EVERY_Nth] = REPLACE_WITH ``` This is slightly different from your code, since it will start with the very first item (i.e. index 0). To get exactly what your code does, use ``` y[REPLACE_EVERY_Nth - 1::REPLACE_EVERY_Nth] = REPLACE_WITH ```
Convert numpy array to PySide QPixmap
9,794,019
14
2012-03-20T20:01:03Z
9,796,921
12
2012-03-21T00:19:25Z
[ "python", "numpy", "pyside" ]
I want to convert an image into a NumPy array to a PySide QPixmap, so I can display it (EDIT: in my PySide UI). I already found this tool: [qimage2ndarray](http://kogs-www.informatik.uni-hamburg.de/~meine/software/qimage2ndarray/), but it only works for PyQt4. I tried to change it to get it working with PySide, but I w...
One alternative is to just use PIL library. ``` >>> import numpy as np >>> import Image >>> im = Image.fromarray(np.random.randint(0,256,size=(100,100,3)).astype(np.uint8)) >>> im.show() ``` You can look at the QPixmap constructor at <http://www.pyside.org/docs/pyside/PySide/QtGui/QImage.html>. It looks like you sho...
Convert numpy array to PySide QPixmap
9,794,019
14
2012-03-20T20:01:03Z
10,015,277
7
2012-04-04T16:21:33Z
[ "python", "numpy", "pyside" ]
I want to convert an image into a NumPy array to a PySide QPixmap, so I can display it (EDIT: in my PySide UI). I already found this tool: [qimage2ndarray](http://kogs-www.informatik.uni-hamburg.de/~meine/software/qimage2ndarray/), but it only works for PyQt4. I tried to change it to get it working with PySide, but I w...
If you create the data yourself, using numpy for example, I think the fastest method is to directly access a QImage. You can create a ndarray from the buffer object QImage.bits(), do some work using the numpy methods and create a QPixmap from QImage when you are done. You can also read or modify existing QImages that w...
python-tesseract OCR: get digits only
9,794,029
11
2012-03-20T20:01:45Z
9,805,486
13
2012-03-21T13:22:09Z
[ "python", "tesseract" ]
I'm using tesseract OCRwith python-tesseract. In the [tesseract FAQ](http://code.google.com/p/tesseract-ocr/wiki/FAQ), regarding digits, we have: > Use > > `TessBaseAPI::SetVariable("tessedit_char_whitelist", "0123456789");` > > BEFORE calling an Init function or put this in a text file called > tessdata/configs/digit...
OK, got it working. According to this [(unofficial ?) documentation](http://fossies.org/dox/tesseract-3.01/classtesseract_1_1TessBaseAPI.html#a2e09259c558c6d8e0f7e523cbaf5adf5) of tesseract-ocr, SetVariable() must be called after Init(), even though the opposite is said in the official FAQ. Calling it after Init() work...
Shared library dependencies with distutils
9,795,793
14
2012-03-20T22:10:27Z
10,252,190
9
2012-04-20T19:13:52Z
[ "python", "distribution", "packaging", "distutils", "software-distribution" ]
I'm a newbie to distutils and I have a problem that really has me stuck. I am compiling a package that requires an extension, so I make the extension thus: ``` a_module = Extension( "amodule", ["initmodule.cpp"], library_dirs=libdirs, extra_objects = [ "u...
You can pass flags to the compiler or linker to let it know where to find libraries at runtime, alleviating the need to have LD\_LIBRARY\_PATH set properly. I'll illustrate with a few examples: ``` # Will link just fine, then fail to find libpcap.so unless it's in LD_LIBRARY_PATH gcc -o blah blah.o -lpcap -L/opt/csw/l...
Multiple occurences of same character in a string regexp - Python
9,795,955
4
2012-03-20T22:25:58Z
9,796,075
11
2012-03-20T22:38:15Z
[ "python", "regex" ]
Given a string made up of 3 capital letters, 1 small caps and another 3 capital ones, e.g. AAAaAAA I can't seem to find a regexp that would find a string which matches a string that has: * first 3 capital letters all different * any small caps letter * first 2 same capital letters as the very first one * last capital...
The following should work: ``` ^([A-Z])(?!.?\1)([A-Z])(?!\2)([A-Z])[a-z]\1\1\3$ ``` For example: ``` >>> regex = re.compile(r'^([A-Z])(?!.?\1)([A-Z])(?!\2)([A-Z])[a-z]\1\1\3$') >>> regex.match('ABAaAAA') # fails: first three are not different >>> regex.match('ABCaABC') # fails: first two of second three are not fi...
how soon is `__del__` called after reference count drops to zero?
9,796,643
4
2012-03-20T23:38:44Z
9,796,689
11
2012-03-20T23:45:02Z
[ "python", "garbage-collection", "python-3.x", "destructor" ]
How soon after the reference count reaches zero is `__del__` method called? Does the language promise that it's done right away, before any other use code can execute? Or can each implementation do what it likes, potentially delaying the call to `__del__` arbitrarily long? Please ignore the situation when the program ...
Python doesn't make any guarantees about when `__del__` is called, or *whether it is called at all*. As it is, `__del__` methods are unlikely to be called if the object is part of a reference cycle, because even if the cycle as a whole is cleaned up, Python has no way to decide where to break the cycle and in what orde...
Creating Python daemon - 'module' object has no attribute 'DaemonContext'
9,796,746
7
2012-03-20T23:52:03Z
9,796,905
13
2012-03-21T00:16:42Z
[ "python", "python-daemon" ]
I'm trying to daemonize my app and am getting the error: ``` out: with daemon.DaemonContext(): out: AttributeError: 'module' object has no attribute 'DaemonContext' ``` It looks like other people are getting this error from the module not being installed. As a newcomer to Python it's a bit confusing that there is...
The program that produces the error is apparently using a *different* module named `daemon`. Did you perhaps call the program itself, or another module in the same directory, `daemon.py`? If so then that will shadow the installed `daemon` module. Rename `daemon.py` (and delete the `daemon.pyc` file that Python will hav...
Creating Python daemon - 'module' object has no attribute 'DaemonContext'
9,796,746
7
2012-03-20T23:52:03Z
18,300,894
15
2013-08-18T15:48:48Z
[ "python", "python-daemon" ]
I'm trying to daemonize my app and am getting the error: ``` out: with daemon.DaemonContext(): out: AttributeError: 'module' object has no attribute 'DaemonContext' ``` It looks like other people are getting this error from the module not being installed. As a newcomer to Python it's a bit confusing that there is...
I run on this proglem too. If I call `print daemon.__file__` it prints `/usr/local/lib/python2.6/dist-packages/daemon.pyc`, which is right file in wrong place, meaning that I have installed packege wrong way. I used command "sudo pip install daemon", which installs only daemon.py file. We should use commnd "sudo pip i...
Django ajax error response best practice
9,797,253
8
2012-03-21T01:02:03Z
9,799,831
17
2012-03-21T06:49:08Z
[ "jquery", "python", "ajax", "django" ]
I'm using ajax to improve user experience in my Django project. My concern here is how to respond error to browser properly. As far as I know, I can either: 1. validate request data piece by piece and guard exception one by one. If something bad happens, raise Http404 or other exception to explicitly announce an error...
If you return a response with a status code of 4xx or 5xx this is a an error and will trigger jQueries `error` handler. While it is certainly possible to simple return status 200 every time and use a "error" field in the JSON response (like suggested by dm03514) this is bad for two reasons: 1. It violates good HTTP pr...
How to install pip in a new python installation
9,797,277
18
2012-03-21T01:03:48Z
9,797,315
17
2012-03-21T01:09:25Z
[ "python", "python-2.7", "pip" ]
I recently installed python 2.7.2 on my Mac running OSX 10.6.8. Previously, I had version 2.6. I set my path in .bash\_profile as follows: ``` export PATH=/usr/local/bin:$PATH export PATH=/usr/local/share/python:$PATH ``` so that when I run python it will refer to my new installation. It does. I would also like to u...
Install distribute as per the instructions at <http://pypi.python.org/pypi/distribute> . Make sure you specify the full path to the python executable (`/usr/local/share/python/python` or smth in your case). ``` $ curl -O https://svn.apache.org/repos/asf/oodt/tools/oodtsite.publisher/trunk/distribute_setup.py $ /usr/lo...
Dividing a string at various punctuation marks using split()
9,797,357
4
2012-03-21T01:16:38Z
9,797,398
8
2012-03-21T01:22:47Z
[ "python", "string", "split" ]
I'm trying to divide a string into words, removing spaces and punctuation marks. I tried using the `split()` method, passing all the punctuation at once, but my results were incorrect: ``` >>> test='hello,how are you?I am fine,thank you. And you?' >>> test.split(' ,.?') ['hello,how are you?I am fine,thank you. And yo...
If you want to split a string based on *multiple* delimiters, as in your example, you're going to need to use the `re` module despite your bizarre objections, like this: ``` >>> re.split('[?.,]', test) ['hello', 'how are you', 'I am fine', 'thank you', ' And you', ''] ``` It's *possible* to get a similar result using...
Dividing a string at various punctuation marks using split()
9,797,357
4
2012-03-21T01:16:38Z
9,797,403
10
2012-03-21T01:23:31Z
[ "python", "string", "split" ]
I'm trying to divide a string into words, removing spaces and punctuation marks. I tried using the `split()` method, passing all the punctuation at once, but my results were incorrect: ``` >>> test='hello,how are you?I am fine,thank you. And you?' >>> test.split(' ,.?') ['hello,how are you?I am fine,thank you. And yo...
This is the best way I can think of without using the re module: ``` "".join((char if char.isalpha() else " ") for char in test).split() ```
How to use libxml2 with python on osx lion?
9,797,402
4
2012-03-21T01:23:20Z
9,797,504
12
2012-03-21T01:36:15Z
[ "python", "osx-lion", "libxml2" ]
I'm on OSX Lion and I have libxml2 installed (by default) and I have python installed (by default) but they don't talk to one another. What's the simplest way to make this work on Lion? ``` $ python -c "import libxml2" Traceback (most recent call last): File "<string>", line 1, in <module> ImportError: No module nam...
1. Visit <ftp://xmlsoft.org/libxml2/python/> and ensure [this is the latest version](ftp://xmlsoft.org/libxml2/python/libxml2-python-2.6.21.tar.gz) 2. Download it 3. unpack it 4. open a term and cd to that directory 5. type `sudo python setup.py install` 6. `ls /Library/Python/2.7/site-packages/` and you should see a b...
elegant way to print "==== middle justified title ====" in python
9,797,758
2
2012-03-21T02:16:13Z
9,797,771
9
2012-03-21T02:18:45Z
[ "python" ]
As I know, there are some elegant ways to print left and right justified string with filling. like this ``` str = "left_justified" str.ljust(20, '0'); ``` or ``` print "{0:{1}<20}".format(str, "=") ``` result will be ``` left_justified===== ``` what is the best way to print middle-justified string with filling
``` >>> "hello".center(50, '=') '======================hello=======================' ```
Enforcing PEP-8'ish formatting in Github commits
9,799,209
8
2012-03-21T05:45:37Z
9,800,351
8
2012-03-21T07:35:40Z
[ "python", "git", "github" ]
Are there any premade solutions to enforce good Python standards in Git commit hooks? Are there way to automamize this process in local checkouts (akin Bazaar where one can push commit hooks to clients)? It should be enough that when you checkout a repo it would come with commit hooks installed, no further work / comm...
You could add a service on GitHub side (see "[GitHub - All the Hooks](https://github.com/blog/964-all-of-the-hooks)", and the [existing third-party services](https://github.com/github/github-services/tree/master/services)). But you cannot "push a hook" (see "[why it is not possible to git add .git/hooks/my-hook](http:...
Is tornado.database asynchronous or not?
9,800,483
2
2012-03-21T07:47:19Z
9,800,509
7
2012-03-21T07:48:53Z
[ "python", "asynchronous", "tornado" ]
Tornado provides a **tornado.database** wrapper to access MySQL database: [www.tornadoweb.org/documentation/database.html](http://www.tornadoweb.org/documentation/database.html) But in documentation I can't find anything about callbacks handlers for methods like **query()**. The same situation is for other methods **C...
The tornado database wrapper is not asynchronous, no. Tornado was written to power FriendFeed, who decided that an asynchronous DB layer was unnecessary because they simply made sure all of their DB calls were extremely short.
Python-mysql: when to explicitly rollback a transaction
9,802,102
10
2012-03-21T09:51:42Z
9,804,463
10
2012-03-21T12:18:03Z
[ "python", "mysql", "mysql-python" ]
Suppose, I have a modifying statement: ``` cursor = conn.cursor() # some code affected_rows1 = cursor.execute(update_statement1, params1) # some code conn.commit() cursor.close() ``` **Should I wrap the block of code with a `try ... except` and explicitly rollback a transaction when an exception is raised, and which ...
[This link](http://mysql-python.sourceforge.net/MySQLdb-1.2.2/private/_mysql_exceptions-module.html) shows the various types of Errors that you can catch. `MySQLdb.Error` is the standard base class from which all other MySQL Errors are derived. I usually use `MySQLdb.Error` because it lets you focus on errors relating...
SQLite python does not update table
9,804,073
5
2012-03-21T11:50:04Z
9,804,118
8
2012-03-21T11:53:11Z
[ "python", "sql", "sqlite3" ]
I have the following code: ``` import sqlite3 con = sqlite3.connect("testDB") cur = con.cursor() #cur.execute('CREATE TABLE test_table (id integer primary key, data text)') cur.execute('INSERT INTO test_table VALUES (?, ?)', (76, 'MyData')) ``` when I run this script it does not update table. But when I do the same...
``` # Save (commit) the changes con.commit() ```
Why I can't read any character in this Python code
9,805,089
2
2012-03-21T12:55:57Z
9,805,129
11
2012-03-21T12:59:33Z
[ "python", "file", "io" ]
I know, `w+` means both `read` and `write`, then I write this code to read some message from a txt file and write some message into it This is my code: ``` f = open('test', 'w+') f.write('yes yes yes\n') print f.read() ...... f.close() ``` when i run it, It only print newline, and didn't print `yes yes yes` then I ...
You should put cursor at the beginning of file before reading. ``` f.seek(0) f.read() ```
How to find names of all collections using PyMongo?
9,805,451
13
2012-03-21T13:19:36Z
9,805,506
21
2012-03-21T13:22:59Z
[ "python", "pymongo" ]
How to find names of all collections using PyMongo and find all fields in chosen collection ? I have name of database and name of chosen collection. (Scenario : user input name of database, need to find all collections and show in dropdown list, when user click on one item need to find all fields in that collection)
To find the collections, you can use `collection_names()` - <http://api.mongodb.org/python/current/api/pymongo/database.html#pymongo.database.Database.collection_names>
How to use python's import function properly __import__()
9,806,963
18
2012-03-21T14:48:18Z
9,811,035
21
2012-03-21T18:55:47Z
[ "python", "import" ]
I'm trying to replicate `from foo.bar import object` using the `__import__` function and I seem to have hit a wall. `from glob import glob` is easy: `glob = __import__("glob",glob)`or `glob = __import__("glob").glob` The problem I'm having is that I am importing from a package (i.e. bar) and I want the script in the ...
The import statement will return the top level module of a package, unless you pass the following additional arguments. ``` _temp = __import__('foo.bar', globals(), locals(), ['object'], -1) object = _temp.object ``` See Python docs on [`__import__` statement](http://docs.python.org/library/functions.html#__import__...
How to use python's import function properly __import__()
9,806,963
18
2012-03-21T14:48:18Z
26,476,048
7
2014-10-20T22:34:01Z
[ "python", "import" ]
I'm trying to replicate `from foo.bar import object` using the `__import__` function and I seem to have hit a wall. `from glob import glob` is easy: `glob = __import__("glob",glob)`or `glob = __import__("glob").glob` The problem I'm having is that I am importing from a package (i.e. bar) and I want the script in the ...
You should use `importlib.import_module`, `__import__` is not advised outside the interpreter. In `__import__`'s doc: > Import a module. Because this function is meant for use by the Python > interpreter and not for general use it is better to use > importlib.import\_module() to programmatically import a module. It ...
PHP: get array value as in Python?
9,807,615
12
2012-03-21T15:24:42Z
9,807,690
8
2012-03-21T15:29:09Z
[ "php", "python", "arrays", "get", "default" ]
In Python I can use "get" method to get value from an dictionary without error. ``` a = {1: "a", 2: "b"} a[3] # error a.get(3, "") # I got empty string. ``` So I search for a common/base function that do this: ``` function GetItem($Arr, $Key, $Default){ $res = ''; if (array_key_exists($Key, $Arr)) { ...
[`isset()`](http://php.net/manual/function.isset.php) is typically faster than `array_key_exists()`. The parameter `$default` is initialized to an empty string if omitted. ``` function getItem($array, $key, $default = "") { return isset($array[$key]) ? $array[$key] : $default; } // Call as $array = array("abc" => 1...
Find all occurences of a key in nested python dictionaries and lists
9,807,634
21
2012-03-21T15:26:08Z
9,807,955
18
2012-03-21T15:40:50Z
[ "python", "recursion", "dictionary", "traversal" ]
I have a dictionary like this: ``` { "id" : "abcde", "key1" : "blah", "key2" : "blah blah", "nestedlist" : [ { "id" : "qwerty", "nestednestedlist" : [ { "id" : "xyz", "keyA" : "blah blah blah" }, { "id" : "fghi", "keyZ" : "blah blah blah" }], "anothernestedne...
``` d = { "id" : "abcde", "key1" : "blah", "key2" : "blah blah", "nestedlist" : [ { "id" : "qwerty", "nestednestedlist" : [ { "id" : "xyz", "keyA" : "blah blah blah" }, { "id" : "fghi", "keyZ" : "blah blah blah" }], "anothernestednestedlist" : [ { "id" : "asdf"...
Find all occurences of a key in nested python dictionaries and lists
9,807,634
21
2012-03-21T15:26:08Z
29,652,561
7
2015-04-15T14:09:34Z
[ "python", "recursion", "dictionary", "traversal" ]
I have a dictionary like this: ``` { "id" : "abcde", "key1" : "blah", "key2" : "blah blah", "nestedlist" : [ { "id" : "qwerty", "nestednestedlist" : [ { "id" : "xyz", "keyA" : "blah blah blah" }, { "id" : "fghi", "keyZ" : "blah blah blah" }], "anothernestedne...
I found this Q/A very interesting, since it provides several different solutions for the same problem. I took all these functions and tested them with a complex dictionary object. I had to take two functions out of the test, because they had to many fail results and they did not support returning lists or dicts as valu...