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
Do overridden methods inherit decorators in python?
4,350,260
22
2010-12-03T22:05:13Z
4,350,337
13
2010-12-03T22:17:22Z
[ "python", "inheritance", "decorator" ]
Just like the title says, do overridden methods inherit decorators? ``` class A: @memoized def fun(self, arg): return None class B(A): def fun(self, arg): #computations return something ``` so does B.fun() maintain the decorator?
Think about it this way ``` class A(object): def fun(self, arg): return None fun = memoized(fun) ```
How to put arbitrary widgets into a gtk.Menu?
4,350,470
6
2010-12-03T22:32:53Z
4,350,500
8
2010-12-03T22:37:32Z
[ "python", "menu", "gtk", "pygtk" ]
How can any gtk.Widget (eg. a progress bar) be put into a gtk.Menu as one of the menu items?
Quoting from the [PyGTK documentation](http://library.gnome.org/devel/pygtk/stable/class-gtkmenuitem.html): > The gtk.MenuItem and its derived > widget subclasses are the only valid > children of menus. So the answer is: You can't. But: > As a gtk.MenuItem is a subclass of gtk.Bin it can hold any valid child widget....
How can I create a ramdisk in Python?
4,351,048
25
2010-12-04T00:06:07Z
4,353,956
13
2010-12-04T14:26:07Z
[ "python", "unit-testing", "cross-platform", "temporary-files", "ramdisk" ]
I want to create a ramdisk in Python. I want to be able to do this in a cross-platform way, so it'll work on Windows XP-to-7, Mac, and Linux. I want to be able to read/write to the ramdisk like it's a normal drive, preferably with a drive letter/path. The reason I want this is to write tests for a script that creates ...
How about [PyFilesystem](http://docs.pyfilesystem.org/)? <http://docs.pyfilesystem.org/en/latest/memoryfs.html#module-fs.memoryfs> <http://docs.pyfilesystem.org/en/latest/tempfs.html#module-fs.tempfs> The downside is that you have to access the filesystem with PyFilesystem API, but you can also access the real fs wi...
Python & Ctypes: Passing a struct to a function as a pointer to get back data
4,351,721
8
2010-12-04T03:11:14Z
4,353,259
15
2010-12-04T11:23:28Z
[ "python", "pointers", "struct", "ctypes" ]
I've looked through other answers but can't seem to get this to work. I'm trying to call a function within a DLL for communicating with SMBus devices. This function takes a pointer to a struct, which has an array as one of it's fields. so... In C: ``` typedef struct _SMB_REQUEST { unsigned char Address; unsig...
Here's a working example. It looks like you are passing the wrong type to the function. ### Test DLL Code ("cl /W4 /LD x.c" on Windows) ``` #include <stdio.h> #define SMBUS_API __declspec(dllexport) #define SMB_MAX_DATA_SIZE 5 typedef void* SMBUS_HANDLE; typedef struct _SMB_REQUEST { unsigned char Address; ...
Python, should I implement __ne__() operator based on __eq__?
4,352,244
42
2010-12-04T06:18:35Z
4,352,272
38
2010-12-04T06:26:22Z
[ "python", "comparison", "operators", "python-datamodel" ]
I have a class where I want to override the `__eq__()` operator. It seems to make sense that I should override the `__ne__()` operator as well, but does it make sense to implement `__ne__` based on `__eq__` as such? ``` class A: def __eq__(self, other): return self.value == other.value def __ne__(self...
Yes, that's perfectly fine. In fact, [the documentation](http://docs.python.org/reference/datamodel.html#object.__ne__) urges you to define `__ne__` when you define `__eq__`: > There are no implied relationships > among the comparison operators. The > truth of `x==y` does not imply that `x!=y` > is false. Accordingly,...
Python, should I implement __ne__() operator based on __eq__?
4,352,244
42
2010-12-04T06:18:35Z
30,676,267
34
2015-06-05T21:41:16Z
[ "python", "comparison", "operators", "python-datamodel" ]
I have a class where I want to override the `__eq__()` operator. It seems to make sense that I should override the `__ne__()` operator as well, but does it make sense to implement `__ne__` based on `__eq__` as such? ``` class A: def __eq__(self, other): return self.value == other.value def __ne__(self...
> **Python, should I implement `__ne__()` operator based on `__eq__`?** # Short Answer: No. Instead, define the `__ne__` in terms of `==` instead of the `__eq__`. E.G. ``` class A(object): def __eq__(self, other): return self.value == other.value def __ne__(self, other): return not self == o...
What's the best way to handle Django's objects.get?
4,353,147
22
2010-12-04T10:50:08Z
4,353,168
44
2010-12-04T10:55:54Z
[ "python", "django" ]
Whenever I do this: ``` thepost = Content.objects.get(name="test") ``` It always throws an error when nothing is found. How do I handle it?
``` from django.core.exceptions import ObjectDoesNotExist try: thepost = Content.objects.get(name="test") except ObjectDoesNotExist: thepost = None ``` I'm writing this from memory, so I'm not sure about the exception.
What's the best way to handle Django's objects.get?
4,353,147
22
2010-12-04T10:50:08Z
4,353,185
14
2010-12-04T11:01:37Z
[ "python", "django" ]
Whenever I do this: ``` thepost = Content.objects.get(name="test") ``` It always throws an error when nothing is found. How do I handle it?
Often, it is more useful to use the Django shortcut function `get_object_or_404` instead of the API directly: ``` from django.shortcuts import get_object_or_404 thepost = get_object_or_404(Content, name='test') ``` Fairly obviously, this will throw a 404 error if the object cannot be found, and your code will contin...
What's the best way to handle Django's objects.get?
4,353,147
22
2010-12-04T10:50:08Z
4,354,529
10
2010-12-04T16:34:07Z
[ "python", "django" ]
Whenever I do this: ``` thepost = Content.objects.get(name="test") ``` It always throws an error when nothing is found. How do I handle it?
You can also catch a generic DoesNotExist. As per the docs at <http://docs.djangoproject.com/en/dev/ref/models/querysets/> ``` from django.core.exceptions import ObjectDoesNotExist try: e = Entry.objects.get(id=3) b = Blog.objects.get(id=1) except ObjectDoesNotExist: print "Either the entry or blog doesn't...
Determining JPG quality in Python (PIL)
4,354,543
11
2010-12-04T16:37:28Z
4,355,281
19
2010-12-04T19:08:35Z
[ "python", "image", "jpeg" ]
I am playing around with PIL library in Python and I am wondering how do I determine quality of given JPG image. I try to open JPG image do something to it and save it again in the its original quality. Image.save let me determine the desired quality: ``` im.save(name, quality = x) ``` but I can't see any way to extr...
In PIL (and mostly all softwares/librairies that use [libjpeg](http://www.google.com/url?sa=t&source=web&cd=1&ved=0CBgQFjAA&url=http%3A%2F%2Fwww.ijg.org%2F&ei=xIv6TNbMOIyt8Ab8o-zvCg&usg=AFQjCNHslBwzbdmbbWUN8u4mM_MyAer7Cg&sig2=dJt01vTnHP5te7Qlb2zK2w)) the quality setting is use to construct the quantization table ([ref....
How to wrap and indent long lines when using print() in Python?
4,355,061
3
2010-12-04T18:24:28Z
4,355,110
7
2010-12-04T18:33:04Z
[ "python", "printing", "indentation", "wrap" ]
I'm using Python to gather data from a Web service. The data itself is a list that will presented to users. I've managed it that it's printed out like: ``` ( 1) Example of strings ( 2) Example 4 ( 3) Another Example ( 4) Another Example 2 ``` I'm using rjust(2) for the numbers. However, if the lines are very long...
Use the textwrap module: <http://docs.python.org/library/textwrap.html>
Creating acronyms in Python
4,355,201
10
2010-12-04T18:49:56Z
4,355,207
8
2010-12-04T18:51:31Z
[ "python" ]
In Python, how do I make an acronym of a given string? Like, input string: ``` 'First Second Third' ``` Output: ``` 'FST' ``` I am trying something like: ``` >>> for e in x: print e[0] ``` But it is not working... Any suggestions on how this can be done? I am sure there is a proper way of doing this but ...
Try ``` print "".join(e[0] for e in x.split()) ``` Your loop actually loops over all characters in the string `x`. If you would like to loop over the words, you can use `x.split()`.
Creating acronyms in Python
4,355,201
10
2010-12-04T18:49:56Z
4,355,337
12
2010-12-04T19:19:22Z
[ "python" ]
In Python, how do I make an acronym of a given string? Like, input string: ``` 'First Second Third' ``` Output: ``` 'FST' ``` I am trying something like: ``` >>> for e in x: print e[0] ``` But it is not working... Any suggestions on how this can be done? I am sure there is a proper way of doing this but ...
If you want to use capitals only ``` >>>line = ' What AboutMe ' >>>filter(str.isupper, line) 'WAM' ``` What about words that may not be Leading Caps. ``` >>>line = ' What is Up ' >>>''.join(w[0].upper() for w in line.split()) 'WIU' ``` What about only the Caps words. ``` >>>line = ' GNU is Not Unix ' >>>''.join(w[...
Mercurial and hgweb on IIS 7.5 - python error
4,355,256
9
2010-12-04T19:01:03Z
4,367,589
15
2010-12-06T14:49:57Z
[ "python", "iis", "mercurial", "hgweb" ]
I am trying to get Mercurial to host on IIS 7.5 (Win 7 x64) and keep running into an error I cant seem to fix. I have followed Jeremy Skinners tutorial here: [Mercurial on IIS7](http://www.jeremyskinner.co.uk/mercurial-on-iis7/) Instead of hgwebdir, I use hgweb as I am using Mercurial 1.7.2 I have python installed a...
I've been struggling with this same setup for the past week or so. It looks to me like they have made some significant changes to how mercurial works in IIS recently, so the link above to Jeremy Skinners tutorial will be problematic for 1.7.2 This is a [more recent link](http://www.eworldui.net/blog/post/2010/04/08/S...
Using Python's FTP library to retrieve files
4,355,446
3
2010-12-04T19:44:48Z
4,355,534
8
2010-12-04T19:59:21Z
[ "python", "sockets", "ftp" ]
this is my first post on here so I'm happy to be a part of the community. I have a fairly mundane question to ask, but it's been a fairly annoying problem so I'm hoping to find answers. So I'm trying to use Python's FTPLIB module to retrieve a binary file. The code entered directly into the interpreter looked like th...
It looks like you are logging-in anonymously (no username/password specified in `ftp.login()`) thus you get permission error. Try logging-in with ``` ftp.login(user='foo', passwd='bar') ``` instead. **Edit:** here is a short example of ftplib usage (simplistic, without error handling): ``` #!/usr/bin/env python fr...
Getting data from ctypes array into numpy
4,355,524
21
2010-12-04T19:58:01Z
4,355,701
22
2010-12-04T20:36:45Z
[ "python", "numpy", "ctypes" ]
I am using a Python (via `ctypes`) wrapped C library to run a series of computation. At different stages of the running, I want to get data into Python, and specifically `numpy` arrays. The wrapping I am using does two different types of return for array data (which is of particular interest to me): * **`ctypes` Arra...
Creating NumPy arrays from a ctypes pointer object is a problematic operation. It is unclear who actually owns the memory the pointer is pointing to. When will it be freed again? How long is it valid? Whenever possible I would try to avoid this kind of construct. It is so much easier and safer to create arrays in the P...
Passing command Line argument to Python script within Eclipse(Pydev)
4,355,721
19
2010-12-04T20:40:54Z
4,355,739
48
2010-12-04T20:45:18Z
[ "python", "eclipse", "pydev" ]
I am new to Python & Eclipse, and having some difficulties understanding how to pass command line argument to script running within Eclipse(Pydev). [The following link](http://diveintopython.net/scripts_and_streams/command_line_arguments.html) explains how to pass command line argument to python script. To pass comma...
Click on the play button down arrow in the tool bar -> run configurations -> (double click) Python Run -> Arguments tab on the right hand side. From there you can fill out the Program Arguments text box: [![enter image description here](http://i.stack.imgur.com/Vwc4w.png)](http://i.stack.imgur.com/Vwc4w.png)
Passing command Line argument to Python script within Eclipse(Pydev)
4,355,721
19
2010-12-04T20:40:54Z
4,355,834
9
2010-12-04T21:07:46Z
[ "python", "eclipse", "pydev" ]
I am new to Python & Eclipse, and having some difficulties understanding how to pass command line argument to script running within Eclipse(Pydev). [The following link](http://diveintopython.net/scripts_and_streams/command_line_arguments.html) explains how to pass command line argument to python script. To pass comma...
If you want your program to ask for arguments interactively, then they cease to be **commandline** arguments, as such. However you could do it something like this (for debugging only!), which will allow you to interactively enter values that the program will see as command line arguments. ``` import sys sys.argv = raw...
How to get center of set of points using Python
4,355,894
5
2010-12-04T21:21:59Z
4,355,934
9
2010-12-04T21:27:54Z
[ "python", "matplotlib", "triangulation" ]
I would like to get the center point(x,y) of a figure created by a set of points. How do I do this?
If you mean centroid, you just get the average of all the points. ``` x = [p[0] for p in points] y = [p[1] for p in points] centroid = (sum(x) / len(points), sum(y) / len(points)) ```
do not understand closures question in python
4,356,048
5
2010-12-04T21:58:07Z
4,356,067
10
2010-12-04T22:01:04Z
[ "python", "closures", "parameter-passing" ]
``` def a(b=[]): b.append(1) return b print a() print a() ``` All of a sudden i got a list with 2 elems, but how? Shouldn't b be getting set to empty list every time. Thanks for the help
Default arguments are only evaluated once, when the function is defined. It retains the same object from one invocation to the next, which means that the same list keeps getting appended to. Use a default value of `None` and check for that instead if you want to get around this.
do not understand closures question in python
4,356,048
5
2010-12-04T21:58:07Z
4,356,069
9
2010-12-04T22:01:45Z
[ "python", "closures", "parameter-passing" ]
``` def a(b=[]): b.append(1) return b print a() print a() ``` All of a sudden i got a list with 2 elems, but how? Shouldn't b be getting set to empty list every time. Thanks for the help
Nothing to do with closures, at least not in the usual sense. The default value for `b` is not "a new empty list"; it is "this particular object which I just created right now while defining the function, initializing it to be an empty list". Every time the function is called without an argument, the same object is us...
Creating a python dictionary from a line of text
4,356,329
8
2010-12-04T23:06:46Z
4,356,415
17
2010-12-04T23:27:43Z
[ "python", "parsing", "dictionary" ]
I have a generated file with thousands of lines like the following: ``` CODE,XXX,DATE,20101201,TIME,070400,CONDITION_CODES,LTXT,PRICE,999.0000,QUANTITY,100,TSN,1510000001 ``` Some lines have more fields and others have fewer, but all follow the same pattern of key-value pairs and each line has a TSN field. When doin...
In Python 2 you could use `izip` in the `itertools` module and the magic of generator objects to write your own function to simplify the creation of pairs of values for the `dict` records. I got the idea for `pairwise()` from a similarly named (but functionally different) [recipe](http://docs.python.org/library/itertoo...
Python use raw_input with a variable
4,356,516
5
2010-12-04T23:52:23Z
4,356,532
9
2010-12-04T23:56:24Z
[ "python" ]
Is it possible to use raw\_input with a variable? For example. ``` max = 100 value = raw_input('Please enter a value between 10 and' max 'for percentage') ``` Thanks, Favolas
You can pass anything that evaluates to a string as a parameter: ``` value = raw_input('Please enter a value between 10 and' + str(max) + 'for percentage') ``` use + to concatenate string objects. You also need to explicitely turn non-strings into string to concatenate them using the str() function.
How can I extract video ID from YouTube's link in Python?
4,356,538
18
2010-12-04T23:57:02Z
4,356,563
38
2010-12-05T00:02:43Z
[ "python", "regex", "parsing", "url-parsing" ]
I know this can be easily done using PHP's `parse_url` and `parse_str` functions: ``` $subject = "http://www.youtube.com/watch?v=z_AbfPXTKms&NR=1"; $url = parse_url($subject); parse_str($url['query'], $query); var_dump($query); ``` But how to achieve this using Python? I can do `urlparse` but what next?
Python has [a library for parsing URLs](http://docs.python.org/library/urlparse.html). ``` import urlparse url_data = urlparse.urlparse("http://www.youtube.com/watch?v=z_AbfPXTKms&NR=1") query = urlparse.parse_qs(url_data.query) video = query["v"][0] ```
How can I extract video ID from YouTube's link in Python?
4,356,538
18
2010-12-04T23:57:02Z
7,936,523
38
2011-10-29T02:04:10Z
[ "python", "regex", "parsing", "url-parsing" ]
I know this can be easily done using PHP's `parse_url` and `parse_str` functions: ``` $subject = "http://www.youtube.com/watch?v=z_AbfPXTKms&NR=1"; $url = parse_url($subject); parse_str($url['query'], $query); var_dump($query); ``` But how to achieve this using Python? I can do `urlparse` but what next?
I've created youtube id parser without regexp: ``` def video_id(value): """ Examples: - http://youtu.be/SA2iWivDJiE - http://www.youtube.com/watch?v=_oPAwA_Udwc&feature=feedu - http://www.youtube.com/embed/SA2iWivDJiE - http://www.youtube.com/v/SA2iWivDJiE?version=3&amp;hl=en_US """ que...
How do I get the email address of the person who clicked the link in the email?
4,356,776
2
2010-12-05T00:56:42Z
4,356,783
9
2010-12-05T00:58:32Z
[ "python", "google-app-engine", "email" ]
I am working with Google App Engine python version. The app sends an email to the user with a link to a page to upload an image as an avatar. It would be nice to have the email so that I can associate the avatar with that email. How can I get the email of the person who just clicked the link? Thank you.
Put a hash in the URL that uniquely identifies the address you sent it to.
How do I return a 401 Unauthorized in Django?
4,356,842
25
2010-12-05T01:15:28Z
4,356,878
10
2010-12-05T01:26:35Z
[ "python", "django" ]
Instead of doing this: ``` res = HttpResponse("Unauthorized") res.status_code = 401 return res ``` Is there a way to do it without typing it every time?
``` class HttpResponseUnauthorized(HttpResponse): def __init__(self): self.status_code = 401 ... return HttpResponseUnauthorized() ```
How do I return a 401 Unauthorized in Django?
4,356,842
25
2010-12-05T01:15:28Z
10,649,158
79
2012-05-18T08:20:56Z
[ "python", "django" ]
Instead of doing this: ``` res = HttpResponse("Unauthorized") res.status_code = 401 return res ``` Is there a way to do it without typing it every time?
I know this is an old one, but it's the top Google result for "django 401", so I thought I'd point this out... Assuming you've already imported `django.http.HttpResponse`, you can do it in a single line: ``` return HttpResponse('Unauthorized', status=401) ``` The `'Unauthorized'` string is optional. Easy.
New to web development. ASP.NET or Django?
4,357,176
4
2010-12-05T03:16:29Z
4,357,372
12
2010-12-05T04:23:26Z
[ "c#", "asp.net", "python", "django" ]
Hello I am interested in hearing objective responses in what should a beginner dedicate his or her time into: **ASP.NET, Visual Studio, C#, IIS, Team Foundation Server?** or **Python, Django, PyCharm?** These are just some criteria that I am interested in: 1. Easy to start out with. 2. Good documentation. 3. Highl...
C# or java will pay the bills, python will be way more fun
Shapefile reader in Python?
4,357,541
15
2010-12-05T05:36:15Z
4,357,563
18
2010-12-05T05:43:28Z
[ "python", "gis", "shapefile" ]
Are there any libraries that I can use to read a shp/shx/dbf/sbx set of files? I mainly need to extract some polygons but something that lets me extract any data that I want would be awesome.
[pyshp](http://code.google.com/p/pyshp/) should be good.
python reverse tokens in a string
4,357,787
4
2010-12-05T07:14:22Z
4,357,823
7
2010-12-05T07:28:45Z
[ "python" ]
I have the following string: ``` apple.orange.red.green.yellow ``` How can i reverse it to get the following: ``` yellow.green.red.orange.apple ```
I like this (more readable?) one: ``` >> s = "yellow.green.red.orange.apple" >> '.'.join(reversed(s.split('.'))) 'apple.orange.red.green.yellow' ```
Filter a list in python get integers
4,357,832
3
2010-12-05T07:32:48Z
4,357,842
8
2010-12-05T07:35:09Z
[ "python" ]
I have a list: ``` ['Jack', 18, 'IM-101', 99.9] ``` How do I filter it to get only the integers from it?? I tried ``` map(int, x) ``` but it gives error. ``` ValueError: invalid literal for int() with base 10: 'Jack' ```
``` >>> x = ['Jack', 18, 'IM-101', 99.9] >>> [e for e in x if isinstance(e, int)] [18] ```
Creating or assigning variables from a dictionary in Python
4,357,851
12
2010-12-05T07:38:41Z
4,357,876
19
2010-12-05T07:47:09Z
[ "python", "variables", "extract" ]
I tried to ask a question normally once in here but nobody understands what I want to ask. So I've found example in PHP. ``` // $_POST = array('address' => '123', 'name' => 'John Doe'); extract($_POST); echo $address; echo $name ``` is there's a function like extract() in PYTHON????? So the same goes to dictionary: ...
You can use the [locals()](http://docs.python.org/library/functions.html#locals) function to access the local symbol table and update that table: ``` >>> mydict = {'raw': 'data', 'code': 500} >>> locals().update(mydict) >>> raw 'data' >>> code 500 ``` Modifying the symbol table that way is quite unusual, though, and ...
Is there a faster way to convert an arbitrary large integer to a big endian sequence of bytes?
4,358,285
7
2010-12-05T10:10:26Z
4,358,429
10
2010-12-05T10:52:38Z
[ "python", "optimization" ]
I have this Python code to do this: ``` from struct import pack as _pack def packl(lnum, pad = 1): if lnum < 0: raise RangeError("Cannot use packl to convert a negative integer " "to a string.") count = 0 l = [] while lnum > 0: l.append(lnum & 0xfffffffffffffff...
Here is a solution calling the Python/C API via `ctypes`. Currently, it uses NumPy, but if NumPy is not an option, it could be done purely with `ctypes`. ``` import numpy import ctypes PyLong_AsByteArray = ctypes.pythonapi._PyLong_AsByteArray PyLong_AsByteArray.argtypes = [ctypes.py_object, ...
Updating a Haystack search index with Django + Celery
4,358,771
26
2010-12-05T12:28:28Z
4,372,357
27
2010-12-07T00:34:51Z
[ "python", "django", "indexing", "celery", "django-haystack" ]
Excuse me if this is a basic question but I searched and couldn't find anything on this. In my Django project I am using Celery. I switched over a command from crontab to be a periodic task and it works well but it is just calling a method on a model. Is it possible to update my Haystack index from a periodic task as w...
the easiest way to do this would probably be to run the management command directly from python and run it in your task ``` from haystack.management.commands import update_index update_index.Command().handle() ```
Updating a Haystack search index with Django + Celery
4,358,771
26
2010-12-05T12:28:28Z
11,260,697
11
2012-06-29T11:08:44Z
[ "python", "django", "indexing", "celery", "django-haystack" ]
Excuse me if this is a basic question but I searched and couldn't find anything on this. In my Django project I am using Celery. I switched over a command from crontab to be a periodic task and it works well but it is just calling a method on a model. Is it possible to update my Haystack index from a periodic task as w...
As for version 2.0.0 beta of haystack, this code should work: ``` from haystack.management.commands import update_index update_index.Command().handle(using='default') ```
How do I uninstall a Python module (“egg”) that I installed with easy_install?
4,358,958
23
2010-12-05T13:13:33Z
4,358,967
26
2010-12-05T13:15:14Z
[ "python", "easy-install", "egg" ]
I’ve installed a couple of Python modules using [easy\_install](http://packages.python.org/distribute/easy_install.html). How do I uninstall them? I couldn’t see an uninstall option listed in `easy_install --help`.
Ah, here we go: ``` $ easy_install -m PackageName $ rm EggFile ``` I’m not exactly clear what the `-m` option does, but this method seems to work for me (i.e. after doing it, I can no longer `import` the modules in my Python interpreter).
Rename script file in distutils
4,359,231
14
2010-12-05T14:24:34Z
4,571,420
8
2010-12-31T17:29:54Z
[ "python", "distutils" ]
I have a python script, myscript.py, which I wish to install using distutils: ``` from distutils.core import setup setup(..., scripts=['myscript.py'], ...) ``` I'd prefer if I could call the installed script using just `myscript` instead of typing `myscript.py`. This could be accomplished by renaming the file to just...
You could always do something like this (in `setup.py`): ``` import os import shutil if not os.path.exists('scripts'): os.makedirs('scripts') shutil.copyfile('myscript.py', 'scripts/myscript') setup(... scripts=['scripts/myscript'], ... ) ```
Rename script file in distutils
4,359,231
14
2010-12-05T14:24:34Z
8,506,532
10
2011-12-14T14:55:27Z
[ "python", "distutils" ]
I have a python script, myscript.py, which I wish to install using distutils: ``` from distutils.core import setup setup(..., scripts=['myscript.py'], ...) ``` I'd prefer if I could call the installed script using just `myscript` instead of typing `myscript.py`. This could be accomplished by renaming the file to just...
You might want to look at the setuptools that do this automatically for you; from <http://pythonhosted.org/setuptools/setuptools.html#automatic-script-creation> : > Packaging and installing scripts can be a bit awkward with the > distutils. For one thing, there’s no easy way to have a script’s > filename match loc...
How do I get multiple values from checkboxes in Django
4,359,238
35
2010-12-05T14:28:09Z
4,359,300
80
2010-12-05T14:44:01Z
[ "python", "django", "django-models", "checkbox" ]
I want to get values of a multiple select check box using `request.POST['xzy']` as a list. Here is my model and template code. **My Model** ``` class Recommend(models.Model): user=models.ForeignKey(User) book=models.ForeignKey(BookModel) friends=models.ManyToManyField(User, related_name="recommended") ``` **My...
``` request.POST.getlist('recommendations') ```
print function in Python
4,359,490
4
2010-12-05T15:25:44Z
4,359,542
9
2010-12-05T15:34:25Z
[ "python", "printing" ]
I need some help in Python, to print: I have: > input =[(3, 'x1'), (5, 'x3'), (2, 'x2')] need to print, in this form: ``` x1=3 x2=2 x3=3 ``` Many thanks
``` print ' '.join('%s=%s' % (k, v) for (v, k) in input) ```
Unable to install pip: Permission denied error
4,359,870
5
2010-12-05T16:41:23Z
4,360,045
14
2010-12-05T17:12:09Z
[ "python", "easy-install", "egg", "pypi" ]
I am trying to install pip but currently unable to. I navigate to the pip folder and `python setup.py install` Everything seems to go fine until the very end: `Extracting pip-0.8.2-py2.6.egg to /Library/Python/2.6/site-packages Adding pip 0.8.2 to easy-install.pth file Installing pip script to /usr/local/bin ...
Looks like you're on an Linux/Unix box and you're not root ... which means you don't have *permission* to put things in `/usr/local/bin` (or a lot of other places). **Update for comments:** Since OS X is (under the hood) FreeBSD Unix, there is still the basic concept of 'root'. Your admin account is *capable* of doin...
Overflow in exp in scipy/numpy in Python?
4,359,959
6
2010-12-05T16:55:48Z
4,360,121
13
2010-12-05T17:25:58Z
[ "python", "numpy", "scipy" ]
What does the following error: ``` Warning: overflow encountered in exp ``` in scipy/numpy using Python generally mean? I'm computing a ratio in log form, i.e. log(a) + log(b) and then taking the exponent of the result, using exp, and using a sum with logsumexp, as follows: ``` c = log(a) + log(b) c = c - logsumexp(...
In your case, it means that `b` is *very* small somewhere in your array, and you're getting a number (`a/b` or `exp(log(a) - log(b))`) that is too large for whatever dtype (float32, float64, etc) the array you're using to store the output is. Numpy can be configured to 1. Ignore these sorts of errors, 2. Print the er...
python + sqlite, insert data from variables into table
4,360,593
6
2010-12-05T19:06:07Z
4,360,624
25
2010-12-05T19:11:07Z
[ "python", "sql", "sqlite" ]
I can insert hardcoded values into an SQLite table with no problem, but I'm trying to do something like this: ``` name = input("Name: ") phone = input("Phone number: ") email = input("Email: ") cur.execute("create table contacts (name, phone, email)") cur.execute("insert into contacts (name, phone, email) values"), (...
You can use `?` to represent a parameter in an SQL query: ``` cur.execute("insert into contacts (name, phone, email) values (?, ?, ?)", (name, phone, email)) ```
lambda returns lambda in python
4,362,153
8
2010-12-06T00:09:01Z
4,362,187
13
2010-12-06T00:17:39Z
[ "python", "function", "anonymous" ]
Very rarely I'll come across some code in python that uses an anonymous function which returns an anonymous function...? Unfortunately I can't find an example on hand, but it usually takes the form like this: ``` g = lambda x,c: x**c lambda c: c+1 ``` Why would someone do this? Maybe you can give an example that mak...
You could use such a construct to do *currying*: ``` curry = lambda f, a: lambda x: f(a, x) ``` You might use it like: ``` >>> add = lambda x, y: x + y >>> add5 = curry(add, 5) >>> add5(3) 8 ```
How do I check the difference, in seconds, between two dates?
4,362,491
58
2010-12-06T01:28:43Z
4,362,514
15
2010-12-06T01:34:18Z
[ "python", "time", "datediff" ]
There has to be an easier way to do this. I have objects that want to be refreshed every so often, so I want to record when they were created, check against the current timestamp, and refresh as necessary. datetime.datetime has proven to be difficult, and I don't want to dive into the ctime library. Is there anything ...
``` import time current = time.time() ...job... end = time.time() diff = end - current ``` would that work for you?
How do I check the difference, in seconds, between two dates?
4,362,491
58
2010-12-06T01:28:43Z
4,362,529
13
2010-12-06T01:38:12Z
[ "python", "time", "datediff" ]
There has to be an easier way to do this. I have objects that want to be refreshed every so often, so I want to record when they were created, check against the current timestamp, and refresh as necessary. datetime.datetime has proven to be difficult, and I don't want to dive into the ctime library. Is there anything ...
``` >>> from datetime import datetime >>> a = datetime.now() # wait a bit >>> b = datetime.now() >>> d = b - a # yields a timedelta object >>> d.seconds 7 ``` (7 will be whatever amount of time you waited a bit above) I find datetime.datetime to be fairly useful, so if there's a complicated or awkward scenario t...
How do I check the difference, in seconds, between two dates?
4,362,491
58
2010-12-06T01:28:43Z
17,191,361
158
2013-06-19T12:35:26Z
[ "python", "time", "datediff" ]
There has to be an easier way to do this. I have objects that want to be refreshed every so often, so I want to record when they were created, check against the current timestamp, and refresh as necessary. datetime.datetime has proven to be difficult, and I don't want to dive into the ctime library. Is there anything ...
if you want to compute differences between two known dates, use `total_seconds` like this: ``` import datetime as dt a = dt.datetime(2013,12,30,23,59,59) b = dt.datetime(2013,12,31,23,59,59) (b-a).total_seconds() ``` 86400.0 ``` #note that seconds doesn't give you what you want: (b-a).seconds ``` 0
sum a list of numbers in Python
4,362,586
92
2010-12-06T02:01:23Z
4,362,599
32
2010-12-06T02:04:34Z
[ "python", "list", "sum" ]
If I have a list of numbers such as `[1,2,3,4,5...]` and I want to calculate `(1+2)/2` and for the second, `(2+3)/2` and the third, `(3+4)/2`, and so on. How can I do that? I would like to sum the first number with the second and divide it by 2, then sum the second with the third and divide by 2, and so on. Also, how...
Sum list of numbers: ``` sum(list_of_nums) ``` Calculating half of n and n - 1 (if I have the pattern correct), using a [list comprehension](http://docs.python.org/release/2.7/tutorial/datastructures.html#list-comprehensions): ``` [(x + (x - 1)) / 2 for x in list_of_nums] ``` Sum adjacent elements, e.g. ((1 + 2) / ...
sum a list of numbers in Python
4,362,586
92
2010-12-06T02:01:23Z
4,362,605
84
2010-12-06T02:07:01Z
[ "python", "list", "sum" ]
If I have a list of numbers such as `[1,2,3,4,5...]` and I want to calculate `(1+2)/2` and for the second, `(2+3)/2` and the third, `(3+4)/2`, and so on. How can I do that? I would like to sum the first number with the second and divide it by 2, then sum the second with the third and divide by 2, and so on. Also, how...
Question 1: So you want (element 0 + element 1) / 2, (element 1 + element 2) / 2, ... etc. What we do is make two lists: one of every element except the first, and one of every element except the last. Then the averages we want are the averages of each pair taken from the two lists. We use `zip` to take pairs from two...
sum a list of numbers in Python
4,362,586
92
2010-12-06T02:01:23Z
30,584,755
7
2015-06-01T23:06:02Z
[ "python", "list", "sum" ]
If I have a list of numbers such as `[1,2,3,4,5...]` and I want to calculate `(1+2)/2` and for the second, `(2+3)/2` and the third, `(3+4)/2`, and so on. How can I do that? I would like to sum the first number with the second and divide it by 2, then sum the second with the third and divide by 2, and so on. Also, how...
``` >>> a = range(10) >>> sum(a) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not callable >>> del sum >>> sum(a) 45 ``` It seems that sum has been defined in the code somewhere and overwrite the default function. So I deleted it and the problem was solved.
Why don't django templates just use python code?
4,362,902
5
2010-12-06T03:20:41Z
4,362,944
10
2010-12-06T03:30:47Z
[ "python", "django", "django-templates" ]
I mean I understand that these templates are aimed at designers and other less code-savvy people, but for developers I feel the template language is just a hassle. I need to re-learn how to do very simple things like iterate through dictionaries or lists that I pass into the template, and it doesn't even seem to work v...
The reason that most people give for limited template languages is that they don't want to mix the business logic of their application with its presentation (that wouldn't work well with the MVC philosophy; using Django I'm sure you understand the benefits of this). Daniel Greenfeld wrote [an article a few days ago ex...
BeautifulSoup: How do I extract all the <li>s from a list of <ul>s that contains some nested <ul>s?
4,362,981
10
2010-12-06T03:39:50Z
4,363,338
7
2010-12-06T04:55:19Z
[ "python", "screen-scraping", "beautifulsoup" ]
My source code looks like: ``` <h3>Header3 (Start here)</h3> <ul> <li>List items</li> <li>Etc...</li> </ul> <h3>Header 3</h3> <ul> <li>List items</li> <ul> <li>Nested list items</li> <li>Nested list items</li></ul> <li>List items</li> </ul> <h2>Header 2 (end here)</h2> ``` I'd like...
`.findAll()` works for nested `li` elements: ``` for ul in uls: for li in ul.findAll('li'): print(li) ``` Output: ``` <li>List items</li> <li>Etc...</li> <li>List items</li> <li>Nested list items</li> <li>Nested list items</li> <li>List items</li> ```
matplotlib color in 3d plotting from an x,y,z data set without using contour
4,363,857
6
2010-12-06T06:32:17Z
4,366,663
16
2010-12-06T13:04:43Z
[ "python", "matplotlib" ]
For the life of me I cannot figure out how to get the same results as [this](http://matplotlib.sourceforge.net/mpl_toolkits/mplot3d/tutorial.html?highlight=3d#mpl_toolkits.mplot3d.Axes3D.plot_surface). The link generates the colored 3d plot without using contour. If I utilize the same technique but with my own x,y,z d...
I think there is a problem with fill "discontinuous" surface (griddata). ![alt text](http://i.stack.imgur.com/Ohs6H.png) Code: ``` from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm import matplotlib.pyplot as plt from matplotlib.mlab import griddata import numpy as np fig = plt.figure() ax = fig.gca(...
Making moves w/ websockets and python / django ( / twisted? )
4,363,899
22
2010-12-06T06:41:19Z
4,369,471
59
2010-12-06T18:04:34Z
[ "python", "django", "sockets", "websocket" ]
The fun part of websockets is sending essentially unsolicited content from the server to the browser right? Well, I'm using django-websocket by Gregor Müllegger. It's a really wonderful early crack at making websockets work in Django. I have accomplished "hello world." The way this works is: when a request is a webs...
I'm the author of django-websocket. I'm not a real expert in the topic of websockets and networking, however I think I have a decent understanding of whats going on. Sorry for going into great detail. Even if most of the answer isn't specific to your question it might help you at some other point. :-) --- # How webso...
How to open an SSH tunnel using python?
4,364,355
4
2010-12-06T08:09:13Z
4,364,389
7
2010-12-06T08:13:37Z
[ "python", "django", "ssh-tunnel" ]
I am trying to connect to a remote mysql database using django. The documentation specifies that it is required to open an SSH tunnel first to connect to the database. Is there a python library that can open an SSH tunnel whenever certain settings are set?
You could try [paramiko](http://www.lag.net/paramiko/)'s [forward](https://github.com/paramiko/paramiko/blob/master/demos/forward.py) functionality. For a paramiko overview, see [here](http://jessenoller.com/2009/02/05/ssh-programming-with-paramiko-completely-different/).
how to implement unittest.skip from python 3.1 in python 2.6?
4,364,500
4
2010-12-06T08:30:58Z
4,365,210
8
2010-12-06T10:03:05Z
[ "python", "unit-testing" ]
do you know of any implementation of unittest.skip of python 3.1 in python 2.6/2.7? <http://docs.python.org/dev/library/unittest.html#skipping-tests-and-expected-failures> thanks
Try installing the [unittest2](http://pypi.python.org/pypi/unittest2) package, "a backport of the new features added to the unittest testing framework" in Python 2.7 and 3.2.
replacing the "new" module
4,364,565
4
2010-12-06T08:43:28Z
4,364,930
7
2010-12-06T09:31:55Z
[ "python", "python-3.x" ]
I have code which contains the following two lines in it:- ``` instanceMethod = new.instancemethod(testFunc, None, TestCase) setattr(TestCase, testName, instanceMethod) ``` How could it be re-written without using the "new" module? Im sure new style classes provide some kind of workaround for this, but I am not sure ...
There is a discussion that suggests that in python 3, this is not required. The same works in Python 2.6 * <http://mail.python.org/pipermail/python-list/2009-April/531898.html> See: ``` >>> class C: pass ... >>> c=C() >>> def f(self): pass ... >>> c.f = f.__get__(c, C) >>> c.f <bound method C.f of <__main__.C inst...
numpy: efficiently reading a large array
4,365,964
7
2010-12-06T11:36:08Z
4,366,379
10
2010-12-06T12:28:27Z
[ "python", "performance", "numpy", "scipy", "large-files" ]
I have a binary file that contains a dense `n*m` matrix of 32-bit floats. What's the most efficient way to read it into a Fortran-ordered `numpy` array? The file is multi-gigabyte in size. I get to control the format, but it must be compact (i.e. about `4*n*m` bytes in length) and must be easy to produce from non-Pyth...
NumPy provides [`fromfile()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromfile.html) to read binary data. ``` a = numpy.fromfile("filename", dtype=numpy.float32) ``` will create a one-dimensional array containing your data. To access it as a two-dimensional Fortran-ordered `n x m` matrix, you can re...
Python symmetric dictionary where d[a][b] == d[b][a]
4,368,423
3
2010-12-06T16:11:39Z
4,368,489
11
2010-12-06T16:17:02Z
[ "python", "inheritance", "dictionary" ]
I have an algorithm in python which creates measures for pairs of values, where `m(v1, v2) == m(v2, v1)` (i.e. it is symmetric). I had the idea to write a dictionary of dictionaries where these values are stored in a memory-efficient way, so that they can easily be retrieved with keys in any order. I like to inherit fr...
You could use a [`frozenset`](http://docs.python.org/library/stdtypes.html#set-types-set-frozenset) as the key for your dict: ``` >>> s_d = {} >>> s_d[frozenset([5,2])] = 4 >>> s_d[frozenset([2,5])] 4 ``` It would be fairly straightforward to write a subclass of `dict` that took iterables as key arguments and then tu...
Any way to execute a piped command in Python using subprocess module, without using shell=True?
4,368,818
12
2010-12-06T16:47:43Z
4,368,868
24
2010-12-06T16:53:59Z
[ "python", "bash" ]
I want to run a piped command line linux/bash command from Python, which first tars files, and then splits the tar file. The command would look like something this in bash: ``` > tar -cvf - path_to_archive/* | split -b 20m -d -a 5 - "archive.tar.split" ``` I know that I could execute it using subprocess, by settings ...
If you want to avoid using shell=True, you can manually use [subprocess pipes](http://docs.python.org/library/subprocess.html#replacing-shell-pipeline). ``` from subprocess import Popen, PIPE p1 = Popen(["tar", "-cvf", "-", "path_to_archive"], stdout=PIPE) p2 = Popen(["split", "-b", "20m", "-d", "-a", "5", "-", "'arch...
Replace \n with <br />
4,369,159
16
2010-12-06T17:26:51Z
4,369,166
80
2010-12-06T17:28:21Z
[ "python", "string", "replace", "newline" ]
I'm parsing text from file with Python. I have to replace all newlines (\n) with cause this text will build html-content. For example, here is some line from file: ``` 'title\n' ``` Now I do: ``` thatLine.replace('\n', '<br />') print thatLine ``` And I still see the text with newline after it.
`thatLine = thatLine.replace('\n', '<br />')` str.replace() returns a copy of the string, it doesn't modify the string you pass in.
Replace \n with <br />
4,369,159
16
2010-12-06T17:26:51Z
4,369,199
31
2010-12-06T17:32:57Z
[ "python", "string", "replace", "newline" ]
I'm parsing text from file with Python. I have to replace all newlines (\n) with cause this text will build html-content. For example, here is some line from file: ``` 'title\n' ``` Now I do: ``` thatLine.replace('\n', '<br />') print thatLine ``` And I still see the text with newline after it.
Just for kicks, you could also do ``` mytext = "<br />".join(mytext.split("\n")) ``` to replace all newlines in a string with `<br />`.
Designing a web based game that would run in a browser - Where should I start?
4,369,314
3
2010-12-06T17:47:25Z
4,369,685
9
2010-12-06T18:30:58Z
[ "python", "web-applications" ]
I would like to design a web based game preferably in Python ( using Django maybe) though I'm open to any language other than Java/Flash/ActionScript. The idea I have in mind is more about data models than graphics and will leverage social networking sites. I would like to extend it with a mobile web interface in the f...
Step 1. Design a good game. Step 2. Be sure that it fits the HTTP model of simple request/reply GET/POST processing. Be sure that the game is still good. Some people try to do "real time" or "push" or other things that don't fit the model well and require lots of sophisticated GUI on the desktop. Step 3. Find a web f...
Class variables of same type in Python
4,369,814
5
2010-12-06T18:45:45Z
4,369,850
7
2010-12-06T18:50:00Z
[ "python", "oop" ]
Messing around with the typical Point class example when learning Python, I noticed that for some reason I can't have a class level (static variable) of the same type as that of the class. E.g. ``` class Point: ORIGIN = Point() # doesn't work def __init__(self, x=0, y=0): self.x = x self.y = y ``` while...
``` class Point(object): pass Point.ORIGIN = Point() ```
Django makemessages errors Unknown encoding "utf8"
4,370,035
8
2010-12-06T19:14:17Z
7,071,930
7
2011-08-15T23:21:43Z
[ "python", "django", "gettext" ]
I searched here and google too! But no success finding the solution, I'm really noob with python but could be able to install python separated from yum. Now, I need to recompile the language pack for the OSQA system, but get this message: ``` Error: errors happened while running xgettext on __init__.py xgettext: ./Dj...
Actually yes, I've already had similar problems with makemessages, because on top of every source file I wrote "# coding: utf8". Even though it worked with source compilation, I've had to replace "utf8" with "utf-8" in every file. If you're not used to makemessages, take care of gettext functions applied to format str...
Tkinter Button Command Being Called Automatically?
4,370,160
2
2010-12-06T19:29:23Z
4,370,272
11
2010-12-06T19:42:30Z
[ "python", "tkinter" ]
For some reason this Button is automatically calling `bot_analysis_frame` without the button being pressed. I'm guessing it's because the command is a function with arguments...is there a way to have the button only call this function and pass the required variables ONLY upon being pressed? ``` Button(topAnalysisFrame...
Read the section here on passing [callbacks](http://effbot.org/zone/tkinter-callbacks.htm). You are storing the result of that function to the command argument and not the function itself. I believe this: ``` command = lambda: bot_analysis_frame(eventConditionL,eventBreakL) ``` might work for you.
View onto a numpy array?
4,370,745
69
2010-12-06T20:41:44Z
4,371,049
162
2010-12-06T21:17:52Z
[ "python", "numpy", "scikits" ]
I have a 2D `numpy` array. Is there a way to create a view onto it that would include the first `k` rows and all columns? The point is to avoid copying the underlying data (the array is so large that making partial copies is not feasible.)
Sure, just index it as you normally would. E.g. `y = x[:k, :]` This will return a view into the original array. No data will be copied, and any updates made to `y` will be reflected in `x` and vice versa. --- Edit: I commonly work with >10GB 3D arrays of uint8's, so I worry about this a lot... Numpy can be very effi...
python numpy euclidean distance calculation between matrices of row vectors
4,370,975
7
2010-12-06T21:08:30Z
4,371,158
12
2010-12-06T21:31:29Z
[ "python", "vector", "numpy", "scipy", "euclidean-distance" ]
I am new to Numpy and I would like to ask you how to calculate euclidean distance between points stored in a vector. Let's assume that we have a numpy.array each row is a vector and a single numpy.array. I would like to know if it is possible to calculate the euclidean distance between all the points and this single p...
While you can use vectorize, @Karl's approach will be rather slow with numpy arrays. The easier approach is to just do `np.hypot(*(points - single_point).T)`. (The transpose assumes that points is a Nx2 array, rather than a 2xN. If it's 2xN, you don't need the `.T`. However this is a bit unreadable, so you write it o...
How to for-loop three columns per row in Django/python?
4,371,338
6
2010-12-06T21:56:17Z
4,371,391
19
2010-12-06T22:01:32Z
[ "python", "django", "for-loop" ]
I would like to display data, three columns per row during my for. I would like my result to look like the following: ``` <table> <tr><td>VALUE1</td><td>VALUE2</td><td>VALUE3</td></tr> <tr><td>VALUE4</td><<td>VALUE5</td><td>VALUE6</td></tr> </table> ``` Anyone know how to do it? Syntax Error TemplateSyntaxError at /...
There's a divisibleby tag. So you can do something (ugly) like: ``` <table><tr> {% for field in form %} <td>{{ field }}</td> {% if forloop.last %} </tr> {% else %} {% if forloop.counter|divisibleby:"3" %} </tr><tr> {% endif %} {% endif %} {% endfor %} </table> ``` Alternatively, you...
Extract Google Search Results
4,371,655
3
2010-12-06T22:38:49Z
4,372,167
12
2010-12-06T23:54:16Z
[ "python", "regex", "subdomain", "extract" ]
I would like to periodically check what sub-domains are being listed by Google. To obtain list of sub-domains, I type 'site:example.com' in Google search box - this lists all the sub-domain results (over 20 pages for our domain). What is the best way to extract only the URL of the addresses returned by the 'site:exam...
Regex is a bad idea for parsing HTML. It's cryptic to read and relies of well-formed HTML. Try [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) for Python. Here's an example script that returns URLs from the first 10 pages of a site:domain.com Google query. ``` import sys # Used to add the BeautifulSoup...
"Flat is better than nested" - for data as well as code?
4,372,229
26
2010-12-07T00:06:54Z
4,372,404
7
2010-12-07T00:42:47Z
[ "python", "theory" ]
[This](http://stackoverflow.com/questions/4372073/traversing-and-modifying-a-tree-like-list-of-dict-structure/4372174#4372174) question got me thinking: should we apply the principle that "flat is better than nested" to data as well as to code? Even when there is a "logical tree structure" to the data? In this case, I...
This is a completely subjective question. The answer is, "it depends." It depends on the primary use of your data. If you continually have to reference the nested structure, then it makes sense to represent it that way. And if you never reference the flat representation except when building the nested structure, then ...
"Flat is better than nested" - for data as well as code?
4,372,229
26
2010-12-07T00:06:54Z
4,372,514
8
2010-12-07T01:07:35Z
[ "python", "theory" ]
[This](http://stackoverflow.com/questions/4372073/traversing-and-modifying-a-tree-like-list-of-dict-structure/4372174#4372174) question got me thinking: should we apply the principle that "flat is better than nested" to data as well as to code? Even when there is a "logical tree structure" to the data? In this case, I...
> should we apply the principle that "flat is better than nested" to data as well as to code? No. > Even when there is a "logical tree structure" to the data? That's what "flat is better than nested" doesn't apply to data. Only to code. > ... the tree structure is obscured. Does that contradict "explicit is better ...
Uses of combining **kwargs and key word arguments in a method signature
4,372,346
4
2010-12-07T00:33:31Z
4,372,370
8
2010-12-07T00:35:55Z
[ "python" ]
Is there a use for combining \*\*kwargs and keyword arguments in a method signature? ``` >>> def f(arg, kw=[123], *args, **kwargs): ... print arg ... print kw ... print args ... print kwargs ... >>> f(5, 'a', 'b', 'c', kw=['abc'], kw2='def') Traceback (most recent call last): File "<stdin>", line 1, in <module...
You're assigning kw twice. In this call `f(5, 'a', 'b', 'c', kw=['abc'], kw2='def')`, arg=5, kw='a', \*args = ('b','c'), and then you're trying to assign kw again.
Uses of combining **kwargs and key word arguments in a method signature
4,372,346
4
2010-12-07T00:33:31Z
4,372,488
12
2010-12-07T00:59:55Z
[ "python" ]
Is there a use for combining \*\*kwargs and keyword arguments in a method signature? ``` >>> def f(arg, kw=[123], *args, **kwargs): ... print arg ... print kw ... print args ... print kwargs ... >>> f(5, 'a', 'b', 'c', kw=['abc'], kw2='def') Traceback (most recent call last): File "<stdin>", line 1, in <module...
In Python 3 you can have keyword-only arguments ([PEP 3102](http://www.python.org/dev/peps/pep-3102/)). With these, your function would look like this: ``` >>> def f(arg, *args, kw=[123], **kwargs): ... print(arg) ... print(kw) ... print(args) ... print(kwargs) >>> f(5, 'a', 'b', 'c', kw=['abc'], kw2='def') 5 ('a...
How do I access all page objects in django-cms from every page?
4,372,731
6
2010-12-07T01:56:03Z
4,411,722
7
2010-12-10T17:44:45Z
[ "python", "django", "django-cms" ]
I am using Django CMS 2.1.0.beta3 and am encountering a problem. I need to have access to all the pages in a variable so that I can loop through them and create my navigation menu using a for loop. The show\_menu functionality provided with django cms will not work for what I am doing. I need a queryset with all pages...
I ended up solving this problem by creating a templatetag in django that serves up all of the cms pages: app/template\_tags/navigation\_tags.py: ``` from django import template from cms.models.pagemodel import Page register = template.Library() def cms_navigation(): cms_pages = Page.objects.filter(in_navigation...
How do I update a Mongo document after inserting it?
4,372,797
29
2010-12-07T02:13:57Z
4,374,288
44
2010-12-07T07:32:39Z
[ "python", "database", "pymongo", "mongodb" ]
Let's say I insert the document. ``` post = { some dictionary } mongo_id = mycollection.insert(post) ``` Now, let's say I want to add a field and update it. How do I do that? This doesn't seem to work..... ``` post = mycollection.find_one({"_id":mongo_id}) post['newfield'] = "abc" mycollection.save(post) ```
In pymongo you can update with: `mycollection.update({'_id':mongo_id}, {"$set": post}, upsert=False)` Upsert parameter will insert instead of updating if the post is not found in the database. Documentation is available at [mongodb site](http://www.mongodb.org/display/DOCS/Updating).
How do I update a Mongo document after inserting it?
4,372,797
29
2010-12-07T02:13:57Z
11,948,570
16
2012-08-14T08:32:42Z
[ "python", "database", "pymongo", "mongodb" ]
Let's say I insert the document. ``` post = { some dictionary } mongo_id = mycollection.insert(post) ``` Now, let's say I want to add a field and update it. How do I do that? This doesn't seem to work..... ``` post = mycollection.find_one({"_id":mongo_id}) post['newfield'] = "abc" mycollection.save(post) ```
I will use `collection.save(the_changed_dict)` this way. I've just tested this, and it still works for me. The following is quoted directly from `pymongo doc.`: `save(to_save[, manipulate=True[, safe=False[, **kwargs]]])` > Save a document in this collection. > > If to\_save already has an "\_id" then > an update() (...
How do I find where Python is located on Unix?
4,373,428
4
2010-12-07T04:35:44Z
4,373,436
7
2010-12-07T04:37:06Z
[ "python", "shell", "unix", "directory", "shebang" ]
I'm working on a new server for a new workplace, and I'm trying to reuse a CGI script I wrote in Python earlier this year. My CGI script starts off with ``` #!/local/usr/bin/python ``` But when I run this on the new server, it complains that there's no such folder. Obviously Python's kept in a different place on this...
Try: ``` which python ``` in a terminal.
Sum array by number in numpy
4,373,631
14
2010-12-07T05:16:43Z
4,387,453
7
2010-12-08T12:33:33Z
[ "python", "numpy" ]
Assuming I have a numpy array like: [1,2,3,4,5,6] and another array: [0,0,1,2,2,1] I want to sum the items in the first array by group (the second array) and obtain n-groups results in group number order (in this case the result would be [3, 9, 9]). How do I do this in numpy?
If the groups are indexed by consecutive integers, you can abuse the `numpy.histogram()` function to get the result: ``` data = numpy.arange(1, 7) groups = numpy.array([0,0,1,2,2,1]) sums = numpy.histogram(groups, bins=numpy.arange(groups.min(), groups.max()+2), weights=...
Sum array by number in numpy
4,373,631
14
2010-12-07T05:16:43Z
8,732,260
21
2012-01-04T18:51:36Z
[ "python", "numpy" ]
Assuming I have a numpy array like: [1,2,3,4,5,6] and another array: [0,0,1,2,2,1] I want to sum the items in the first array by group (the second array) and obtain n-groups results in group number order (in this case the result would be [3, 9, 9]). How do I do this in numpy?
This is a vectorized method of doing this sum based on the implementation of numpy.unique. According to my timings it is up to 500 times faster than the loop method and up to 100 times faster than the histogram method. ``` def sum_by_group(values, groups): order = np.argsort(groups) groups = groups[order] ...
Sum array by number in numpy
4,373,631
14
2010-12-07T05:16:43Z
23,670,867
12
2014-05-15T06:33:37Z
[ "python", "numpy" ]
Assuming I have a numpy array like: [1,2,3,4,5,6] and another array: [0,0,1,2,2,1] I want to sum the items in the first array by group (the second array) and obtain n-groups results in group number order (in this case the result would be [3, 9, 9]). How do I do this in numpy?
The numpy function `bincount` was made exactly for this purpose and I'm sure it will be much faster than the other methods for all sizes of inputs: ``` data = [1,2,3,4,5,6] ids = [0,0,1,2,2,1] np.bincount(ids, weights=data) #returns [3,9,9] as a float64 array ``` The i-th element of the output is the sum of all the...
How can I randomly place several non-colliding rects?
4,373,741
6
2010-12-07T05:43:13Z
4,382,286
9
2010-12-07T22:27:56Z
[ "python", "collision-detection", "pygame", "rect" ]
I'm working on some 2D games with Pygame. I need to place several objects at the same time randomly **without them intersecting**. I have tried a few obvious methods but they didn't work. Obvious methods follow (in pseudo): ``` create list of objects for object in list: for other object in list: if object...
I've changed my answer a bit to address your follow-up question about whether it could be modified to instead generate random non-colliding *squares* rather than arbitrarily rectangles. I did this in the simplest way I could that would work, which was to post-process the rectangular output of my original answer and tur...
Check for mutability in Python?
4,374,006
19
2010-12-07T06:35:42Z
4,374,075
14
2010-12-07T06:51:13Z
[ "python", "python-3.x", "immutability", "python-2.x", "hashable" ]
Consider this [code](http://docs.python.org/library/stdtypes.html#dict.copy): ``` a = {...} # a is an dict with arbitrary contents b = a.copy() ``` 1. What role does mutability play in the keys and values of the dicts? 2. How do I ensure changes to keys or values of one dict are not reflected in the other? 3. How doe...
1) Keys must not be mutable, **unless** you have a user-defined class that is hashable but also mutable. That's all that's forced upon you. *However, using a hashable, mutable object as a dict key might be a bad idea.* 2) By not sharing values between the two dicts. It's OK to share the keys, because they must be immu...
How to set sys.stdout encoding in Python 3?
4,374,455
25
2010-12-07T07:59:34Z
4,374,457
26
2010-12-07T07:59:56Z
[ "python", "unicode", "python-3.x", "stdout" ]
Setting the default output encoding in Python 2 is a well-known idiom: ``` sys.stdout = codecs.getwriter("utf-8")(sys.stdout) ``` This wraps the `sys.stdout` object in a codec writer that encodes output in UTF-8. However, this technique does not work in Python 3 because `sys.stdout.write()` expects a `str`, but the ...
Python 3.1 added `io.TextIOBase.detach()`, with a note in the documentation for [`sys.stdout`](http://docs.python.org/py3k/library/sys.html#sys.stdout): > The standard streams are in text mode by default. To write or read binary data to these, use the underlying binary buffer. For example, to write bytes to `stdout`, ...
How to set sys.stdout encoding in Python 3?
4,374,455
25
2010-12-07T07:59:34Z
4,375,225
7
2010-12-07T09:44:02Z
[ "python", "unicode", "python-3.x", "stdout" ]
Setting the default output encoding in Python 2 is a well-known idiom: ``` sys.stdout = codecs.getwriter("utf-8")(sys.stdout) ``` This wraps the `sys.stdout` object in a codec writer that encodes output in UTF-8. However, this technique does not work in Python 3 because `sys.stdout.write()` expects a `str`, but the ...
sys.stdout is in text mode in Python 3. Hence you write unicode to it directly, and the idiom for Python 2 is no longer needed. Where this would fail in Python 2: ``` >>> import sys >>> sys.stdout.write(u"ûnicöde") Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeEncodeError: 'ascii' ...
How to set sys.stdout encoding in Python 3?
4,374,455
25
2010-12-07T07:59:34Z
4,376,072
16
2010-12-07T11:23:47Z
[ "python", "unicode", "python-3.x", "stdout" ]
Setting the default output encoding in Python 2 is a well-known idiom: ``` sys.stdout = codecs.getwriter("utf-8")(sys.stdout) ``` This wraps the `sys.stdout` object in a codec writer that encodes output in UTF-8. However, this technique does not work in Python 3 because `sys.stdout.write()` expects a `str`, but the ...
> Setting the default output encoding in Python 2 is a well-known idiom Eek! Is that a well-known idiom in Python 2? It looks like a dangerous mistake to me. It'll certainly mess up any script that tries to write binary to stdout (which you'll need if you're a CGI script returning an image, for example). Bytes and ch...
How to set sys.stdout encoding in Python 3?
4,374,455
25
2010-12-07T07:59:34Z
7,865,013
10
2011-10-23T07:53:19Z
[ "python", "unicode", "python-3.x", "stdout" ]
Setting the default output encoding in Python 2 is a well-known idiom: ``` sys.stdout = codecs.getwriter("utf-8")(sys.stdout) ``` This wraps the `sys.stdout` object in a codec writer that encodes output in UTF-8. However, this technique does not work in Python 3 because `sys.stdout.write()` expects a `str`, but the ...
I found this thread while searching for solutions to the same error, An alternative solution to those already suggested is to set the `PYTHONIOENCODING` environment variable **before** Python starts, for my use - this is less trouble then swapping `sys.stdout` after Python is initialized: ``` PYTHONIOENCODING=utf-8:s...
numpy: compute x.T*x for a large matrix
4,375,617
4
2010-12-07T10:28:05Z
4,376,697
8
2010-12-07T12:44:50Z
[ "python", "numpy", "scipy", "matrix-multiplication", "transpose" ]
In `numpy`, what's the most efficient way to compute `x.T * x`, where `x` is a large (200,000 x 1000) dense `float32` matrix and `.T` is the transpose operator? For the avoidance of doubt, the result is 1000 x 1000. **edit**: In my original question I stated that `np.dot(x.T, x)` was taking hours. It turned out that ...
This may not be the answer you're looking for, but one way to speed it up considerably is to use a gpu instead of your cpu. If you have a decently powerful graphics card around, it'll outperform your cpu any day, even if your system is very well tuned. For nice integration with numpy, you could use theano (if your gra...
Executing a C program in python?
4,376,397
8
2010-12-07T12:08:23Z
4,376,421
32
2010-12-07T12:11:49Z
[ "python", "c" ]
I have this C program, at least I think it is (files: spa.c, spa.h). Is there any way I can execute this script from Python WITHOUT passing extra arguments to the Python interpreter (if not, what would the arguments be?) **Update**: Thanks for your replies. The source code can be found at <http://www.nrel.gov/midc/spa...
There is no such thing as a **C script**. If you meant a **C program** you need to compile `spa.c` and `spa.h` into an executable before running it. If you use **GCC** in Linux or Mac OS X: ``` $ gcc -Wall spa.c -o spa ``` Will get you an executable named `spa`. After that, you can run `spa` program from your Pytho...
Executing a C program in python?
4,376,397
8
2010-12-07T12:08:23Z
4,376,554
9
2010-12-07T12:26:27Z
[ "python", "c" ]
I have this C program, at least I think it is (files: spa.c, spa.h). Is there any way I can execute this script from Python WITHOUT passing extra arguments to the Python interpreter (if not, what would the arguments be?) **Update**: Thanks for your replies. The source code can be found at <http://www.nrel.gov/midc/spa...
[cinpy](http://www.cs.tut.fi/~ask/cinpy/) comes close using the awesome combination of tcc and ctypes The following code is ripped from cinpy\_test.py included in the package. ``` import ctypes import cinpy # Fibonacci in Python def fibpy(x): if x<=1: return 1 return fibpy(x-1)+fibpy(x-2) # Fibonacci in C f...
Shell Script: Execute a python program from within a shell script
4,377,109
38
2010-12-07T13:30:53Z
4,377,147
53
2010-12-07T13:34:45Z
[ "python", "shell" ]
I've tried googling the answer but with no luck. I need to use my works supercomputer server, but for my python script to run, it must be executed via a shell script. For example I want `job.sh` to execute `python_script.py` How can this be accomplished?
Just make sure the python executable is in your PATH environment variable then add in your script ``` python path/to/the/python_script.py ``` Details: * In the file job.sh, put this > ``` > #!/bin/sh > python python_script.py > ``` * Execute this command to make the script runnable for you : `chmod u+x job.sh` * R...
Shell Script: Execute a python program from within a shell script
4,377,109
38
2010-12-07T13:30:53Z
4,377,344
49
2010-12-07T13:54:30Z
[ "python", "shell" ]
I've tried googling the answer but with no luck. I need to use my works supercomputer server, but for my python script to run, it must be executed via a shell script. For example I want `job.sh` to execute `python_script.py` How can this be accomplished?
## Method 1 - Create a shell script: Suppose you have a python file `hello.py`Create a file called `job.sh` that contains ``` #!/bin/bash python hello.py ``` mark it executable using ``` $ chmod +x job.sh ``` then run it ``` $ ./job.sh ``` ## Method 2 (BETTER) - Make the python itself run from shell: Modify you...
Reload django object from database
4,377,861
64
2010-12-07T14:44:05Z
4,874,091
19
2011-02-02T11:47:25Z
[ "python", "django", "django-models" ]
Is it possible to refresh the state of a django object from database? I mean behavior roughly equivalent to: ``` new_self = self.__class__.objects.get(pk=self.pk) for each field of the record: setattr(self, field, getattr(new_self, field)) ``` **UPD:** Found a reopen/wontfix war in the tracker: <http://code.djang...
I've found it relatively easy to [reload the object from the database](http://www.technomancy.org/python/django-refresh-object-from-database/) like so: ``` x = X.objects.get(id=x.id) ```
Reload django object from database
4,377,861
64
2010-12-07T14:44:05Z
12,373,013
9
2012-09-11T15:21:19Z
[ "python", "django", "django-models" ]
Is it possible to refresh the state of a django object from database? I mean behavior roughly equivalent to: ``` new_self = self.__class__.objects.get(pk=self.pk) for each field of the record: setattr(self, field, getattr(new_self, field)) ``` **UPD:** Found a reopen/wontfix war in the tracker: <http://code.djang...
In reference to @grep's comment, shouldn't it be possible to do: ``` # Put this on your base model (or monkey patch it onto django's Model if that's your thing) def reload(self): new_self = self.__class__.objects.get(pk=self.pk) # You may want to clear out the old dict first or perform a selective merge se...
Reload django object from database
4,377,861
64
2010-12-07T14:44:05Z
31,412,166
69
2015-07-14T16:22:50Z
[ "python", "django", "django-models" ]
Is it possible to refresh the state of a django object from database? I mean behavior roughly equivalent to: ``` new_self = self.__class__.objects.get(pk=self.pk) for each field of the record: setattr(self, field, getattr(new_self, field)) ``` **UPD:** Found a reopen/wontfix war in the tracker: <http://code.djang...
As of Django 1.8 refreshing objects is built in. [Link to docs](https://docs.djangoproject.com/en/1.8/ref/models/instances/#refreshing-objects-from-database). ``` def test_update_result(self): obj = MyModel.objects.create(val=1) MyModel.objects.filter(pk=obj.pk).update(val=F('val') + 1) # At this point obj...
Can Gnuplot take different arguments at run time? maybe with Python?
4,379,330
11
2010-12-07T16:57:20Z
4,380,176
21
2010-12-07T18:25:28Z
[ "python", "scripting", "gnuplot" ]
I have 500 files to plot and I want to do this automatically. I have the gnuplot script that does the plotting with the file name hard coded. I would like to have a loop that calls gnuplot every iteration with a different file name, but it does not seem that gnuplot support command line arguments. Is there an easy way...
You can transform your gnuplot script to a shell script by prepending the lines ``` #!/bin/sh gnuplot << EOF ``` appending the line ``` EOF ``` and substituting every `$` by `\$`. Then, you can substitute every occurence of the filename by `$1` and call the shell script with the filename as parameter.
any idea how to update python PIP on a windows box?
4,379,970
31
2010-12-07T18:02:35Z
4,379,999
63
2010-12-07T18:05:55Z
[ "python", "windows", "virtualenv", "pip" ]
`pip install --upgrade pip` doesn't work because the windows FS is brain damaged and won't let you delete an open file. I've tried setting my environment to the virtualenv that I want to update and then running from a different pip, but that fails with: ``` (jm) E:\python\jm>c:\Python26\Scripts\pip install --upgrade ...
`easy_install -U pip` :-)
any idea how to update python PIP on a windows box?
4,379,970
31
2010-12-07T18:02:35Z
13,465,532
10
2012-11-20T01:59:35Z
[ "python", "windows", "virtualenv", "pip" ]
`pip install --upgrade pip` doesn't work because the windows FS is brain damaged and won't let you delete an open file. I've tried setting my environment to the virtualenv that I want to update and then running from a different pip, but that fails with: ``` (jm) E:\python\jm>c:\Python26\Scripts\pip install --upgrade ...
[UPDATE 2015-11-15] This post is obsolete and out of date. Current best practice is [according to pip](http://pip.readthedocs.org/en/stable/installing/#id6) is to use the following: ``` python -m pip install -U pip setuptools ``` It's not necessary to use [`easy_install`](http://pythonhosted.org/setuptools/easy_insta...
any idea how to update python PIP on a windows box?
4,379,970
31
2010-12-07T18:02:35Z
28,617,019
34
2015-02-19T21:14:04Z
[ "python", "windows", "virtualenv", "pip" ]
`pip install --upgrade pip` doesn't work because the windows FS is brain damaged and won't let you delete an open file. I've tried setting my environment to the virtualenv that I want to update and then running from a different pip, but that fails with: ``` (jm) E:\python\jm>c:\Python26\Scripts\pip install --upgrade ...
Run pip as a script, using python as the main executable. ``` python -m pip install -U pip ```