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
AttributeError: type object ... has no attribute 'objects'
7,785,608
5
2011-10-16T16:19:38Z
7,785,665
9
2011-10-16T16:29:14Z
[ "python", "django", "django-models" ]
fragment of models.py ``` class Hardware_type(models.Model): type = models.CharField(blank = False, max_length = 50, verbose_name="Type") description = models.TextField(blank = True, verbose_name="Description") slug = models.SlugField(unique = True, max_length = 255, verbose_name = "Slug") class Software_...
If you add a custom manager to a model then the default manager at `objects` will not be created. Either add it yourself in the class definition, or stick with using the custom manager.
How to iterate through dict in random order in Python?
7,785,672
9
2011-10-16T16:30:34Z
7,785,679
7
2011-10-16T16:32:08Z
[ "python", "random" ]
How can I iterate through all items of a dictionary in a random order? I mean something random.shuffle, but for a dictionary.
You can't. Get the list of keys with `.keys()`, shuffle them, then iterate through the list while indexing the original dict. Or use `.items()`, and shuffle and iterate that.
How to iterate through dict in random order in Python?
7,785,672
9
2011-10-16T16:30:34Z
7,788,914
14
2011-10-17T02:50:48Z
[ "python", "random" ]
How can I iterate through all items of a dictionary in a random order? I mean something random.shuffle, but for a dictionary.
A `dict` is an unordered set of key-value pairs. When you iterate a `dict`, it is effectively random. But to explicitly randomize the sequence of key-value pairs, you need to work with a different object that is ordered, like a list. `dict.items()`, `dict.keys()`, and `dict.values()` each return lists, which can be shu...
What does `__import__('pkg_resources').declare_namespace(__name__)` do?
7,785,944
27
2011-10-16T17:15:30Z
7,787,223
21
2011-10-16T20:49:38Z
[ "python", "module", "namespaces", "runtime" ]
In some `__init__.py` files of modules I saw such single line: ``` __import__('pkg_resources').declare_namespace(__name__) ``` What does it do and why people use it? Suppose it's related to dynamic importing and creating namespace at runtime.
It boils down to two things: 1. `__import__` is a Python function that will import a package using a string as the name of the package. It returns a new object that represents the imported package. So `foo = __import__('bar')` will import a package named `bar` and store a reference to its objects in a local object var...
How to use PyBrain?
7,786,737
6
2011-10-16T19:32:35Z
7,837,535
9
2011-10-20T14:32:23Z
[ "python", "neural-network" ]
[PyBrain](http://pybrain.org/) is a Python-based library for creating neural networks. I've looked at the tutorials on their site but they don't seem to help me very much. The simulation I plan to do is have a car that drives on a track, equipped with 5 rangefinders showing the current distance between it and the walls...
It seems that this is a supervised learning problem. In this type of problem you NEED to provide some answers BEFORE to train your NN. You can try following approach 1. Create a simple maze for your car. 2. Drive your car manually in this maze. 3. Collect your turning information Lets assume you have following car. ...
Python Shorthand Operator?
7,786,924
3
2011-10-16T20:02:32Z
7,786,940
8
2011-10-16T20:05:23Z
[ "python", "shorthand" ]
I was researching some information on the topic of trial division, and I came across this symbol in Python: ``` //= ``` I got this from [here](http://en.wikipedia.org/wiki/Trial_division) where the code in the example says: ``` n //= p ``` I can't tell what this is supposed to mean, and my research continues to bri...
`//` is integer division and the ``` n //= p ``` syntax is short for ``` n = n // p ``` except the value n is modified directly [if it supports this](http://docs.python.org/library/operator.html#operator.__ifloordiv__).
Python check if a process is running or not
7,787,120
11
2011-10-16T20:33:02Z
7,788,702
15
2011-10-17T01:54:47Z
[ "python", "windows" ]
I am trying to create a python script which I will later run as a service. Now I want to run a particular part of the code only when iTunes is running. I understand from some research that polling the entire command list and then searching for the application for that list is expensive. I found out that Programs in un...
You can not rely on lock files in Linux or Windows. I would just bite the bullet and iterate through all the running programs. I really do not believe it will be as "expensive" as you think. [psutil](http://code.google.com/p/psutil/) is an excellent cross-platform python module cable of enumerating all the running prog...
Python Imaging Library (PIL) Drawing--Rounded rectangle with gradient
7,787,375
5
2011-10-16T21:13:46Z
7,788,322
10
2011-10-17T00:25:33Z
[ "python", "drawing", "python-imaging-library", "gradient" ]
I am trying to use PIL to draw a rectangle with rounded corners and a gradient fill for the color. I found a cool web site ( <http://web.archive.org/web/20130306020911/http://nadiana.com/pil-tutorial-basic-advanced-drawing#Drawing_Rounded_Corners_Rectangle> ) that shows how to draw a solid-color rounded rectangle and I...
This is a very brute force method, but it gets the job done. Code to produce the gradients was borrowed from [here](http://djangosnippets.org/snippets/787/). ``` from PIL import Image, ImageDraw def channel(i, c, size, startFill, stopFill): """calculate the value of a single color channel for a single pixel""" ...
Evaluate expression as float in Python
7,788,419
2
2011-10-17T00:50:00Z
7,788,433
10
2011-10-17T00:53:37Z
[ "python" ]
I want to write a function which inputs two variables a, b and which returns a/b as a float irrespective of the types of a and b. Right now I'm doing this as: ``` def f(a, b): return float(a)/float(b) ``` Is there a better way to do this?
Assuming you are using Python2, put this at the top of the file ``` from __future__ import division ``` now `/` will always give a float. Use `//` for the old behaviour. If you are using Python3, then this is already the default behaviour of `/`
Ipython / pylab / matplotlib plotting error
7,789,201
5
2011-10-17T03:52:16Z
7,789,336
7
2011-10-17T04:19:29Z
[ "python", "numpy", "matplotlib", "scipy", "ipython" ]
I've installed Enthought's EPD (64 bit for Windows 7). I'm trying to plot historical stock quote data using Yahoo's API. All the code I'm trying to use is on this blog post: <http://www.traineetrader.com/importing-stock-data-from-yahoo-using-python/> The ystockquote.py file works fine. But the second script to plot ...
In addition to adding `from pylab import *`, you need to add `show()` after the last line of the script (i.e., after `grid(True)`) in your question to actually display the plot. Here is what I get after adding `show()`: ![Google Adjusted Close](http://i.stack.imgur.com/2XgwF.png)
How to read a file (or stdin) line by line in Python not waiting for reading entire file
7,791,559
4
2011-10-17T09:07:47Z
7,791,586
7
2011-10-17T09:09:26Z
[ "python", "filter" ]
We have couple of huge files (greater than size of RAM) in disk. I want to read them line by line in python and output results in terminal. I have gone through [1] and [2], but I am looking for methods which do not wait till the entire file is read into memory. I would be using both of these commands: ``` cat fileNam...
This is the [standard behavior of file objects](http://docs.python.org/tutorial/inputoutput.html#methods-of-file-objects) in Python: ``` with open("myfile.txt", "r") as myfile: for line in myfile: # do something with the current line ``` or ``` for line in sys.stdin: # do something with the current l...
How can I print a Python file's docstring when executing it?
7,791,574
34
2011-10-17T09:09:03Z
7,791,595
42
2011-10-17T09:10:11Z
[ "python", "docstring" ]
I have a Python script with a docstring. When the parsing of the command-line arguments does not succeed, I want to print the docstring for the user's information. Is there any way to do this? ## Minimal example ``` #!/usr/bin/env python """ Usage: script.py This describes the script. """ import sys if len(sys.a...
The docstring is stored in the module's `__doc__` global. ``` print(__doc__) ``` By the way, this goes for any module: `import sys; print(sys.__doc__)`. Docstrings of functions and classes are also in their `__doc__` attribute.
How can I print a Python file's docstring when executing it?
7,791,574
34
2011-10-17T09:09:03Z
15,064,168
8
2013-02-25T09:50:43Z
[ "python", "docstring" ]
I have a Python script with a docstring. When the parsing of the command-line arguments does not succeed, I want to print the docstring for the user's information. Is there any way to do this? ## Minimal example ``` #!/usr/bin/env python """ Usage: script.py This describes the script. """ import sys if len(sys.a...
Here is an alternative that does not hardcode the script's filename, but instead uses sys.argv[0] to print it. Using %(scriptName)s instead of %s improves readability of the code. ``` #!/usr/bin/env python """ Usage: %(scriptName)s This describes the script. """ import sys if len(sys.argv) < 2: print __doc__ % {'...
How to use Django model inheritance with signals?
7,792,287
24
2011-10-17T10:14:04Z
7,792,612
13
2011-10-17T10:45:32Z
[ "python", "django", "django-signals" ]
I have a few model inheritance levels in Django: ``` class WorkAttachment(models.Model): """ Abstract class that holds all fields that are required in each attachment """ work = models.ForeignKey(Work) added = models.DateTimeField(default=datetime.datetime.now) views = mo...
You could try something like: ``` model_classes = [WorkAttachment, WorkAttachmentFileBased, WorkAttachmentPicture, ...] def update_attachment_count_on_save(sender, instance, **kwargs): instance.work.attachment_count += 1 instance.work.save() for model_class in model_classes: post_save.connect(update_atta...
How to use Django model inheritance with signals?
7,792,287
24
2011-10-17T10:14:04Z
17,173,716
25
2013-06-18T16:03:59Z
[ "python", "django", "django-signals" ]
I have a few model inheritance levels in Django: ``` class WorkAttachment(models.Model): """ Abstract class that holds all fields that are required in each attachment """ work = models.ForeignKey(Work) added = models.DateTimeField(default=datetime.datetime.now) views = mo...
You could register the connection handler without `sender` specified. And filter the needed models inside it. ``` from django.db.models.signals import post_save from django.dispatch import receiver @receiver(post_save) def my_handler(sender, **kwargs): # Returns false if 'sender' is NOT a subclass of AbstractMod...
How to use Django model inheritance with signals?
7,792,287
24
2011-10-17T10:14:04Z
29,106,313
10
2015-03-17T17:53:04Z
[ "python", "django", "django-signals" ]
I have a few model inheritance levels in Django: ``` class WorkAttachment(models.Model): """ Abstract class that holds all fields that are required in each attachment """ work = models.ForeignKey(Work) added = models.DateTimeField(default=datetime.datetime.now) views = mo...
The simplest solution is to not restrict on the `sender`, but to check in the signal handler whether the respective instance is a subclass: ``` @receiver(post_save) def update_attachment_count_on_save(sender, instance, **kwargs): if isinstance(instance, WorkAttachment): ... ``` However, this may incur a s...
User Authentication in Pyramid
7,792,769
37
2011-10-17T10:58:25Z
7,797,054
57
2011-10-17T17:00:36Z
[ "python", "authentication", "pyramid" ]
I'm building a webapp and needed to choose between Django and Pyramid. I decided to go with Pyramid. I understand Pyramid comes with its own authentication/authorization framework which looks nice. But I haven't seen anywhere in Pyramid where users/groups/permissions are defined. In Django these things come for free. ...
Pyramid has a much more flexible authentication system. And yes, if you want something simple like Django's user/group/permission concept, then flexible might be scary. Pyramid does not have a "User" object, as it makes no assumptions about how you store your data or what ORM you use, therefore there isn't something f...
What Is ** In Python?
7,794,009
5
2011-10-17T12:51:48Z
7,794,023
12
2011-10-17T12:52:57Z
[ "python" ]
I read the following python code: ``` a=2**b ``` I know several languages like c,c++,c#,java... i even googled \*\* operator without any results. so what does 2\*\*b means?
It is the exponentiation operator. In your example, `a` will have the result of `2` to the `b`th power. Check out the last entry in the table in [this section](http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex).
What Is ** In Python?
7,794,009
5
2011-10-17T12:51:48Z
7,794,027
9
2011-10-17T12:53:09Z
[ "python" ]
I read the following python code: ``` a=2**b ``` I know several languages like c,c++,c#,java... i even googled \*\* operator without any results. so what does 2\*\*b means?
it's simple `**` means power, so `2**b` means 2 to the power of b
What Is ** In Python?
7,794,009
5
2011-10-17T12:51:48Z
7,794,036
7
2011-10-17T12:54:07Z
[ "python" ]
I read the following python code: ``` a=2**b ``` I know several languages like c,c++,c#,java... i even googled \*\* operator without any results. so what does 2\*\*b means?
It's python's [power operator](http://docs.python.org/reference/expressions.html#the-power-operator). You can write this as `a = pow(2, b)`
Running javascript in Selenium using Python
7,794,087
32
2011-10-17T12:58:27Z
7,794,217
56
2011-10-17T13:09:07Z
[ "javascript", "python", "selenium" ]
I am totally new to Selenium. I want to execute a javascript snippet in the following code(as commented in the code), but can't do so. Please help. ``` from selenium import webdriver import selenium from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.keys import Keys import tim...
Try `browser.execute_script` instead of `selenium.GetEval`. See [this answer](http://stackoverflow.com/questions/5585343/getting-the-return-value-of-javascript-code-in-selenium/5585345#5585345) for example.
Running javascript in Selenium using Python
7,794,087
32
2011-10-17T12:58:27Z
29,273,838
18
2015-03-26T08:23:30Z
[ "javascript", "python", "selenium" ]
I am totally new to Selenium. I want to execute a javascript snippet in the following code(as commented in the code), but can't do so. Please help. ``` from selenium import webdriver import selenium from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.keys import Keys import tim...
A python example: ``` driver = webdriver.Firefox() driver.get("http://stackoverflow.com/questions/7794087/running-javascript-in-selenium-using-python") driver.execute_script("document.getElementsByClassName('comment-user')[0].click()") ```
How can I remove duplicate words in a string with Python?
7,794,208
6
2011-10-17T13:08:35Z
7,794,257
7
2011-10-17T13:12:56Z
[ "python", "string", "duplicates" ]
Following example: ``` string1 = "calvin klein design dress calvin klein" ``` How can I remove the second two duplicates `"calvin"` and `"klein"`? The result should look like ``` string2 = "calvin klein design dress" ``` only the second duplicates should be removed and the sequence of the words should not be chang...
``` def unique_list(l): ulist = [] [ulist.append(x) for x in l if x not in ulist] return ulist a="calvin klein design dress calvin klein" a=' '.join(unique_list(a.split())) ```
How can I remove duplicate words in a string with Python?
7,794,208
6
2011-10-17T13:08:35Z
7,794,619
11
2011-10-17T13:40:19Z
[ "python", "string", "duplicates" ]
Following example: ``` string1 = "calvin klein design dress calvin klein" ``` How can I remove the second two duplicates `"calvin"` and `"klein"`? The result should look like ``` string2 = "calvin klein design dress" ``` only the second duplicates should be removed and the sequence of the words should not be chang...
``` string1 = "calvin klein design dress calvin klein" words = string1.split() print " ".join(sorted(set(words), key=words.index)) ``` This sorts the set of all the (unique) words in your string by the word's index in the original list of words.
Using tastypie resource in view
7,795,463
6
2011-10-17T14:45:28Z
7,804,546
9
2011-10-18T08:42:38Z
[ "python", "django", "rest", "tastypie" ]
my first question here : So I'm using tastypie to have api's for my app. I want to be able to use tastypie to render json and then include that in a django view so that I can bootstrap my app's data. There is an example of this in django tastypie cookbook here : <http://django-tastypie.readthedocs.org/en/latest/cook...
So here I found the solution, the problem was with url resolving ... I needed to add ``` def get_resource_uri(self, bundle_or_obj): return '/api/v1/%s/%s/' % (self._meta.resource_name,bundle_or_obj.obj.id) ``` to the related object (session here) in order for it to work (don't ask why!) So here is my working solu...
What is the simplest way to sort a list of strings in the following way?
7,795,679
2
2011-10-17T15:02:35Z
7,795,707
10
2011-10-17T15:05:16Z
[ "python", "string", "list", "sorting", "integer" ]
I have a list of strings which can represent integers as well as names. The default string compare does the following: ``` sorted(['1','2','3','4','10','102','14','Alice','John','Sally']) ['1', '10', '102', '14', '2', '3', '4', 'Alice', 'John', 'Sally'] ``` I would like to sort the list as follows: ``` ['1', '2', '3...
If there are no negative numbers: ``` lyst = ['1','2','3','4','10','102','14','Alice','John','Sally'] print sorted(lyst, key=lambda k: int(k) if k.isdigit() else k) ``` Here's a version that doesn't rely on CPython details and works with Python 3: ``` sorted(lyst, key=lambda k: (0, int(k)) if k.isdigit() else (1, k)...
How to get parent element of my element?
7,796,248
5
2011-10-17T15:49:26Z
7,796,271
9
2011-10-17T15:51:37Z
[ "python", "lxml" ]
For example: ``` test = label.find('image').attrib['url'] ``` How to get parent element of image ?
You can use the `getparent()` method: ``` image_parent = label.find('image').getparent() ```
python environment case senstivity - os.environ[...]
7,797,269
4
2011-10-17T17:23:35Z
7,797,329
8
2011-10-17T17:30:55Z
[ "python" ]
I need to access the process' environment block in a platform-independent manner. The python [os module docs](http://docs.python.org/library/os.html) don't specify anything about case-sensitivity of the `os.environ` / `os.getenv`. Experimenting on my ubuntu and win7 dev box's, I see that os.environ is case sensitive o...
When the documentation doesn't specify the behaviour and you want to discover the answer yourself, you can look in the source code. In this case you can get the source code for `os.py` online at <http://svn.python.org/>: * [`os.py` (Python trunk)](http://svn.python.org/projects/python/trunk/Lib/os.py). * [`os.py` (Pyt...
How to get currently running testcase name from testsuite in unittest
7,797,442
10
2011-10-17T17:40:04Z
7,798,114
29
2011-10-17T18:46:19Z
[ "python", "unit-testing", "selenium" ]
How can I get **currently running testcase name**, while in the testsuite collection there are 16 testcases. Tests are executed sequentially (in the order of adding test to the testSuite collection). When I add all tests to testSuite collection I can preview this object but how can I get currently executing test while ...
[unittest.TestCase.ShortDescription()](http://docs.python.org/library/unittest.html#unittest.TestCase.shortDescription) > Returns a description of the test, or None if no description has been provided. The default implementation of this method returns the first line of the test method’s docstring, if available, or N...
Can i cycle through line styles in matplotlib
7,799,156
45
2011-10-17T20:25:29Z
7,799,661
70
2011-10-17T21:16:13Z
[ "python", "matplotlib" ]
I know how to cycle through a list of colors in matplotlib. But is it possible to do something similar with line styles (plain, dotted, dashed, etc.)? I'd need to do that so my graphs would be easier to read when printed. Any suggestions how to do that?
Something like this might do the trick: ``` import matplotlib.pyplot as plt from itertools import cycle lines = ["-","--","-.",":"] linecycler = cycle(lines) plt.figure() for i in range(10): x = range(i,i+10) plt.plot(range(10),x,next(linecycler)) plt.show() ``` Result: ![enter image description here](http://...
Can i cycle through line styles in matplotlib
7,799,156
45
2011-10-17T20:25:29Z
9,276,196
9
2012-02-14T11:39:45Z
[ "python", "matplotlib" ]
I know how to cycle through a list of colors in matplotlib. But is it possible to do something similar with line styles (plain, dotted, dashed, etc.)? I'd need to do that so my graphs would be easier to read when printed. Any suggestions how to do that?
If you want the change to be automatic you can add this two lines in the axes.py file of matplotlib: Look for that line: ``` self.color_cycle = itertools.cycle(clist) ``` and add the following line underneath: ``` self.line_cycle = itertools.cycle(["-",":","--","-.",]) ``` And look for the line: ``` kw['c...
Can i cycle through line styles in matplotlib
7,799,156
45
2011-10-17T20:25:29Z
33,173,356
12
2015-10-16T14:46:26Z
[ "python", "matplotlib" ]
I know how to cycle through a list of colors in matplotlib. But is it possible to do something similar with line styles (plain, dotted, dashed, etc.)? I'd need to do that so my graphs would be easier to read when printed. Any suggestions how to do that?
The upcoming matplotlib v1.5 will deprecate color\_cycle for the new prop\_cycler feature: <http://matplotlib.org/devdocs/users/whats_new.html?highlight=prop_cycle#added-axes-prop-cycle-key-to-rcparams> `plt.rcParams['axes.prop_cycle'] = ("cycler('color', 'rgb') +" "cycler('lw', [1, 2, 3])")` Then go ahead and create ...
How to split a Python module into multiple files?
7,799,286
12
2011-10-17T20:38:15Z
7,799,406
10
2011-10-17T20:50:16Z
[ "python", "python-module" ]
I have a single Python module which contains 3 classes: A, A1 and A2. A1 and A2 derive from A. A contains functions which operate on A1 and A2. This all works fine when it's in one .py file. But that file has grown quite long and I would like to split A1 and A2 off into their own files. How can I split this file despi...
modA.py: ``` class A(...): ... ``` modA1.py: ``` import modA class A1(modA.A): ... ``` modA2.py: ``` import modA class A2(modA.A): ... ``` modfull: ``` from modA import A from modA1 import A1 from modA2 import A2 ``` Even if A "processes" A1s and A2s you should be fine because thanks to duck typing you...
How should we test exceptions with nose?
7,799,593
18
2011-10-17T21:09:19Z
7,799,676
8
2011-10-17T21:17:51Z
[ "python", "testing", "nose" ]
I'm testing exceptions with nose. Here's an example: ``` def testDeleteUserUserNotFound(self): "Test exception is raised when trying to delete non-existent users" try: self.client.deleteUser('10000001-0000-0000-1000-100000000000') # make nose fail here except UserNotFoundException: ...
``` def testDeleteUserUserNotFound(self): "Test exception is raised when trying to delete non-existent users" try: self.client.deleteUser('10000001-0000-0000-1000-100000000000') assert False # <--- except UserNotFoundException: assert True ``` The semantics of `try`/`except` imply t...
How should we test exceptions with nose?
7,799,593
18
2011-10-17T21:09:19Z
8,241,858
29
2011-11-23T12:04:04Z
[ "python", "testing", "nose" ]
I'm testing exceptions with nose. Here's an example: ``` def testDeleteUserUserNotFound(self): "Test exception is raised when trying to delete non-existent users" try: self.client.deleteUser('10000001-0000-0000-1000-100000000000') # make nose fail here except UserNotFoundException: ...
**nose** provides tools for testing exceptions (like unittest does). Try this example (and read about the other tools at [Nose Testing Tools](http://readthedocs.org/docs/nose/en/latest/testing_tools.html) ``` from nose.tools import * l = [] d = dict() @raises(Exception) def test_Exception1(): '''this test should...
Google App Engine, Python 2.7 runtime, ImportError: cannot import name djangoforms
7,799,764
11
2011-10-17T21:26:07Z
7,800,914
9
2011-10-17T23:44:06Z
[ "python", "google-app-engine" ]
If I comment out the handlers that use djangoforms everything else seems to work. The following is my modified app.yaml: ``` application: xxxxxxx version: 5 #` -1+1 # runtime: python runtime: python27 api_version: 1 inbound_services: - mail #` +3 libraries: - name: django version: "1.2" handlers: - url: /(.*\.(h...
The `google.appengine.ext.db.djangoforms` module is not provided with the Python 2.7. You could patch in a copy yourself, but a better idea would be to modify your form handling code to not rely on it - it's unsupported and frankly a bit of a hack.
Numpy vs Cython speed
7,799,977
20
2011-10-17T21:46:35Z
7,802,144
20
2011-10-18T03:37:07Z
[ "python", "performance", "numpy", "cython" ]
I have an analysis code that does some heavy numerical operations using numpy. Just for curiosity, tried to compile it with cython with little changes and then I rewrote it using loops for the numpy part. To my surprise, the code based on loops was much faster (8x). I cannot post the complete code, but I put together ...
As mentioned in the other answers, version 2 is essentially the same as version 1 since cython is unable to dig into the array access operator in order to optimise it. There are 2 reasons for this * First, there is a certain amount of overhead in each call to a numpy function, as compared to optimised C code. However ...
Numpy vs Cython speed
7,799,977
20
2011-10-17T21:46:35Z
10,486,566
24
2012-05-07T17:42:04Z
[ "python", "performance", "numpy", "cython" ]
I have an analysis code that does some heavy numerical operations using numpy. Just for curiosity, tried to compile it with cython with little changes and then I rewrote it using loops for the numpy part. To my surprise, the code based on loops was much faster (8x). I cannot post the complete code, but I put together ...
With slight modification, version 3 becomes twice as fast: ``` @cython.boundscheck(False) @cython.wraparound(False) @cython.nonecheck(False) def process2(np.ndarray[DTYPE_t, ndim=2] array): cdef unsigned int rows = array.shape[0] cdef unsigned int cols = array.shape[1] cdef unsigned int row, col, row2 ...
How do you delete a node in networkx?
7,800,133
6
2011-10-17T22:04:21Z
7,800,184
11
2011-10-17T22:09:46Z
[ "python", "graph-theory", "networkx" ]
I have a dataset that I'm uploading as a graph for various timeframes and trying to figure relationships between them. I want to delete all the nodes that do not have edges but I'm not sure the command to remove or delete nodes. Any idea how to do this?
``` import networkx as nx import matplotlib.pyplot as plt G=nx.Graph() G.add_edges_from([('A','B'),('A','C'),('B','D'),('C','D')]) nx.draw(G) plt.show() ``` ![enter image description here](http://i.stack.imgur.com/8MkUw.png) ``` G.remove_node('B') nx.draw(G) plt.show() ``` ![enter image description here](http://i.s...
gcc error from easy_install of setproctitle
7,800,574
4
2011-10-17T22:56:37Z
7,800,621
9
2011-10-17T23:02:43Z
[ "python", "easy-install", "setup.py" ]
I'm trying to install setproctitle. I've tried just downloading the package and using setup.py to install and I've tried easy\_install. Neither method works, both come up with something that looks like: ``` :~$ sudo easy_install setproctitle Searching for setproctitle Reading http://pypi.python.org/simple/setproctitle...
Install the [python-dev](http://packages.ubuntu.com/precise/python-dev) package.
Can Native Client (NaCl) programs be written in languages other than C or C++?
7,800,693
18
2011-10-17T23:12:41Z
7,844,298
8
2011-10-21T02:15:36Z
[ "python", "google-chrome", "google-chrome-extension", "go", "google-nativeclient" ]
Would it be possible to write a native client application in Python or Go that could then run in the browser?
Go used to compile to NaCl, but NaCl's been such a moving target that the support was removed from Go. It'll probably be resurrected at some point if/when NaCl settles down.
Syntax Highlighting with Pygments is failing via Liquid Templates String Error
7,801,197
17
2011-10-18T00:34:41Z
7,809,628
21
2011-10-18T15:17:56Z
[ "python", "markdown", "jekyll", "liquid", "pygments" ]
I'm using Jekyll to convert my markdown and Pygments for syntax highlighting. Here is the error maruku displays: ``` Liquid error: undefined method `join' for "\n song_info = []\n for song in songs:\n song_info.append(song.name) \n":String ``` The markup is as follows: ``` {% highlight python %} song_info = [] ...
I had the same problem and reverted the liquid gem to version 2.2.2 as a workaround. Seems like a bug in the 2.3.0 version's pygments support, or Jekyll's use of it. ``` sudo gem uninstall liquid sudo gem install liquid --version '2.2.2' ```
Print a float number in normal form, not Exponential
7,801,586
9
2011-10-18T01:45:26Z
7,801,683
16
2011-10-18T02:06:23Z
[ "python", "python-3.x", "floating-point" ]
I have a number that prints out in exponential form: ``` >>> >>> a = 1/1221759 >>> print(a) 8.184920266599223e-07 >>> ``` How can i make it print in normal form?
You can format it as a fixed-point number. ``` >>> a = 1/1221759 >>> '{0:.10f}'.format(a) '0.0000008185' ```
How to convert a dictionary to query string in Python?
7,801,991
43
2011-10-18T03:10:19Z
7,802,002
84
2011-10-18T03:13:24Z
[ "python", "urllib2", "urllib" ]
After using `cgi.parse_qs()`, how to convert the result (dictionary) back to query string? Looking for something similar to `urllib.urlencode()`.
From [the docs](http://docs.python.org/library/urllib.html#urllib.urlencode): > `urllib.urlencode`(`query`[, `doseq`]) > Convert **a mapping object** or a sequence of two-element tuples to a “percent-encoded” string... a series of `key=value` pairs separated by `'&'` characters... A `dict` is a mapping.
Issues using python's string formatting libraries
7,802,265
3
2011-10-18T04:00:38Z
7,802,297
11
2011-10-18T04:05:31Z
[ "python", "string", "formatting" ]
``` cur.execute('INSERT INTO company VALUES (%(cname), %(symbol), %(start_date), %(end_date))' %{'cname' : company, 'symbol' : company, 'start_date' : startdate, 'end_date' : enddate}) ``` Trying to run this line on my computer results in a string formatting error: ValueError: unsupported format character ',' (0x2c) a...
You need an "s" after each of those positional arguments. ``` (%(cname)s, %(symbol)s, .... ```
Email an attachment in R with gmail
7,802,360
23
2011-10-18T04:17:32Z
7,802,431
17
2011-10-18T04:30:13Z
[ "python", "jython" ]
I am desiring to send an email in R with an attachment using gmail. I have found that sendmailR does not work with gmail because it requires authentication (I couldn't get it to work with gmail so I assume this to be true unless someone tells me I'm wrong , in which case I'll post the R output and error message for tha...
You are running Jython code inside of your R environment, so you're looking for a way to send an attachment using the Jython language, not R. Since Jython is basically Python, here is a way to send an email with an attachment with Python: [How to send Email Attachments with python](http://stackoverflow.com/questions/3...
In Python, heapq.heapify doesn't take cmp or key functions as arguments like sorted does
7,803,121
16
2011-10-18T06:11:39Z
7,803,240
11
2011-10-18T06:25:58Z
[ "python" ]
I'm using python2.6. Is it available in higher version of python? Else is there any other way I can maintain priority queues for list of objects of non-trivial classes? What I need is something like this ``` >>> l = [ ['a', 3], ['b', 1] ] >>> def foo(x, y): ... return x[1]-y[1] >>> heap = heapify(l, cmp=foo) ``` ...
Just write an appropriate `__lt__` method for the objects in the list so they sort correctly: ``` class FirstList(list): def __lt__(self, other): return self[0] < other[0] lst = [ ['a', 3], ['b', 1] ] lst = [FirstList(item) for item in lst] ``` Only `__lt__` is needed by Python for sorting, though it's ...
In Python, heapq.heapify doesn't take cmp or key functions as arguments like sorted does
7,803,121
16
2011-10-18T06:11:39Z
7,810,917
16
2011-10-18T16:56:49Z
[ "python" ]
I'm using python2.6. Is it available in higher version of python? Else is there any other way I can maintain priority queues for list of objects of non-trivial classes? What I need is something like this ``` >>> l = [ ['a', 3], ['b', 1] ] >>> def foo(x, y): ... return x[1]-y[1] >>> heap = heapify(l, cmp=foo) ``` ...
The traditional solution is to store (priority, task) tuples on the heap: ``` pq = [ ] heappush(pq, (10, task1)) heappush(pq, (5, task2)) heappush(pq, (15, task3)) priority, task = heappop(pq) ``` This works fine as long as no two tasks have the same priority; otherwise, the tasks themselves are compared (which might...
dateutil.parser.parse() gives error "initial_value must be unicode or None, not str" on Windows platform
7,804,505
5
2011-10-18T08:38:35Z
7,804,999
14
2011-10-18T09:19:18Z
[ "python", "python-dateutil" ]
I'm sure there's a really simple solution to this, but I'm still fairly new to Python. I'm trying to use dateutil.parser.parse() to parse a string with a timestamp in it: ``` >>> import dateutil.parser >>> a = dateutil.parser.parse("2011-10-01 12:00:00+01:00") >>> print a 2011-10-01 12:00:00+01:00 ``` This works fin...
It's not a Windows issue, it's Python version / library version issue. dateutil 2.0 is written to support only Python 3, not Python 2.X. Both cases here contain bugs when used with Python 2.X. In the first case: ``` dateutil.parser.parse("2011-10-01 12:00:00+01:00") ``` the `io.StringIO` class allows only unicode a...
Python unicode list join
7,804,743
6
2011-10-18T08:59:57Z
7,804,780
15
2011-10-18T09:03:09Z
[ "python", "string", "list", "unicode" ]
i want to join a unicode python list for example: ``` a = [u'00', u'0c', u'29', u'58', u'86', u'16'] ``` and now i want a string of a that looks like this: ``` '00:0c:29:58:86:16' ``` How would i join this?
``` >>> a = [u'00', u'0c', u'29', u'58', u'86', u'16'] >>> u":".join(a) u'00:0c:29:58:86:16' >>> str(u":".join(a)) '00:0c:29:58:86:16' ```
Fitting a histogram with python
7,805,552
14
2011-10-18T10:08:23Z
8,624,485
32
2011-12-24T12:22:59Z
[ "python", "histogram", "curve-fitting" ]
I have a histogram ``` H=hist(my_data,bins=my_bin,histtype='step',color='r') ``` I can see that the shape is almost gaussian but I would like to fit this histogram with a gaussian function and print the value of the mean and sigma I get. Can you help me?
Here you have an example working on py2.6 and py3.2: ``` from scipy.stats import norm import matplotlib.mlab as mlab import matplotlib.pyplot as plt # read data from a text file. One number per line arch = "test/Log(2)_ACRatio.txt" datos = [] for item in open(arch,'r'): item = item.strip() if item != '': ...
Fitting a histogram with python
7,805,552
14
2011-10-18T10:08:23Z
15,521,359
15
2013-03-20T10:47:05Z
[ "python", "histogram", "curve-fitting" ]
I have a histogram ``` H=hist(my_data,bins=my_bin,histtype='step',color='r') ``` I can see that the shape is almost gaussian but I would like to fit this histogram with a gaussian function and print the value of the mean and sigma I get. Can you help me?
Here is an example that uses scipy.optimize to fit a non-linear functions like a Gaussian, even when the data is in a histogram that isn't well ranged, so that a simple mean estimate would fail. An offset constant also would cause simple normal statistics to fail ( just remove p[3] and c[3] for plain gaussian data). `...
What is a more succinct way of converting python boolean to javascript boolean literals?
7,805,994
4
2011-10-18T10:44:14Z
7,806,047
14
2011-10-18T10:48:36Z
[ "python" ]
I want to convert a python boolean into JS's boolean literal. This is what I am working with: ``` store = dict(vat=True) if store['vat']: store.update({'vat': 'true'}) else: store.update({'vat': 'false'}) ``` Is there a more less verbose way to replace this code snippet ?
``` >>> store['vat'] = json.dumps(store['vat']) >>> store {'vat': 'true'} ```
Python: merge nested lists
7,806,511
3
2011-10-18T11:30:08Z
7,806,568
12
2011-10-18T11:34:28Z
[ "python", "merge", "nested-lists" ]
beginner to python here. I have 2 nested lists that I want to merge: ``` list1 = ['a', (b, c), (d, e), (f, g, h) ] list2 = [(p,q), (r, s), (t), (u, v, w) ] ``` the output I am looking for is: ``` list3 = [(a, p, q), (b, c, r, s), (d, e, t), ...
Use the power of the [`zip`](http://docs.python.org/library/functions.html#zip) function and [list comprehensions](http://docs.python.org/tutorial/datastructures.html#list-comprehensions): ``` list1 = [('a', ), ('b', 'c'), ('d', 'e'), ('f', 'g', 'h') ] list2 = [('p', 'q'), ('r', 's'), ...
How to unzip a file with Python 2.4?
7,806,563
27
2011-10-18T11:34:07Z
7,806,727
48
2011-10-18T11:49:37Z
[ "python", "zip", "zipfile", "python-2.4" ]
I'm having a hard time figuring out how to unzip a zip file with 2.4. `extract()` is not included in 2.4. I'm restricted to using 2.4.4 on my server. Can someone please provide a simple code example?
You have to use `namelist()` and `extract()`. Sample considering directories ``` import zipfile import os.path import os zfile = zipfile.ZipFile("test.zip") for name in zfile.namelist(): (dirname, filename) = os.path.split(name) print "Decompressing " + filename + " on " + dirname if not os.path.exists(dirname):...
How to unzip a file with Python 2.4?
7,806,563
27
2011-10-18T11:34:07Z
14,596,064
12
2013-01-30T03:12:49Z
[ "python", "zip", "zipfile", "python-2.4" ]
I'm having a hard time figuring out how to unzip a zip file with 2.4. `extract()` is not included in 2.4. I'm restricted to using 2.4.4 on my server. Can someone please provide a simple code example?
There's some problem with Vinko's answer (at least when I run it). I got: ``` IOError: [Errno 13] Permission denied: '01org-webapps-countingbeads-422c4e1/' ``` Here's how to solve it: ``` # unzip a file def unzip(path): zfile = zipfile.ZipFile(path) for name in zfile.namelist(): (dirname, filename) =...
Calling parent's __call__ method within class
7,806,593
7
2011-10-18T11:36:16Z
7,806,655
11
2011-10-18T11:42:22Z
[ "python", "inheritance", "methods", "superclass" ]
I'd like to call a parent's **call** method from inherited class Code looks like this ``` #!/usr/bin/env python class Parent(object): def __call__(self, name): print "hello world, ", name class Person(Parent): def __call__(self, someinfo): ...
The `super` function takes the *derived* class as its first parameter, not the base class. ``` super(Person, self).__call__(someinfo) ``` If you need to use the base class, you can do it directly (but beware that this will break multiple inheritance, so you shouldn't do it unless you're sure that's what you want): `...
Is there a way to know by which Python version the .pyc file was compiled?
7,807,541
25
2011-10-18T12:57:01Z
7,807,661
38
2011-10-18T13:05:57Z
[ "python", "compilation" ]
Is there any way to know by which Python version the `.pyc` file was compiled?
The first two bytes of the `.pyc` file are the magic number that tells the version of the bytecodes. The word is stored in little-endian format, and the known values are: ``` # Python/import.c - merged by aix from Python 2.7.2 and Python 3.2.2 # EDIT: added little endian hex values for comparison first two bytes of Ig...
Is there a way to know by which Python version the .pyc file was compiled?
7,807,541
25
2011-10-18T12:57:01Z
7,807,749
40
2011-10-18T13:11:52Z
[ "python", "compilation" ]
Is there any way to know by which Python version the `.pyc` file was compiled?
You can get the magic number of your Python as follows: ``` $ python -V Python 2.6.2 # python >>> import imp >>> imp.get_magic().encode('hex') 'd1f20d0a' ``` To get the magic number for a pyc file you can do the following: ``` >>> f = open('test25.pyc') >>> magic = f.read(4) >>> magic.encode('hex') 'b3f20d0a' >>> f ...
Python naming conventions for attributes and methods meant to be overwritten
7,809,287
5
2011-10-18T14:53:56Z
7,809,563
10
2011-10-18T15:13:45Z
[ "python", "naming-conventions", "template-method-pattern" ]
I have some object oriented code in Python, where some classes are meant to be extended to provide the missing custom bits of code (a la [Template Method pattern](http://en.wikipedia.org/wiki/Template_method_pattern), but also with variables), that will only be used by the super class, not by the client code using them...
I usually use single underscore e.g. `_myvar` for protected (as in C++) methods/attributes, which can be used by derived classes and use double underscore e.g. `__var` when it should not be used by anybody else, and as double-underscore names at class definition level are [mangled](http://docs.python.org/reference/expr...
Python naming conventions for attributes and methods meant to be overwritten
7,809,287
5
2011-10-18T14:53:56Z
7,809,571
7
2011-10-18T15:14:13Z
[ "python", "naming-conventions", "template-method-pattern" ]
I have some object oriented code in Python, where some classes are meant to be extended to provide the missing custom bits of code (a la [Template Method pattern](http://en.wikipedia.org/wiki/Template_method_pattern), but also with variables), that will only be used by the super class, not by the client code using them...
First of all i think that you are mistaken when you say that: > about prepending underscore to private members not intended to be used by subclasses. Actually prepending a method/attribute by underscore is a python convention that mean that this method/attribute shouldn't be accessed outside the class (and its subcla...
Attributes initialization/declaration in Python class: where to place them?
7,809,407
31
2011-10-18T15:01:54Z
7,809,443
38
2011-10-18T15:04:31Z
[ "python", "coding-style", "attributes" ]
I was wondering what was the best practice for initializing object attributes in Python, in the body of the class or inside the `__init__` function? i.e. ``` class A(object): foo = None ``` vs ``` class A(object): def __init__(self): self.foo = None ```
If you want the attribute to be shared by all instances of the class, use a class attribute: ``` class A(object): foo = None ``` This causes `('foo',None)` to be a `(key,value)` pair in `A.__dict__`. If you want the attribute to be customizable on a per-instance basis, use an instance attribute: ``` class A(obj...
Can you make multiple "if" conditions in Python?
7,809,698
8
2011-10-18T15:23:02Z
7,809,732
34
2011-10-18T15:25:17Z
[ "python", "if-statement" ]
In JavaScript, one could do this: ``` if (integer > 3 && integer < 34){ document.write("Something") } ``` Is this possible in Python?
Python indeed allows you to do such a thing ``` if integer > 3 and integer < 34 ``` Python is also smart enough to handle: ``` if 3 < integer < 34: # do your stuff ```
Can you make multiple "if" conditions in Python?
7,809,698
8
2011-10-18T15:23:02Z
7,809,749
7
2011-10-18T15:26:28Z
[ "python", "if-statement" ]
In JavaScript, one could do this: ``` if (integer > 3 && integer < 34){ document.write("Something") } ``` Is this possible in Python?
Python replaces the usual C-style boolean operators (`&&`, `||`, `!`) with words: `and`, `or`, and `not` respectively. So you can do things like: ``` if (isLarge and isHappy) or (isSmall and not isBlue): ``` which makes things more readable.
Can you make multiple "if" conditions in Python?
7,809,698
8
2011-10-18T15:23:02Z
7,810,860
7
2011-10-18T16:51:32Z
[ "python", "if-statement" ]
In JavaScript, one could do this: ``` if (integer > 3 && integer < 34){ document.write("Something") } ``` Is this possible in Python?
Just on formatting. If you have very long conditions, I like this way of formatting ``` if (isLarge and isHappy) \ or (isSmall and not isBlue): pass ``` It fits in nicely with Python's comb formatting
google app engine oauth2 provider
7,810,607
9
2011-10-18T16:29:11Z
10,855,271
22
2012-06-01T18:09:00Z
[ "python", "google-app-engine", "oauth-2.0" ]
I want to set up a rest api with an oauth 2.0 provider for authentication.I use python. is there any library for setting up an oauth 2.0 provider coded in python that runs on app engine ? Thanks.
OAuth2 support in builtin on both the Python and Java App Engine runtimes. In Python all you need is: ``` from google.appengine.api import oauth # Note, unlike in the Android app below, there's no 'oauth2:' prefix here SCOPE = 'https://www.googleapis.com/auth/userinfo.email' # magic happens here user = oauth.get_cu...
How to fill specific positional arguments with partial in python?
7,811,247
14
2011-10-18T17:26:02Z
7,811,270
21
2011-10-18T17:28:11Z
[ "python" ]
Basically, what I'd like to do is: ``` >>> from functools import partial >>> partial(str.startswith, prefix='a')('a') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: startswith() takes no keyword arguments ``` But more generally the question is, **how to fill specific positional ar...
It cannot be done. You have to make a wrapper function. Ostensibly, you would use keyword arguments, as you tried to do - that's what they're for, right? Unfortunately, as you've discovered, python's standard library functions [do not take named parameters](http://muharem.wordpress.com/2006/12/01/first-experiments-wit...
How do I convert a Django QuerySet into list of dicts?
7,811,556
35
2011-10-18T17:52:59Z
7,811,582
41
2011-10-18T17:55:24Z
[ "python", "django" ]
How can I convert a Django QuerySet into a list of dicts? I haven't found an answer to this so I'm wondering if I'm missing some sort of common helper function that everyone uses.
Use the [`.values()`](https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.values) method: ``` >>> Blog.objects.values() [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}], >>> Blog.objects.values('id', 'name') [{'id': 1, 'name': 'Beatles Blog'}] ```
How do I convert a Django QuerySet into list of dicts?
7,811,556
35
2011-10-18T17:52:59Z
25,718,112
12
2014-09-08T05:51:02Z
[ "python", "django" ]
How can I convert a Django QuerySet into a list of dicts? I haven't found an answer to this so I'm wondering if I'm missing some sort of common helper function that everyone uses.
The [`.values()`](https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.values) method will return you a result of type `ValuesQuerySet` which is typically what you need in most cases. But if you wish, you could turn `ValuesQuerySet` into a native Python list using Python list com...
Convert array of string (category) to array of int from a pandas dataframe
7,813,132
9
2011-10-18T20:16:12Z
7,821,507
10
2011-10-19T12:43:50Z
[ "python", "numpy", "pandas" ]
I am trying to do something very similar to that [previous question](http://stackoverflow.com/questions/3172509/numpy-convert-categorical-string-arrays-to-an-integer-array) but I meet error. I have a pandas dataframe containing features and label I need to do some convertion to send the features and the label variable ...
If you have a vector of strings or other objects and you want to give it categorical labels, you can use the `Factor` class (available in the `pandas` namespace): ``` In [1]: s = Series(['single', 'touching', 'nuclei', 'dusts', 'touching', 'single', 'nuclei']) In [2]: s Out[2]: 0 single 1 touching 2 nuclei ...
Python: Inline if to print non-empty strings?
7,813,669
2
2011-10-18T21:01:19Z
7,813,732
7
2011-10-18T21:06:42Z
[ "python", "if-statement" ]
I'm trying to print out just the non-empty strings in a list. I can't seem to get the below to work, what am I doing wrong?? ``` print item in mylist if item is not "" ```
The following is invalid syntax: `print item in mylist if item is not ""` You could perhaps achieve what you want using a list comprehension: ``` >>> mylist = ["foo","bar","","baz"] >>> print [item for item in mylist if item] ['foo', 'bar', 'baz'] ```
Django Tastypie: How to Authenticate with API Key
7,814,128
13
2011-10-18T21:42:33Z
7,814,317
17
2011-10-18T22:05:33Z
[ "python", "django", "tastypie" ]
I'm making an internal API with TastyPie. I have ``` from tastypie.authentication import ApiKeyAuthentication class MyResource(ModelResource): Meta: authentication = ApiKeyAuthentication() ``` With Auth rules disabled, my API works great. With it on, I get a 401 (UNAUTHORIZED) response no matter what I try. I'...
Add the username and api\_key parameters to your GET variables. Make sure that you have the ``` curl http://localhost:8000/api/v1/books/?username=issackelly\&api_key=123456789adfljafal ``` Make sure to follow the other instructions from teh docs when setting it up: ### ApiKeyAuthentication As an alternative to requ...
Including child resources in a Django Tastypie API
7,815,756
8
2011-10-19T02:00:15Z
7,815,868
13
2011-10-19T02:19:16Z
[ "python", "django", "api", "rest", "tastypie" ]
I'm planning a site with Django and Tastypie for the REST API, and I'm having a tough time figuring out the "right" way to include child resources in a returned resource. As a sandbox, I made a small app with a Ticket model and a TicketComment model, where comments belong to a ticket. I looked at the Tastypie Cookbook...
You're looking for related fields: <http://django-tastypie.readthedocs.org/en/latest/fields.html#relationship-fields>
Syslog messages show up as "Unknown" when I use Python's logging.handlers.SysLogHandler
7,815,811
10
2011-10-19T02:10:06Z
7,822,224
14
2011-10-19T13:41:43Z
[ "python", "logging", "syslog" ]
When I run this on my mac: ``` import logging.handlers logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) syslog_address = '/var/run/syslog' logger.addHandler(logging.handlers.SysLogHandler(syslog_address)) logger.error("What the crap?") ``` It shows up like this in the syslog: ``` Oct 18 19:02:06 ...
I think the APP-NAME (which indicates the source) is an optional component in the syslog header. The latest version of SysLogHandler (for Python 3.3) includes support for an APP-NAME (called `ident` as per the C syslog API), but it's not available in earlier versions. See [this Python issue](http://bugs.python.org/issu...
Proper capitalization for titles in Python
7,816,347
7
2011-10-19T03:50:33Z
7,816,387
14
2011-10-19T03:59:55Z
[ "python" ]
I'm looking for a library that properly capitalizes a given string by assuming it is a title. I know there is string.title(), but it capitalizes every work, not just the one's that should be capitalized. Anyone know any libraries? Examples of words that should not be capitalized in titles: * Propositions (in, from, e...
The term to Google for is "titlecase". The [first hit](http://muffinresearch.co.uk/archives/2008/05/27/titlecasepy-titlecase-in-python/) is [the `titlecase` package](http://pypi.python.org/pypi/titlecase/0.5.1): ``` $ pip install titlecase ... $ python ... >>> from titlecase import titlecase >>> titlecase('the spam an...
if A vs if A is not None:
7,816,363
54
2011-10-19T03:55:06Z
7,816,439
66
2011-10-19T04:09:41Z
[ "python" ]
Can I use: ``` if A: ``` instead of ``` if A is not None: ``` The latter seems so verbose. Is there a difference?
The statement ``` if A: ``` will call `A.__nonzero__()` (see [Special method names](http://docs.python.org/reference/datamodel.html#object.__nonzero__) documentation) and use the return value of that function. Here's the summary: > ### `object.__nonzero__(self)` > > Called to implement truth value testing and the bu...
if A vs if A is not None:
7,816,363
54
2011-10-19T03:55:06Z
7,816,516
12
2011-10-19T04:23:58Z
[ "python" ]
Can I use: ``` if A: ``` instead of ``` if A is not None: ``` The latter seems so verbose. Is there a difference?
A lot of functions return None if there are no appropriate results. For example, an SQLAlchemy query's `.first()` method returns None if there were no rows in the result. Suppose you were selecting a value that might return 0 and need to know whether it's actually 0 or whether the query had no results at all. A common...
if A vs if A is not None:
7,816,363
54
2011-10-19T03:55:06Z
7,816,773
26
2011-10-19T05:07:15Z
[ "python" ]
Can I use: ``` if A: ``` instead of ``` if A is not None: ``` The latter seems so verbose. Is there a difference?
As written in [PEP8](http://www.python.org/dev/peps/pep-0008/): > * Comparisons to singletons like *None* **should always be done with > 'is' or 'is not', never the equality operators**. > > Also, **beware of writing "if x" when you really mean "if x is not None"** > -- e.g. when testing whether a variable or ar...
Getting py2exe to work with zope.interface
7,816,799
4
2011-10-19T05:10:58Z
11,632,115
19
2012-07-24T13:39:39Z
[ "python", "pygtk", "twisted", "py2exe", "zope.interface" ]
I have a Python app based on Twisted and PyGTK. Twisted itself depends on zope.interface, and I don't import it directly. Unfortunately, when I try to run my app, the following error ends up in the error log: ``` Traceback (most recent call last): File "tasks.py", line 4, in <module> File "ui\__init__.pyc", line ...
I don't know if you ever solved this, or if it's even relevant to you anymore, but for future searchers, I found an easy way to fix the zope import problem [here](http://twistedmatrix.com/pipermail/twisted-python/2010-December/023243.html). Specifically, add an empty `__init__.py` file to the `PYTHONDIR/Lib/site-packa...
Why doesn't os.normpath collapse a leading double slash?
7,816,818
3
2011-10-19T05:13:02Z
7,816,833
7
2011-10-19T05:15:43Z
[ "python", "filepath" ]
Under Unix, *os.path.normpath* collapses multiple slashes into single ones **except when exactly two slashes appear that the start of the path**. Why the exception? To illustrate, I get the following transformations: ``` //double/slash/stays -> //double/slash/stays /double/slash//gone// -> /double/slash/gone/ double/...
Because POSIX allows treating a path beginning with two slashes in an implementation-defined manner. In other words, //foo does not necessarily mean the same thing as /foo on all POSIX systems. From [IEEE Std 1003.1](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap04.html#tag_04_11): > A pathname that...
How to convert a strictly sorted list of strings into dict?
7,818,245
2
2011-10-19T08:02:36Z
7,818,683
8
2011-10-19T08:43:10Z
[ "python", "string", "list", "dictionary", "tree" ]
I have a strictly sorted list of strings: ``` ['a', 'b', 'b/c', 'b/d', 'e', 'f', 'f/g', 'f/h', 'f/h/i', 'f/h/i/j'] ``` This list is similar to tree representation. So, I need to convert it to dict: ``` {'a': {}, 'b': {'c': {}, 'd': {}}, 'e': {}, 'f': {'g': {}, 'h': {'i': {'j': {}}}}} ``` A...
If you don't insist on `None` as the leaf value, you can use the compact code ``` my_dict = lambda: defaultdict(my_dict) d = my_dict() for x in my_list: reduce(defaultdict.__getitem__, x.split("/"), d) ``` Admittedly, it isn't *that* obvious what this code does, but it's succinct :)
Import Error: No module named numpy
7,818,811
30
2011-10-19T08:54:16Z
7,818,845
11
2011-10-19T08:58:10Z
[ "python", "import", "numpy", "scipy" ]
I have a very similar question to [this question](http://stackoverflow.com/questions/1517129/python-how-do-i-install-scipy-on-64-bit-windows), but still 1 step behind. I have only one version of python 3 installed on my Windows 7(*sorry*) 64-bit system. I installed numpy following this [link](http://sourceforge.net/pro...
[Support for Python 3 was added in NumPy version 1.5.0](http://sourceforge.net/projects/numpy/files//NumPy/1.5.0/NOTES.txt/view), so to begin with, you must download/install a newer version of NumPy.
Import Error: No module named numpy
7,818,811
30
2011-10-19T08:54:16Z
35,476,722
17
2016-02-18T08:51:48Z
[ "python", "import", "numpy", "scipy" ]
I have a very similar question to [this question](http://stackoverflow.com/questions/1517129/python-how-do-i-install-scipy-on-64-bit-windows), but still 1 step behind. I have only one version of python 3 installed on my Windows 7(*sorry*) 64-bit system. I installed numpy following this [link](http://sourceforge.net/pro...
You can simply use ``` pip install numpy ```
python ternary operator with assignment
7,818,992
2
2011-10-19T09:12:45Z
7,819,025
11
2011-10-19T09:15:20Z
[ "python" ]
I am new to python. I'm trying to write this ``` if x not in d: d[x] = {} q = d[x] ``` in a more compact way using the ternary operator ``` q = d[x] if x in d else (d[x] = {}) ``` but this gives the syntax error. What am I missing?
The conditional operator in Python is used for *expressions* only, but assignments are *statements*. You can use ``` q = d.setdefault(x, {}) ``` to get the desired effect in this case. See also the [documentation of `dict.setdefualt()`](http://docs.python.org/library/stdtypes.html#dict.setdefault).
Plotting Ellipsoid with Matplotlib
7,819,498
8
2011-10-19T09:54:55Z
7,820,701
13
2011-10-19T11:36:29Z
[ "python", "matplotlib" ]
Does anyone have sample code for plotting ellipsoids? There is one for sphere on `matplotlib` site, but nothing for ellipsoids. I am trying to plot ``` x**2 + 2*y**2 + 2*z**2 = c ``` where `c` is a constant (like 10) that defines an ellipsoid. I tried the `meshgrid(x,y)` route, reworked the equation so `z` is on one ...
Here is how you can do it via spherical coordinates: ``` from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np fig = plt.figure(figsize=plt.figaspect(1)) # Square figure ax = fig.add_subplot(111, projection='3d') coefs = (1, 2, 2) # Coefficients in a0/c x**2 + a1/c y**2 + a2/c ...
Plotting Ellipsoid with Matplotlib
7,819,498
8
2011-10-19T09:54:55Z
14,958,796
7
2013-02-19T13:31:21Z
[ "python", "matplotlib" ]
Does anyone have sample code for plotting ellipsoids? There is one for sphere on `matplotlib` site, but nothing for ellipsoids. I am trying to plot ``` x**2 + 2*y**2 + 2*z**2 = c ``` where `c` is a constant (like 10) that defines an ellipsoid. I tried the `meshgrid(x,y)` route, reworked the equation so `z` is on one ...
Building on EOL's answer. Sometimes you have an ellipsoid in matrix format: A and c Where A is the ellipsoid matrix and c is a vector representing the centre of the ellipsoid. ``` import numpy as np import numpy.linalg as linalg import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # your ellispsoi...
Override specific admin css files in Django
7,819,730
3
2011-10-19T10:14:17Z
7,822,520
9
2011-10-19T14:03:48Z
[ "python", "css", "django", "django-admin" ]
Overriding admin templates is as easy as creating a folder `admin` in your templates directory and copying whatever template files you'd like to override into it. I simply want to play with the admin style sheets however, so I made a folder `admin` in my static files folder and put `css/base.css` into it. Unlike the te...
What I'm doing to achieve that is to override `base_site.html` template like this: ``` {% block blockbots %} <link rel="stylesheet" type="text/css" href="/media/css/my_admin.css" /> {{ block.super }} {% endblock %} ``` I put the CSS in `blockbots`instead of `extrahead` to be sure that is loaded at the end, so it will...
What happens if two python scripts want to write in the same file?
7,820,021
9
2011-10-19T10:41:13Z
7,820,062
7
2011-10-19T10:44:07Z
[ "python", "file", "io" ]
I have a pipeline which at some point splits work into various sub-processes that do the same thing in parallel. Thus their output should go into the same file. Is it too risky to say all of those processes should write into the same file? Or does python try and retry if it sees that this resource is occupied?
In general, this is not a good idea and will take a lot of care to get right. Since the writes will have to be serialized, it might also adversely affect scalability. I'd recommend writing to separate files and merging (or just leaving them as separate files).
What happens if two python scripts want to write in the same file?
7,820,021
9
2011-10-19T10:41:13Z
7,820,136
8
2011-10-19T10:50:14Z
[ "python", "file", "io" ]
I have a pipeline which at some point splits work into various sub-processes that do the same thing in parallel. Thus their output should go into the same file. Is it too risky to say all of those processes should write into the same file? Or does python try and retry if it sees that this resource is occupied?
This is system dependent. In Windows, the resource is locked and you get an exception. In Linux you can write the file with two processes (written data could be mixed) Ideally in such cases you should use **semaphores** to synchronize access to shared resources. If using semaphores is too heavy for your needs, then t...
Python number-like class that remembers arithmetic operations?
7,820,771
8
2011-10-19T11:42:02Z
7,820,810
7
2011-10-19T11:46:28Z
[ "python" ]
I'm wondering if there exists a python module that would allow me to do something like this: ``` x = MagicNumber() x.value = 3 y = 2 * (x + 2) ** 2 - 8 print y # 42 x.value = 2 print y # 24 ``` So `MagicNumber` would implement all the special operator methods, and they would all return instances of MagicNumber, w...
You could give [sympy](https://github.com/sympy/sympy), a computer algebra system written in Python, give a try. E.g. ``` >>> from sympy import Symbol >>> x = Symbol('x') >>> y = 2 * (x + 2) ** 2 - 8 >>> y 2*(x + 2)**2 - 8 >>> y.subs(x,3) 42 >>> y.subs(x,2) 24 ```
Python number-like class that remembers arithmetic operations?
7,820,771
8
2011-10-19T11:42:02Z
7,844,038
10
2011-10-21T01:17:23Z
[ "python" ]
I'm wondering if there exists a python module that would allow me to do something like this: ``` x = MagicNumber() x.value = 3 y = 2 * (x + 2) ** 2 - 8 print y # 42 x.value = 2 print y # 24 ``` So `MagicNumber` would implement all the special operator methods, and they would all return instances of MagicNumber, w...
Something like this? ``` import operator MAKE_BINARY = lambda opfn : lambda self,other : BinaryOp(self, asMagicNumber(other), opfn) MAKE_RBINARY = lambda opfn : lambda self,other : BinaryOp(asMagicNumber(other), self, opfn) class MagicNumber(object): __add__ = MAKE_BINARY(operator.add) __sub__ = MAKE_...
Understanding weird boolean 2d-array indexing behavior in numpy
7,820,809
10
2011-10-19T11:46:28Z
7,821,135
16
2011-10-19T12:14:41Z
[ "python", "numpy" ]
Why does this work: ``` a=np.random.rand(10,20) x_range=np.arange(10) y_range=np.arange(20) a_tmp=a[x_range<5,:] b=a_tmp[:,np.in1d(y_range,[3,4,8])] ``` and this does not: ``` a=np.random.rand(10,20) x_range=np.arange(10) y_range=np.arange(20) b=a[x_range<5,np.in1d(y_range,[3,4,8])] ```
The Numpy reference documentation's [page on indexing](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#boolean) contains the answers, but requires a bit of careful reading. The answer here is that indexing with booleans is equivalent to indexing with integer arrays obtained by first transforming the boo...
Matplotlib: save plot to numpy array
7,821,518
8
2011-10-19T12:44:17Z
7,821,917
20
2011-10-19T13:19:35Z
[ "python", "numpy", "matplotlib" ]
In Python and Matplotlib, it is easy to either display the plot as a popup window or save the plot as a PNG file. How can I instead save the plot to a numpy array in RGB format?
This is a handy trick for unit tests and the like, when you need to do a pixel-to-pixel comparison with a saved plot. One way is to use `fig.canvas.tostring_rgb` and then `numpy.fromstring` with the approriate dtype. There are other ways as well, but this is the one I tend to use. E.g. ``` import matplotlib.pyplot a...
How to code autocompletion in python?
7,821,661
17
2011-10-19T12:58:20Z
7,821,956
30
2011-10-19T13:22:31Z
[ "python", "autocomplete", "type-hinting" ]
I'd like to code autocompletion in Linux terminal. The code should work as follows. It has a list of strings (e.g. "hello, "hi", "how are you", "goodbye", "great", ...). In terminal the user will start typing and when there is some match possibility, he gets the hint for possible strings, from which he can choose (si...
(I'm aware this isn't exactly what you're asking for, but) If you're happy with the auto-completion/suggestions appearing on `TAB` (as used in many shells), then you can quickly get up and running using the [readline](http://docs.python.org/library/readline.html) module. Here's a quick example based on [Doug Hellmann'...
Using class attributes as function parameters?
7,822,249
2
2011-10-19T13:43:59Z
7,822,271
10
2011-10-19T13:45:45Z
[ "python", "function" ]
So I have a working sorting algorithm in Python. (Its exact contents are irrelevant to this question.) It uses a list called 'people' containing class instances, and the function is hard-coded to sort that list by a specific attribute, 'wealth'. ``` def my_sort(seq): # sorts by seq[n].wealth ... my_sort(people...
You could pass *the name* of the attribute: ``` def my_sort2(seq, keyname): sort by getattr(seq[n], keyname) my_sort2(people, 'wealth') ``` or a getter functor: ``` def my_sort2(seq, keyfunc): sort by keyfunc(seq[n]) my_sort2(people, operator.attrgetter('wealth')) ``` I prefer the latter approach as it is...
how to convert negative integer value to hex in python
7,822,956
10
2011-10-19T14:35:10Z
7,823,051
24
2011-10-19T14:40:13Z
[ "python", "integer", "hex", "negative-number" ]
I use python 2.6 ``` >>> hex(-199703103) '-0xbe73a3f' >>> hex(199703103) '0xbe73a3f' ``` Positive and negative value are the same? When I use calc, the value is `FFFFFFFFF418C5C1`.
Python's integers can grow arbitrarily large. In order to compute the raw [two's-complement](http://en.wikipedia.org/wiki/Two%27s_complement) the way you want it, you would need to specify the desired bit width. Your example shows `-199703103` in 64-bit two's complement, but it just as well could have been 32-bit or 12...
Can't import Webkit from gi.repository
7,823,972
9
2011-10-19T15:39:42Z
7,966,081
18
2011-11-01T12:01:13Z
[ "python", "webkit", "importerror", "pygobject", "gtk3" ]
When I try to import `Webkit` from `gi.repository`, it gives an `ImportError`: ``` from gi.repository import Webkit ERROR:root:Could not find any typelib for Webkit Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: cannot import name Webkit ``` What am I doing wrong?
Your error seems a typo and the library is not found for that. You have to put "WebKit" instead of "Webkit". Additionaly if you use Ubuntu check the library existence with: ``` $ locate girepository | grep WebKit /usr/lib/girepository-1.0/WebKit-3.0.typelib ``` If doesn't exist you need install the package gir1.2-w...
Return HTTP status code 201 in flask
7,824,101
40
2011-10-19T15:48:13Z
7,824,605
52
2011-10-19T16:23:30Z
[ "python", "flask", "httpresponse" ]
We're using Flask for one of our API's and I was just wondering if anyone knew how to return a HTTP response 201? For errors such as 404 we can call: ``` from flask import abort abort(404) ``` But for 201 I get > LookupError: no exception for 201 Do I need to create my own exception like [this](http://werkzeug.poc...
You can read about it [here.](http://flask.pocoo.org/docs/quickstart/#about-responses) ``` return render_template('page.html'), 201 ```
Including docstring in Sphinx Documentation
7,825,263
6
2011-10-19T17:14:08Z
7,832,437
11
2011-10-20T07:20:08Z
[ "python", "python-sphinx", "autodoc" ]
I'd like to include just the docstring of a specific function in my Sphinx documentation. However there seem to be no options to just display these details without associated class and function definitions using <http://sphinx.pocoo.org/ext/autodoc.html> I've tried creating a class as outlined in [show \*only\* docstr...
After looking through the source and experimenting - here is how to do it in Sphinx 1.1. In your conf.py file create a new MethodDocumenter subclass. Here you can set a new "objtype", make sure the docstring is not indented, and remove the title. ``` from sphinx.ext import autodoc class SimpleDocumenter(autodoc.Meth...
python math, numpy modules different results?
7,825,543
4
2011-10-19T17:38:46Z
7,825,588
10
2011-10-19T17:41:57Z
[ "python", "numpy", "floating-point" ]
I get slightly different results calculating the cosine of a value. How can I check that this difference is within machine precision? ``` import math math.cos(60.0/180.0*math.pi) -> 0.5000000000000001 import numpy numpy.cos(60.0/180.0*numpy.pi) -> 0.50000000000000011 ```
The difference seems to be caused by the formatting routines only: ``` >>> '%.30f' % math.cos(60./180.*math.pi) '0.500000000000000111022302462516' >>> '%.30f' % np.cos(60./180.*np.pi) '0.500000000000000111022302462516' ``` Note that `np.cos` returns `np.float64` rather than `float`, and apparently that type is printe...