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
Homebrew , python installing
13,088,998
27
2012-10-26T14:37:16Z
15,195,648
18
2013-03-04T06:15:19Z
[ "python", "osx", "osx-snow-leopard", "homebrew" ]
i got an error while trying to install python throught homebrew. brew says what it failed to link python , here is output: ``` Linking /usr/local/Cellar/python/2.7.3... Warning: Could not link python. Unlinking... Error: Could not symlink file: /usr/local/Cellar/python/2.7.3/bin/smtpd2.py /usr/local/bin/smtpd2.py may ...
Did you try `brew link --overwrite python`? This worked for me without having to uninstall python - see [this question](http://stackoverflow.com/questions/13354207/how-to-symlink-python-in-homebrew) for more details.
How to fix a Database Error and ghost migration error in Django?
13,089,163
3
2012-10-26T14:46:38Z
13,089,985
9
2012-10-26T15:34:48Z
[ "python", "django", "model", "django-south" ]
I am getting an DatabaseError saying no column named playlist exists and I'm trying to figure out how to fix it. I'm using South. I deleted the old files in the my migrations folder and ran: ``` python manage.py schemamigration app_name --initial python manage.py migrate reserve ``` I get this error when I do that: ...
Just run ``` python manage.py migrate reserve --delete-ghost-migrations ``` This should remove non existing migration from the database table `south_migrationhistory`.
replacing text in a file with Python
13,089,234
18
2012-10-26T14:50:56Z
13,089,373
41
2012-10-26T14:58:06Z
[ "python", "string", "file", "replace" ]
I'm new to Python. I want to be able to open a file and replace every instance of certain words with a given replacement via Python. as an example say replace every word 'zero' with '0', 'temp' with 'bob', and say 'garbage' with 'nothing'. I had first started to use this: ``` for line in fileinput.input(fin): ...
This should do it ``` replacements = {'zero':'0', 'temp':'bob', 'garbage':'nothing'} with open('path/to/input/file') as infile, open('path/to/output/file', 'w') as outfile: for line in infile: for src, target in replacements.iteritems(): line = line.replace(src, target) outfile.write(l...
reinitialize an object with self.__init__(...)
13,091,221
8
2012-10-26T16:58:32Z
13,091,300
10
2012-10-26T17:05:22Z
[ "python" ]
Could anybody explain whether it is safe to reinitialize an object by calling "self.**init**(". as shown in the following simplified example? The reason i'm asking is that i couldn't find this method neither in several python books nor in internet. There are some who suggest to list all attributes and set them to init...
I would consider it a very bad practice - you should not `__init__` manually (unless calling `__init__` of the parent class). Also, passing object's data back to `__init__` is somewhat strange. Why not something like this: ``` class Book(object): def __init__(self,name,author): self.name = name se...
reinitialize an object with self.__init__(...)
13,091,221
8
2012-10-26T16:58:32Z
13,091,370
14
2012-10-26T17:09:44Z
[ "python" ]
Could anybody explain whether it is safe to reinitialize an object by calling "self.**init**(". as shown in the following simplified example? The reason i'm asking is that i couldn't find this method neither in several python books nor in internet. There are some who suggest to list all attributes and set them to init...
The only thing special about `__init__` is that it is called automatically when an instance is created. Other than that it is a normal method, and it is safe to use it to set your object back to its initial state. That being said, just because it is safe doesn't mean it is a good idea. Other people looking at your cod...
Python global/local variables
13,091,357
9
2012-10-26T17:08:49Z
13,091,387
8
2012-10-26T17:10:55Z
[ "python", "global-variables", "local-variables" ]
Why does this code work: ``` var = 0 def func(num): print num var = 1 if num != 0: func(num-1) func(10) ``` but this one gives a "local variable 'var' referenced before assignment" error: ``` var = 0 def func(num): print num var = var if num != 0: func(num-1) func(10) ```
Because in the first code, you have created a local variable `var` and used its value, whereas in the 2nd code, you are using the local variable `var`, without defining it. So, if you want to make your 2nd function work, you need to declare : - ``` global var ``` in the function before using `var`. ``` def func(num...
python data analysis, difficulty understanding cookbook code
13,091,504
2
2012-10-26T17:20:39Z
13,091,532
9
2012-10-26T17:23:23Z
[ "python", "numpy", "matplotlib", "scipy" ]
I'm learning to use python for data analysis, etc. and I am a little confused about what is going on in this code from the [scipy cookbook](http://www.scipy.org/Cookbook/LoktaVolterraTutorial). When the cookbook describes the integration and then plotting process, via matplotlib, it has first: ``` t = linspace(0, 15,...
`X.T` is the transpose of `X`. So, in that line, `X` must be an array with shape `(N,2)`. When you transpose it you get an array of shape `(2,N)` which can be unpacked. Consider: ``` >>> import numpy as np >>> a = np.arange(10).reshape((5,2)) >>> a array([[0, 1], [2, 3], [4, 5], [6, 7], [8...
/bin/env: python: No such file or directory (Windows through Git Bash trying to install new Parse Cloud Code)
13,091,522
12
2012-10-26T17:22:26Z
13,119,481
27
2012-10-29T10:08:37Z
[ "python", "windows", "msysgit", "git-bash" ]
Trying to install python from the [link here](http://www.python.org/download/) does not seem to give access to the `python` command in Msysgit... following [the instructions here](http://stackoverflow.com/questions/12436475/how-to-install-parse-com-cloud-code-on-windows), does not actually say how to get `python` to wo...
This error means that Git Bash does not know where your python.exe is. It searches your normal windows search path, the `PATH` environment variable. You're probably failing the 4th step on the instructions already "Make sure Python is working in the Git Bash": ``` $ python --version sh.exe: python: command not found `...
unique plot marker for each plot in matplotlib
13,091,649
13
2012-10-26T17:31:55Z
13,092,467
39
2012-10-26T18:31:59Z
[ "python", "matplotlib" ]
I have a loop where i create some plots and I need unique marker for each plot. I think about creating function, which returns random symbol, and use it in my program in this way: ``` for i in xrange(len(y)): plt.plot(x, y [i], randomMarker()) ``` but I think this way is not good one. I need this just to distingu...
`itertools.cycle` will iterate over a list or tuple indefinitely. This is preferable to a function which randomly picks markers for you. ``` import itertools marker = itertools.cycle((',', '+', '.', 'o', '*')) for n in y: plt.plot(x,n, marker = marker.next(), linestyle='') ``` You can use that to produce a plot ...
If range() is a generator in Python 3.3, why can I not call next() on a range?
13,092,267
29
2012-10-26T18:18:13Z
13,092,317
33
2012-10-26T18:21:23Z
[ "python", "python-3.x", "generator" ]
Perhaps I've fallen victim to misinformation on the web, but I think it's more likely just that I've misunderstood something. Based on what I've learned so far, range() is a generator, and generators can be used as iterators. However, this code: ``` myrange = range(10) print(next(myrange)) ``` gives me this error: `...
`range` is a class of immutable iterable objects. Their iteration behavior can be compared to `list`s: you can't call `next` directly on them; you have to get an iterator by using `iter`. So no, `range` is not a generator. You may be thinking, "why didn't they make it directly iterable"? Well, `range`s have some usef...
How do I split an ndarray based on array of indexes?
13,092,807
5
2012-10-26T19:00:12Z
13,093,147
10
2012-10-26T19:24:46Z
[ "python", "numpy" ]
I'm fairly new to Python, and very new to Numpy. So far I have an ndarray of data where is a list of lists, and I have an array of indexes. How can I remove every row who's index is inside of the array of indexes and put that row into a new ndarray? For example, my data looks like ``` [[1 1 1 1] [2 3 4 5] [6 7 8 9...
Sorry, so you already have `take` and basically need the opposite of `take`, you can get that with some indexing nicely: ``` a = np.arange(16).reshape((8,2)) b = [2, 6, 7] mask = np.ones(len(a), dtype=bool) mask[b,] = False x, y = a[b], a[mask] # instead of a[b] you could also do a[~mask] print x array([[ 4, 5], ...
lxml (or lxml.html): print tree structure
13,093,091
6
2012-10-26T19:20:37Z
13,134,559
7
2012-10-30T07:35:33Z
[ "python", "html", "xml", "lxml" ]
I'd like to print out the tree structure of an etree (formed from an html document) in a differentiable way (means that two etrees should print out differently). What I mean by structure is the "shape" of the tree, which basically means all the tags but no attribute and no text content. Any idea? Is there something i...
Maybe just run some XSLT over the source XML to strip everything but the tags, it's then easy enough to use `etree.tostring` to get a string you could hash... ``` from lxml import etree as ET def pp(e): print ET.tostring(e, pretty_print=True) print root = ET.XML("""\ <project id="8dce5d94-4273-47ef-8d1b-0c78...
Mocking the super class calls on python
13,093,526
6
2012-10-26T19:53:44Z
22,411,552
11
2014-03-14T17:10:46Z
[ "python", "unit-testing", "mocking" ]
I am doing some unit testing and at some point I need to mock a `super` call to throw an error, for example: ``` @classmethod def myfunc(cls, *args, **kwargs) try: super(MyClass, cls).my_function(args, kwargs) except MyException as e: #... ``` I am using the [mocker](http://labix.org/mocker#he...
With the mock library I would do something like this. In your class definition: ``` from somelib import ASuperClass class MyClass(ASuperClass): def my_cool_method(self): return super(MyClass, self).my_cool_method() ``` In the module where your calling MyClass: ``` from mock import patch from mymodule i...
python import statement semantics
13,093,665
13
2012-10-26T20:05:05Z
13,093,714
8
2012-10-26T20:07:47Z
[ "python", "python-import" ]
I'm a python novice, and am having difficulty understanding the import statement and its variations. Suppose I'm using the lxml module for scraping websites. The examples show, ``` from lxml.html import parse parse( 'http://somesite' ) ``` Google's python style guide prefers the basic import statement, to preserve ...
``` import lxml.html as LH doc = LH.parse('http://somesite') ``` `lxml.html` is a module. When you `import lxml`, the `html` module is not imported into the `lxml` namespace. This is a developer's decision. Some packages automatically import some modules, some don't. In this case, you have to do it yourself with `impo...
How to replace unicode characters in string with something else python?
13,093,727
10
2012-10-26T20:08:44Z
13,093,911
29
2012-10-26T20:23:18Z
[ "python" ]
I have a string that I got from reading a URL of a page with bullets that have a symbol like "•" because of the bulleted list. Note that the text is an html source from a web address using Python 2.7's urllib2.read(webaddress). I know the unicode character for that as U+2022, but how do I actually replace that unico...
1. Decode the string to Unicode. Assuming it's UTF-8-encoded: ``` str.decode("utf-8") ``` 2. Call the `replace` method and be sure to pass it a Unicode string as its first argument: ``` str.decode("utf-8").replace(u"\u2022", "*") ``` 3. Encode back to UTF-8, if needed: ``` str.decode("utf-8")...
How can I override the 'type' attribute of a ModelForm in Django?
13,094,320
4
2012-10-26T20:58:17Z
13,094,465
10
2012-10-26T21:08:51Z
[ "python", "django", "html5", "django-widget" ]
Specifically, I would like to render date widget in a form but I would like it to 'be' HTML5 (so I can just forget about the javascript or whatever and trust Chrome, Opera and Safari to display the datepicker). No javascript solutions please, I have already found those on the web. Here is a snippet of my code, but it...
## Using django-html5 1. Install [django-html5](https://github.com/rhec/django-html5/blob/master/html5/forms/widgets.py): `pip install django-html5` 2. In forms.py, `import html5.forms.widgets as html5_widgets` 3. Set `widgets['thedate'] = html5_widgets.DateInput` I did not personally test it because I just found out...
Bidirectional flow between D3.js frontend and Python Backend? / Interactive graphs in a website
13,094,426
9
2012-10-26T21:05:34Z
13,094,569
12
2012-10-26T21:18:59Z
[ "python", "d3.js" ]
So this is somewhat similar to [What's easiest way to get Python script output on the web?](http://stackoverflow.com/questions/731470/whats-easiest-way-to-get-python-script-output-on-the-web) and [Matplotlib: interactive plot on a web server](http://stackoverflow.com/questions/3354883/matplotlib-interactive-plot-on-a-...
It sounds like you need to write a web service in Python that consumes and returns [JSON](http://www.json.org/). I'm not sure if the data is originating on the client or the server, so for this example, I'm assuming it comes from the client. 1. POST your graph data in JSON format to your webservice 2. Do processing se...
Getting an AttributeError: <class> has no attribute <method>
13,094,713
5
2012-10-26T21:30:30Z
14,046,894
15
2012-12-26T22:14:12Z
[ "python", "attributeerror" ]
I am creating a method in a class in a module mod1 and calling it as follows: ``` class blahblah: def foobar(self, bvar, **dvar) //// return dvar ``` And calling it as: ``` obj1 = mod1.blahblah() dvar1 = obj1.foobar(True, **somedictionary) ``` It throws a `Attribute error: blahblah has no attribute...
The type of error you describe can be caused simply by mismatched indentation. If the method is at the very bottom of your class, move it up in the class a bit and the problem will become apparent. When python interpreters run into mismatched indents (like say you started using tabs at the bottom of a file that was in...
Convert list of strings to space-separated string
13,094,918
3
2012-10-26T21:50:07Z
13,094,939
17
2012-10-26T21:51:36Z
[ "python", "string", "list" ]
I am using underscores to represent the length of a unknown word. How can I print just the underscores without the brackets that represent the list? Basically, if I have a list of the form `['_', '_', '_', '_']`, I want to print the underscores without printing them in list syntax as `"_ _ _ _"`
Does this work for you ``` >>> my_dashes = ['_', '_', '_', '_'] >>> print ''.join(my_dashes) ____ >>> print ' '.join(my_dashes) _ _ _ _ ```
Switch to Python 3.x in Spyder
13,094,941
10
2012-10-26T21:51:57Z
17,067,938
13
2013-06-12T14:19:29Z
[ "python", "spyder" ]
By default Spyder uses Python 2.7.2, and my question is: is there a way to set up Spyder so that it automatically uses Python 3.x? Thanks!
Since end of May, version v2.3.0dev1 of Spyder works for **Python 3.3 and above**. It is in a usable state but there are a few minor problems. Hopefully they will be resolved soon.
Switch to Python 3.x in Spyder
13,094,941
10
2012-10-26T21:51:57Z
28,014,207
8
2015-01-18T20:01:14Z
[ "python", "spyder" ]
By default Spyder uses Python 2.7.2, and my question is: is there a way to set up Spyder so that it automatically uses Python 3.x? Thanks!
To use Spyder for Python 3, you just need v2.3.0 or later. **Ubuntu 12.10 and later** You can get this by using `pip3`. ``` sudo apt-get install python3-pip python3-pyqt4 sudo pip3 install spyder ``` **Ubuntu 12.04** Ubuntu 12.04 doesn't have `python3-pip` in the repositories, but you can get it with `setuptools`,...
Unicode in Python - just UTF-16?
13,095,499
3
2012-10-26T22:55:30Z
13,095,555
17
2012-10-26T23:03:33Z
[ "python", "unicode", "character-encoding", "utf-16" ]
I was happy in my Python world knowing that I was doing everything in Unicode and encoding as UTF-8 when I needed to output something to a user. Then, one of my colleagues sent me [this article](http://utf8everywhere.org/) on UTF-8 and it confused me. The author of the article indicates a number of times that UCS-2, t...
The internal representation of a Unicode string in Python (versions from 2.2 up to 3.2) depends on whether Python was compiled in *wide* or *narrow* modes. Most Python builds are narrow (you can check with `sys.maxunicode` -- it is 65535 on narrow builds and 1114111 on wide builds). With a wide build, strings are inte...
Restricted Permutations of Strings in Python
13,095,520
2
2012-10-26T22:58:14Z
13,095,565
8
2012-10-26T23:04:47Z
[ "python", "permutation" ]
How can I do the following in Python? Given two strings. Print all the interleavings of the two strings. Interleaving means that the if B comes after A, it should also come after A in the interleaved string. ex- AB and CD ABCD ACBD ACDB CABD CADB CDAB
This is effectively a tree-walking problem (namely, the decision tree of whether to advance along one string or the other). Oftentimes, the simplest way to approach a tree-walking problem is a recursive solution. --- Here's an example: ``` def ordered_permutations(str1, str2): perms = [] if len(str1) + len(s...
Why is numpy vectorized function apparently called an extra time?
13,095,792
6
2012-10-26T23:42:57Z
13,096,301
7
2012-10-27T01:05:57Z
[ "python", "numpy", "vectorization" ]
I have a numpy object array containing several lists of index numbers: ``` >>> idxLsts = np.array([[1], [0, 2]], dtype=object) ``` I define a vectorized function to append a value to each list: ``` >>> idx = 99 >>> f = np.vectorize(lambda idxLst: idxLst.append(idx)) ``` I invoke the function. I don't care about t...
From the `vectorize` docstring: > ``` > The data type of the output of `vectorized` is determined by calling > the function with the first element of the input. This can be avoided > by specifying the `otypes` argument. > ``` And from the code: ``` theout = self.thefunc(*newargs) ``` This is an extra call ...
Open source project for downloading mailing list archives preferably in Python
13,097,891
2
2012-10-27T06:35:56Z
13,097,949
7
2012-10-27T06:47:41Z
[ "python", "python-2.7" ]
I am interested in knowing if there are any open source projects (preferably in Python) which can be used to download (crawl?) the mailing list archives of open source projects such as Lucene/Hadoop (such as <http://mail-archives.apache.org/mod_mbox/lucene-java-user/>). I am specially looking for a crawler/downloader c...
There's usually facilities for downloading mbox files. In the link you provided, you can for example append the mbox name and get the mail archive directly. Example, the mbox for October 2012: <http://mail-archives.apache.org/mod_mbox/lucene-java-user/201210.mbox> So getting the archives programmatically is pretty st...
How to get python to open an outside file?
13,098,310
4
2012-10-27T07:51:09Z
13,098,473
13
2012-10-27T08:22:21Z
[ "python", "file-io", "typeerror" ]
I am writing a program for class that opens a file, counts the words, returns the number of words, and closes. I understand how to do everything excpet get the file to open and display the text This is what I have so far: ``` fname = open("C:\Python32\getty.txt") file = open(fname, 'r') data = file.read()...
You're using `open()` twice, so you've actually already opened the file, and then you attempt to open the already opened file object... change your code to: ``` fname = "C:\\Python32\\getty.txt" infile = open(fname, 'r') data = infile.read() print(data) ``` The `TypeError` is saying that it cannot open type `_io.Text...
How to iterate over the elements of a map in python
13,098,638
3
2012-10-27T08:53:16Z
13,098,651
8
2012-10-27T08:55:46Z
[ "python", "string", "map", "iteration" ]
Given a string `s`, I want to know how many times each character at the string occurs. Here is the code: ``` def main() : while True : try : line=raw_input('Enter a string: ') except EOFError : break; mp={}; for i in range(len(line)) : if line[i] in mp : mp[line[i]] += 1; ...
You could try a Counter (Python 2.7 and above; see below for a pre-2.7 option): ``` >>> from collections import Counter >>> Counter('abbba') Counter({'b': 3, 'a': 2}) ``` You can then access the elements just like a dictionary: ``` >>> counts = Counter('abbba') >>> counts['a'] 2 >>> counts['b'] 3 ``` And to iterate...
Python printing from non returning functions
13,099,774
3
2012-10-27T11:30:47Z
13,099,855
9
2012-10-27T11:41:13Z
[ "python", "printing" ]
**Question 1:** `word = 'fast'` `print '"',word,'" is nice'` gives output as `" fast " is nice`. How do i get the output `"fast" is nice` ie I want the spaces to be removed before and after `word`? **Question 2:** ``` def faultyPrint(): print 'nice' ``` `print 'Word is', faultyPrint()` gives me output as ```...
A more extensible approach would be the following. ## For the first part: ``` word = "fast" print('"{0}" is nice'.format(word)) ``` (For the brackets: If you pass only one argument, they make no difference and give you python3 compatibility for free in most of the cases) For more details on this one, see [Python St...
In Django admin, how can I hide Save and Continue and Save and Add Another buttons on a model admin?
13,101,281
11
2012-10-27T15:00:05Z
13,104,313
7
2012-10-27T21:24:03Z
[ "python", "django", "django-templates", "django-admin" ]
I have a workflow for a model in the Django admin that is very similar to the users' workflow. First, I have a form with basic fields and then, a second form with the rest of the data. It's the same workflow as auth.user I need to remove "save and continue" and "save and add another" buttons to prevent the user break...
This isn't possible with an 'out of the box' option as far as I can tell, but this is how I'd go about doing what you want to do. The bit of code we care about is [this templatetag](https://github.com/django/django/blob/master/django/contrib/admin/templatetags/admin_modify.py#L23) - this seems to override `show_save_a...
In Django admin, how can I hide Save and Continue and Save and Add Another buttons on a model admin?
13,101,281
11
2012-10-27T15:00:05Z
13,106,661
11
2012-10-28T05:39:56Z
[ "python", "django", "django-templates", "django-admin" ]
I have a workflow for a model in the Django admin that is very similar to the users' workflow. First, I have a form with basic fields and then, a second form with the rest of the data. It's the same workflow as auth.user I need to remove "save and continue" and "save and add another" buttons to prevent the user break...
Beside its (a bit awkward) hacking style, you could aslo override the template tag directly. Normally overriding template is more recommended. ``` # put this in some app such as customize/templatetags/admin_modify.py and place the app # before the 'django.contrib.admin' in the INSTALLED_APPS in settings from django.c...
Compute fast log base 2 ceiling in python
13,105,875
7
2012-10-28T02:24:07Z
13,106,017
18
2012-10-28T02:54:48Z
[ "python", "math", "logging", "binary" ]
for given `x < 10^15`, quickly and accurately determine the maximum integer `p` such that `2^p <= x` Here are some things I've tried: First I tried this but it's not accurate for large numbers: ``` >>> from math import log >>> x = 2**3 >>> x 8 >>> p = int(log(x, 2)) >>> 2**p == x True >>> x = 2**50 >>> p = int(log(x...
In Python >= 2.7, you can use the `.bit_length()` method of integers: ``` def brute(x): # determine max p such that 2^p <= x p = 0 while 2**p <= x: p += 1 return p-1 def easy(x): return x.bit_length() - 1 ``` which gives ``` >>> brute(0), brute(2**3-1), brute(2**3) (-1, 2, 3) >>> easy(0)...
Python functions that can modify their own input
13,105,968
4
2012-10-28T02:46:48Z
13,105,984
10
2012-10-28T02:49:22Z
[ "python" ]
I want to create a Python function that can inspect its own input, rather than the output of its input. For example, a function raw\_str that returns its input exactly, as a string: ``` >>> raw_str(2+2) '2+2' ``` rather than: ``` >>> str(2+2) '4' ``` Is there any way to do this?
This is not possible because the arguments are evaluated *before* they are passed on to the function - so there will be no way to distinguish between `2 + 2` and `3 + 1` (for instance) within the function body. Without more context, it's hard to suggest possible solutions to the problem.
How to find out number/name of unicode character in Python?
13,106,175
19
2012-10-28T03:38:42Z
13,106,217
28
2012-10-28T03:48:52Z
[ "python", "unicode", "python-3.x" ]
In Python: ``` >>>"\N{BLACK SPADE SUIT}" >>>'♠' >>>"\u2660" >>>'♠' ``` Now, let's say I have a character which I don't know the name or number for. Is there a Python function which gives this information like this: ``` >>>wanted_function('♠') >>>["BLACK SPADE SUIT", "u2660"] ``` ?
You may find the [unicodedata](http://docs.python.org/py3k/library/unicodedata.html) module handy: ``` >>> s = "\N{BLACK SPADE SUIT}" >>> s '♠' >>> import unicodedata >>> unicodedata.name(s) 'BLACK SPADE SUIT' >>> ord(s) 9824 >>> hex(ord(s)) '0x2660' ```
Tkinter and ttk python2.7
13,106,488
2
2012-10-28T04:59:53Z
13,106,549
7
2012-10-28T05:11:57Z
[ "python", "tkinter", "tk", "ttk" ]
i found this code online and i wanted to try it out because im trying to figure out how to have my label to change while i type things into my messagebox. I tried the getmethod but i have been struggling with using it. So i found this code and when i tried it i get the error that ttk is undefined but it clearly is. ``...
> So i found this code and when i tried it i get the error that ttk is > undefined but it clearly is. You're star-importing *from* the module, though, using `from ttk import *`, so the name `ttk` doesn't refer to anything. For example, `from math import *` would bring `sin`, `cos`, etc., all into your namespace but th...
Numpy Installation on Mac 10.8.2
13,106,919
9
2012-10-28T06:42:19Z
14,131,249
13
2013-01-03T00:10:18Z
[ "python", "numpy", "osx-mountain-lion" ]
I am running python 2.6 on MacOS 10.8.2, and trying to install Numpy to use NLTK. I have looked at several approaches highlighted below, but am yet to have any luck installing the package. 1. I have installed xcode as per [this](http://stackoverflow.com/questions/7338051/install-numpy-on-mac-os-x-lion-10-7) suggestion...
This is how I fixed this problem: ``` export CC=gcc export CXX=g++ export FFLAGS=ff2c ``` Based on the information I found under the 10.7 installation instructions here: <http://www.scipy.org/Installing_SciPy/Mac_OS_X>
Python recursion permutations
13,109,274
5
2012-10-28T13:43:18Z
13,109,403
11
2012-10-28T13:59:00Z
[ "python", "recursion", "permutation" ]
Im having trouble trying to make a permutation code with recursion. This is suppose to return a list back to the use with all the posible position for each letter. so for the word `cat` it is suppose to return `['cat','act',atc,'cta','tca','tac']` . so far i have this ``` def permutations(s): lst=[] if len(s) ...
You want to do recursion, so you first have to find out how the recursion would work. In this case it is the following: ``` permutation [a,b,c,...] = [a + permutation[b,c,...], b + permutation[a,c,..], ...] ``` And as a final condition: ``` permutation [a] = [a] ``` So the recursion splits up the list in sublists w...
Matplotlib backend missing modules with underscore
13,110,403
10
2012-10-28T15:56:04Z
13,112,702
10
2012-10-28T20:26:02Z
[ "python", "matplotlib" ]
I've been using matplotlib for some time without problems. It's been a while since i needed the interactive plot functions (for which Tkaag was used). Since then i updated matplotlib a few times. I tried to use it today, but it spawned an error. ``` /usr/local/lib/python2.7/dist-packages/matplotlib/backends/tkagg.py ...
Thanks to peison's comment I've checked the installation log for matplotlib and it showed lots of dependencies. I haven't noticed that before because the whole process of instalation ran really fast using `pip install matplotlib` and ended with a succesfull install. To answer the question. The solution was to insta...
How do I mock a django signal handler?
13,112,302
23
2012-10-28T19:39:27Z
13,119,150
11
2012-10-29T09:47:37Z
[ "python", "django", "mocking", "signals", "django-signals" ]
I have a signal\_handler connected through a decorator, something like this very simple one: ``` @receiver(post_save, sender=User, dispatch_uid='myfile.signal_handler_post_save_user') def signal_handler_post_save_user(sender, *args, **kwargs): # do stuff ``` What I want to do is to mock it **with the mo...
So, I ended up with a kind-of solution: mocking a signal handler simply means to connect the mock itself to the signal, so this exactly is what I did: ``` def test_cache(): with mock.patch('myapp.myfile.signal_handler_post_save_user', autospec=True) as mocked_handler: post_save.connect(mocked_handler, send...
Selenium webdriver using switch_to_windows() and printing the title doesn't print the title.
13,113,954
11
2012-10-28T23:09:00Z
13,113,989
8
2012-10-28T23:14:12Z
[ "python", "selenium" ]
Here is the code ``` for handle in browser.window_handles: print "Handle = ",handle browser.switch_to_window(handle); elem = browser.find_element_by_tag_name("title") print elem.get_attribute("value") ``` I am getting the following output ``` Handle = {564f8459-dd20-45b8-84bf-97c69f369738} None Hand...
The title of the page wouldn't be in a `value` attribute of a `title` element, it would be the text contents of that element. The correct way to access that text would be `browser.find_element_by_tag_name("title").text` Or even easier, just access `browser.title`.
Selenium webdriver using switch_to_windows() and printing the title doesn't print the title.
13,113,954
11
2012-10-28T23:09:00Z
15,331,795
27
2013-03-11T05:30:02Z
[ "python", "selenium" ]
Here is the code ``` for handle in browser.window_handles: print "Handle = ",handle browser.switch_to_window(handle); elem = browser.find_element_by_tag_name("title") print elem.get_attribute("value") ``` I am getting the following output ``` Handle = {564f8459-dd20-45b8-84bf-97c69f369738} None Hand...
``` driver.switch_to_window(driver.window_handles[-1]) title=driver.title ``` You can do it simply use the code above. driver.window\_handles[-1] would get the lastest window.
How to find a open reading frame in Python
13,114,246
10
2012-10-28T23:49:52Z
13,114,364
7
2012-10-29T00:06:56Z
[ "python", "python-3.x", "python-2.7", "biopython" ]
I am using Python and a regular expression to find an `ORF` (open reading frame). Find a sub-string a string that is composed ONLY of the letters `ATGC` (no spaces or new lines) that: Starts with `ATG`, ends with `TAG` or `TAA` or `TGA` and should consider the sequence from the first character, then second and then t...
As you have tagged it Biopython I suppose you know of Biopython. Have you checked out the docu yet? <http://biopython.org/DIST/docs/tutorial/Tutorial.html#htoc231> might help. I adjusted the code from the above link a bit to work on your sequence: ``` from Bio.Seq import Seq seq = Seq("CCTCAGCGAGGACAGCAAGGGACTAGCCAG...
Calculating difference between two rows in Python / Pandas
13,114,512
17
2012-10-29T00:28:10Z
13,115,473
38
2012-10-29T03:17:30Z
[ "python", "pandas" ]
In python, how can I reference previous row and calculate something against it? Specifically, I am working with `dataframes` in `pandas` - I have a data frame full of stock price information that looks like this: ``` Date Close Adj Close 251 2011-01-03 147.48 143.25 250 2011-01-04 147.64 143....
I think you want to do something like this: ``` In [26]: data Out[26]: Date Close Adj Close 251 2011-01-03 147.48 143.25 250 2011-01-04 147.64 143.41 249 2011-01-05 147.05 142.83 248 2011-01-06 148.66 144.40 247 2011-01-07 147.93 143.69 In [27]: data.set_index('Date').diff...
Exponential of very small number in python
13,115,176
9
2012-10-29T02:26:00Z
13,115,205
12
2012-10-29T02:31:53Z
[ "python", "math", "exponential", "underflow" ]
I am trying to calculate the exponential of -1200 in python (it's an example, I don't need -1200 in particular but a collection of numbers that are around -1200). ``` >>> math.exp(-1200) 0.0 ``` It is giving me an underflow; How may I go around this problem? Thanks for any help :)
In the standard library, you can look at the `decimal` module: ``` >>> import decimal >>> decimal.Decimal(-1200) Decimal('-1200') >>> decimal.Decimal(-1200).exp() Decimal('7.024601888177132554529322758E-522') ``` If you need more functions than `decimal` supports, you could look at the library `mpmath`, which I use a...
New to Python, GMail SMTP error
13,115,724
10
2012-10-29T04:06:13Z
13,115,740
18
2012-10-29T04:08:45Z
[ "python", "smtp", "gmail", "smtplib" ]
I am writing a simple sendmail function to myself and I keep getting this error: NameError: name 'SMTPException' is not defined What is wrong with my code? Any suggestions? ``` import smtplib sender = "user@gmail.com" receiver = ["user@gmail.com"] message = "Hello!" try: session = smptlib.SMTP('smtp.gmail.com'...
In Python, you will need to fully qualify the name by prefixing it with its module: ``` except smtplib.SMTPException: ``` This is true unless you specifically import the unqualified name (but I wouldn't recommend doing this for your program, just showing what's possible): ``` from smtplib import SMTPException ```
Python scoping in dict comprehension
13,117,020
7
2012-10-29T06:45:03Z
13,117,064
11
2012-10-29T06:49:09Z
[ "python", "scoping", "locals" ]
``` >>> x = 'foo' >>> {0: locals().get('x')} {0: 'foo'} >>> {0: locals().get('x' + spam) for spam in ['']} {0: None} ``` What is the reason for this discrepancy in behaviour?
Dict comprehensions and generator comprehensions create their own local scope. List comprehensions do not in Python 2.x, but do in Python 3. (Note that your first example is not a dict comprehension. It's just a literal dict that happens to have an expression as the value for the key 0.)
How to Format/Overwrite Django Form Error Message?
13,117,477
2
2012-10-29T07:26:02Z
13,117,569
19
2012-10-29T07:33:19Z
[ "python", "html", "django", "forms" ]
forms.py ``` class MyForm(forms.Form): no = forms.CharField(error_messages={'required': u'must be xxx') ``` template.html ``` {{form.no.error}} ``` `{{form.no.error}}` is `<ul class="errorlist"><li>must be xxx</li></ul>` I want to format `{{form.no.error}}` to plain text message without any html tags
You could either just remove the tags: ``` {{ form.no.errors|striptags }} ``` Or just access the raw error: ``` {{ form.no.errors.as_text }} ```
Deleting the folders in python recursively
13,118,029
44
2012-10-29T08:20:09Z
13,118,112
118
2012-10-29T08:27:57Z
[ "python", "directory" ]
I have problem in deleting the directories that are empty. I have the code like this: ``` for dirpath, dirnames, filenames in os.walk(dir_to_search): //other codes try: os.rmdir(dirpath) except OSError as ex: print(ex) ``` The argument `dir_to_search` is where I'm passing the directory wh...
Try shutil module: ``` import shutil shutil.rmtree('/path/to/your/dir/') ```
Deleting the folders in python recursively
13,118,029
44
2012-10-29T08:20:09Z
13,118,119
14
2012-10-29T08:28:13Z
[ "python", "directory" ]
I have problem in deleting the directories that are empty. I have the code like this: ``` for dirpath, dirnames, filenames in os.walk(dir_to_search): //other codes try: os.rmdir(dirpath) except OSError as ex: print(ex) ``` The argument `dir_to_search` is where I'm passing the directory wh...
The default behavior of `os.walk()` is to walk from root to leaf. Set `topdown=False` in `os.walk()` to walk from leaf to root.
Deleting the folders in python recursively
13,118,029
44
2012-10-29T08:20:09Z
13,118,133
7
2012-10-29T08:29:41Z
[ "python", "directory" ]
I have problem in deleting the directories that are empty. I have the code like this: ``` for dirpath, dirnames, filenames in os.walk(dir_to_search): //other codes try: os.rmdir(dirpath) except OSError as ex: print(ex) ``` The argument `dir_to_search` is where I'm passing the directory wh...
Try rmtree in [shutil](https://docs.python.org/2/library/shutil.html#shutil.rmtree). in python std library
Can the ipython notebook YouTubeVideo class play from time offset
13,119,791
8
2012-10-29T10:27:15Z
13,121,051
10
2012-10-29T11:48:54Z
[ "python", "ipython-notebook" ]
If I am embedding a youtube video clip into an iPython notebook: ``` from IPython.display import YouTubeVideo YouTubeVideo("Pi9NpxAvYSs") ``` Is there a way I can embed this such that it would play from a specific time? So 1:47:03 - 1 hour, 47 minutes and 3 seconds?
## Update Now you can use [any parameter](https://developers.google.com/youtube/player_parameters#parameter-subheader) you like from the youtube player: ``` from datetime import timedelta start=int(timedelta(hours=1, minutes=46, seconds=40).total_seconds()) YouTubeVideo("Pi9NpxAvYSs", start=start, autoplay=1, theme...
How can I use io.StringIO() with the csv module?
13,120,127
22
2012-10-29T10:47:29Z
13,120,279
18
2012-10-29T10:56:37Z
[ "python", "csv", "unicode", "python-2.7" ]
I tried to backport a Python 3 program to 2.7, and I'm stuck with a strange problem: ``` >>> import io >>> import csv >>> output = io.StringIO() >>> output.write("Hello!") # Fail: io.StringIO expects Unicode Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unicode argument...
The Python 2.7 `csv` module doesn't support Unicode input: see the [note at the beginning of the documentation](http://docs.python.org/2.7/library/csv.html#module-csv). It seems that you'll have to encode the Unicode strings to byte strings, and use `io.BytesIO`, instead of `io.StringIO`. The [examples](http://docs.p...
How can I use io.StringIO() with the csv module?
13,120,127
22
2012-10-29T10:47:29Z
19,243,243
15
2013-10-08T08:56:05Z
[ "python", "csv", "unicode", "python-2.7" ]
I tried to backport a Python 3 program to 2.7, and I'm stuck with a strange problem: ``` >>> import io >>> import csv >>> output = io.StringIO() >>> output.write("Hello!") # Fail: io.StringIO expects Unicode Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unicode argument...
Please use StringIO.StringIO(). <http://docs.python.org/library/io.html#io.StringIO> <http://docs.python.org/library/stringio.html> `io.StringIO` is a class. It handles Unicode. It reflects the preferred Python 3 library structure. `StringIO.StringIO` is a class. It handles strings. It reflects the legacy Python 2 ...
Make Python version depending on env var (using travis-ci)
13,121,840
5
2012-10-29T12:40:14Z
13,138,093
10
2012-10-30T11:31:46Z
[ "python", "django", "continuous-integration", "travis-ci" ]
Is there a way to configure travis-ci to make the Python versions dependent on a certain env var? Please consider the following `travis.yml` config: ``` language: python python: - "2.5" - "2.6" - "2.7" env: - DJANGO=1.3.4 - DJANGO=1.4.2 - DJANGO=https://github.com/django/django/zipball/master install: -...
You can specify configurations that you want to exclude from the build matrix (i.e. combinations that you don't want to test). Add this to your `.travis.yml`: ``` matrix: exclude: - python: "2.5" env: DJANGO=https://github.com/django/django/zipball/master ``` **Note:** only *exact matches* will be excluded...
How to source virtualenv activate in a Bash script
13,122,137
23
2012-10-29T12:57:30Z
13,122,219
19
2012-10-29T13:02:45Z
[ "python", "bash", "virtualenv" ]
How do you create a Bash script to activate a Python virtualenv? I have a directory structure like: ``` .env bin activate ...other virtualenv files... src shell.sh ...my code... ``` I can activate my virtualenv by: ``` user@localhost:src$ . ../.env/bin/activate (.env)user@localhost:src$ ...
When you source, you're loading the activate script into your active shell. When you do it in a script, you load it into that shell which exits when your script finishes and you're back to your original, unactivated shell. Your best option would be to do it in a function ``` activate () { . ../.env/bin/activate } ...
How to source virtualenv activate in a Bash script
13,122,137
23
2012-10-29T12:57:30Z
13,123,926
9
2012-10-29T14:46:36Z
[ "python", "bash", "virtualenv" ]
How do you create a Bash script to activate a Python virtualenv? I have a directory structure like: ``` .env bin activate ...other virtualenv files... src shell.sh ...my code... ``` I can activate my virtualenv by: ``` user@localhost:src$ . ../.env/bin/activate (.env)user@localhost:src$ ...
Although it doesn't add the "(.env)" prefix to the shell prompt, I found this script works as expected. ``` #!/bin/bash script_dir=`dirname $0` cd $script_dir /bin/bash -c ". ../.env/bin/activate; exec /bin/bash -i" ``` e.g. ``` user@localhost:~/src$ which pip /usr/local/bin/pip user@localhost:~/src$ which python /u...
How to compress by removing duplicates in python?
13,122,575
3
2012-10-29T13:27:57Z
13,122,618
7
2012-10-29T13:30:52Z
[ "python", "string", "compression", "whitespace" ]
I have strings with blocks of the same character in, eg '1254,,,,,,,,,,,,,,,,982'. What I'm aiming to do is replace that with something along the lines of '1254(,16)982' so that the original string can be reconstructed. If anyone could point me in the right direction that would be greatly appreciated
You're looking for [run-length encoding](http://en.wikipedia.org/wiki/Run-length_encoding): here is a Python implementation based loosely on [this one](http://wordaligned.org/articles/runlength-encoding-in-python). ``` import itertools def runlength_enc(s): '''Return a run-length encoded version of the string''' ...
how to pass arguments efficiently (**kwargs in python)
13,124,961
10
2012-10-29T15:46:07Z
13,125,197
18
2012-10-29T15:59:31Z
[ "python", "inheritance", "kwargs" ]
I have a class that inherits from 2 other classes. These are the base classes: ``` class FirstBase(object): def __init__(self, detail_text=desc, backed_object=backed_object, window=window, droppable_zone_obj=droppable_zone_obj, bound_zone_obj=bound_zone_object, ...
Your problem is that you only tried to use `super` in the child class. If you use `super` in the base classes too, then this will work. Each constructor will "eat" the keyword arguments it takes and not pass them up to the next constructor. When the constructor for `object` is called, if there are any keyword argument...
arbitrary number of arguments in a python function
13,125,218
14
2012-10-29T16:00:38Z
13,125,332
9
2012-10-29T16:05:46Z
[ "python" ]
I'd like to learn how to pass an arbitrary number of args in a python function, so I wrote a simple sum function in a recursive way as follows: ``` def mySum(*args): if len(args) == 1: return args[0] else: return args[-1] + mySum(args[:-1]) ``` but when I tested `mySum(3, 4)`, I got this error: ``` TypeE...
This line: ``` return args[-1] + mySum(args[:-1]) ``` `args[:-1]` returns a slice of the arguments tuple. I assume your goal is to recursively call your function using that slice of the arguments. Unfortunately, your current code simply calls your function using a single object - the slice itself. What you want to d...
How is super() in Python 3 implemented?
13,126,727
12
2012-10-29T17:32:15Z
28,605,694
10
2015-02-19T11:52:44Z
[ "python", "python-3.x", "metaprogramming", "super", "python-internals" ]
I'm wondering how is the new super in Python 3 implemented. This question was born in my head after I have made a small example and I got a strange error. I'm using [Pyutilib Component architecture (PCA)](https://software.sandia.gov/trac/pyutilib/wiki/Documentation/PyUtilibOverview) and I've made my custom metaclass t...
**TL;DR**: This `"empty __class__ cell"` error will happen when the metaclass tries to call a method in the defined class (or instantiate it) before it is done with its `__new__` and `__init__`,and the called method uses `super`. The error will also happen if one writes a call to `super()` in a function defined outside...
String splitting in Python
13,128,565
4
2012-10-29T19:49:02Z
13,128,650
9
2012-10-29T19:54:33Z
[ "python", "string", "split", "delimiter" ]
Is there a way to split a string in Python using multiple delimiters instead of one? `split` seems to take in only one parameter as delimiter. Also, I cannot import the `re` module. (This is the main stumbling block really.) Any suggestions on how I should do it? Thanks!
In order to split on multiple sequences you could simply replace all of the sequences you need to split on with just one sequence and then split on that one sequence. So ``` s = s.replace("z", "s") s.split("s") ``` Will split on s and z.
Matplotlib - Finance volume overlay
13,128,647
5
2012-10-29T19:54:17Z
13,216,161
12
2012-11-04T04:51:03Z
[ "python", "numpy", "matplotlib", "scipy" ]
I'm making a candlestick chart with two data sets: [open, high, low, close] and volume. I'm trying to overlay the volumes at the bottom of the chart like this: ![finviz.com](http://i.stack.imgur.com/8rtCE.png) I'm calling [volume\_overlay3](http://doc.astro-wise.org/matplotlib.finance.html#-volume_overlay3) but inste...
The volume\_overlay3 did not work for me. So I tried your idea to add a bar plot to the candlestick plot. After creating a twin axis for the volume re-position this axis (make it short) and modify the range of the candlestick y-data to avoid collisions. ``` import numpy as np import matplotlib import matplotlib.pyplo...
ctypes unload dll
13,128,995
8
2012-10-29T20:18:08Z
13,129,176
16
2012-10-29T20:31:21Z
[ "python", "ctypes" ]
I am loading a dll with ctypes like this: ``` lib = cdll.LoadLibrary("someDll.dll"); ``` When I am done with the library, I need to unload it to free resources it uses. I am having problems finding anything in the docs regarding how to do this. I see this rather old post: [How can I unload a DLL using ctypes in Pytho...
The only truly effective way I have ever found to do this is to take charge of calling `LoadLibrary` and `FreeLibrary`. Like this: ``` import ctypes # get the module handle and create a ctypes library object libHandle = ctypes.windll.kernel32.LoadLibraryA('mydll.dll') lib = ctypes.WinDLL(None, handle=libHandle) # do...
Python combination generation
13,129,454
6
2012-10-29T20:51:10Z
13,129,543
11
2012-10-29T20:56:28Z
[ "python", "python-2.7", "python-2.x" ]
*I am new to programming and to Python. Not sure how to proceed to achieve this (explained below) problem, hence the question.* I have n number of lists, each containing 1 or more items. I want to have a new list with all possible combinations, which uses one item from each list once, and always. Example: ``` list_1...
use [`itertools.product()`](http://docs.python.org/2/library/itertools.html#itertools.product) here: ``` >>> list_1 = ['1','2','3'] >>> list_2 = ['2','5','7'] >>> list_3 = ['9','9','8'] >>> from itertools import product >>> ["".join(x) for x in product(list_1,list_2,list_3)] ['129', '129', '128', '159', '159', '158', ...
Histogram values of a Pandas Series
13,129,618
17
2012-10-29T21:01:02Z
13,130,357
32
2012-10-29T22:07:25Z
[ "python", "numpy", "pandas" ]
I have some values in a Python Pandas Serie (type: pandas.core.series.Series) ``` In [1]: serie = pd.Series([0.0,950.0,-70.0,812.0,0.0,-90.0,0.0,0.0,-90.0,0.0,-64.0,208.0,0.0,-90.0,0.0,-80.0,0.0,0.0,-80.0,-48.0,840.0,-100.0,190.0,130.0,-100.0,-100.0,0.0,-50.0,0.0,-100.0,-100.0,0.0,-90.0,0.0,-90.0,-90.0,63.0,-90.0,0.0,...
You just need to use the histogram function of numpy: ``` import numpy as np count,division = np.histogram(serie) ``` where division is the automatically calculated border for your bins and count is the population inside each bin. If you need to fix a certain number of bins, you can use the argument bins and specify...
Bound method error
13,130,574
12
2012-10-29T22:27:29Z
13,130,602
20
2012-10-29T22:30:30Z
[ "python", "class" ]
I am creating a word parsing class and keep getting a "bound method Word\_Parser.sort\_word\_list of <**main**.Word\_Parser instance at 0x1037dd3b0>" error when I run this: ``` class Word_Parser: """docstring for Word_Parser""" def __init__(self, sentences): self.sentences = sentences def parser(s...
There's no error here. You're printing a function, and that's what functions look like. To actually *call* the function, you have to put parens after that. You're already doing that above. If you want to print the result of calling the function, just have the function return the value, and put the print there. For exa...
Lemmatize French text
13,131,139
16
2012-10-29T23:27:57Z
13,131,445
9
2012-10-30T00:07:39Z
[ "python", "nltk", "lemmatization" ]
I have some text in French that I need to process in some ways. For that, I need to: * First, tokenize the text into words * Then lemmatize those words to avoid processing the same root more than once As far as I can see, the wordnet lemmatizer in the NLTK only works with English. I want something that can return "vo...
[**Here**](http://osdir.com/ml/python.nltk.devel/2007-06/msg00018.html)'s an old but relevant comment by an nltk dev. Looks like most advanced stemmers in nltk are all English specific: > The nltk.stem module currently contains 3 stemmers: the Porter > stemmer, the Lancaster stemmer, and a Regular-Expression based > s...
Building a small numpy array from individual values: Fast and readable method?
13,131,220
13
2012-10-29T23:37:28Z
13,131,609
9
2012-10-30T00:29:23Z
[ "python", "numpy" ]
I found that a bottleneck in my program is the creation of numpy arrays from a list of given values, most commonly putting four values into a 2x2 array. There is an obvious, easy-to-read way to do it: ``` my_array = numpy.array([[1, 3], [2.4, -1]]) ``` which takes 15 us -- very very slow since I'm doing it millions o...
This is a great question. I can't find anything which will approach the speed of your completely unrolled solution (**edit** *@BiRico was able to come up with something close. See comments and update* :). Here are a bunch of different options that I (and others) came up with and associated timings: ``` import numpy as...
Logging variable data with new format string
13,131,400
37
2012-10-30T00:00:38Z
13,131,479
10
2012-10-30T00:11:42Z
[ "python", "python-2.7" ]
I use logging facility for python 2.7.3. [Documentation for this Python version say](http://docs.python.org/2/howto/logging.html): > the logging package pre-dates newer formatting options such as str.format() and string.Template. These newer formatting options are supported... I like 'new' format with curly braces. S...
The easier solution would be to use the [excellent `logbook` module](http://packages.python.org/Logbook/) ``` import logbook logbook.debug('Format this message {0}', 1) ``` Or the more complete: ``` >>> import logbook >>> l = logbook.Logger('MyLog') >>> l.debug('Format this message {0}', 1) [2012-10-30 00:13] DEBUG:...
Logging variable data with new format string
13,131,400
37
2012-10-30T00:00:38Z
13,131,690
25
2012-10-30T00:39:53Z
[ "python", "python-2.7" ]
I use logging facility for python 2.7.3. [Documentation for this Python version say](http://docs.python.org/2/howto/logging.html): > the logging package pre-dates newer formatting options such as str.format() and string.Template. These newer formatting options are supported... I like 'new' format with curly braces. S...
**EDIT:** take a look at the [`StyleAdapter` approach in @Dunes' answer](http://stackoverflow.com/a/24683360/4279) unlike this answer; it allows to use alternative formatting styles without the boilerplate while calling logger's methods (debug(), info(), error(), etc). --- From the docs — [Use of alternative format...
Logging variable data with new format string
13,131,400
37
2012-10-30T00:00:38Z
24,683,360
8
2014-07-10T18:01:15Z
[ "python", "python-2.7" ]
I use logging facility for python 2.7.3. [Documentation for this Python version say](http://docs.python.org/2/howto/logging.html): > the logging package pre-dates newer formatting options such as str.format() and string.Template. These newer formatting options are supported... I like 'new' format with curly braces. S...
This was my solution to the problem when I found logging only uses printf style formatting. It allows logging calls to remain the same -- no special syntax such as `log.info(__("val is {}", "x"))`. The change required to code is to wrap the logger in a `StyleAdapter`. ``` from inspect import getargspec class BraceMes...
Logging variable data with new format string
13,131,400
37
2012-10-30T00:00:38Z
26,003,573
17
2014-09-23T19:51:14Z
[ "python", "python-2.7" ]
I use logging facility for python 2.7.3. [Documentation for this Python version say](http://docs.python.org/2/howto/logging.html): > the logging package pre-dates newer formatting options such as str.format() and string.Template. These newer formatting options are supported... I like 'new' format with curly braces. S...
Here is another option that does not have the keyword problems mentioned in Dunes' answer. It can only handle positional (`{0}`) arguments and not keyword (`{foo}`) arguments. It also does not require two calls to format (using the underscore). It does have the ick-factor of subclassing `str`: ``` class BraceString(st...
one line if else condition in python
13,134,743
2
2012-10-30T07:52:50Z
13,134,776
8
2012-10-30T07:56:11Z
[ "python", "condition" ]
``` def sum10(a, b): if sum([a, b]) % 10 == 0: return True; return False print sum10(7, 3) print sum10(-13, -17) print sum10(3, 8) ``` the result is: ``` True True None ``` not what I expected: ``` True True False ``` any idea?
This is what you want. ``` def sum10(a, b): return sum([a, b]) % 10 == 0 ``` Also the ternary `If` in Python works like this ``` <True Statment> if <Conditional Expression> else <False Statement> ``` eg ``` True if sum([a,b]) % 10 == 0 else False ``` Might i also recommend using the plus operator? ``` True i...
one line if else condition in python
13,134,743
2
2012-10-30T07:52:50Z
13,134,778
7
2012-10-30T07:56:22Z
[ "python", "condition" ]
``` def sum10(a, b): if sum([a, b]) % 10 == 0: return True; return False print sum10(7, 3) print sum10(-13, -17) print sum10(3, 8) ``` the result is: ``` True True None ``` not what I expected: ``` True True False ``` any idea?
Your code ``` def sum10(a, b): if sum([a, b]) % 10 == 0: return True; return False ``` is equivalent to ``` def sum10(a, b): if sum([a, b]) % 10 == 0: return True; return False ``` so `return False` is never evaluated. --- Some (of the probably endless) alternatives: ``` if sum([a, b]) % 10 ...
class method __instancecheck__ does not work
13,135,712
9
2012-10-30T09:06:45Z
13,135,792
12
2012-10-30T09:12:57Z
[ "python" ]
I am using python 2.7.3 on Windows. I tried to override the `__instancecheck__` magic method as a class method. But I can not make it work. ``` class Enumeration(int): @classmethod def __instancecheck__(cls, inst): if type(inst) == cls: return True if isinstance(inst, int) and inst ...
`instancecheck` must be defined in a metaclass: ``` class Enumeration(type): def __instancecheck__(self, other): print 'hi' return True class EnumInt(int): __metaclass__ = Enumeration print isinstance('foo', EnumInt) # prints True ``` Why is that? For the same reason why your second example...
Django if user.is_authenticated not working
13,136,057
3
2012-10-30T09:29:36Z
13,136,184
8
2012-10-30T09:38:09Z
[ "python", "django", "authentication", "django-forms" ]
I am just trying to run a simple `{% if user.is_authenticated %}` . But it always return `False`. Here are my all the files. `views.py` ``` from django.shortcuts import render_to_response, redirect from django.core.urlresolvers import reverse from django.template import RequestContext from django.contrib.auth.models...
You never log your user in. Try something along the following lines: ``` from django.contrib.auth import authenticate, login as auth_login if request.method == 'POST': form = UserLoginForm(request.POST or None) if form.is_valid(): username = User.objects.get(email=form.cleaned_data['email']) p...
Why can't pip uninstall pysqlite?
13,136,060
9
2012-10-30T09:29:43Z
13,136,153
10
2012-10-30T09:36:04Z
[ "python", "pip", "pysqlite" ]
I'm trying to remove `pysqlite` from my system using `pip`. What I get doing so makes no sense: ``` $ pip uninstall pysqlite ``` The command worked, but watch this: ``` $ pip freeze [...] pysqlite==1.0.1 ``` Let's try again ``` $ pip uninstall pysqlite Can't uninstall 'pysqlite'. No files were found to uninstall....
Go to your `/usr/lib/python2.6/site-packages/pysqlite*.egg/` (or anywhere else you store your eggs in your python path) and look for the `installed-files.txt` file. If it does not exists, `pip` will not be able to uninstall it, if it does, you remove all the files within and you're rid of pysqlite. And as Martijn sugg...
How to build and install libvirt on Mac?
13,136,884
2
2012-10-30T10:18:14Z
13,137,450
8
2012-10-30T10:52:36Z
[ "python", "osx", "install", "libvirt" ]
I referred to [this article](http://lsimons.wordpress.com/2011/06/02/libvirt-vmware-fusion-mac-os-x/), but used more recent libraries. To be explicit, I downloaded `libgpg-error-1.10`, `libgcrypt-1.5.0`,`gnutls-3.1.3` and `libvirt-1.0.0` `libgpg-error-1.10`, `libgcrypt-1.5.0` installed OK and when configure `gnutls-3....
Your easiest options is probably using [homebrew](http://mxcl.github.com/homebrew/) to install `libvirt`: ``` $ brew install libvirt ``` After that compiling the Python bindings for `libvirt` should be trivial.
Combining websockets and WSGI in a python app
13,137,449
11
2012-10-30T10:52:35Z
13,138,361
12
2012-10-30T11:49:46Z
[ "python", "websocket", "wsgi" ]
I'm working on a scientific experiment where about two dozen test persons play a turn-based game with/against each other. Right now, it's a Python web app with a WSGI interface. I'd like to augment the usability with websockets: When all players have finished their turns, I'd like to notify all clients to update their ...
Here is an example that does what you want: * <https://github.com/tavendo/AutobahnPython/tree/master/examples/twisted/websocket/echo_wsgi> It runs a WSGI web app (Flask-based in this case, but can be anything WSGI conforming) plus a WebSocket server under 1 server and 1 port. You can send WS messages from within Web...
How to download image using requests
13,137,817
140
2012-10-30T11:14:25Z
13,137,873
217
2012-10-30T11:18:15Z
[ "python", "urllib2", "python-requests" ]
I'm trying to download and save an image from the web using python's `requests` module. Here is the (working) code I used: ``` img = urllib2.urlopen(settings.STATICMAP_URL.format(**data)) with open(path, 'w') as f: f.write(img.read()) ``` Here is the new (non-working) code using `requests`: ``` r = requests.get...
You can either use the [`response.raw` file object](http://docs.python-requests.org/en/latest/api/#requests.Response.raw), or iterate over the response. To use the `response.raw` file-like object will not, by default, decode compressed responses (with GZIP or deflate). You can force it to decompress for you anyway by ...
How to download image using requests
13,137,817
140
2012-10-30T11:14:25Z
18,043,472
90
2013-08-04T13:32:16Z
[ "python", "urllib2", "python-requests" ]
I'm trying to download and save an image from the web using python's `requests` module. Here is the (working) code I used: ``` img = urllib2.urlopen(settings.STATICMAP_URL.format(**data)) with open(path, 'w') as f: f.write(img.read()) ``` Here is the new (non-working) code using `requests`: ``` r = requests.get...
Get a file-like object from the request and copy it to a file. This will also avoid reading the whole thing into memory at once. ``` import shutil import requests url = 'http://example.com/img.png' response = requests.get(url, stream=True) with open('img.png', 'wb') as out_file: shutil.copyfileobj(response.raw, ...
How to download image using requests
13,137,817
140
2012-10-30T11:14:25Z
18,108,000
35
2013-08-07T15:52:16Z
[ "python", "urllib2", "python-requests" ]
I'm trying to download and save an image from the web using python's `requests` module. Here is the (working) code I used: ``` img = urllib2.urlopen(settings.STATICMAP_URL.format(**data)) with open(path, 'w') as f: f.write(img.read()) ``` Here is the new (non-working) code using `requests`: ``` r = requests.get...
I have the same need for downloading images using requests. I first tried the answer of Martijn Pieters, and it works well. But when I did a profile on this simple function, I found that it uses so many function calls compared to urllib and urllib2. I then tried the [way recommended](http://docs.python-requests.org/en...
How to download image using requests
13,137,817
140
2012-10-30T11:14:25Z
21,595,698
23
2014-02-06T06:33:00Z
[ "python", "urllib2", "python-requests" ]
I'm trying to download and save an image from the web using python's `requests` module. Here is the (working) code I used: ``` img = urllib2.urlopen(settings.STATICMAP_URL.format(**data)) with open(path, 'w') as f: f.write(img.read()) ``` Here is the new (non-working) code using `requests`: ``` r = requests.get...
How about this, a quick solution. ``` import requests url = "http://craphound.com/images/1006884_2adf8fc7.jpg" response = requests.get(url) if response.status_code == 200: f = open("/Users/apple/Desktop/sample.jpg", 'wb') f.write(response.content) f.close() ```
How to download image using requests
13,137,817
140
2012-10-30T11:14:25Z
25,931,507
18
2014-09-19T10:12:38Z
[ "python", "urllib2", "python-requests" ]
I'm trying to download and save an image from the web using python's `requests` module. Here is the (working) code I used: ``` img = urllib2.urlopen(settings.STATICMAP_URL.format(**data)) with open(path, 'w') as f: f.write(img.read()) ``` Here is the new (non-working) code using `requests`: ``` r = requests.get...
How about this way: ``` # filename.py import requests url = 'http://www.example.com/image.jpg' page = requests.get(url) with open('test', 'wb') as test: test.write(page.content) ```
How to download image using requests
13,137,817
140
2012-10-30T11:14:25Z
33,866,125
11
2015-11-23T08:02:30Z
[ "python", "urllib2", "python-requests" ]
I'm trying to download and save an image from the web using python's `requests` module. Here is the (working) code I used: ``` img = urllib2.urlopen(settings.STATICMAP_URL.format(**data)) with open(path, 'w') as f: f.write(img.read()) ``` Here is the new (non-working) code using `requests`: ``` r = requests.get...
This might be easier than using `requests`. This is the only time I'll ever suggest not using `requests` to do HTTP stuff. Two liner using `urllib`: ``` >>> import urllib >>> urllib.urlretrieve("http://www.example.com/songs/mp3.mp3", "mp3.mp3") ``` --- There is also a nice Python module named `wget` that is pretty ...
benchmarks: does python have a faster way of walking a network folder?
13,138,160
29
2012-10-30T11:35:57Z
13,138,301
8
2012-10-30T11:45:49Z
[ "python", "ruby", "vbscript", "benchmarking" ]
I need to walk through a folder with approximately ten thousand files. My old vbscript is very slow in handling this. Since I've started using Ruby and Python since then, I made a benchmark between the three scripting languages to see which would be the best fit for this job. The results of the tests below on a subset...
The Ruby implementation for `Dir` is in C (the file `dir.c`, according to [this documentation](http://www.ruby-doc.org/core-1.9.3/Dir.html)). However, the Python equivalent is implemented [in Python](http://hg.python.org/cpython/file/abe8a2908f08/Lib/os.py#l209). It's not surprising that Python is less performant than...
Remove empty string from list
13,138,978
4
2012-10-30T12:27:32Z
13,139,077
13
2012-10-30T12:33:53Z
[ "python", "string", "list" ]
I just started Python classes and I'm really in need of some help. Please keep in mind that I'm new if you're answering this. I have to make a program that takes the average of all the elements in a certain list "l". That is a pretty easy function by itself; the problem is that the teacher wants us to remove any empty...
You can use a list comprehension to remove all elements that are `''`: ``` mylist = [1, 2, 3, '', 4] mylist = [i for i in mylist if i != ''] ``` Then you can calculate the average by taking the sum and dividing it by the number of elements in the list: ``` avg = sum(mylist)/len(mylist) ``` ### Floating Point Averag...
How can I change the font size of ticks of axes object in matplotlib
13,139,630
7
2012-10-30T13:04:25Z
13,141,146
11
2012-10-30T14:29:36Z
[ "python", "matplotlib", "axis", "subplot" ]
I have a figure I added subfigure to (inset). I have used: ``` fig = plt.figure() ax = fig.add_subplot(111) subA = fig.add_axes([0.4,0.14,0.2,0.2]) ``` I now want to change the `xtick` font size of the subfigure. I tried some naive approach such as ``` subA.get_xaxis().get_xticks().set_fontsize(10) ``` without any ...
``` fig = plt.figure() ax = fig.add_subplot(111) plt.xticks([0.4,0.14,0.2,0.2], fontsize = 50) # work on current fig plt.show() ``` the x/yticks has the same properties as [matplotlib.text](http://matplotlib.org/api/artist_api.html#matplotlib.text.Text)
How can I change the font size of ticks of axes object in matplotlib
13,139,630
7
2012-10-30T13:04:25Z
32,365,139
7
2015-09-03T00:14:51Z
[ "python", "matplotlib", "axis", "subplot" ]
I have a figure I added subfigure to (inset). I have used: ``` fig = plt.figure() ax = fig.add_subplot(111) subA = fig.add_axes([0.4,0.14,0.2,0.2]) ``` I now want to change the `xtick` font size of the subfigure. I tried some naive approach such as ``` subA.get_xaxis().get_xticks().set_fontsize(10) ``` without any ...
Use: ``` subA.tick_params(labelsize=6) ```
Python performance of conditional evaluation
13,140,619
2
2012-10-30T13:58:39Z
13,140,732
16
2012-10-30T14:05:26Z
[ "python", "performance" ]
I was trying to find out if there's any penalty for negating a boolean when evaluation a conditional statement (python 2.6.6). I first tried this simple test (no `else` branch) ``` >>> import timeit >>> timeit.timeit("if not True: pass", number=100000) 0.011913061141967773 >>> timeit.timeit("if True: pass", number=100...
First, the "real world" news: if you really are in a situation where writing "if not" or "if ..pass else..." would impact the performance of your application, I'd suggest you did some serious profiling, and rewrite your inner loop in native code -either using Cython or C (and even other options, such as Fortran - Pytho...
is it possible to query with a logical OR in django
13,141,138
2
2012-10-30T14:29:04Z
13,141,252
7
2012-10-30T14:33:56Z
[ "python", "django", "django-queryset" ]
I have a model 'Organization' which has following fields ``` class Organization(models.Model): members = models.ManyToManyField(User,related_name='org_members') title = models.CharField(max_length=200) description = models.TextField() founder = models.ForeignKey(User,related_name='org_founder') def...
To query with a logical OR, you need to use the Q objects: ``` from django.db import models Organization.objects.filter(models.Q(members=me) | models.Q(founder=me)) ```
Expandable and contracting frame in Tkinter
13,141,259
9
2012-10-30T14:34:07Z
13,169,685
11
2012-11-01T01:13:42Z
[ "python", "user-interface", "tkinter", "ttk" ]
Does anyone know if there is already a widget/class to handle expanding/contracting a frame based on a toggled button (checkbutton) in tkinter/ttk? This question stems from my attempt to clean up a cluttered gui that has lots of options categorized by specific actions. I would like something along the lines of: ![ent...
I am actually surprised at how close I was to getting functioning code. I decided to work on it some more and have develop a simple little class to perform exactly what I wanted (comments and suggestions on the code are welcome): ``` import tkinter as tk from tkinter import ttk class ToggledFrame(tk.Frame): de...
How to remove leading and trailing zeros in a string? Python
13,142,347
35
2012-10-30T15:29:20Z
13,142,375
79
2012-10-30T15:30:35Z
[ "python", "string", "trailing", "chomp", "leading-zero" ]
I have several alphanumeric strings like these ``` listOfNum = ['000231512-n','1209123100000-n00000','alphanumeric0000', '000alphanumeric'] ``` The desired output for removing **trailing** zeros would be: ``` listOfNum = ['000231512-n','1209123100000-n','alphanumeric', '000alphanumeric'] ``` The desired output for ...
What about a basic ``` your_string.strip("0") ``` to remove both trailing and leading zeros ? If you're only interested in removing trailing zeros, use `.rstrip` instead (and `.lstrip` for only the leading ones). [More info in the [doc](http://docs.python.org/2/library/stdtypes.html?highlight=split#str.strip).] You...
Python regex: Including whitespace inside character range
13,142,440
4
2012-10-30T15:33:06Z
13,142,474
14
2012-10-30T15:34:27Z
[ "python", "regex", "python-2.7" ]
I have a regular expression that matches alphabets, numbers, \_ and - (with a minimum and maximum length). ``` ^[a-zA-Z0-9_-]{3,100}$ ``` I want to include whitespace in that set of characters. According to the Python documentation: > Character classes such as \w or \S are also accepted inside a set. So I tried: ...
The problem is not the `\s` but the `-` which indicates a character range, unless it is at the end or start of the class. Use this: ``` ^[a-zA-Z0-9_\s-]{3,100}$ ```
IPython notebook directory traversal
13,142,676
4
2012-10-30T15:44:39Z
13,144,541
7
2012-10-30T17:32:00Z
[ "python", "ipython" ]
A previous question, "Multiple directories and/or subdirectories in IPython Notebook session," asked about directory traversal. The answer given was that the feature is coming. I have also seen a command line flag that starts the server in a specific directory. I can no longer find this post. The flag is not mentioned ...
I believe the flag you're looking for is `--notebook-dir=/home/foo/wherever`. I found this by running `ipython notebook --help`. Navigating directories while the server is running is still 'coming', unfortunately. It's one of those things that will need to be done the right way, and the people who can do it (which doe...
Lazy transform in C++
13,144,280
7
2012-10-30T17:14:18Z
13,145,000
9
2012-10-30T18:00:47Z
[ "c++", "python", "functional-programming", "lazy-evaluation" ]
I have the following Python snippet that I would like to reproduce using C++: ``` from itertools import count, imap source = count(1) pipe1 = imap(lambda x: 2 * x, source) pipe2 = imap(lambda x: x + 1, pipe1) sink = imap(lambda x: 3 * x, pipe2) for i in sink: print i ``` I've heard of [Boost Phoenix](http://www....
Employing [Boost.Range](http://www.boost.org/libs/range/): ``` int main(){ auto map = boost::adaptors::transformed; // shorten the name auto sink = generate(1) | map([](int x){ return 2*x; }) | map([](int x){ return x+1; }) | map([](int x){ return 3*x; }); for(...
how to verify a reboot occurs?
13,145,175
4
2012-10-30T18:11:39Z
13,145,310
7
2012-10-30T18:20:08Z
[ "python", "amazon-web-services", "boto" ]
I want to reboot some instances using `ec2.reboot_instances([instanceId])` and that works fine but: 1. how to verify a reboot occurs? I thought `launch_time` will be changed but looks like all parameters remains the same.. I'd prefer to do this check without ssh or ping - is it possible? May be it's possible to use `i...
This shell command will give you how long the system has been booted: ``` ssh hostname uptime ``` To automate it you will want to add you ssh public key to the `.ssh/authorized_keys` file on the host. With boto it would probably be something like this (although I've not used boto): ``` s = boto.manage.cmdshell.SSHC...
Stem plot in matplotlib?
13,145,218
13
2012-10-30T18:14:41Z
13,145,410
14
2012-10-30T18:26:17Z
[ "python", "matplotlib" ]
I want to `plot(x, sin(x))` but instead of a line from `(xi,yi)` to `(x_i+1,y_i+1)` I want a vertical line to each point from `(xi,0)` to `(xi,yi)` as sometimes interpolation between the points makes no sense (e.g. quantized data) (and it looks much better with that vertical line than without). Much like the stem plot...
There is a [stem plot](http://matplotlib.org/1.2.1/api/pyplot_api.html?highlight=stem#matplotlib.pyplot.stem) (a.k.a. lollipop plot) in the matplotlib as well. --- Below you can find an example from [the docs](http://matplotlib.org/1.2.1/examples/pylab_examples/stem_plot.html) (of course one wouldn't `import *` from ...
Django annotate count with a distinct field
13,145,254
22
2012-10-30T18:17:04Z
13,145,407
40
2012-10-30T18:26:11Z
[ "python", "django" ]
I have two models defined loosely like this: ``` class InformationUnit(models.Model): username = models.CharField(max_length=255) project = models.ForeignKey('Project') ... class Project(models.Model): name = models.CharField(max_length=255) ``` Now, in a view, I want to annotate all the InformationUnits...
`Count` can take a `distinct` argument, like so: ``` p = Project.objects.all().annotate(Count('informationunit__username', distinct=True)) ``` This doesn't seem to be documented, but you can find it in the source for Count.
PyInstaller Runtime Error? (R6034)
13,146,899
7
2012-10-30T20:13:41Z
39,022,238
7
2016-08-18T15:34:19Z
[ "python", "pyinstaller" ]
I've finally gotten PyInstaller to build an exe file, but it's not running. As soon as I open it, I get this in a dialog: ``` Runtime Error! Program C:\.....\MCManager.exe R6034 An application has made an attempt to load the C runtime library incorrectly. Please contact the application's support team for more informa...
I was going to leave a comment, but not enough rep. Though this was asked awhile ago I recently ran into the same issue and it turned out to be a Pyinstaller bug with version 3.2. Resulting exe terminates with R6034 after upgrade to pyinstaller 3.2: <https://github.com/pyinstaller/pyinstaller/issues/1985> PyInstaller...
How to simulate HTTP post request using Python Requests module?
13,147,914
8
2012-10-30T21:35:32Z
13,148,109
22
2012-10-30T21:51:41Z
[ "python", "forms", "post", "python-requests" ]
[This](http://docs.python-requests.org/en/latest/) is the module that I'm trying to use and there is a form I'm trying to fill automatically. The reason I'd like to use Requests over Mechanize is because with Mechanize, I have to load the login page first before I can fill it out and submit, whereas with Requests, I ca...
Some example code: ``` import requests URL = 'https://www.yourlibrary.ca/account/index.cfm' payload = { 'barcode': 'your user name/login', 'telephone_primary': 'your password', 'persistent': '1' # remember me } session = requests.session() r = requests.post(URL, data=payload) print r.cookies ``` The fi...