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
Convert Unicode to double ASCII letters in Python (ß -> ss)
11,248,467
5
2012-06-28T15:58:42Z
11,248,596
7
2012-06-28T16:05:55Z
[ "python", "unicode", "encoding" ]
Some Unicode characters can also be written as two ASCII letters (e.g.: ß -> ss, å -> aa). Is there any way to convert these in Python, without having a list with all of them? ### LATER EDIT: This kind of conversion is done by a lof of websites, including Stackoverflow (url from this page was converted), and Twitte...
There are no universal rules. You could try [unidecode](http://pypi.python.org/pypi/Unidecode) module to transliterate Unicode text to ASCII.
How to plot data from multiple two column text files with legends in Matplotlib?
11,248,812
18
2012-06-28T16:18:01Z
11,249,340
13
2012-06-28T16:49:07Z
[ "python", "numpy", "matplotlib" ]
How do I open multiple text files from different directories and plot them on a single graph with legends?
Assume your file looks like this and is named test.txt (space delimited): ``` 1 2 3 4 5 6 7 8 ``` Then: ``` #!/usr/bin/python import numpy as np import matplotlib.pyplot as plt with open("test.txt") as f: data = f.read() data = data.split('\n') x = [row.split(' ')[0] for row in data] y = [row.split(' ')[1] f...
How to plot data from multiple two column text files with legends in Matplotlib?
11,248,812
18
2012-06-28T16:18:01Z
11,249,430
27
2012-06-28T16:55:14Z
[ "python", "numpy", "matplotlib" ]
How do I open multiple text files from different directories and plot them on a single graph with legends?
This is relatively simple if you use pylab (included with matplotlib) instead of matplotlib directly. Start off with a list of filenames and legend names, like [ ('name of file 1', 'label 1'), ('name of file 2', 'label 2'), ...]. Then you can use something like the following: ``` import pylab datalist = [ ( pylab.loa...
python: extracting one slice of a multidimensional array given the dimension index
11,249,446
4
2012-06-28T16:56:14Z
11,249,478
7
2012-06-28T16:58:11Z
[ "python", "numpy" ]
I know how to take `x[:,:,:,:,j,:]` (which takes the jth slice of dimension 4). Is there a way to do the same thing if the dimension is known at runtime, and is not a known constant?
One option to do so is to construct the slicing programatically: ``` slicing = (slice(None),) * 4 + (j,) + (slice(None),) ``` An alternative is to use `numpy.take()` or `ndarray.take()`: ``` >>> a = numpy.array([[1, 2], [3, 4]]) >>> a.take((1,), axis=0) array([[3, 4]]) >>> a.take((1,), axis=1) array([[2], [4]...
Python methods to find duplicates
11,249,824
2
2012-06-28T17:24:01Z
11,249,874
14
2012-06-28T17:27:33Z
[ "python" ]
Is there a way to find if a list contains duplicates. For example: ``` list1 = [1,2,3,4,5] list2 = [1,1,2,3,4,5] list1.*method* = False # no duplicates list2.*method* = True # contains duplicates ```
If you convert the list to a set temporarily, that will eliminate the duplicates in the set. You can then compare the lengths of the list and set. In code, it would look like this: ``` list1 = [...] tmpSet = set(list1) haveDuplicates = len(list1) != len(tmpSet) ```
Is there any way to know if the value of an argument is the default vs. user-specified?
11,251,119
3
2012-06-28T18:54:45Z
11,251,165
11
2012-06-28T18:57:32Z
[ "python", "arguments" ]
I'm looking for something that works like Lisp's arg-supplied-p variables, to help differentiate a default value from the same value specified by a user. Example: ``` def foo(a=10): pass ``` I'd like to know in foo if it was called like this: ``` foo() ``` or like this: ``` foo(10) ``` or even like this: ``...
Except for inspecting the source code, there is no way to tell the three function calls apart – they are *meant* to have exactly the same meaning. If you need to differentiate between them, use a different default value, e.g. `None`. ``` def foo(a=None): if a is None: a = 10 # no value for a prov...
Check if item is in an array
11,251,709
41
2012-06-28T19:39:16Z
11,251,732
105
2012-06-28T19:40:26Z
[ "python", "arrays", "contains" ]
If I've got an array of strings, can I check to see if a string is in the array without doing a `for` loop? Specifically, I'm looking for a way to do it within an `if` statement, so something like this: ``` if [check that item is in array]: ```
Assuming you mean "list" where you say "array", you can do ``` if item in my_list: # whatever ```
Check if item is in an array
11,251,709
41
2012-06-28T19:39:16Z
11,251,781
7
2012-06-28T19:43:54Z
[ "python", "arrays", "contains" ]
If I've got an array of strings, can I check to see if a string is in the array without doing a `for` loop? Specifically, I'm looking for a way to do it within an `if` statement, so something like this: ``` if [check that item is in array]: ```
I'm also going to assume that you mean "list" when you say "array." Sven Marnach's solution is good. If you are going to be doing repeated checks on the list, then it might be worth converting it to a set or frozenset, which can be faster for each check. Assuming your list of strs is called `subjects`: ``` subject_set...
lightweight python library to query city/state name by zip code?
11,251,762
2
2012-06-28T19:42:28Z
11,251,872
9
2012-06-28T19:49:49Z
[ "python", "zipcode" ]
Pretty simple here, I'm looking for a lightweight library that will allow me to lookup a city/state pairing for a given zip code. I am using django FWIW. Thanks in advance.
Try [pyzipcode](http://pypi.python.org/pypi/pyzipcode/). An example from the home page: ``` >>> from pyzipcode import ZipCodeDatabase >>> zcdb = ZipCodeDatabase() >>> zipcode = zcdb[54115] >>> zipcode.zip u'54115' >>> zipcode.city u'De Pere' >>> zipcode.state u'WI' >>> zipcode.longitude -88.078959999999995 >>> zipcode...
How much memory in numpy array? Is RAM a limiting factor?
11,253,443
3
2012-06-28T21:51:21Z
11,253,528
10
2012-06-28T21:59:51Z
[ "python", "arrays", "memory", "numpy" ]
I'm using numpy to create a cube array with sides of length 100, thus containing 1 million entries total. For each of the million entries, I am inserting a 100x100 matrix whose entries are comprised of randomly generated numbers. I am using the following code to do so: ``` import random from numpy import * cube = ara...
A couple points: * The size in memory of numpy arrays is easy to calculate. It's simply the number of elements times the data size, plus a small constant overhead. For example, if your `cube.dtype` is `int64`, and it has 1,000,000 elements, it will require `1000000 * 64 / 8 = 8,000,000` bytes (8Mb). * However, as @Gab...
numpy: applying argsort to an array
11,253,495
5
2012-06-28T21:55:41Z
11,253,931
7
2012-06-28T22:42:49Z
[ "python", "arrays", "numpy" ]
The [`argsort()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html#numpy.argsort) function returns a matrix of indices that can be used to index the original array so that the result would match the `sort()` result. Is there a way to apply those indices? I have two arrays, one is the array used f...
This is probably overkill, but this will work in the nd case: ``` import numpy as np axis = 0 index = list(np.ix_(*[np.arange(i) for i in z2.shape])) index[axis] = z2.argsort(axis) z2[index] # Or if you only need the 3d case you can use np.ogrid. axis = 0 index = np.ogrid[:z2.shape[0], :z2.shape[1], :z2.shape[2]] in...
Removing the background noise of a captcha image by replicating the chopping filter of TesserCap
11,253,899
6
2012-06-28T22:38:44Z
11,254,902
9
2012-06-29T01:07:45Z
[ "python", "image-processing", "imagemagick", "python-imaging-library" ]
I have a captcha image that looks like this: ![](http://i.stack.imgur.com/SlDew.png) Using a utility called [TesserCap](http://www.mcafee.com/us/downloads/free-tools/tessercap.aspx) from McAfee, I could apply a "chopping" filter to the image. (Before running it, I made sure there were only two colors in the image, wh...
The algorithm essentially checks if there are multiple target pixels (in this case, non-white pixels) in a row, and changes those pixels if the number of pixels is less than or equal to the chop factor. For example, in a sample row of pixels, where `#` is black and `-` is white, applying a chop factor of `2` would tra...
when to commit data in ZODB
11,254,384
9
2012-06-28T23:42:16Z
11,260,581
25
2012-06-29T11:00:30Z
[ "python", "zodb" ]
I am trying to handel the data generated by the following piece of code: ``` for Gnodes in G.nodes() # Gnodes iterates over 10000 values Gvalue = someoperation(Gnodes) for Hnodes in H.nodes() # Hnodes iterates over 10000 values Hvalue =someoperation(Hnodes) score = SomeOperation on (G...
Your goal is to make your process manageable within memory constraints. To be able to do this with the ZODB as a tool you need to understand how ZODB transactions work, and how to use them. ## Why your ZODB grows so large First of all you need to understand what a transaction commit does here, which also explains why...
Background Worker with Flask
11,256,002
25
2012-06-29T04:18:10Z
11,257,228
20
2012-06-29T06:45:07Z
[ "python", "flask" ]
I have a webapp that's built on python/Flask and it has a corresponding background job that runs continuously, periodically polling for data for each registered user. I would like this background job to start when the system starts and keep running til it shuts down. Instead of setting up /etc/rc.d scripts, I just had...
Try [flask-celery](https://github.com/ask/flask-celery/). It's a framework for running delayed, background or distributed tasks. It needs a broker app though: usually RabbitMQ is used, but you can use a database that you already have, see the [Celery project](http://celeryproject.org/) docs. Using it is as simple as t...
how to return javascript in Pyramid/Pylon
11,256,560
2
2012-06-29T05:37:21Z
11,258,181
7
2012-06-29T08:03:07Z
[ "javascript", "python", "pyramid" ]
how can I return some javascript code or a javascript file with view callables in Pyramid/Pylon framework?
You can do that as you'd do with any template/view callable. It's not that different. I'd still recommend setting the content type as such. ``` from pyramid.view import view_config @view_config(name='javascript', renderer='templates/javascript.mako') def my_js_view(request): request.response.content_type = 'appli...
Combining grid/pack Tkinter
11,257,771
3
2012-06-29T07:28:58Z
11,261,014
10
2012-06-29T11:31:56Z
[ "python", "tkinter", "ttk" ]
I know there have been many questions on grid and pack in the past but I just don't understand how to combine the two as I'm having difficulties expanding my 'table' in both directions (row/column). Buttons I wish to keep the same size but always stay at the bottom of the window. The 'table' however I wish to expand a...
Your first problem is that the main frame, `win1` is packed with no options. The default is for it to *not* fill the part of its container that it is in. Thus, no matter what you do to the inner widgets, the whole thing will stack anchored to the top portion of the window. The first thing you should do, then, is tell `...
Python matplotlib restrict to integer tick locations
11,258,212
8
2012-06-29T08:06:09Z
11,417,609
18
2012-07-10T16:18:29Z
[ "python", "matplotlib" ]
Quite often I want to make a bar chart of counts. If the counts are low I often get major and/or minor tick locations that are not integers. How can I prevent this? It makes no sense to have a tick at 1.5 when the data are counts. This is my first attempt: ``` import pylab pylab.figure() ax = pylab.subplot(2, 2, 1) p...
You can use the `MaxNLocator` method, like so: ``` from pylab import MaxNLocator ya = axes.get_yaxis() ya.set_major_locator(MaxNLocator(integer=True)) ```
Running Django with Run can not find LESS CSS
11,258,291
7
2012-06-29T08:14:01Z
25,388,418
7
2014-08-19T16:24:30Z
[ "python", "django", "pycharm" ]
I have a Django project that uses buildout. When running or debugging the application it runs fine by using my buildout script. I also use django-compressor to compress and compile my LESS files. I installed LESS server side with node and you can access the lessc binary from the shell as normal. django-compressor runs ...
I had the same issue. To fix this I opened terminal and ``` $ which lessc ``` which gave me /usr/local/bin/lessc next, in Pycharm i opened the Run/Debug configurations for my project. Under the Django server drop down I selected my project. In the configuration view to the right click the '...' after the 'Environm...
Python: why regular expression is slower than replace() method?
11,258,511
2
2012-06-29T08:33:56Z
11,258,534
8
2012-06-29T08:35:35Z
[ "python", "regex" ]
I have next 2 blocks of code: ``` def replace_re(text): start = time.time() new_text = re.compile(r'(\n|\s{4})').sub('', text) finish = time.time() return finish - start def replace_builtin(text): start = time.time() new_text = text.replace('\n', '').replace(' ', '') finish = time.time(...
Because regular expressions are *more* than 4.5 times more complex than a fixed string replacement.
Creating a generator expression or list comprehension without variable "x in" (e.g. for range) in Python
11,261,033
4
2012-06-29T11:34:09Z
11,261,181
11
2012-06-29T11:45:08Z
[ "python", "list-comprehension", "generator-expression" ]
In Python, is there any way to write this list comprehension without the "x in" variable (since it is left completely unused)? Same applies to a generator expression. I doubt this comes up very often, but I stumbled onto this a few times and was curious to know. Here's an example: ``` week_array = ['']*7 four_weeks =...
I don't believe so, and there is no harm in the `x`. A common thing to see when a value is unused in this way is to use an underscore as the free variable, e.g.: ``` [week_array[:] for _ in range(4)] ``` But it's nothing more than a convention to denote that the free variable goes unused.
Python - Fast Way to Remove Duplicates in This List?
11,261,493
5
2012-06-29T12:08:15Z
11,261,512
14
2012-06-29T12:09:18Z
[ "python", "list" ]
You know, to turn list: ``` a = ["hello", "hello", "hi", "hi", "hey"] ``` into list: ``` b = ["hello", "hi", "hey"] ``` You simply do it like this: ``` b = list(set(a)) ``` It's fast and pythonic. But what if i need to turn this list: ``` a = [["hello", "hi"], ["hello", "hi"], ["how", "what"], ["hello", "hi"], ...
``` >>> a = [["hello", "hi"], ["hello", "hi"], ["how", "what"], ["hello", "hi"], ["how", "what"]] >>> set(map(tuple, a)) set([('how', 'what'), ('hello', 'hi')]) ```
Tuples readability : [0,0] vs (0,0)
11,261,662
21
2012-06-29T12:19:21Z
11,261,769
12
2012-06-29T12:27:05Z
[ "python", "tuples", "readability" ]
I'm using Python since some times and I am discovering the "pythonic" way to code. I am using a lot of tuples in my code, most of them are polar or Cartesian positions. I found myself writing this : ``` window.set_pos([18,8]) ``` instead of this : ``` window.set_pos((18,8)) ``` to get rid of the double parenthesis...
You say > It seems that python is automatically doing the type conversion from list to tuple That's doubtful. Since lists and tuples are both [sequence types](http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange), they both implement many of the same behaviors, an...
Tuples readability : [0,0] vs (0,0)
11,261,662
21
2012-06-29T12:19:21Z
11,262,060
24
2012-06-29T12:46:49Z
[ "python", "tuples", "readability" ]
I'm using Python since some times and I am discovering the "pythonic" way to code. I am using a lot of tuples in my code, most of them are polar or Cartesian positions. I found myself writing this : ``` window.set_pos([18,8]) ``` instead of this : ``` window.set_pos((18,8)) ``` to get rid of the double parenthesis...
I'd be careful deciding to eschew tuples in favor of lists everywhere. Have you ever used the [dis](http://docs.python.org/library/dis.html) module? Watch what Python is doing at the bytecode level when you make a list verses making a tuple: ``` >>> def f(): ... x = [1,2,3,4,5,6,7] ... return x ... >>> def g(...
Tuples readability : [0,0] vs (0,0)
11,261,662
21
2012-06-29T12:19:21Z
11,262,694
8
2012-06-29T13:28:20Z
[ "python", "tuples", "readability" ]
I'm using Python since some times and I am discovering the "pythonic" way to code. I am using a lot of tuples in my code, most of them are polar or Cartesian positions. I found myself writing this : ``` window.set_pos([18,8]) ``` instead of this : ``` window.set_pos((18,8)) ``` to get rid of the double parenthesis...
I seriously doubt that tuples vs. lists make noticable difference in performance in your case. Don't do micro-optimizations unless your profiler says so. Readability is a priority. `list` and `tuple` are both [sequence types](http://docs.python.org/dev/glossary.html#term-sequence). *Semantically* tuples might be pref...
django - TypeError: coercing to Unicode
11,261,986
4
2012-06-29T12:42:22Z
11,262,092
8
2012-06-29T12:49:02Z
[ "python", "django" ]
I'm getting **TypeError: coercing to Unicode: need string or buffer, int found** This is my models.py: ``` class FollowingModel(models.Model): user = models.ForeignKey(User) person = models.IntegerField(max_length=20, blank=False) def __unicode__(self): return self.person ``` When I retrieve...
The [`__unicode__` method should return just that, unicode](http://docs.python.org/reference/datamodel.html#object.__unicode__): ``` def __unicode__(self): return unicode(self.person) ```
Broken prompt, simple if statements? (Python)
11,262,488
2
2012-06-29T13:14:24Z
11,262,524
7
2012-06-29T13:16:29Z
[ "python", "if-statement" ]
``` def prompt(): x = raw_input('Type a command: ') return x def nexus(): print 'Welcome to the Nexus,', RANK, '. Are you ready to fight?'; print 'Battle'; print 'Statistics'; print 'Shop'; command = prompt() if command == "Statistics" or "Stats" or "Stat": Statistics() eli...
The condition ``` command == "Statistics" or "Stats" or "Stat" ``` is always considered `True`. It either evaluates to `True` if `command` is `Statistics`, or it evaluates to `"Stats"`. You probably want ``` if command in ["Statistics", "Stats", "Stat"]: # ... ``` instead, or better ``` command = command.strip...
Where does __import__ get alias names from?
11,263,027
2
2012-06-29T13:50:15Z
11,263,077
11
2012-06-29T13:52:55Z
[ "python", "import", "alias" ]
Python allows aliasing of imports, through `...as <ALIAS>` clauses in the import statement, like this: ``` import mymodule as somealias from myothermodule import spam as spamalias, ham as hamalias ``` Now, in the default case at least, import statements, including those that have `as`-clauses like the ones above, res...
The function `__import__()` does not bind any names in the calling scope. Basically, ``` import foo ``` is similar to ``` foo = __import__("foo") ``` and ``` import foo as bar ``` is similar to ``` bar = __import__("foo") ``` Name binding happens in the calling scope, not inside the function, so `__import__()` ...
What is the Pythonic way to find the longest common prefix of a list of lists?
11,263,172
11
2012-06-29T13:58:23Z
11,263,863
12
2012-06-29T14:41:24Z
[ "python" ]
**Given**: a list of lists, such as `[[3,2,1], [3,2,1,4,5], [3,2,1,8,9], [3,2,1,5,7,8,9]]` **Todo**: Find the longest common prefix of all sublists. **Exists**: In another thread "[Common elements between two lists not using sets in Python](http://stackoverflow.com/questions/2727650/common-elements-between-two-lists-...
I am not sure how pythonic it is ``` from itertools import takewhile,izip x = [[3,2,1], [3,2,1,4,5], [3,2,1,8,9], [3,2,1,5,7,8,9]] def allsame(x): return len(set(x)) == 1 r = [i[0] for i in takewhile(allsame ,izip(*x))] ```
What is the Pythonic way to find the longest common prefix of a list of lists?
11,263,172
11
2012-06-29T13:58:23Z
21,419,164
21
2014-01-28T23:31:38Z
[ "python" ]
**Given**: a list of lists, such as `[[3,2,1], [3,2,1,4,5], [3,2,1,8,9], [3,2,1,5,7,8,9]]` **Todo**: Find the longest common prefix of all sublists. **Exists**: In another thread "[Common elements between two lists not using sets in Python](http://stackoverflow.com/questions/2727650/common-elements-between-two-lists-...
[`os.path.commonprefix()`](http://docs.python.org/2/library/os.path.html#os.path.commonprefix) works well for lists :) ``` >>> x = [[3,2,1], [3,2,1,4,5], [3,2,1,8,9], [3,2,1,5,7,8,9]] >>> import os >>> os.path.commonprefix(x) [3, 2, 1] ```
Using a RegEx to match IP addresses in Python
11,264,005
8
2012-06-29T14:50:46Z
11,264,056
16
2012-06-29T14:53:24Z
[ "python", "regex" ]
I'm trying to make a test for checking whether a sys.argv input matches the RegEx for an IP address... As a simple test, I have the following... ``` import re pat = re.compile("\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}") test = pat.match(hostIP) if test: print "Acceptable ip address" else: print "Unacceptable ip address...
You have to modify your regex in the following way ``` pat = re.compile("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$") ``` that's because `.` is a wildcard that stands for "every character"
Using a RegEx to match IP addresses in Python
11,264,005
8
2012-06-29T14:50:46Z
11,264,379
23
2012-06-29T15:13:38Z
[ "python", "regex" ]
I'm trying to make a test for checking whether a sys.argv input matches the RegEx for an IP address... As a simple test, I have the following... ``` import re pat = re.compile("\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}") test = pat.match(hostIP) if test: print "Acceptable ip address" else: print "Unacceptable ip address...
Using regex to validate IP address is a bad idea - this will pass 999.999.999.999 as valid. Try this approach using socket instead - much better validation and just as easy, if not easier to do. ``` import socket def valid_ip(address): try: socket.inet_aton(address) return True except: ...
Using a RegEx to match IP addresses in Python
11,264,005
8
2012-06-29T14:50:46Z
11,277,266
7
2012-06-30T20:05:01Z
[ "python", "regex" ]
I'm trying to make a test for checking whether a sys.argv input matches the RegEx for an IP address... As a simple test, I have the following... ``` import re pat = re.compile("\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}") test = pat.match(hostIP) if test: print "Acceptable ip address" else: print "Unacceptable ip address...
regex for ip v4: **^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$** otherwise you take not valid ip address like 999.999.999.999, 256.0.0.0 etc
Date ticks and rotation in matplotlib
11,264,521
46
2012-06-29T15:22:18Z
11,269,325
80
2012-06-29T21:40:03Z
[ "python", "matplotlib" ]
I am having an issue trying to get my date ticks rotated in matplotlib. A small sample program is below. If I try to rotate the ticks at the end, the ticks do not get rotated. If I try to rotate the ticks as shown under the comment 'crashes', then matplot lib crashes. This only happens if the x-values are dates. If I ...
Move plt.xticks(rotation=70) to right *before* the two avail\_plot calls, eg ``` plt.xticks(rotation=70) avail_plot(axs[0], dates, s1, 'testing', 'green') avail_plot(axs[1], dates, s1, 'testing2', 'red') ``` This sets the rotation property before setting up the labels. Since you have two axes here, I think plt.xticks...
Google Closure Linter not working in Sublime Text 2 for Windows
11,264,535
6
2012-06-29T15:23:13Z
11,295,337
8
2012-07-02T14:05:51Z
[ "javascript", "python", "google-closure-compiler", "sublimetext2" ]
Has anyone gotten the Google Closure Linter (**gjslint**) to work with Sublime Text 2 for Windows? When I run it I get the following (via Tools menu or CTRL+SHIFT+J): > The filename, directory name, or volume label syntax is incorrect. > > closure linter: ignored 0 errors. My steps were as follows: * Installed [Pyt...
I had the same issue on Windows 7. The only way i found to fix it was to remove the double quotes around the `gjslint` call **line 34** of `gjslint.py` inside the `sublime` package original (not working): ``` cmd = '"' + s.get('gjslint_path', 'jslint') + '" ' + s.get('gjslint_flags', '') + ' "' + file_path + '"' ```...
how to get the memory address of a numpy array for C
11,264,838
6
2012-06-29T15:41:48Z
11,266,170
9
2012-06-29T17:18:08Z
[ "python", "numpy" ]
I constructed an numpy array:: ``` a=np.ndarray([2,3]) ``` then i want to see where its data are:: ``` a.data >>>Out[213]: <read-write buffer for 0x0482C1D0, size 48, offset 0 at 0x049E87A0> a.data >>>Out[214]: <read-write buffer for 0x0482C1D0, size 48, offset 0 at 0x049E82A0> a.data >>>Out[215]: <read-write b...
Also, have a look at [`ndarray.__array_interface__`](http://docs.scipy.org/doc/numpy/reference/arrays.interface.html), which is a dict that contains all of the information you're after. In your case, ``` pointer, read_only_flag = a.__array_interface__['data'] ```
Define method aliases in Python?
11,264,923
11
2012-06-29T15:46:46Z
11,264,957
9
2012-06-29T15:49:00Z
[ "python", "class", "operator-overloading", "override", "operator-keyword" ]
I have a vector class and I defined the `__mul__` method to multiply a vector by a number. Here is the `__mul__` method : ``` def __mul__(self, other): x = self.x * other y = self.y * other new = Vector() new.set_pos((x, y)) return new ``` My problem is that I don't know which is which between th...
Simply list it as an attribute: ``` __rmul__ = __mul__ ``` This is the same way you'd create an alias of a function in a module; creating an alias of a method within a class body works the same.
Define method aliases in Python?
11,264,923
11
2012-06-29T15:46:46Z
11,265,050
13
2012-06-29T15:54:08Z
[ "python", "class", "operator-overloading", "override", "operator-keyword" ]
I have a vector class and I defined the `__mul__` method to multiply a vector by a number. Here is the `__mul__` method : ``` def __mul__(self, other): x = self.x * other y = self.y * other new = Vector() new.set_pos((x, y)) return new ``` My problem is that I don't know which is which between th...
`self` will never be the number in `__mul__()` because the object the method is attached to is not the number, it's the vector, and by definition it's the multiplicand. `other` will be a number if your object is being multiplied by a number. Or it could be something else, such as another vector, which you could test f...
Virtualenv not creating an environment
11,265,091
10
2012-06-29T15:56:43Z
11,265,655
9
2012-06-29T16:35:52Z
[ "python", "virtualenv", "virtualbox", "symlink", "shared-folders" ]
I installed Virtualenv on Ubuntu 12.04 and was using it to work on a sample project under the unity desktop. I'm using VirtualBox and was having some issues with the unity desktop so changed to the KDE desktop. I'm now trying to create a new project but the virtualenv won't allow me to create a new environment in my p...
Ok after a bit more in-depth googling found that this is a VirtualBox issue, not a Ubuntu problem. The shared folders are protected from this activity. I don't know how/why it worked the first time round but it is a known bug. I created a project outside of the shared folder with no problems. Thanks for the input Douga...
Virtualenv not creating an environment
11,265,091
10
2012-06-29T15:56:43Z
21,450,513
7
2014-01-30T07:43:40Z
[ "python", "virtualenv", "virtualbox", "symlink", "shared-folders" ]
I installed Virtualenv on Ubuntu 12.04 and was using it to work on a sample project under the unity desktop. I'm using VirtualBox and was having some issues with the unity desktop so changed to the KDE desktop. I'm now trying to create a new project but the virtualenv won't allow me to create a new environment in my p...
Ahti Kitsik posted a workaround on his blog: <http://ahtik.com/blog/fixing-your-virtualbox-shared-folder-symlink-error/> ``` VBoxManage setextradata YOURVMNAME VBoxInternal2/SharedFoldersEnableSymlinksCreate/YOURSHAREFOLDERNAME 1 ``` `YOURSHAREFOLDERNAME` is the name of the shared folder according to VirtualBox. If ...
Virtualenv not creating an environment
11,265,091
10
2012-06-29T15:56:43Z
24,353,494
7
2014-06-22T16:53:24Z
[ "python", "virtualenv", "virtualbox", "symlink", "shared-folders" ]
I installed Virtualenv on Ubuntu 12.04 and was using it to work on a sample project under the unity desktop. I'm using VirtualBox and was having some issues with the unity desktop so changed to the KDE desktop. I'm now trying to create a new project but the virtualenv won't allow me to create a new environment in my p...
Virtualenv is using symbolic links ([shutil.copytree](https://docs.python.org/2/library/shutil.html#shutil.copytree) uses them, see traceback). Creating symbolic links in a VirtualBox shared folder is disabled. Simple test in terminal: ``` $ ln -s testfile ``` Either you'll get a `failed to create symbolic link './te...
python plugin IPDB installation
11,265,358
2
2012-06-29T16:13:24Z
11,738,155
9
2012-07-31T10:33:15Z
[ "python" ]
I tried to install ipdb for debugging python, but after I downloaded ipdb0.61 and extracted it, there are only a few .py file. I don't know how to install it? I tried to run setup.py, it did not work. In the folder "IPDB" there are two py files: **main**.py and **init**.py. How should I install it? I know there is anot...
easy\_install should be able to install it for you by typing ``` easy_install ipdb ``` If you don't have setup\_tools get them from <http://pypi.python.org/pypi/setuptools/>
How can I vectorize this triple-loop over 2d arrays in numpy?
11,265,497
7
2012-06-29T16:23:23Z
11,265,642
9
2012-06-29T16:34:55Z
[ "python", "numpy", "linear-algebra", "vectorization" ]
Can I eliminate all Python loops in this computation: ``` result[i,j,k] = (x[i] * y[j] * z[k]).sum() ``` where `x[i]`, `y[j]`, `z[k]` are vectors of length `N` and `x`,`y`,`z` have first dimensions with length `A`,`B`,`C` s.t. output is shape `(A,B,C)` and each element is the sum of a triple-product (element-wise). ...
If you are using numpy > 1.6, there is the awesome `np.einsum` function: ``` np.einsum('im,jm,km->ijk',x,y,z) ``` Which is equivalent to your looped versions. I'm not sure how this will fair on efficiency once you get up to the size of your arrays in the real problem (I'm actually getting a segfault on my machine, wh...
How can I vectorize this triple-loop over 2d arrays in numpy?
11,265,497
7
2012-06-29T16:23:23Z
11,267,412
8
2012-06-29T18:52:27Z
[ "python", "numpy", "linear-algebra", "vectorization" ]
Can I eliminate all Python loops in this computation: ``` result[i,j,k] = (x[i] * y[j] * z[k]).sum() ``` where `x[i]`, `y[j]`, `z[k]` are vectors of length `N` and `x`,`y`,`z` have first dimensions with length `A`,`B`,`C` s.t. output is shape `(A,B,C)` and each element is the sum of a triple-product (element-wise). ...
Using [`einsum`](http://stackoverflow.com/a/11265642/577088) makes a lot of sense in your case; but you can do this pretty easily by hand. The trick is to make the arrays broadcastable against one another. That means reshaping them so that each array varies independently along its own axis. Then multiply them together,...
How do I export the output of Python's built-in help() function
11,265,603
8
2012-06-29T16:31:53Z
11,266,394
9
2012-06-29T17:35:24Z
[ "python" ]
I've got a python package which outputs considerable help text from: `help(package)` I would like to export this help text to a file, in the format in which it's displayed by `help(package)` How might I go about this?
pydoc.render\_doc(thing) to get thing's help text as a string. Other parts of pydoc like pydoc.text and pydoc.html can help you write it to a file. Using the `-w` modifier in linux will write the output to a html in the current directory, for example; ``` pydoc -w Rpi.GPIO ``` Puts all the `help()` text that would b...
Nicer way of method chaining in Python?
11,265,720
3
2012-06-29T16:41:23Z
11,265,771
12
2012-06-29T16:45:07Z
[ "python" ]
So I have a really long chain of methods, something similar to: ``` return self.append_command("fbghasjfa").append_command(input_file_part).append_command(output_video_codec_part).append_command(output_resolution_part).append_command(output_video_bitrate_part).append_command(strict_part).append_command(output_audio_co...
You can use backslash line continuation: ``` return self.append_command("ffasfgas") \ .append_command("fvasgvsd") \ .append_command("hsdhsdhsd") ``` or parentheses: ``` return (self.append_command("ffasfgas") .append_command("fvasgvsd") .append_command("hsdhsdhsd")) ``` But the most Pythonic...
PySide/PyQt - Starting a CPU intensive thread hangs the whole application
11,265,812
8
2012-06-29T16:47:37Z
11,265,981
8
2012-06-29T17:03:12Z
[ "python", "qt", "pyqt4", "pyside", "qthread" ]
I'm trying to do a fairly common thing in my PySide GUI application: I want to delegate some CPU-Intensive task to a background thread so that my GUI stays responsive and could even display a progress indicator as the computation goes. Here is what I'm doing (I'm using PySide 1.1.1 on Python 2.7, Linux x86\_64): ``` ...
This is probably caused by the worker thread holding Python's GIL. In some Python implementations, only one Python thread can execute at a time. The GIL prevents other threads from executing Python code, and is released during function calls that don't need the GIL. For example, the GIL is released during actual IO, s...
Compiling Python modules on Windows x64
11,267,463
11
2012-06-29T18:57:08Z
13,751,649
27
2012-12-06T20:07:20Z
[ "python", "visual-studio", "python-2.7", "compilation", "windows-7-x64" ]
I'm starting out some projects in words processing and I needed NumPy and NLTK. That was the first time I got to know `easy_install` and how to compile new module of python into the system. I have Python 2.7 x64 plus VS 11 and VS 12. Also Cygwin (the latest one I guess). I could see in the file that compiles using VS ...
***Update:** As [Zooba](http://stackoverflow.com/users/891/zooba) mentions below, [free x86 and AMD64 (x86-64) VC90 c-compilers for Python-2.7 are now available from Microsoft](http://www.microsoft.com/en-us/download/details.aspx?id=44266).* ***Update:** [Patch `vcvarsall.bat`](https://gist.github.com/mikofski/1102433...
Compiling Python modules on Windows x64
11,267,463
11
2012-06-29T18:57:08Z
27,065,853
11
2014-11-21T16:21:03Z
[ "python", "visual-studio", "python-2.7", "compilation", "windows-7-x64" ]
I'm starting out some projects in words processing and I needed NumPy and NLTK. That was the first time I got to know `easy_install` and how to compile new module of python into the system. I have Python 2.7 x64 plus VS 11 and VS 12. Also Cygwin (the latest one I guess). I could see in the file that compiles using VS ...
Since the other answers, Microsoft has released a compiler package specifically for building extensions for Python 2.7 (and any version of Python that used VS 2008/VC9). Here's how to use it: 1. Go to <http://aka.ms/vcpython27>, download and install the package (it's fairly small and does not require administrator rig...
Conceptual inquiry about __main__ in Python
11,267,751
2
2012-06-29T19:22:03Z
11,267,820
7
2012-06-29T19:27:25Z
[ "python", "function", "main", "conceptual" ]
I am currently working with Python and have been confused over the fact that functions are listed in `__main__`. I have been looking over multiple python scripts to try to find a common theme as to what functions warrant a place in `__main__`, but to no avail. Here I have a sample of my own code. `firstfunction` and `a...
It's not clear what you mean by "listed in `__main__`". `__main__` is not an entity in the source file. Rather, it is the *name* of the module, if you execute it directly. When you do `if __name__=="__main__"`, you are telling Python to execute the code in that block if and only if the code is being executed as the mai...
Efficient way to get highly correlated pairs from large data set in Python or R
11,268,822
4
2012-06-29T20:55:35Z
11,269,784
9
2012-06-29T22:34:36Z
[ "python", "algorithm" ]
I have a large data set (Let's say 10,000 variables with about 1000 elements each), we can think of it as 2D list, something like: ``` [[variable_1], [variable_2], ............ [variable_n] ] ``` I want to extract highly correlated variable pairs from that data. I want "highly correlated" to be a parameter that I ...
You didn't tell us how fast you need fast to be, so here's a naive solution. Simply compute the correlation matrix and then use `which` to get the indices of the pairs you're after: ``` x <- matrix(rnorm(10000*1000), ncol = 10000) corm <- cor(x) out <- which(abs(corm) > 0.80, arr.ind=TRUE) ``` You can then use subse...
How to hide output of subprocess in Python 2.7
11,269,575
133
2012-06-29T22:08:57Z
11,269,627
198
2012-06-29T22:15:36Z
[ "python", "python-2.7", "subprocess", "espeak" ]
I'm using eSpeak on Ubuntu and have a Python 2.7 script that prints and speaks a message: ``` import subprocess text = 'Hello World.' print text subprocess.call(['espeak', text]) ``` eSpeak produces the desired sounds, but clutters the shell with some errors (ALSA lib..., no socket connect) so i cannot easily read wh...
Redirect the output to DEVNULL: ``` import os import subprocess FNULL = open(os.devnull, 'w') retcode = subprocess.call(['echo', 'foo'], stdout=FNULL, stderr=subprocess.STDOUT) ``` It is effectively the same as running this shell command: ``` retcode = os.system("echo 'foo' &> /dev/null") ```
How to hide output of subprocess in Python 2.7
11,269,575
133
2012-06-29T22:08:57Z
11,270,665
47
2012-06-30T01:02:41Z
[ "python", "python-2.7", "subprocess", "espeak" ]
I'm using eSpeak on Ubuntu and have a Python 2.7 script that prints and speaks a message: ``` import subprocess text = 'Hello World.' print text subprocess.call(['espeak', text]) ``` eSpeak produces the desired sounds, but clutters the shell with some errors (ALSA lib..., no socket connect) so i cannot easily read wh...
Here's a more portable version (just for fun, it is not necessary in your case): ``` #!/usr/bin/env python # -*- coding: utf-8 -*- from subprocess import Popen, PIPE, STDOUT try: from subprocess import DEVNULL # py3k except ImportError: import os DEVNULL = open(os.devnull, 'wb') text = u"René Descartes"...
open file in python without file's full name?
11,270,184
3
2012-06-29T23:33:51Z
11,270,193
9
2012-06-29T23:35:34Z
[ "python" ]
I am trying to execute `f = open('filename')` in python. However, I dont know the full name of the file. All I know is that it starts with 's12' and ends with '.ka',I know the folder where it's located, and I know it is the only file in that folder that starts and ends with "s12" and ".ka". Is there a way to do this?
Glob is your friend: ``` from glob import glob filename = glob('s12*.ka')[0] ``` Careful though, glob returns a list of *all* files matching this pattern so you might want to assert that you get the file you actually want somehow.
python logging: Custom Python LogRecord Throwing an error
11,270,205
2
2012-06-29T23:36:34Z
11,271,334
8
2012-06-30T04:11:45Z
[ "python", "logging" ]
I am trying to use the python logging module to create a custom log file that records other information like host name and adds it to my DB. Below are the classes I created to do this, and the Handler part was working just fine, but now that I added a custom `LogRecord` class, it throws this error: ``` /src/lib/__init...
The error is telling you exactly what's wrong; you are calling the constructor with too many arguments. To see what I mean, take a look at how log-records are ordinarily constructed in the default implementation of `makeRecord`: ``` def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None)...
Why doesn't cv2 dilate actually affect my image?
11,270,937
6
2012-06-30T02:23:57Z
11,299,645
7
2012-07-02T19:02:53Z
[ "python", "opencv" ]
So, I'm generating a binary (well, really gray scale, 8bit, used as binary) image with python and opencv2, writing a small number of polygons to the image, and then dilating the image using a kernel. However, my source and destination image always end up the same, no matter what kernel I use. Any thoughts? ``` from ma...
So, it turns out the problem was in the creation of both the kernel and the image. I believe that openCV expects `'uint8'` as a data type for both the kernel and the image. In this particular case, I created the kernel with `dtype='int'`, which defaults to `'int64'`. Additionally, I created the image as `'int8'`, not `...
if else branching in jinja2
11,271,657
6
2012-06-30T05:19:07Z
11,271,726
10
2012-06-30T05:31:18Z
[ "python", "wsgi", "jinja2" ]
what sort of conditions can we use for branching in jinja2? I mean can we use python like statements. For example, I want to check the length of the caption. If bigger than 60 characters, I want to limit it to 60 characters and put "..." Right now, I'm doing something like this but it doesn't work. error.log reports th...
You're pretty close, you just have to move it to your Python script instead. So you can define a predicate like this: ``` def short_caption(someitem): return len(someitem) < 60 ``` Then register it on the environment by adding it to the 'tests' dict ): ``` your_environment.tests["short_caption"] = short_caption ...
the python x=x+x is 120 times slower than y=x+x?! why?
11,271,965
2
2012-06-30T06:20:37Z
11,272,034
11
2012-06-30T06:34:20Z
[ "python", "performance" ]
I recently used the timeit module to do a very simple performance test of the python. The result really stunned me: the time consumed by `x=x+x` is about **125 times** of `x+x` or `y=x+x,` why?! I really hope someone will give me some clue about this, maybe I used the timeit wrong? Thanks! Please notice that `y=x+x;x=...
When you compute `x=x+x` many thousands of times, `x` becomes a very large. You're measuring the length of time it takes to add two very large numbers.
How can I use GridLayout in Kivy?
11,272,708
2
2012-06-30T08:31:33Z
11,414,353
7
2012-07-10T13:27:02Z
[ "python", "kivy" ]
I want to use simple grid layout in my kivy program, but I don't appropriate example; here is my code: ``` import kivy from kivy.uix.gridlayout import GridLayout from kivy.app import App from kivy.uix.button import Button layout = GridLayout(cols=2, row_force_default=True, row_default_height=40) layout.add_wid...
You missed to create an initial App class, and run it: ``` import kivy from kivy.uix.gridlayout import GridLayout from kivy.app import App from kivy.uix.button import Button class MyApp(App): def build(self): layout = GridLayout(cols=2, row_force_default=True, row_default_height=40) layout.add_wid...
is twisted incompatible with multiprocessing events and queues?
11,272,874
5
2012-06-30T09:02:58Z
11,283,425
7
2012-07-01T15:50:15Z
[ "python", "twisted", "multiprocessing" ]
I am trying to simulate a network of applications that run using twisted. As part of my simulation I would like to synchronize certain events and be able to feed each process large amounts of data. I decided to use multiprocessing Events and Queues. However, my processes are getting hung. I wrote the example code belo...
The short answer is yes, Twisted and multiprocessing are not compatible with each other, and you cannot reliably use them as you are attempting to. On all POSIX platforms, child process management is closely tied to `SIGCHLD` handling. POSIX signal handlers are process-global, and there can be only one per signal type...
get the referer url in python/webapp2 for a post request
11,273,085
2
2012-06-30T09:36:34Z
11,291,345
13
2012-07-02T09:54:06Z
[ "python", "google-app-engine", "webapp2" ]
I want to get the referer url that has sent in the request to the server. I am using the webapp2 framework on appengine. when i do: ``` def post(self, slug): print self.request ``` i get the following output: ``` OST /first/person/ HTTP/1.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8...
As mentioned in your comment, this happens in webapp2, however if you want to redirect the user to the location from where the request has come, it can be as simple as: ``` webapp2.redirect(self.request.referer) ```
Stacked bar chart with differently ordered colors using matplotlib
11,273,196
4
2012-06-30T09:58:47Z
11,274,394
11
2012-06-30T13:22:42Z
[ "python", "charts", "matplotlib", "stacked" ]
I am a begginer of python. I am trying to make a horizontal barchart with differently ordered colors. I have a data set like the one in the below: ``` dataset = [{'A':19, 'B':39, 'C':61, 'D':70}, {'A':34, 'B':68, 'C':32, 'D':38}, {'A':35, 'B':45, 'C':66, 'D':50}, {'A':23, 'B':23, 'C':...
It's a long program, but it works, I added one dummy data to distinguish rows count and columns count: ``` import numpy as np from matplotlib import pyplot as plt dataset = [{'A':19, 'B':39, 'C':61, 'D':70}, {'A':34, 'B':68, 'C':32, 'D':38}, {'A':35, 'B':45, 'C':66, 'D':50}, {'A':23, ...
os.getcwd() vs os.path.abspath(os.path.dirname(__file__))
11,274,040
23
2012-06-30T12:22:52Z
11,274,226
23
2012-06-30T12:53:41Z
[ "python", "django" ]
I am using the os module to have relative paths in my Django projects `settings.py` file. The variable SITE\_ROOT is set to the current working directory of the `settings.py` file and then used to reference all of the `static/media` directories also located in that same directory. Heres my issue: ``` print os.getcwd(...
As mouad said, `os.getcwd()` won't give you exactly what you're expecting. `os.getcwd()` does a bit more than returning the current working directory. It default to $PWD in your env. It's not where the script is located but where you were when you executed the script. Being in `/home/user` and doing `python manage.py...
Determine the user language in Pyramid
11,274,420
13
2012-06-30T13:26:32Z
11,274,586
14
2012-06-30T13:52:35Z
[ "python", "localization", "pyramid" ]
I want to make internationalization for my project. I followed how it is described in official documentation, but localization still doesn't work. Here is how I try get user locale: ``` def get_locale_name(request): """ Return the :term:`locale name` associated with the current request (possibly cached).""" ...
Pyramid doesn't dictate how a locale should be negotiated. Basing your site language on the "Accept-Language" header can cause problems as most users do not know how to set their preferred browser languages. Make sure your users can switch languages easily and use a cookie to store that preference for future visits. Y...
Embed Python/Numpy/Matplotlib in a C++ Qt application?
11,275,407
7
2012-06-30T15:40:52Z
11,276,152
8
2012-06-30T17:31:32Z
[ "c++", "python", "qt", "matplotlib" ]
I am currently working on a small C++ Qt 4.8 (and 5.0 when it will be released) scientific application, and I would like to know if it is possible to embed Python+Numpy+Maptplotlib (and to have a portable app even for people without Python installed) in a C++ Qt application in order to make beautiful plots inside my ap...
The common way to deal with Python from C++ is with [Boost.Python](http://www.boost.org/doc/libs/1_50_0/libs/python/doc/), but it is possible to get along without it. What you need to remember is that the "Python interpreter" consists of two parts: The Python DLL/SO and the Python stdlib, both of which you will need t...
How do I write a regex to replace a word but keep its case in Python?
11,275,786
4
2012-06-30T16:37:21Z
11,275,862
8
2012-06-30T16:48:56Z
[ "python", "regex" ]
Is this even possible? Basically, I want to turn these two calls to sub into a single call: ``` re.sub(r'\bAword\b', 'Bword', mystring) re.sub(r'\baword\b', 'bword', mystring) ``` What I'd really like is some sort of conditional substitution notation like: ``` re.sub(r'\b([Aa])word\b', '(?1=A:B,a:b)word') ``` I on...
You can have functions to parse every match: ``` >>> def f(match): return chr(ord(match.group(0)[0]) + 1) + match.group(0)[1:] >>> re.sub(r'\b[aA]word\b', f, 'aword Aword') 'bword Bword' ```
Request a simple alembic working example for Auto Generating Migrations
11,276,017
10
2012-06-30T17:12:49Z
11,280,521
18
2012-07-01T08:20:54Z
[ "python", "orm", "sqlalchemy", "data-migration", "alembic" ]
I installed alembic 0.3.4, sqlalchemy, SQLite version 3.7.4, and upgraded SQLAlchemy 0.6.4 to SQLAlchemy 0.7 or greater from my ubuntu. I followed the instruction: <http://alembic.readthedocs.org/en/latest/tutorial.html> Now I am testing: Auto Generating Migrations I have created a package: schemas, and a package mark...
I also found that Alembic couldn't find my model modules. As a workaround, I found that, by adding the following to my `env.py` before importing my models, I could force it to work: ``` import os, sys sys.path.append(os.getcwd()) ``` This is probably not the best solution, but it got Alembic to autogenerate my migrat...
Append to a dict of lists with a dict comprehension
11,276,473
4
2012-06-30T18:13:47Z
11,276,513
7
2012-06-30T18:18:52Z
[ "python", "dictionary" ]
Suppose I have a large list of words. For an example: ``` >>> with open('/usr/share/dict/words') as f: ... words=[word for word in f.read().split('\n') if word] ``` If I wanted to build an index by first letter of this word list, this is easy: ``` d={} for word in words: if word[0].lower() in 'aeiou': ...
No - dict comprehensions are designed to generate non-overlapping keys with each iteration; they don't support aggregation. For this particular use case, a loop is the proper way to accomplish the task efficiently (in linear time).
run a simple python script in ios
11,276,656
2
2012-06-30T18:37:37Z
11,421,536
9
2012-07-10T20:37:24Z
[ "python", "xcode", "methods" ]
I want to run a python script on ios. I don't want to write the whole Application in Python just a little part of it. I have tried to understand PyObjC but it is not that easy. Could you give me an example, please? I would like to save the result for the following method in a `NSString` variable. ``` def doSomething...
Here is an example of calling a function defined in `myModule`. The equivient python would be: ``` import myModule pValue = myModule.doSomething() print pValue ``` In Objective-c: ``` #include <Python.h> - (void)example { PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pValue; NSString *nsString; ...
How do I emit a PySide signal with a custom python type argument?
11,277,068
4
2012-06-30T19:35:59Z
11,278,687
7
2012-07-01T00:25:27Z
[ "python", "qt", "signals-slots", "pyside" ]
I am having trouble correctly using signals in my PySide python Qt program. I want to emit a signal that takes a single argument of a custom python type. The [documentation](http://www.pyside.org/docs/pyside-git/newsigslot.html) says > Signals can be defined using the QtCore.signal() class. Python types > and C types ...
You created an ["old-style class"](http://docs.python.org/reference/datamodel.html#new-style-and-classic-classes), which apparently isn't supported as a signal parameter type. The class should inherit from another new-style class, or from the base `object` type: ``` class Foo(object): pass ```
How to remove a key from a python dictionary?
11,277,432
527
2012-06-30T20:27:59Z
11,277,439
897
2012-06-30T20:29:18Z
[ "python", "dictionary" ]
When trying to delete a key from a dictionary, I write: ``` if 'key' in myDict: del myDict['key'] ``` Is there a one line way of doing this?
Use [`dict.pop()`](http://docs.python.org/library/stdtypes.html#dict.pop): ``` my_dict.pop('key', None) ``` This will return `my_dict[key]` if `key` exists in the dictionary, and `None` otherwise. If the second parameter is not specified (ie. `my_dict.pop('key')`) and `key` does not exist, a `KeyError` is raised.
How to remove a key from a python dictionary?
11,277,432
527
2012-06-30T20:27:59Z
11,277,484
154
2012-06-30T20:36:44Z
[ "python", "dictionary" ]
When trying to delete a key from a dictionary, I write: ``` if 'key' in myDict: del myDict['key'] ``` Is there a one line way of doing this?
Specifically to answer "is there a one line way of doing this?" ``` if 'key' in myDict: del myDict['key'] ``` ...well, you *asked* ;-) You should consider, though, that this way of deleting an object from a `dict` is [not atomic](http://stackoverflow.com/q/17326067/722332)—it is possible that `'key'` may be in `my...
How to remove a key from a python dictionary?
11,277,432
527
2012-06-30T20:27:59Z
15,206,537
85
2013-03-04T16:43:20Z
[ "python", "dictionary" ]
When trying to delete a key from a dictionary, I write: ``` if 'key' in myDict: del myDict['key'] ``` Is there a one line way of doing this?
It took me some time to figure out what exactly `my_dict.pop("key", None)` is doing. So I'll add this as an answer to save others googling time: > pop(key[, default]) > > If key is in the dictionary, remove it and return its value, else > return default. If default is not given and key is not in the > dictionary, a Ke...
python 2 code: if python 3 then sys.exit()
11,277,721
17
2012-06-30T21:14:17Z
11,277,768
33
2012-06-30T21:20:56Z
[ "python", "python-3.x", "python-2.x" ]
I have a large piece of Python 2 only code. It want to check for Python 3 at the beginning, and exit if python3 is used. So I tried: ``` import sys if sys.version_info >= (3,0): print("Sorry, requires Python 2.x, not Python 3.x") sys.exit(1) print "Here comes a lot of pure Python 2.x stuff ..." ### a lot of ...
Python will byte-compile your source file before starting to execute it. The whole file must at least *parse* correctly, otherwise you will get a `SyntaxError`. The easiest solution for your problem is to write a small wrapper that parses as both, Python 2.x and 3.x. Example: ``` import sys if sys.version_info >= (3,...
How to create file with open function in Python?
11,278,738
3
2012-07-01T00:39:48Z
11,278,766
9
2012-07-01T00:44:07Z
[ "python", "linux", "file" ]
In Linux environment, I want to create a file and write text into it: ``` HTMLFILE: "$MYUSER/OUTPUT/myfolder/mytext.html" f = open(HTMLFILE, 'w') IOError: [Errno 2] No such file or directory: "$MYUSER/OUTPUT/myfolder/mytext.html" ``` I have read/write permission do "$MYUSER/OUTPUT/myfolder/" directories. Why do I g...
`os.path.expandvars()` can help: ``` f = open(os.path.expandvars(HTMLFILE), 'w') ``` `open` only deals with actual file names. `expandvars` can expand environment variables in strings.
to read line from file in python without getting "\n" appended at the end
11,280,282
11
2012-07-01T07:31:49Z
11,280,329
24
2012-07-01T07:39:37Z
[ "python", "linux", "file-io", "ubuntu-10.04" ]
My file is "xml.txt" with following contents: ``` books.xml news.xml mix.xml ``` if I use readline() function it appends "\n" at the name of all the files which is an error because I want to open the files contained within the xml.txt. I wrote this: ``` fo = open("xml.tx","r") for i in range(count.__len__()): #here...
To remove just the newline at the end: ``` line = line.rstrip('\n') ``` The reason `readline` keeps the newline character is so you can distinguish between an empty line (has the newline) and the end of the file (empty string).
Python Mongodb Pymongo Json encoding and decoding
11,280,382
7
2012-07-01T07:52:12Z
11,286,259
8
2012-07-01T22:58:46Z
[ "python", "json", "mongodb", "flask", "pymongo" ]
I'm having some trouble with Mongodb and Python (Flask). I have this api.py file, and I want all requests and responses to be in JSON, so I implement as such. ``` # # Imports # from datetime import datetime from flask import Flask from flask import g from flask import jsonify from flask import json from flask import...
When you pass `db.units.find()` to `response` you pass a [`pymongo.cursor.Cursor`](http://api.mongodb.org/python/current/api/pymongo/cursor.html) object to `json.dumps` ... and `json.dumps` doesn't know how to serialize it to JSON. Try getting the actual objects by iterating over the cursor to get its results: ``` [do...
Python Mongodb Pymongo Json encoding and decoding
11,280,382
7
2012-07-01T07:52:12Z
11,286,988
25
2012-07-02T01:33:30Z
[ "python", "json", "mongodb", "flask", "pymongo" ]
I'm having some trouble with Mongodb and Python (Flask). I have this api.py file, and I want all requests and responses to be in JSON, so I implement as such. ``` # # Imports # from datetime import datetime from flask import Flask from flask import g from flask import jsonify from flask import json from flask import...
While @ErenGüven shows you a nice manual approach to solving this json serializing issue, pymongo comes with a [utility to accomplish this for you](http://api.mongodb.org/python/1.4/api/pymongo/json_util.html). I use this in my own django mongodb project: ``` import json from bson import json_util json_docs = [] for...
How can I add the corresponding elements of several lists of numbers?
11,280,536
11
2012-07-01T08:23:40Z
11,280,545
26
2012-07-01T08:25:28Z
[ "python" ]
I have some lists of numbers: ``` [1, 2, 3, 4, 5] [2, 3, 4, 5, 6] [3, 4, 5, 6, 7] ``` How can I add these lists' elements, assuming that all of the lists that I'm using are the same length? Here's the kind of output I'd like to get from doing this to the above lists. ``` [6, 9, 12, 15, 18] ``` I know that I'll nee...
Try this functional style code: ``` >>> map(sum, zip(*lists)) [6, 9, 12, 15, 18] ``` The [`zip`](http://docs.python.org/library/functions.html#zip) function matches elements with the same index. ``` >>> zip(*lists) [(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7)] ``` Then [`sum`](http://docs.python.org/libra...
Best way to get query string from a URL in python?
11,280,948
14
2012-07-01T09:36:04Z
11,281,019
40
2012-07-01T09:49:58Z
[ "python", "django", "comparison", "urlencode", "urlparse" ]
I have this url = <http://stackoverflow.com/questions/ask?next=1&value=3> Now I need to get the query string from this url. I don;t wanna use request.META for getting query string. How ever I figured it out that there are two more ways to get the query string 1. **Using urlparse** Use urlparse.urlparse(url).query d...
Third option: ``` >>> from urlparse import urlparse, parse_qs >>> url = 'http://something.com?blah=1&x=2' >>> urlparse(url).query 'blah=1&x=2' >>> parse_qs(urlparse(url).query) {'blah': ['1'], 'x': ['2']} ```
Best way to get query string from a URL in python?
11,280,948
14
2012-07-01T09:36:04Z
11,281,362
24
2012-07-01T10:55:10Z
[ "python", "django", "comparison", "urlencode", "urlparse" ]
I have this url = <http://stackoverflow.com/questions/ask?next=1&value=3> Now I need to get the query string from this url. I don;t wanna use request.META for getting query string. How ever I figured it out that there are two more ways to get the query string 1. **Using urlparse** Use urlparse.urlparse(url).query d...
You can make Query string using GET parameters like this ``` request.GET.urlencode() ```
Best way to get query string from a URL in python?
11,280,948
14
2012-07-01T09:36:04Z
22,276,999
14
2014-03-09T00:40:03Z
[ "python", "django", "comparison", "urlencode", "urlparse" ]
I have this url = <http://stackoverflow.com/questions/ask?next=1&value=3> Now I need to get the query string from this url. I don;t wanna use request.META for getting query string. How ever I figured it out that there are two more ways to get the query string 1. **Using urlparse** Use urlparse.urlparse(url).query d...
I prefer using ``` request.META['QUERY_STRING'] ``` From docs: <https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.META>
Python dynamic class methods
11,281,698
4
2012-07-01T11:48:20Z
11,281,744
11
2012-07-01T11:56:03Z
[ "python", "runtime", "class-method" ]
Say there is: ``` class A(B): ... ``` where `B` could be `object` and `...` is **not**: ``` @classmethod # or @staticmethod def c(cls): print 'Hello from c!' ``` What do I have to do that calling `A.c()` wont trigger `AttributeError`? In other words, I know it is possible to manually add class methods to a cla...
You can achieve this by using a [`__getattr__` hook](http://docs.python.org/reference/datamodel.html#object.__getattr__) on a [metaclass](http://docs.python.org/reference/datamodel.html#customizing-class-creation). ``` class DefaultClassMethods(type): def __getattr__(cls, attr): def _defaultClassMethod(cls...
Bottle web framework - How to stop?
11,282,218
14
2012-07-01T13:07:59Z
16,056,443
7
2013-04-17T09:30:48Z
[ "python", "bottle" ]
When starting a bottle webserver without a thread or a subprocess, there's no problem. To exit the bottle app -> `CTRL` + `c`. In a thread, how can I **programmatically** stop the bottle web server ? I didn't find a `stop()` method or something like that in the documentation. Is there a reason ?
For the default (WSGIRef) server, this is what I do (actually it is a cleaner approach of Vikram Pudi's suggestion): ``` from bottle import Bottle, ServerAdapter class MyWSGIRefServer(ServerAdapter): server = None def run(self, handler): from wsgiref.simple_server import make_server, WSGIRequestHandl...
Can I fake/mock the type of my mock objects in python unittests
11,282,401
5
2012-07-01T13:33:38Z
11,283,173
16
2012-07-01T15:16:16Z
[ "python", "unit-testing", "mocking" ]
In my python code I check the type of one of the parameters to make sure it is of the type I expect, like ``` def myfunction(dbConnection): if (type(dbConnection)<>bpgsql.Connection): r['error'] += ' invalid database connection' ``` now I want to pass a mock connection for testing purposes, is there a way...
With all due respect, It looks like you guys are not quite right! I can use duck typing as said, but there is a way to do what I intended to do in the first place: from <http://docs.python.org/dev/library/unittest.mock.html> Mock objects that use a class or an instance as a spec or spec\_set are able to pass isintan...
python random.shuffle() in a while loop
11,282,655
3
2012-07-01T14:12:58Z
11,282,671
8
2012-07-01T14:14:32Z
[ "python", "python-3.x" ]
I have a list: ``` k = [1,2,3,4,5] ``` Now I want 3 permutations of this list to be listed in another list but when I do this: ``` x = [] i = 0 while i < 3: random.shuffle(k) x.append(k) i += 1 ``` I end up with 3 times the same permutation of k in x, like this: ``` x = ...
Shuffling a list changes it in-place, and you are creating 3 references to the same list. Create a *copy* of the list before shuffling: ``` x = [] for i in range(3): kcopy = k[:] random.shuffle(kcopy) x.append(kcopy) ``` I've simplified your loop as well; just use `for i in range(3)`. Or, to place this in...
memory error in python
11,283,220
11
2012-07-01T15:22:21Z
11,284,642
8
2012-07-01T18:34:27Z
[ "python", "memory" ]
``` Traceback (most recent call last): File "/run-1341144766-1067082874/solution.py", line 27, in main() File "/run-1341144766-1067082874/solution.py", line 11, in main if len(s[i:j+1]) > 0: MemoryError Error in sys.excepthook: Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/apport_python_hoo...
This one here: ``` s = raw_input() a=len(s) for i in xrange(0, a): for j in xrange(0, a): if j >= i: if len(s[i:j+1]) > 0: sub_strings.append(s[i:j+1]) ``` seems to be very inefficient and expensive for large strings. Better do ``` for i in xrange(0, a): for j in xrange(i...
partial string formatting
11,283,961
47
2012-07-01T17:00:01Z
11,284,021
9
2012-07-01T17:06:33Z
[ "python", "string-formatting" ]
Is it possible to do partial string formatting with the advanced string formatting methods, similar to the string template `safe_substitute()` function? For example: ``` s = '{foo} {bar}' s.format(foo='FOO') #Problem: raises KeyError 'bar' ```
If you define your own `Formatter` which overrides the `get_value` method, you could use that to map undefined field names to whatever you wanted: <http://docs.python.org/library/string.html#string.Formatter.get_value> For instance, you could map `bar` to `"{bar}"` if `bar` isn't in the kwargs. However, that require...
partial string formatting
11,283,961
47
2012-07-01T17:00:01Z
11,284,026
26
2012-07-01T17:07:17Z
[ "python", "string-formatting" ]
Is it possible to do partial string formatting with the advanced string formatting methods, similar to the string template `safe_substitute()` function? For example: ``` s = '{foo} {bar}' s.format(foo='FOO') #Problem: raises KeyError 'bar' ```
You can trick it into partial formatting by overwriting the mapping: ``` import string class FormatDict(dict): def __missing__(self, key): return "{" + key + "}" s = '{foo} {bar}' formatter = string.Formatter() mapping = FormatDict(foo='FOO') print(formatter.vformat(s, (), mapping)) ``` printing ``` FO...
partial string formatting
11,283,961
47
2012-07-01T17:00:01Z
18,343,661
40
2013-08-20T19:39:51Z
[ "python", "string-formatting" ]
Is it possible to do partial string formatting with the advanced string formatting methods, similar to the string template `safe_substitute()` function? For example: ``` s = '{foo} {bar}' s.format(foo='FOO') #Problem: raises KeyError 'bar' ```
If you know in what order you're formatting things: ``` s = '{foo} {{bar}}' ``` Use it like this: ``` ss = s.format(foo='FOO') print ss >>> 'FOO {bar}' print ss.format(bar='BAR') >>> 'FOO BAR' ``` You can't specify `foo` and `bar` at the same time - you have to do it sequentially.
partial string formatting
11,283,961
47
2012-07-01T17:00:01Z
23,305,496
19
2014-04-26T01:25:42Z
[ "python", "string-formatting" ]
Is it possible to do partial string formatting with the advanced string formatting methods, similar to the string template `safe_substitute()` function? For example: ``` s = '{foo} {bar}' s.format(foo='FOO') #Problem: raises KeyError 'bar' ```
This limitation of `.format()` - the inability to do partial substitutions - has been bugging me. After evaluating writing a custom `Formatter` class as described in many answers here and even considering using third-party packages such as [lazy\_format](https://pypi.python.org/pypi/lazy_format), I discovered a much s...
partial string formatting
11,283,961
47
2012-07-01T17:00:01Z
29,490,102
8
2015-04-07T11:07:26Z
[ "python", "string-formatting" ]
Is it possible to do partial string formatting with the advanced string formatting methods, similar to the string template `safe_substitute()` function? For example: ``` s = '{foo} {bar}' s.format(foo='FOO') #Problem: raises KeyError 'bar' ```
Not sure if this is ok as a quick workaround, but how about ``` s = '{foo} {bar}' s.format(foo='FOO', bar='{bar}') ``` ? :)
How to do multiple arguments with Python Popen?
11,284,147
2
2012-07-01T17:23:43Z
11,309,864
22
2012-07-03T11:22:19Z
[ "python", "pygtk", "subprocess", "popen", "gnome-terminal" ]
I am trying to make a PyGtk Gui, that has a button. When the user presses this button, `gnome-terminal` prompts the user to write their password. Then it will clone this [Git repository](https://github.com/pererinha/gedit-snippet-jquery) for `gedit` JQuery snippets. And then, it copies the `js.xml` file to `/usr/shar...
To directly answer your question, read below. But there's a lot of problems with your program, some of which I cover in "Better practice." --- By default, [`subprocess.Popen`](https://docs.python.org/2/library/subprocess.html#subprocess.Popen) commands are supplied as a list of strings. However, you can also you can...
try ... except ... as error in Python 2.5 - Python 3.x
11,285,313
20
2012-07-01T20:17:56Z
11,285,562
30
2012-07-01T20:54:03Z
[ "python", "exception", "try-catch" ]
I want to keep & use the error value of an exception in both Python 2.5, 2.7 and 3.2. In Python 2.5 and 2.7 (but not 3.x), this works: ``` try: print(10 * (1/0)) except ZeroDivisionError, error: # old skool print("Yep, error caught:", error) ``` In Python 2.7 and 3.2 (but not in 2.5), this works: ```...
You can use one code base on Pythons 2.5 through 3.2, but it isn't easy. You can take a look at [coverage.py](http://bitbucket.org/ned/coveragepy), which runs on 2.3 through 3.3 with a single code base. The way to catch an exception and get a reference to the exception that works in all of them is this: ``` except Va...
Recommended way to manage credentials with multiple AWS accounts?
11,286,479
15
2012-07-01T23:44:47Z
11,294,256
8
2012-07-02T13:02:35Z
[ "python", "amazon-web-services", "boto" ]
What is the best way to manage multiple Amazon Web Services (AWS) accounts through `boto`? I am familiar with [BotoConfig](http://docs.pythonboto.org/en/latest/boto_config_tut.html) files, which I'm using. But each file describes only a single account...and I am working with more than just the one organization. For al...
In the future, boto will provide better tools to help you manage multiple credentials but at the moment, there are a couple of environment variables that might help out. First, you can set BOTO\_CONFIG to point to a boto config file that you want to use and it will override any config file found in the normal location...
Recommended way to manage credentials with multiple AWS accounts?
11,286,479
15
2012-07-01T23:44:47Z
21,345,540
42
2014-01-25T01:48:47Z
[ "python", "amazon-web-services", "boto" ]
What is the best way to manage multiple Amazon Web Services (AWS) accounts through `boto`? I am familiar with [BotoConfig](http://docs.pythonboto.org/en/latest/boto_config_tut.html) files, which I'm using. But each file describes only a single account...and I am working with more than just the one organization. For al...
**updated 2015-02-06, corrected 2015-03-19** by following top section # New standardized sharing of boto and AWSCLI credentials (boto>==2.29.0) Since boto 2.29 there is new easy way for sharing BOTO and AWS CLI credentials as described by Mike Garnaat in [A New and Standardized Way to Manage Credentials in the AWS SD...
How do I specify a single test in a file with nosetests?
11,286,688
49
2012-07-02T00:26:29Z
11,286,817
76
2012-07-02T00:58:19Z
[ "python", "testcase", "nosetests" ]
I have a file called test\_web.py containing a class TestWeb and many methods named like test\_something(). I can run every test in the class like so: ``` $ nosetests test_web.py ... ====================================================================== FAIL: checkout test -------------------------------------------...
You must specify it like so: `nosetests <file>:<Test_Case>.<test_method>`, or ``` nosetests test_web.py:TestWeb.test_checkout ``` See [the docs](http://nose.readthedocs.org/en/latest/usage.html#selecting-tests)
How do I specify a single test in a file with nosetests?
11,286,688
49
2012-07-02T00:26:29Z
18,332,546
7
2013-08-20T10:19:17Z
[ "python", "testcase", "nosetests" ]
I have a file called test\_web.py containing a class TestWeb and many methods named like test\_something(). I can run every test in the class like so: ``` $ nosetests test_web.py ... ====================================================================== FAIL: checkout test -------------------------------------------...
You can also specify a module: ``` nosetests tests.test_integration:IntegrationTests.test_user_search_returns_users ```
Is there a way to check if NumPy arrays share the same data?
11,286,864
27
2012-07-02T01:09:32Z
11,286,976
22
2012-07-02T01:30:34Z
[ "python", "numpy" ]
My impression is that in NumPy, two arrays can share the same memory. Take the following example: ``` import numpy as np a=np.arange(27) b=a.reshape((3,3,3)) a[0]=5000 print (b[0,0,0]) #5000 #Some tests: a.data is b.data #False a.data == b.data #True c=np.arange(27) c[0]=5000 a.data == c.data #True ( Same data, not ...
You can use the [base](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.base.html) attribute to check if an array shares the memory with another array: ``` >>> import numpy as np >>> a = np.arange(27) >>> b = a.reshape((3,3,3)) >>> b.base is a True >>> a.base is b False ``` Not sure if that solves yo...
Is there a way to check if NumPy arrays share the same data?
11,286,864
27
2012-07-02T01:09:32Z
11,287,440
8
2012-07-02T03:16:09Z
[ "python", "numpy" ]
My impression is that in NumPy, two arrays can share the same memory. Take the following example: ``` import numpy as np a=np.arange(27) b=a.reshape((3,3,3)) a[0]=5000 print (b[0,0,0]) #5000 #Some tests: a.data is b.data #False a.data == b.data #True c=np.arange(27) c[0]=5000 a.data == c.data #True ( Same data, not ...
I think jterrace's answer is probably the best way to go, but here is another possibility. ``` def byte_offset(a): """Returns a 1-d array of the byte offset of every element in `a`. Note that these will not in general be in order.""" stride_offset = np.ix_(*map(range,a.shape)) element_offset = sum(i*s ...
Why should I use operator.itemgetter(x) instead of [x]?
11,287,207
17
2012-07-02T02:25:32Z
11,287,216
14
2012-07-02T02:27:27Z
[ "python", "operators" ]
There is a more general question here: [In what situation should the built-in `operator` module be used in python?](http://stackoverflow.com/questions/467920/in-what-situation-should-the-built-in-operator-module-be-used-in-python) The top answer claims that `operator.itemgetter(x)` is "neater" than, presumably, than `...
You shouldn't worry about performance unless your code is in a tight inner loop, and is actually a performance problem. Instead, use code that best expresses your intent. Some people like lambdas, some like itemgetter. Sometimes it's just a matter of taste. `itemgetter` is more powerful, for example, if you need to ge...