title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Python regex:combining re pattern format with a variable
8,667,454
5
2011-12-29T11:45:37Z
8,667,505
14
2011-12-29T11:50:25Z
[ "python", "regex" ]
I would like to combine a python variable and pattern. How can I do it? below is what I would like to do. ``` re.search(r'**some_variable+pattern**',str_for_pattern_match,flags) ``` Thanks for your help.
The usual string formatting way works well ``` re.search(r'**%s+pattern**' % some_variable, str_for_pattern_match, flags) ```
MySQL database being hit too many times with django query
8,667,705
2
2011-12-29T12:09:23Z
8,668,355
8
2011-12-29T13:16:42Z
[ "python", "mysql", "django" ]
I'm using django-favorites to pull the list of objects faved by a user. The app has a model and a manager ``` class FavoriteManager(models.Manager): """ A Manager for Favorites """ def favorites_for_user(self, user): """ Returns Favorites for a specific user """ return self.get_quer...
You can decide between several solutions: 1. **Generic relation pre-fetching**, you can use [this snippet](http://djangosnippets.org/snippets/1079/) like this [example app](https://github.com/justquick/django-activity-stream/blob/master/actstream/gfk.py). 2. **Identity map/caching**, use the content type and object id...
Python 3 string.join() equivalent?
8,668,152
20
2011-12-29T12:57:11Z
8,668,177
26
2011-12-29T12:59:07Z
[ "python", "string", "methods", "python-3.x" ]
I've been using string.join() method in python 2 but it seems like it has been removed in python 3. What is the equivalent method in python 3? string.join() method let me combine multiple strings together with a string in between every other string. For example, string.join(("a", "b", "c"), ".") would result "a.b.c".
`'.'.join()` or `".".join()`.. So any string *instance* has the method `join()`
Python 3 string.join() equivalent?
8,668,152
20
2011-12-29T12:57:11Z
8,668,179
9
2011-12-29T12:59:10Z
[ "python", "string", "methods", "python-3.x" ]
I've been using string.join() method in python 2 but it seems like it has been removed in python 3. What is the equivalent method in python 3? string.join() method let me combine multiple strings together with a string in between every other string. For example, string.join(("a", "b", "c"), ".") would result "a.b.c".
There are method `join` for string objects: `".".join(("a","b","c"))`
Python 3 string.join() equivalent?
8,668,152
20
2011-12-29T12:57:11Z
21,122,866
7
2014-01-14T20:02:28Z
[ "python", "string", "methods", "python-3.x" ]
I've been using string.join() method in python 2 but it seems like it has been removed in python 3. What is the equivalent method in python 3? string.join() method let me combine multiple strings together with a string in between every other string. For example, string.join(("a", "b", "c"), ".") would result "a.b.c".
`str.join()` works fine in Python 3, you just need to get the order of the arguments correct ``` >>> str.join('.', ('a', 'b', 'c')) 'a.b.c' ```
Python argparse positional arguments and sub-commands
8,668,519
10
2011-12-29T13:35:14Z
8,671,961
7
2011-12-29T18:41:54Z
[ "python", "argparse", "subcommand", "positional-operator" ]
I'm working with argparse and am trying to mix sub-commands and positional arguments, and the following issue came up. This code runs fine: ``` import argparse parser = argparse.ArgumentParser() subparsers = parser.add_subparsers() parser.add_argument('positional') subparsers.add_parser('subpositional') parser.pars...
At first I thought the same as jcollado, but then there's the fact that, if the subsequent (top level) positional arguments have a specific `nargs` (`nargs` = `None`, `nargs` = integer), then it works as you expect. It fails when `nargs` is `'?'` or `'*'`, and sometimes when it is `'+'`. So, I went down to the code, to...
Get emails with Python and pop lib
8,669,202
6
2011-12-29T14:40:46Z
8,669,293
14
2011-12-29T14:48:45Z
[ "python", "email", "poplib" ]
I would like to log into my account with Python and get python to print the messages I received in my mail box. I know how to connect ``` import getpass, poplib user = 'my_user_name' Mailbox = poplib.POP3_SSL('pop.googlemail.com', '995') Mailbox.user(user) Mailbox.pass_('my_password') ``` but then I don't know how...
Using the POP3 example [from the docs](http://docs.python.org/library/poplib.html#pop3-example): ``` import getpass, poplib user = 'my_user_name' Mailbox = poplib.POP3_SSL('pop.googlemail.com', '995') Mailbox.user(user) Mailbox.pass_('my_password') numMessages = len(Mailbox.list()[1]) for i in range(numMessages): ...
Get emails with Python and pop lib
8,669,202
6
2011-12-29T14:40:46Z
8,669,459
8
2011-12-29T15:05:02Z
[ "python", "email", "poplib" ]
I would like to log into my account with Python and get python to print the messages I received in my mail box. I know how to connect ``` import getpass, poplib user = 'my_user_name' Mailbox = poplib.POP3_SSL('pop.googlemail.com', '995') Mailbox.user(user) Mailbox.pass_('my_password') ``` but then I don't know how...
You have not posted your source code, but here is my response: How to get the total number of messages: ``` (numMsgs, totalSize) = self.conn_pop3.stat() ``` **How to get a specific message, knowing its number in the mailbox:** ``` (server_msg, body, octets) = self.conn_pop3.retr(number) ``` So the function you mig...
Alternative for scipy.stats.norm.pdf?
8,669,235
3
2011-12-29T14:43:48Z
8,669,381
7
2011-12-29T14:58:00Z
[ "python", "math", "scipy", "normal-distribution" ]
Does anyone know of an alternative for scipy.stats.norm.pdf()? I'm hosting my python site on Google App Engine and Google doesn't support SciPy. I've tried this function, but that didn't return the same results as scipy: ``` def normpdf(x, mu, sigma): u = (x-mu)/abs(sigma) y = (1/(sqrt(2*pi)*abs(sigma)))*exp(...
You got tricked by pythons integer division arithmetics! Here is some working code: ``` from __future__ import division import scipy.stats from numpy import * def normpdf(x, mu, sigma): u = (x-mu)/abs(sigma) y = (1/(sqrt(2*pi)*abs(sigma)))*exp(-u*u/2) return y print scipy.stats.norm.pdf(20, 20, 10) pri...
Indices of k-minimum values along an axis of a numpy array
8,669,261
4
2011-12-29T14:46:03Z
8,669,461
7
2011-12-29T15:05:19Z
[ "python", "arrays", "numpy", "indices", "minim" ]
Is there a way to return the indices of k-minimum values along an axis of a numpy array without using loops?
``` import numpy as np x = np.array([[5, 2, 3],[1, 9, 2]]) # example data k = 2 # return the indices of the 2 smallest values np.argsort(x, axis=1)[:,0:k] # by row array([[1, 2], [0, 2]]) ```
Error to execute python-scrappy module
8,671,071
4
2011-12-29T17:25:18Z
9,731,858
13
2012-03-16T04:24:12Z
[ "python", "web-scraping", "scrapy" ]
I am getting the error while executing the python-scrappy sample module My Stacktrace: ``` gridlex@gridlex-laptop:~/Documents/tutorial$ scrapy crawl tutorial/dmoz /usr/lib/python2.6/dist-packages/zope/__init__.py:3: UserWarning: Module twisted was already imported from /usr/lib/python2.6/dist-packages/twisted/__...
Debian or Ubuntu (9.04 or older) If you’re running Debian Linux, run the following command as root: ``` apt-get install python-twisted python-libxml2 python-pyopenssl python-simplejson ``` Then: ``` easy_install -U w3lib ``` And then follow the instructions in Install Scrapy.
pythonic way to iterate over part of a list
8,671,280
32
2011-12-29T17:44:04Z
8,671,323
31
2011-12-29T17:47:39Z
[ "python" ]
I want to iterate over everything in a list except the first few elements, e.g.: ``` for line in lines[2:]: foo(line) ``` This is concise, but copies the whole list, which is unnecessary. I could do: ``` del lines[0:2] for line in lines: foo(line) ``` But this modifies the list, which isn't always good. I ...
You can try [`itertools.islice(iterable[, start], stop[, step])`](http://docs.python.org/library/itertools.html#itertools.islice): ``` import itertools for line in itertools.islice(list , start, stop): foo(line) ```
Passing list of parameters to SQL in psycopg2
8,671,702
18
2011-12-29T18:21:04Z
8,671,854
30
2011-12-29T18:34:14Z
[ "python", "postgresql", "psycopg2" ]
I have a list of ids of rows to fetch from database. I'm using python and psycopg2, and my problem is how to effectively pass those ids to SQL? I mean that if I know the length of that list, it is pretty easy because I can always manually or automatically add as many "%s" expressions into query string as needed, but he...
Python tuples are converted to sql lists in psycopg2: ``` cur.mogrify("SELECT * FROM table WHERE column IN %s;", ((1,2,3),)) ``` would output ``` 'SELECT * FROM table WHERE column IN (1,2,3);' ```
Matplotlib: avoiding overlapping datapoints in a "scatter/dot/beeswarm" plot
8,671,808
14
2011-12-29T18:30:18Z
21,276,920
18
2014-01-22T07:40:47Z
[ "python", "charts", "matplotlib" ]
When drawing a dot plot using matplotlib, I would like to offset overlapping datapoints to keep them all visible. For examples, if I have ``` CategoryA: 0,0,3,0,5 CategoryB: 5,10,5,5,10 ``` I want each of the `CategoryA` "0" datapoints to be set side by side, rather than right on top of each other, while still rema...
Extending the answer by @user2467675, here's how I did it: ``` def rand_jitter(arr): stdev = .01*(max(arr)-min(arr)) return arr + np.random.randn(len(arr)) * stdev def jitter(x, y, s=20, c='b', marker='o', cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, hold=None, **kwargs...
How to show the error messages caught by assertRaises() in unittest in Python2.7?
8,672,754
31
2011-12-29T19:57:04Z
8,673,096
21
2011-12-29T20:34:36Z
[ "python", "unit-testing" ]
In order to make sure that the error messages from my module are informative, I would like to see all the error messages caught by assertRaises(). Today I do it for each assertRaises(), but as there are lots of them in the test code it gets very tedious. How can I print the error messages for all the assertRaises()? I...
Out-of-the-box `unittest` doesn't do this. If this is something you want to do frequently, you can try something like this: ``` class ExtendedTestCase(unittest.TestCase): def assertRaisesWithMessage(self, msg, func, *args, **kwargs): try: func(*args, **kwargs) self.assertFail() except Exception ...
How to show the error messages caught by assertRaises() in unittest in Python2.7?
8,672,754
31
2011-12-29T19:57:04Z
9,965,090
43
2012-04-01T14:22:09Z
[ "python", "unit-testing" ]
In order to make sure that the error messages from my module are informative, I would like to see all the error messages caught by assertRaises(). Today I do it for each assertRaises(), but as there are lots of them in the test code it gets very tedious. How can I print the error messages for all the assertRaises()? I...
I once preferred the most excellent answer given above by @Robert Rossney. Nowadays, I prefer to use assertRaises as a context manager (a new capability in unittest2) like so: ``` with self.assertRaises(TypeError) as cm: failure.fail() self.assertEqual( 'The registeraddress must be an integer. Given: 1.0', ...
How to show the error messages caught by assertRaises() in unittest in Python2.7?
8,672,754
31
2011-12-29T19:57:04Z
16,282,604
21
2013-04-29T15:33:59Z
[ "python", "unit-testing" ]
In order to make sure that the error messages from my module are informative, I would like to see all the error messages caught by assertRaises(). Today I do it for each assertRaises(), but as there are lots of them in the test code it gets very tedious. How can I print the error messages for all the assertRaises()? I...
You are looking for [assertRaisesRegexp](http://docs.python.org/2/library/unittest.html#unittest.TestCase.assertRaisesRegexp), which is available since Python 2.7. From the docs: ``` self.assertRaisesRegexp(ValueError, 'invalid literal for.*XYZ$', int, 'XYZ') ``` or: ``` with self.assertRaisesRegexp(ValueError, 'lit...
Detecting a repeating cycle in a sequence of numbers (python)
8,672,853
8
2011-12-29T20:10:58Z
8,672,966
15
2011-12-29T20:23:08Z
[ "python", "numbers", "sequence", "cycle" ]
I was wondering what would be a a fairly 'common' or normal way of doing this. Wasn't really looking for the shortest possible answer like a 2-liner or anything. I've just quickly put this piece of code together but I can't not feel like there's way too much in there. Also if there are any libraries that could help wit...
I may not be properly understanding this, but I think there is a very simple solution with regex. ``` (.+ .+)( \1)+ ``` Here is an example: ``` >>> regex = re.compile(r'(.+ .+)( \1)+') >>> match = regex.search('3 0 5 5 1 5 1 6 8') >>> match.group(0) # entire match '5 1 5 1' >>> match.group(1) # repeating porti...
transitive closure python tuples
8,673,482
10
2011-12-29T21:08:14Z
8,674,062
9
2011-12-29T22:07:16Z
[ "python", "closures" ]
Does anyone know if there's a python builtin for computing transitive closure of tuples? I have tuples of the form `(1,2),(2,3),(3,4)` and I'm trying to get `(1,2),(2,3),(3,4),(1,3)(2,4)` Thanks.
There's no builtin for transitive closures. They're quite simple to implement though. Here's my take on it: ``` def transitive_closure(a): closure = set(a) while True: new_relations = set((x,w) for x,y in closure for q,w in closure if q == y) closure_until_now = closure | new_relations ...
Sampling from bivariate normal in python
8,674,832
2
2011-12-29T23:48:42Z
8,674,948
10
2011-12-30T00:23:35Z
[ "python", "numpy", "distribution", "random-sample" ]
I'm trying to create two random variables which are correlated with one another, and I believe the best way is to draw from a bivariate normal distribution with given parameters (open to other ideas). The uncorrelated version looks like this: ``` import numpy as np sigma = np.random.uniform(.2, .3, 80) theta = np.rand...
Use the built-in: <http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.multivariate_normal.html> ``` >>> import numpy as np >>> mymeans = [13,5] >>> # stdevs = sqrt(5),sqrt(2) >>> # corr = .3 / (sqrt(5)*sqrt(2) = .134 >>> mycov = [[5,.3], [.3,2]] >>> np.cov(np.random.multivariate_normal(mymeans,mycov...
Price of switching control between C++ and Python
8,675,062
8
2011-12-30T00:46:32Z
8,675,112
7
2011-12-30T00:54:22Z
[ "c++", "python", "performance" ]
I'm developing a C++ application that is extended/ scriptable with Python. Of course C++ is much faster than Python, in general, but does that necessarily mean that you should prefer to execute C++ code over Python code as often as possible? I'm asking this because I'm not sure, is there any performance cost of switch...
I don't know there is a concrete rule for this, but a general rule that many follow is to: * Prototype in python. This is quicker to write, and *may be* easier to read/reason about. * Once you have a prototype, you can now identify the slow portions that should be written in c++ (through profiling). * Depending on the...
In python - the operator which a set uses for test if an object is in the set
8,675,105
10
2011-12-30T00:53:02Z
8,675,150
9
2011-12-30T01:01:18Z
[ "python", "object", "set", "override" ]
If I have a list of objects, I can use the `__cmp__` method to override objects are compared. This affects how the `==` operator works, and the `item in list` function. However, it doesn't seem to affect the `item in set` function - I'm wondering how I can change the MyClass object so that I can override the behaviour ...
`set` uses `__hash__` for comparison. Override that, and you'll be good: ``` class MyClass(object): def __init__(self, s): self.s = s def __cmp__(self, other): return cmp(self.s, other.s) def __hash__(self): return hash(self.s) # Use default hash for 'self.s' instance1, instance2 =...
How to use "map" function in Python? (How to rewrite a for loop?)
8,675,431
4
2011-12-30T01:53:16Z
8,675,445
9
2011-12-30T01:55:54Z
[ "python", "map" ]
I have an array of classes and I want to create objects of them. This works: ``` classArray = [Auto, Wheel] objectArray = [] for myClass in classArray: objectArray += [myClass()] ``` Can I use the map function to accomplish the same? ``` objectArray = map( ??? , classArray) ``` My apologies ...
You could use a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions) instead. Many consider them to be preferred over the `map` function. ``` objectArrray = [ c() for c in classArray ] ``` --- If you insist on using `map`, you can do ``` map(lambda c: c(), classArray) ``` H...
getting 64 bit integer in python
8,676,682
2
2011-12-30T06:05:55Z
8,676,794
14
2011-12-30T06:23:25Z
[ "python", "integer", "bit" ]
So I am thinking of writing a bitboard in python or lisp. But I don't know how to ensure I would get a 64 bit integer in python. I have been reading documentation and found that mpz library returns a unsigned 32 bit integer. Is this true? If not what should I do?
Python 2 has two integer types: `int`, which is a signed integer whose size equals your machine's word size (but is always at least 32 bits), and `long`, which is unlimited in size. Python 3 has only one integer type, which is called `int` but is equivalent to a Python 2 `long`.
better django model design
8,676,924
3
2011-12-30T06:44:27Z
8,677,197
8
2011-12-30T07:23:55Z
[ "python", "django", "django-models" ]
Here is my situation: I have a django model: ``` class Invoice(models.Model): invoiceid = models.CharField(max_length=20) totalamount = models.DecimalField(max_digits=15,decimal_places=2,default=0) downpayment = models.DecimalField(max_digits=15,decimal_places=2,default=0) subtotal = models.DecimalFie...
You could create an abstract base class and have both models inherit from it: ``` class InvoiceAbstract(models.Model): invoiceid = models.CharField(max_length=20) totalamount = models.DecimalField(max_digits=15,decimal_places=2,default=0) downpayment = models.DecimalField(max_digits=15,decimal_places=2,def...
Django model error- "TypeError: 'xxx' is an invalid keyword argument for this function
8,677,750
8
2011-12-30T08:53:38Z
8,677,873
25
2011-12-30T09:09:59Z
[ "python", "django", "django-models" ]
I get the error: ``` TypeError: 'person' is an invalid keyword argument for this function ``` My model is: ``` class Investment(models.Model): company = models.ManyToManyField("Company", related_name ="Investments_company") financial_org = models.ManyToManyField("Financial_org", related_name ="Investments_financial_...
1. **Instanciate your model without many to many**, `investment1 = Investment()` 2. **Save your model**, `investment1.save()` 3. **Add many to many**, there are [several ways to do it](https://docs.djangoproject.com/en/1.3/ref/models/relations/) like `investment1.person.add(person_model)` or `investment1.person.create(...
Gevent monkeypatching breaking multiprocessing
8,678,307
16
2011-12-30T10:04:42Z
14,736,531
11
2013-02-06T18:50:08Z
[ "python", "multiprocessing", "gevent" ]
I am attempting to use multiprocessing's pool to run a group of processes, each of which will run a gevent pool of greenlets. The reason for this is that there is a lot of network activity, but also a lot of CPU activity, so to maximise my bandwidth and all of my CPU cores, I need multiple processes AND gevent's async ...
use `monkey.patch_all(thread=False, socket=False)` I have run into the same issue in a similar situation and tracked this down to line 115 in `gevent/monkey.py` under the `patch_socket()` function: `_socket.socket = socket.socket`. Commenting this line out prevents the breakage. This is where gevent replaces the stdl...
Gevent monkeypatching breaking multiprocessing
8,678,307
16
2011-12-30T10:04:42Z
14,819,934
7
2013-02-11T20:06:17Z
[ "python", "multiprocessing", "gevent" ]
I am attempting to use multiprocessing's pool to run a group of processes, each of which will run a gevent pool of greenlets. The reason for this is that there is a lot of network activity, but also a lot of CPU activity, so to maximise my bandwidth and all of my CPU cores, I need multiple processes AND gevent's async ...
Application of multiprocessing in the context of gevent is unfortunately known to raise problems. Your rationale, however, is reasonable ("a lot of network activity, but also a lot of CPU activity"). If you like, have a look at <http://gehrcke.de/gipc>. This is designed primarily for your use case. With gipc, you can e...
Best practices for coding simple mathematical calculations in Python
8,678,428
4
2011-12-30T10:19:17Z
8,678,521
13
2011-12-30T10:31:31Z
[ "math", "coding-style", "python", "python-2.7" ]
I need to perform simple mathematical calculations in Python 2.7 with sums, subtractions, divisions, multiplications, sums over lists of numbers etc. I want to write elegant, bullet-proof, and efficient code but I must admit I got confused by several things, for example: * if I have `1/(N-1)*x` in my equation should ...
1. If you use Python 2.7, **ALWAYS** use `from __future__ import division`. It removes a hell of a lot confusion and bugs. With this you should never have to worry if a division is a float or not, `/` will always be a float and `//` will always be an int. 2. You should convert your input with `float()`. You will do...
Python free variables.Why does this fail?
8,678,745
5
2011-12-30T11:01:32Z
8,678,788
7
2011-12-30T11:04:43Z
[ "python", "function", "variables", "binding" ]
The following code prints 123: ``` >>> a = 123 >>> def f(): ... print a ... >>> f() 123 >>> ``` But the following fails: ``` >>> a = 123 >>> def f(): ... print a ... a = 456 ... print a ... >>> f() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in f...
If a function only reads from a variable, it's assumed to be global. If the function writes to it ever, it's assumed to be local. In your second function, a is written to, so it's assumed to be local. Then the line above (where it's read from) isn't valid. Here's a link to the Python FAQ: <http://docs.python.org/faq/p...
Binding <Return> to button is not working as expected
8,679,453
5
2011-12-30T12:29:44Z
8,679,841
11
2011-12-30T13:17:18Z
[ "python", "button", "tkinter", "bind" ]
I bound the event `<Return>` to a Button, thinking that this would cause the `command` to be run after hitting `Enter`: ``` Button(self.f, text="Print", command=self.Printer).pack(side=RIGHT, padx=10, pady=10) self.button1 = Button(self.f, text="search", command=self.search) self.button1.bind('<Return>', self.search) ...
Your code looks fine, but note that the focus must be on the button if you want `Return` to call `self.search()`. You can change the focus from widget to widget by pressing `Tab`. The widget in focus is outlined with a thin black line. You may have to press `Tab` one or more times to move the focus to the button before...
Drag and drop with Sikuli
8,679,929
4
2011-12-30T13:27:08Z
14,054,539
10
2012-12-27T12:15:14Z
[ "python", "drag-and-drop", "sikuli" ]
I am having trouble using drag and drop with Sikuli. I would like to drag something in any other direction (up, down, left, right) for a fixed number of pixels. This looks like it should work: ``` t = find("1325249963143.png") dragDrop(t, [t.x + 100, t.y + 100]) ``` Sikuli IDE log says ``` [log] DRAG (741,525) to n...
only to say hello here - an alternative coding: ``` dragDrop(t, t.offset(Location(100, 100)) ```
Why are Python strings immutable? Best practices for using them
8,680,080
25
2011-12-30T13:45:24Z
8,680,110
31
2011-12-30T13:48:33Z
[ "python", "string", "immutability" ]
1. What are the design reasons of making Python strings immutable? How does it make programming easier? 2. I'm used to mutable strings, like the ones in C. How am I supposed to program without mutable strings? Are there any best practices?
When you receive a string, you'll be sure that it stays the same. Suppose that you'd construct a `Foo` as below with a string argument, and would then modify the string; then the `Foo`'s name would suddenly change: ``` class Foo(object): def __init__(self, name): self.name = name name = "Hello" foo = Foo(...
FFT in Matlab and numpy / scipy give different results
8,680,909
10
2011-12-30T15:16:22Z
8,681,764
12
2011-12-30T16:43:21Z
[ "python", "matlab", "numpy", "scipy", "fft" ]
I am trying to re-implement one of the matlab toolboxes. they use fft over there. when i perform same operation on the same data i get different results to those from matlab. Just take a look: **MATLAB**: ``` Msig = 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 ...
Matlab applies the fft over the columns of the matrix, numpy applies the fft over the last axis (the rows) by default. You want: ``` >>> np.fft.fft(Msig.T, axis=0) array([[ 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j], [ 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.-1.j, 0.+0.j], [ 0.+0.j, 0.+0.j, 0....
Python: variables scope and profile.run
8,682,716
4
2011-12-30T18:32:40Z
8,682,791
10
2011-12-30T18:40:19Z
[ "python", "variables", "scope", "profile" ]
I want to call profile.run within my function, i.e.: ``` def g(): ... def f(): x = ... run.profile('g(x)') ``` However, it says 'x is not defined' when calling run.profile. As far as I understand, I have to supply import statement before calling g(x) inside string argument to run.profile, and I could do t...
Instead of using `run()` use `runctx()` which allows you to supply locals and globals. For example: ``` >>> import cProfile >>> def g(x): ... print "g(%d)" % x ... >>> x=100 >>> cProfile.runctx('g(x)', {'x': x, 'g': g}, {}) g(100) 3 function calls in 0.000 CPU seconds Ordered by: standard name ncal...
When do I need to call mainloop in a Tkinter application?
8,683,217
27
2011-12-30T19:27:43Z
8,685,760
26
2011-12-31T01:54:57Z
[ "python", "tkinter" ]
Every tkinter tutorial I have seen claims that `tkinter.mainloop` must be called for windows to be drawn and events to be processed, and they always call this function, even in hello world programs. However, when I try these out in the interactive shell, windows are drawn correctly without having to call mainloop. [Thi...
The answer to your main question is, you must call mainloop once and only once, when you are ready for your application to run. `mainloop` is really nothing more than an infinite loop that looks roughly like this (those aren't the actual names of the methods, the names merely serve to illustrate the point): ``` while...
Understanding NLTK collocation scoring for bigrams and trigrams
8,683,588
12
2011-12-30T20:09:16Z
8,684,029
21
2011-12-30T20:57:18Z
[ "python", "nlp", "nltk" ]
**Background:** I am trying to compare pairs of words to see which pair is "more likely to occur" in US English than another pair. My plan is/was to use the collocation facilities in NLTK to score word pairs, with the higher scoring pair being the most likely. **Approach:** I coded the following in Python using NLTK...
The NLTK collocations document seems pretty good to me. <http://nltk.googlecode.com/svn/trunk/doc/howto/collocations.html> You need to give the scorer some actual sizable corpus to work with. Here is a working example using the Brown corpus built into NLTK. It takes about 30 seconds to run. ``` import nltk.collocatio...
works in IDLE but not the command prompt
8,684,002
2
2011-12-30T20:53:54Z
8,684,050
7
2011-12-30T21:00:39Z
[ "python" ]
This code works in IDLE but not in the commandline. Why the difference? ``` poem = 'poem.txt' f = file(poem) while True: line = f.readline() if len(line) == 0: break print line, f.close() ``` The `poem.txt` file exists (it is a string). The shell output is this: ``` "Programming is fun When the ...
I believe you are not RUNNING the python script from the same directory as the poem.txt is in. Verify this by putting: ``` import os print os.getcwd() ``` in your script. ### Update It seems like I was right. When you run: `C:/Users/Python/filepractice.py` the current working directory is the directory you are runn...
Use html5lib to convert an HTML fragment to plain text
8,685,332
4
2011-12-31T00:19:29Z
8,685,425
12
2011-12-31T00:37:05Z
[ "python", "html", "html5lib" ]
Is there an easy way to use the Python library html5lib to convert something like this: ``` <p>Hello World. Greetings from <strong>Mars.</strong></p> ``` to ``` Hello World. Greetings from Mars. ```
With `lxml` as the parser backend: ``` import html5lib body = "<p>Hello World. Greetings from <strong>Mars.</strong></p>" doc = html5lib.parse(body, treebuilder="lxml") print doc.text_content() ``` To be honest, this is actually cheating, as it is equivalent to the following (only the relevant parts are changed): `...
How do I run long term (infinite) Python processes?
8,685,695
20
2011-12-31T01:39:40Z
8,685,815
19
2011-12-31T02:07:38Z
[ "python", "apache", "daemon", "infinite-loop" ]
I've recently started experimenting with using Python for web development. So far I've had some success using Apache with mod\_wsgi and the Django web framework for Python 2.7. However I have run into some issues with having processes constantly running, updating information and such. I have written a script I call "d...
I'll open by stating that this is *one* way to manage a long running process (LRP) -- not de facto by any stretch. In my experience, the best possible product comes from concentrating on the specific problem you're dealing with, while delegating supporting tech to other libraries. In this case, I'm referring to the ac...
adding header to python request module
8,685,790
18
2011-12-31T02:02:08Z
8,685,813
36
2011-12-31T02:07:16Z
[ "python", "http-headers", "python-requests" ]
Earlier I used `httplib` module to add header in the request. Now I am trying same thing with the request module. This is the python request module I am using: <http://pypi.python.org/pypi/requests> How can I add header to the `request.post` and `request.get` say I have to add `foobar` key in each request in header.
From <http://docs.python-requests.org/en/latest/user/quickstart/> ``` url = 'https://api.github.com/some/endpoint' payload = {'some': 'data'} headers = {'content-type': 'application/json'} r = requests.post(url, data=json.dumps(payload), headers=headers) ``` You just need to create a dict with your headers (key: val...
Python: Writing a dictionary to a csv file with one line for every 'key: value'
8,685,809
37
2011-12-31T02:06:27Z
8,685,873
77
2011-12-31T02:22:01Z
[ "python", "csv", "dictionary" ]
I've got a dictionary: `mydict = {key1: value_a, key2: value_b, key3: value_c}` I want to write the data to a file dict.csv, in this style: ``` key1: value_a key2: value_b key3: value_c ``` I wrote: ``` import csv f = open('dict.csv','wb') w = csv.DictWriter(f,mydict.keys()) w.writerow(mydict) f.close() ``` But n...
The `DictWriter` doesn't work the way you expect. ``` with open('dict.csv', 'wb') as csv_file: writer = csv.writer(csv_file) for key, value in mydict.items(): writer.writerow([key, value]) ``` To read it back: ``` with open('dict.csv', 'rb') as csv_file: reader = csv.reader(csv_file) mydict = ...
Python, hstack column numpy arrays (column vectors) of different types
8,685,994
4
2011-12-31T02:54:29Z
8,686,079
8
2011-12-31T03:23:04Z
[ "python", "numpy" ]
I currently have a numpy multi-dimensional array (of type float) and a numpy column array (of type int). I want to combine the two into a mutli-dimensional numpy array. ``` import numpy >> dates.shape (1251,) >> data.shape (1251,10) >> test = numpy.hstack((dates, data)) ValueError: all the input arrays must have same...
``` import numpy as np np.column_stack((dates, data)) ``` The types are cast automatically to the most precise, so your int array will be converted to float.
How to select Python code block using Vim?
8,686,159
15
2011-12-31T03:54:23Z
8,686,480
20
2011-12-31T05:22:11Z
[ "python", "vim" ]
I can use `vi{` and `va{` to select C++ code blocks. It helps me a lot when I need to yank/delete them. But Python uses indentation to indicate code blocks. I cannot find any better way. Any ideas?
I have not had much of an occasion to use it yet, but Michael Smith’s [vim-indent-object](http://www.vim.org/scripts/script.php?script_id=3037) sounds like it may be close to what you want. Example usage (line numbers shown as with `set number` active): ``` 1 This is 2 some text 3 with multiple 4 le...
Pythonic way to pass keyword arguments on conditional
8,686,225
9
2011-12-31T04:12:22Z
8,686,243
13
2011-12-31T04:20:39Z
[ "python" ]
Is there a more pythonic way to do this? ``` if authenticate: connect(username="foo") else: connect(username="foo", password="bar", otherarg="zed") ```
1. You could add them to a list of kwargs like this: ``` connect_kwargs = dict(username="foo") if authenticate: connect_kwargs['password'] = "bar" connect_kwargs['otherarg'] = "zed" connect(**connect_kwargs) ``` This can sometimes be helpful when you have a complicated set of options tha...
Validate a filename in python
8,686,880
6
2011-12-31T07:04:25Z
8,686,943
8
2011-12-31T07:24:27Z
[ "python", "filenames" ]
I'm writing a personal wiki-style program in python that stores text-files in a user configurable directory. The program should be able to take a string (e.g. "foo") from a user and create a filename of foo.txt. The user will only be able to create the file inside the wiki directory, and slashes will create a subdir (...
You can enforce the user to create a file/directory inside wiki by normalizing the path with [os.path.normpath](http://docs.python.org/library/os.path.html) and then checking if the path begins with say '(path-to-wiki)' ``` os.path.normpath('(path-to-wiki)/foo/bar.txt').startswith('(path-to-wiki)') ``` To ensure that...
Python image processing : Help needed for corner detection in preferably PIL or any relevant module
8,686,926
7
2011-12-31T07:19:55Z
9,173,430
28
2012-02-07T08:59:33Z
[ "python", "image-processing", "python-imaging-library" ]
I'm new to image processing and got to do corner detection for this image: ![enter image description here](http://i.stack.imgur.com/N9H4v.png) In this image, I need to extract the starting and end points of each line segment or the coordinates of the corners. This is just a small part in my project and I'm stuck on th...
Here's a solution, using [scikit-image](http://scikit-image.org): ``` from skimage import io, color, morphology from scipy.signal import convolve2d import numpy as np import matplotlib.pyplot as plt img = color.rgb2gray(io.imread('6EnOn.png')) # Reduce all lines to one pixel thickness snakes = morphology.skeletonize...
Python string replace two things at once?
8,687,018
21
2011-12-31T07:44:36Z
8,687,035
13
2011-12-31T07:49:29Z
[ "python", "string" ]
Say I have a string, "ab" I want to replace "a" with "b" and "b" with "a" in one swoop. So the end string should say "ba" and not "aa" or "bb" and not use more than one line. Is this doable?
``` import string "abaababb".translate(string.maketrans("ab", "ba")) # result: 'babbabaa' ``` Note that this only works for one-character substitutions. For longer substrings or substitutions, this is a bit complex, but might work: ``` import re def replace_all(repls, str): # return re.sub('|'.join(repls.keys()...
Python string replace two things at once?
8,687,018
21
2011-12-31T07:44:36Z
8,687,380
27
2011-12-31T09:24:10Z
[ "python", "string" ]
Say I have a string, "ab" I want to replace "a" with "b" and "b" with "a" in one swoop. So the end string should say "ba" and not "aa" or "bb" and not use more than one line. Is this doable?
When you need to swap variables, say *x* and *y*, a common pattern is to introduce a temporary variable *t* to help with the swap: `t = x; x = y; y = t`. The same pattern can also be used with strings: ``` >>> # swap a with b >>> 'obama'.replace('a', '%temp%').replace('b', 'a').replace('%temp%', 'b') 'oabmb' ``` Thi...
How to write a tuple of tuples to a CSV file using Python
8,687,568
3
2011-12-31T10:25:01Z
8,687,607
8
2011-12-31T10:32:37Z
[ "python", "csv", "tuples" ]
I have a tuple of tuples ``` import csv A = (('Max', 3 ,' M'),('bob',5,'M'),('jane',6,'F')) result = open("newfile.csv",'wb') writer = csv.writer(result, dialect = 'excel') writer.writerow(A) result.close ``` This writes a CSV file with rows with A[0], A[1] and A[2] . What i want is a row with name, age and gender , ...
Write all rows at once: ``` writer.writerows(A) ``` instead of ``` writer.writerow(A) ``` File newfile.csv looks now like this: ``` Max,3, M bob,5,M jane,6,F ``` Also, add `()` to your last line, it is a function call: `result.close()`. If you are on Python 2.6 or newer, you can use this form: ``` import csv A ...
PyQt:How do I display a image properly?
8,687,723
9
2011-12-31T11:02:13Z
8,687,918
10
2011-12-31T11:46:01Z
[ "python", "pyqt" ]
I want to display an image in pyqt so,i used a label and the pixmap option,and the scaledContents but the image is distorted.Should I use another widget or do something else? Thanks. This is the code: ``` from PyQt4 import QtCore, QtGui self.label.setPixmap(QtGui.QPixmap(_fromUtf8('image.jpg'))) self.label.setScaledC...
Use the `scaled(const QSize, Qt::AspectRatioMode, Qt::TransformationMode)` method of the pixmap, it has an option `Qt::KeepAspectRatio` that does not deform the image. The default is to ignore the aspect ratio Also, note that the `scaled` method returns the scaled `pixmap`, so it must be used this way: ``` myPixmap =...
Python OpenCV SVM implementation
8,687,885
9
2011-12-31T11:37:43Z
8,693,200
12
2012-01-01T12:59:03Z
[ "python", "opencv", "classification", "svm" ]
So I have a matrix with my sample images (all turned into vectors) which was run trough PCA/LDA, and a vector which denotes the class each images belongs to. Now I want to use the OpenCV SVM class to train my SVM (I am using Python, OpenCV 2.3.1). But I have a problem with defining the parameters: ``` test = cv2.SVM()...
To use OpenCV machine learning algorithms, you have to write some wrapper classes: **1. First parent class** ``` class StatModel(object): '''parent class - starting point to add abstraction''' def load(self, fn): self.model.load(fn) def save(self, fn): self.model.save(fn) ``` **2. Fin...
Python multi-inheritance, __init__
8,688,114
24
2011-12-31T12:36:27Z
8,688,121
8
2011-12-31T12:38:19Z
[ "python", "oop", "inheritance", "init", "super" ]
Regarding multiple parent inheritance, when I call the `super`.`__init__`, why doesn't parent2's `__init__` function get called? Thanks. ``` class parent(object): var1=1 var2=2 def __init__(self,x=1,y=2): self.var1=x self.var2=y class parent2(object): var4=11 var5=12 def __init...
Because `parent` is next in [method resolution order (MRO)](https://www.python.org/download/releases/2.3/mro/), and it never uses `super()` to call into `parent2`.
Python multi-inheritance, __init__
8,688,114
24
2011-12-31T12:36:27Z
8,688,123
25
2011-12-31T12:38:28Z
[ "python", "oop", "inheritance", "init", "super" ]
Regarding multiple parent inheritance, when I call the `super`.`__init__`, why doesn't parent2's `__init__` function get called? Thanks. ``` class parent(object): var1=1 var2=2 def __init__(self,x=1,y=2): self.var1=x self.var2=y class parent2(object): var4=11 var5=12 def __init...
If you want to use `super` in `child` to call `parent.__init__` and `parent2._init__`, then both parent `__init__`s must also call `super`: ``` class parent(Base): def __init__(self,x=1,y=2): super(parent,self).__init__(x,y) class parent2(Base): def __init__(self,x=3,y=4): super(parent2,sel...
virtualenv on windows 7 returns AssertionError
8,688,709
7
2011-12-31T14:43:39Z
8,688,733
11
2011-12-31T14:46:53Z
[ "python", "windows-7", "virtualenv" ]
Having trouble with virtualenv on Windows 7. I run: ``` virtualenv _testenv ``` It returns: ``` Traceback (most recent call last): File "C:\Python27\Scripts\virtualenv-script.py", line 9, in <module> load_entry_point('virtualenv==1.5.2', 'console_scripts', 'virtualenv')() File "C:\Python27\lib\site-packages...
Try to set `PYTHONPATH` to `PYTHONPATH=C:\Python27;C:\Python27\Lib` (uppercase C at the start). This can be done at the command prompt by typing `set PYTHONPATH=C:\Python27;C:\Python27\Lib`. `PYTHONPATH` will revert back to whatever it previously was once that command prompt window is closed.
Django-compressor: how to write to S3, read from CloudFront?
8,688,815
16
2011-12-31T15:04:32Z
8,888,930
30
2012-01-17T02:22:33Z
[ "python", "django", "amazon-s3", "amazon-cloudfront", "django-compressor" ]
I want to serve my compressed CSS/JS from CloudFront (they live on S3), but am unable to work out how to do it via the compressor settings in settings.py, I have the following: ``` COMPRESS_OFFLINE = True COMPRESS_URL = 'http://static.example.com/' #same as STATIC_URL, so unnecessary, just here for simplicity...
I wrote a wrapper storage backend around the one provided by boto myapp/storage\_backends.py: ``` import urlparse from django.conf import settings from storages.backends.s3boto import S3BotoStorage def domain(url): return urlparse.urlparse(url).hostname class MediaFilesStorage(S3BotoStorage): def __init...
Django-compressor: how to write to S3, read from CloudFront?
8,688,815
16
2011-12-31T15:04:32Z
8,982,201
11
2012-01-24T05:00:16Z
[ "python", "django", "amazon-s3", "amazon-cloudfront", "django-compressor" ]
I want to serve my compressed CSS/JS from CloudFront (they live on S3), but am unable to work out how to do it via the compressor settings in settings.py, I have the following: ``` COMPRESS_OFFLINE = True COMPRESS_URL = 'http://static.example.com/' #same as STATIC_URL, so unnecessary, just here for simplicity...
I made a few, different changes to settings.py ``` AWS_S3_CUSTOM_DOMAIN = 'XXXXXXX.cloudfront.net' #important: no "http://" AWS_S3_SECURE_URLS = True #default, but must set to false if using an alias on cloudfront COMPRESS_STORAGE = 'example_app.storage.CachedS3BotoStorage' #from the docs (linked below) STATICFILES_S...
Remove empty first column of a Treeview object
8,688,839
3
2011-12-31T15:08:56Z
8,739,800
11
2012-01-05T08:53:04Z
[ "python", "tkinter", "treeview", "ttk" ]
I'm trying to make a program that retrieves records from a database using `sqlite3`, and then display them using a `Treeview`. I succeeded in having a table created with the records, but I just can't remove the first empty column. ``` def executethiscommand(search_str): comm.execute(search_str) records = comm...
That first empty column is the identifier of the item, you can suppress that by setting the show parameter. ``` t = ttk.Treeview(w) t['show'] = 'headings' ``` That will eliminate that empty column.
NameError: name 'reduce' is not defined in Python
8,689,184
37
2011-12-31T16:25:28Z
8,689,190
68
2011-12-31T16:27:38Z
[ "python", "reduce", "python-3.2" ]
I'm using Python 3.2. Tried this: ``` xor = lambda x,y: (x+y)%2 l = reduce(xor, [1,2,3,4]) ``` And got the following error: ``` l = reduce(xor, [1,2,3,4]) NameError: name 'reduce' is not defined ``` Tried printing `reduce` into interactive console - got this error: ``` NameError: name 'reduce' is not defined ``` ...
It was moved to [`functools`](http://docs.python.org/py3k/library/functools.html#functools.reduce).
NameError: name 'reduce' is not defined in Python
8,689,184
37
2011-12-31T16:25:28Z
29,386,693
27
2015-04-01T08:59:51Z
[ "python", "reduce", "python-3.2" ]
I'm using Python 3.2. Tried this: ``` xor = lambda x,y: (x+y)%2 l = reduce(xor, [1,2,3,4]) ``` And got the following error: ``` l = reduce(xor, [1,2,3,4]) NameError: name 'reduce' is not defined ``` Tried printing `reduce` into interactive console - got this error: ``` NameError: name 'reduce' is not defined ``` ...
You can add ``` from functools import reduce ``` before you use the reduce.
How can I remove non-ASCII characters but leave periods and spaces using Python?
8,689,795
39
2011-12-31T18:23:44Z
8,689,826
74
2011-12-31T18:29:33Z
[ "python", "text", "unicode", "filter", "ascii" ]
I'm working with a .txt file. I want a string of the text from the file with no non-ASCII characters. However, I want to leave spaces and periods. At present, I'm stripping those too. Here's the code: ``` def onlyascii(char): if ord(char) < 48 or ord(char) > 127: return '' else: return char def get_my_string(...
You can filter all characters from the string that are not printable using [string.printable](http://docs.python.org/library/string.html#string.printable), like this: ``` >>> s = "some\x00string. with\x15 funny characters" >>> import string >>> printable = set(string.printable) >>> filter(lambda x: x in printable, s) ...
How can I remove non-ASCII characters but leave periods and spaces using Python?
8,689,795
39
2011-12-31T18:23:44Z
18,430,817
24
2013-08-25T15:50:21Z
[ "python", "text", "unicode", "filter", "ascii" ]
I'm working with a .txt file. I want a string of the text from the file with no non-ASCII characters. However, I want to leave spaces and periods. At present, I'm stripping those too. Here's the code: ``` def onlyascii(char): if ord(char) < 48 or ord(char) > 127: return '' else: return char def get_my_string(...
An easy way to change to a different codec, is by using encode() or decode(). In your case, you want to convert to ASCII and ignore all symbols that are not supported. For example, the Swedish letter å is not an ASCII character: ``` >>>s = u'Good bye in Swedish is Hej d\xc3' >>>s = s.encode('ascii',errors='ig...
Libtorrent - Given a magnet link, how do you generate a torrent file?
8,689,828
15
2011-12-31T18:29:47Z
9,563,296
10
2012-03-05T07:52:52Z
[ "c++", "python", "libtorrent" ]
I have read through the [manual](http://www.rasterbar.com/products/libtorrent/manual.html) and I cannot find the answer. Given a magnet link I would like to generate a torrent file so that it can be loaded on the next startup to avoid redownloading the metadata. I have tried the fast resume feature, but I still have to...
Solution found here: <http://code.google.com/p/libtorrent/issues/detail?id=165#c5> See creating torrent: <http://www.rasterbar.com/products/libtorrent/make_torrent.html> Modify first lines: ``` file_storage fs; // recursively adds files in directories add_files(fs, "./my_torrent"); create_torrent t(fs); ``` To ...
Why do some functions have underscores "__" before and after the function name?
8,689,964
205
2011-12-31T18:57:01Z
8,689,983
238
2011-12-31T19:01:13Z
[ "python", "function", "methods", "double-underscore" ]
This seems to occur a lot, and was wondering if this was a requirement in the Python language, or merely a matter of convention? Also, could someone name and explain which functions tend to have the underscores, and why (`__init__`, for instance)?
From the Python PEP 8 -- Style Guide for Python Code (<http://www.python.org/dev/peps/pep-0008/>): > the following special forms using leading or trailing underscores are > recognized (these can generally be combined with any case convention): > > * \_single\_leading\_underscore: weak "internal use" indicator. E.g. "f...
Why do some functions have underscores "__" before and after the function name?
8,689,964
205
2011-12-31T18:57:01Z
8,690,287
17
2011-12-31T20:05:11Z
[ "python", "function", "methods", "double-underscore" ]
This seems to occur a lot, and was wondering if this was a requirement in the Python language, or merely a matter of convention? Also, could someone name and explain which functions tend to have the underscores, and why (`__init__`, for instance)?
The other respondents are correct in describing the double leading and trailing underscores as a naming convention for "special" or "magic" methods. While you can call these methods directly (`[10, 20].__len__()` for example), the presence of the underscores is a hint that these methods are intended to be invoked indi...
Pygame MemoryError
8,690,301
3
2011-12-31T20:08:21Z
8,690,348
8
2011-12-31T20:19:06Z
[ "python", "memory", "audio", "pygame" ]
HI i wrote a simple block collecting program that was working just fine and dandy until i added sound. Then all the sudden i get a MemoryError which is something ive never seen before. my code is attached along with the sound(wav) file that seem to be the problem. Any help would be great, and yes the code and the soun...
I think you have to initialize the mixer first, before using sounds. ``` pygame.mixer.init(44100, -16, 2, 2048) # Read the docs to know what these numbers are ```
Python: How to write multiple strings in one line?
8,691,311
5
2012-01-01T00:54:01Z
8,691,360
29
2012-01-01T01:09:55Z
[ "python", "string" ]
I've started to learn Python with LPTHW and I've gotten to exercise 16: <http://learnpythonthehardway.org/book/ex16.html> And feel like an idiot because I can't figure out one of the seemingly simple "extra credit" assignments that wants the following: ``` target.write(line1) target.write('\n') target.write(line2) t...
``` target.write(line1 \n, line2 \n, line3 \n) ``` '\n' only make sense inside a string literal. Without the quotes, you don't have string literals. ``` target.write('line1 \n, line2 \n, line3 \n') ``` Ok, now everything is a string literal. But you want line1, line2, line3 to not be string literals. You need those ...
Summarizing a Wikipedia Article
8,691,537
15
2012-01-01T02:21:07Z
8,692,274
11
2012-01-01T07:32:44Z
[ "python", "statistics", "machine-learning", "wikipedia", "summarization" ]
I find myself having to learn new things all the time. I've been trying to think of ways I could expedite the process of learning new subjects. I thought it might be neat if I could write a program to parse a wikipedia article and remove everything but the most valuable information. I started by taking the Wikipedia a...
Considering that your question relates more to a research activity than a programming problem, you should probably look at scientific literature. Here you will find published details of a number of algorithms that perform exactly what you want. A google search for "keyword summarization" finds the following: [Single d...
How to put a Tkinter window on top of the others
8,691,655
8
2012-01-01T03:15:32Z
8,691,795
9
2012-01-01T04:09:28Z
[ "python", "tkinter", "osx-lion", "pyobjc", "py2app" ]
I'm using Python 2 with `Tkinter` and `PyObjC`, and then I'm using `py2app`. The program is working fine, but the window starts as hidden whenever I open the program, so it doesn't appear until I click on the icon on the dock to bring it up. Is there anyway to control this, make the window to be on top of other windo...
If I take the code you give and add the first and last line you get: ``` from Tkinter import * root = Tk() root.title("app") screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() root.geometry("550x250+%d+%d" % (screen_width/2-275, screen_height/2-125)) root.configure(background='gold') r...
How to put a Tkinter window on top of the others
8,691,655
8
2012-01-01T03:15:32Z
9,543,822
10
2012-03-03T05:42:21Z
[ "python", "tkinter", "osx-lion", "pyobjc", "py2app" ]
I'm using Python 2 with `Tkinter` and `PyObjC`, and then I'm using `py2app`. The program is working fine, but the window starts as hidden whenever I open the program, so it doesn't appear until I click on the icon on the dock to bring it up. Is there anyway to control this, make the window to be on top of other windo...
I got into same issue today. OSX LION 10.7.2 Add this code before `mainloop()` solves the issue. ``` root.call('wm', 'attributes', '.', '-topmost', '1') ``` EDIT: Sorry, it sets "Always On Top". For real solve, We need to make it a app bundle, with py2app.
How to put a Tkinter window on top of the others
8,691,655
8
2012-01-01T03:15:32Z
17,437,429
9
2013-07-02T23:28:59Z
[ "python", "tkinter", "osx-lion", "pyobjc", "py2app" ]
I'm using Python 2 with `Tkinter` and `PyObjC`, and then I'm using `py2app`. The program is working fine, but the window starts as hidden whenever I open the program, so it doesn't appear until I click on the icon on the dock to bring it up. Is there anyway to control this, make the window to be on top of other windo...
Update for OSX 10.8.3: the combination of the answers provided by vdbuilder and user2435139 did the trick for me, i.e. ``` self.root.lift() self.root.call('wm', 'attributes', '.', '-topmost', True) self.root.after_idle(self.root.call, 'wm', 'attributes', '.', '-topmost', False) ``` called before ``` self.root.mainlo...
How to remove a path prefix in Python?
8,693,024
16
2012-01-01T12:11:06Z
8,693,057
20
2012-01-01T12:20:32Z
[ "python", "string", "prefix" ]
I wanted to know what is the pythonic function for this : I want to remove everything before the wa path. ``` p = path.split('/') counter = 0 while True: if p[counter] == 'wa': break counter += 1 path = '/'+'/'.join(p[counter:]) ``` For instance, I want '/book/html/wa/foo/bar/' to become '/wa/foo/bar...
``` >>> path = '/book/html/wa/foo/bar/' >>> path[path.find('/wa'):] '/wa/foo/bar/' ```
How to remove a path prefix in Python?
8,693,024
16
2012-01-01T12:11:06Z
19,856,910
53
2013-11-08T10:35:16Z
[ "python", "string", "prefix" ]
I wanted to know what is the pythonic function for this : I want to remove everything before the wa path. ``` p = path.split('/') counter = 0 while True: if p[counter] == 'wa': break counter += 1 path = '/'+'/'.join(p[counter:]) ``` For instance, I want '/book/html/wa/foo/bar/' to become '/wa/foo/bar...
A better answer would be to use os.path.relpath: <http://docs.python.org/2/library/os.path.html#os.path.relpath> ``` >>> import os >>> full_path = '/book/html/wa/foo/bar/' >>> print os.path.relpath(full_path, '/book/html') 'wa/foo/bar' ```
Why do I get a MemoryError with itertools.product?
8,695,422
11
2012-01-01T20:48:17Z
8,695,606
7
2012-01-01T21:16:32Z
[ "python", "itertools" ]
I would expect the following snippet to give me an iterator yielding pairs from the Cartesian product of the two input iterables: ``` $ python Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import itertools >>> one = x...
`itertools.product` does not store the intermediate products in memory, but it does store `tuple` versions of the original iterators. This can be seen by looking at the source of the `itertools` module. It's in the file `Modules/itertoolsmodule.c` in the Python 2.7.2 source distribution. There we find, in the function...
Why do I get a MemoryError with itertools.product?
8,695,422
11
2012-01-01T20:48:17Z
8,695,700
14
2012-01-01T21:32:47Z
[ "python", "itertools" ]
I would expect the following snippet to give me an iterator yielding pairs from the Cartesian product of the two input iterables: ``` $ python Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import itertools >>> one = x...
It doesn't store intermediate *results*, but it has to store the input values because each of those might be needed several times for several output values. Since you can only iterate once over an iterator, `product` cannot be implemented equivalent to this: ``` def prod(a, b): for x in a: for y in b: yi...
proper use of list comprehensions - python
8,695,488
10
2012-01-01T20:59:14Z
8,695,515
10
2012-01-01T21:03:37Z
[ "python", "list-comprehension" ]
Normally, list comprehensions are used to derive a new list from an existing list. Eg: ``` >>> a = [1, 2, 3, 4, 5] >>> [i for i in a if i > 2] [3, 4, 5] ``` Should we use them to perform other procedures? Eg: ``` >>> a = [1, 2, 3, 4, 5] >>> b = [] >>> [b.append(i) for i in a] [None, None, None, None, None] >>> print...
You should indeed avoid using list comprehensions (along with dictionary comprehensions, set comprehensions and generator expressions) for side effects. Apart from the fact that they'd accumulate a bogus list and thus waste memory, it's also confusing. I expect a list comprehension to generate a (meaningful) value, and...
Why does this AttributeError in python occur?
8,696,322
17
2012-01-01T23:34:06Z
8,696,339
31
2012-01-01T23:36:22Z
[ "python", "import", "attributeerror" ]
There is one thing, that I do not understand. Why does this ``` import scipy # happens with several other modules, too. I took scipy as an example now... matrix = scipy.sparse.coo_matrix(some_params) ``` produce this error: ``` AttributeError: 'module' object has no attribute 'sparse' ```
This happens because the `scipy` module doesn't have any attribute named `sparse`. That attribute only gets defined when you `import scipy.sparse`. Submodules don't automatically get imported when you just `import scipy`; you need to import them explicitly. The same holds for most packages, although a package can choo...
How to best deal with this Python numerical error?
8,696,676
3
2012-01-02T01:04:49Z
8,696,783
9
2012-01-02T01:34:02Z
[ "python", "math", "floating-point" ]
I have this code that throws a `math domain error` exception: ``` v = -1.0 for i in range (201): print acos (v) v += 0.01 ``` But if I change it to this, it works: ``` v = -100 for i in range (201): print acos (v / 100.0) v += 1 ``` Is this because of rounding? How to best solve this in Python? O...
If you do: ``` >>> format(0.01, '.30f') '0.010000000000000000208166817117' ``` you can see that `0.01` (as a floating point number with double precision) is bigger than the number `0.01` you learned at school. So, when you sum it 100 times, the error gets bigger: ``` >>> sum([0.01]*100) 1.0000000000000007 ``` And ...
What's the most elegant way to write this for loop in Python?
8,697,155
5
2012-01-02T03:26:39Z
8,697,189
11
2012-01-02T03:35:12Z
[ "python", "math", "loops", "for-loop" ]
Basically I want to go from -1 to 1 in `n` steps, including -1 and 1: ``` x = -1.0 n = 21 for i in range(n): print x x += 0.01 -1.0 -0.9 -0.8 ... 0.8 0.9 1.0 ``` How can I write this in the most elegant, simplest way for any `n` value?
There is no built-in solution, but probably a good way to solve it is to define your own `range` function: ``` def my_range(start, end, how_many): incr = float(end - start)/(how_many - 1) return [start + i*incr for i in range(how_many)] ``` And you can use it in a for-loop: ``` >>> for i in my_range(-1, 1, 1...
What's the most elegant way to write this for loop in Python?
8,697,155
5
2012-01-02T03:26:39Z
8,697,192
11
2012-01-02T03:36:48Z
[ "python", "math", "loops", "for-loop" ]
Basically I want to go from -1 to 1 in `n` steps, including -1 and 1: ``` x = -1.0 n = 21 for i in range(n): print x x += 0.01 -1.0 -0.9 -0.8 ... 0.8 0.9 1.0 ``` How can I write this in the most elegant, simplest way for any `n` value?
If it's OK to use `numpy`, this works fine: ``` import numpy as np n = 21 for i in np.linspace(-1, 1, n): print i ```
Invalid syntax with if statement
8,698,325
2
2012-01-02T07:13:11Z
8,698,336
10
2012-01-02T07:14:44Z
[ "python", "syntax", "if-statement", "python-3.x" ]
I will just paste in the entire function, as it is not that long: ``` def decideTile(): global tile global exp global maxexp tile += 1 exp += math.ceil(random.randrange(math.ceil((maxexp/2)/2,maxexp/2)) if exp >= maxexp: levelUp() else: tileChoices = ['Battle','Loot','Nothin...
There's a parenthesis missing in the previous line. To fix the problem just add a closing parenthesis to the end of that line as follows: ``` exp += math.ceil(random.randrange(math.ceil((maxexp/2)/2,maxexp/2))) ```
Python computing error
8,699,001
8
2012-01-02T09:00:14Z
8,699,068
13
2012-01-02T09:11:16Z
[ "python", "math", "floating-point", "fixed-point", "arbitrary-precision" ]
I’m using the API mpmath to compute the following sum Let us consider the serie u0, u1, u2 defined by: ``` u0 = 3/2 = 1,5 u1 = 5/3 = 1,6666666… un+1 = 2003 - 6002/un + 4000/un un-1 ``` The serie converges on 2, but with rounding problem it seems to converge on 2000. ``` n Calculated value Rounded off exa...
Using the decimal module, you can see the series also has a solution converging at 2000: ``` from decimal import Decimal, getcontext getcontext().prec = 100 u0=Decimal(3) / Decimal(2) u1=Decimal(5) / Decimal(3) u=[u0, u1] for i in range(100): un1 = 2003 - 6002/u[-1] + 4000/(u[-1]*u[-2]) u.append(un1) prin...
Python: How to import, from two modules, Classes that have same names?
8,700,360
2
2012-01-02T11:39:53Z
8,700,382
8
2012-01-02T11:42:36Z
[ "python", "class", "import" ]
I'm writing a python programm to do granular syncs between different DB. I'm using SQLAlchemy and a module named sqlautocode for DB inspecting and Schema Classes production. Having two DB to sync, with same tables name, the Classes written by sqlautocode results with same names. I have to import theese Classes with ...
Just import the modules and don't try to pull the names from them. `from X import Y` should be used sporadically, anyway. ``` import module_a import module_b module_a.x module_b.x ```
Identifying common elements in multiple files
8,700,666
3
2012-01-02T12:13:08Z
8,700,747
7
2012-01-02T12:21:26Z
[ "python", "perl", "shell" ]
I have 8 files of one column and non uniform number of rows in each column. I need to identify the elements which are common in all of these 8 files. I can do this task for comparing two files, but I am unable to write workable one liner in shell to do the same. Any ideas..... Thank you in advance. File 1 Paul ...
The following one-liner should do (change 3 to 8 to match your case) ``` $ sort * | uniq -c | grep 3 3 Paul ``` Probably better to do this in python though, using `sets`...
python class instance variables and class variables
8,701,500
19
2012-01-02T13:38:21Z
8,701,644
29
2012-01-02T13:51:19Z
[ "python", "class", "variables", "instance" ]
im having a problem understanding how class / instance variables work in python. I dont understand why when i try this code the list variable seems to be a class variable ``` class testClass(): list = [] def __init__(self): self.list.append('thing') p = testClass() print p.list f = testClass() print ...
This is because of the way Python resolves names with the `.`. When you write `self.list` the Python runtime tries to resolve the `list` name first looking for it in the instance object, and if not found in the class instance. Let's look into it step by step ``` self.list.append(1) ``` 1. Is there a `list` name into...
binary to string, better than a dictionary?
8,702,060
6
2012-01-02T14:35:45Z
8,702,151
14
2012-01-02T14:46:48Z
[ "python", "string", "dictionary", "binary" ]
Objective: Convert binary to string Example: 0111010001100101011100110111010001100011011011110110010001100101 -> testCode (without space) I use a dictionary and my function, i search a better way and more efficient ``` from textwrap import wrap DICO = {'\x00': '00', '\x04': '0100', '\x08': '01000', '\x0c': '01100',...
``` ''.join([ chr(int(p, 2)) for p in wrap(binstr, 8) ]) ``` What this does: `wrap` first splits your string up into chunks of 8. Then, I iterate through each one, and convert it to an integer (base 2). Each of those converted integer now get covered to a character with `chr`. Finally I wrap it all up with a `''.join`...
Python catch any exception, and print or log traceback with variable values
8,702,230
6
2012-01-02T14:53:45Z
8,702,293
8
2012-01-02T15:01:23Z
[ "python" ]
When I catch unexpected error with sys.excepthook ``` import sys import traceback def handleException(excType, excValue, trace): print 'error' traceback.print_exception(excType, excValue, trace) sys.excepthook = handleException h = 1 k = 0 print h/k ``` This is output I get ``` error Traceback (most rece...
By looking at the source of `cgitb.py`, you should be able to use something like this: ``` import sys import traceback import cgitb def handleException(excType, excValue, trace): print 'error' cgitb.Hook(format="text")(excType, excValue, trace) sys.excepthook = handleException h = 1 k = 0 print h/k ```
Django get list of models in application
8,702,772
31
2012-01-02T15:51:44Z
8,702,854
72
2012-01-02T16:00:08Z
[ "python", "django", "model" ]
So, i have a file models.py in MyApp folder: ``` from django.db import models class Model_One(models.Model): ... class Model_Two(models.Model): ... ... ``` It can be about 10-15 classes. **How to find all models in the MyApp and get their names?** Since models are not iterable, i don't know if this is even p...
This is the best way to accomplish what you want to do: ``` from django.db.models import get_app, get_models app = get_app('my_application_name') for model in get_models(app): # do something with the model ``` In this example, `model` is the actual model, so you can do plenty of things with it: ``` for model in...
Django get list of models in application
8,702,772
31
2012-01-02T15:51:44Z
31,184,258
21
2015-07-02T12:07:45Z
[ "python", "django", "model" ]
So, i have a file models.py in MyApp folder: ``` from django.db import models class Model_One(models.Model): ... class Model_Two(models.Model): ... ... ``` It can be about 10-15 classes. **How to find all models in the MyApp and get their names?** Since models are not iterable, i don't know if this is even p...
From Django 1.7 on, you can use this code, for example in your admin.py to register all models: ``` from django.apps import apps from django.contrib import admin from django.contrib.admin.sites import AlreadyRegistered app_models = apps.get_app_config('my_app').get_models() for model in app_models: try: a...
Remove Sub String by using Python
8,703,017
11
2012-01-02T16:18:43Z
8,703,078
31
2012-01-02T16:26:34Z
[ "python", "regex", "string" ]
I already extract some information from a forum. It is the raw string I have now: ``` string = 'i think mabe 124 + <font color="black"><font face="Times New Roman">but I don\'t have a big experience it just how I see it in my eyes <font color="green"><font face="Arial">fun stuff' ``` The thing I do not like is the su...
``` import re re.sub('<.*?>', '', string) "i think mabe 124 + but I don't have a big experience it just how I see it in my eyes fun stuff" ``` The `re.sub` function takes a regular expresion and replace all the matches in the string with the second parameter. In this case, we are searching for all tags (`'<.*?>'`) and...
Remove Sub String by using Python
8,703,017
11
2012-01-02T16:18:43Z
8,703,088
7
2012-01-02T16:27:59Z
[ "python", "regex", "string" ]
I already extract some information from a forum. It is the raw string I have now: ``` string = 'i think mabe 124 + <font color="black"><font face="Times New Roman">but I don\'t have a big experience it just how I see it in my eyes <font color="green"><font face="Arial">fun stuff' ``` The thing I do not like is the su...
``` >>> import re >>> st = " i think mabe 124 + <font color=\"black\"><font face=\"Times New Roman\">but I don't have a big experience it just how I see it in my eyes <font color=\"green\"><font face=\"Arial\">fun stuff" >>> re.sub("<.*?>","",st) " i think mabe 124 + but I don't have a big experience it just how I see ...
Usage of pickle.dump in Python
8,703,366
15
2012-01-02T17:00:53Z
8,703,425
28
2012-01-02T17:08:40Z
[ "python", "serialization", "pickle", "python-3.2" ]
I'm trying to learn how to use the `pickle` module in Python: ``` import pickle x = 123 f = open('data.txt','w') pickle.dump(x,f) ``` Here's what I get: ``` Traceback (most recent call last): File "D:\python\test.py", line 5, in <module> pickle.dump(x,f) TypeError: must be str, not bytes ``` However, this cod...
The problem is that you're opening the file in text mode. You need to use binary here: ``` >>> f = open('data.txt','w') >>> pickle.dump(123,f) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: must be str, not bytes >>> >>> f = open('data.txt','wb') >>> pickle.dump(123,f) >>> ```
Hash Map in Python
8,703,496
37
2012-01-02T17:17:10Z
8,703,509
77
2012-01-02T17:18:52Z
[ "java", "python", "hashmap" ]
I want to implement a HashMap in Python. I want to ask a user for an input. depending on his input I am retrieving some information from the HashMap. If the user enters a key of the HashMap, I would like to retrieve the corresponding value. How do I implement this functionality in Python? ``` HashMap<String,String> s...
[Python dictionary](http://docs.python.org/library/stdtypes.html#dict) is a built-in type that supports key-value pairs. ``` streetno = {"1":"Sachine Tendulkar", "2":"Dravid", "3":"Sehwag", "4":"Laxman","5":"Kohli"} ``` as well as using the dict keyword: ``` streetno = dict({"1":"Sachine Tendulkar", "2":"Dravid"}) `...
Hash Map in Python
8,703,496
37
2012-01-02T17:17:10Z
8,703,519
7
2012-01-02T17:19:36Z
[ "java", "python", "hashmap" ]
I want to implement a HashMap in Python. I want to ask a user for an input. depending on his input I am retrieving some information from the HashMap. If the user enters a key of the HashMap, I would like to retrieve the corresponding value. How do I implement this functionality in Python? ``` HashMap<String,String> s...
All you wanted was a hint. Here's a hint: In Python, you can use [dictionaries](http://docs.python.org/tutorial/datastructures.html#dictionaries).
Hash Map in Python
8,703,496
37
2012-01-02T17:17:10Z
8,703,525
7
2012-01-02T17:20:01Z
[ "java", "python", "hashmap" ]
I want to implement a HashMap in Python. I want to ask a user for an input. depending on his input I am retrieving some information from the HashMap. If the user enters a key of the HashMap, I would like to retrieve the corresponding value. How do I implement this functionality in Python? ``` HashMap<String,String> s...
It's built-in for Python. See [dictionaries](http://docs.python.org/tutorial/datastructures.html#dictionaries). Based on your example: ``` streetno = {"1": "Sachine Tendulkar", "2": "Dravid", "3": "Sehwag", "4": "Laxman", "5": "Kohli" } ``` You could then access it lik...
Hash Map in Python
8,703,496
37
2012-01-02T17:17:10Z
8,703,535
7
2012-01-02T17:21:07Z
[ "java", "python", "hashmap" ]
I want to implement a HashMap in Python. I want to ask a user for an input. depending on his input I am retrieving some information from the HashMap. If the user enters a key of the HashMap, I would like to retrieve the corresponding value. How do I implement this functionality in Python? ``` HashMap<String,String> s...
``` streetno = { 1 : "Sachin Tendulkar", 2 : "Dravid", 3 : "Sehwag", 4 : "Laxman", 5 : "Kohli" } ``` And to retrieve values: ``` name = streetno.get(3, "default value") ``` Or ``` name = streetno[3] ``` That's using number as keys, put quotes around the numbers to us...
Populate list or tuple from callable or lambda in python
8,703,999
2
2012-01-02T18:19:02Z
8,704,025
7
2012-01-02T18:21:22Z
[ "python", "arrays", "list", "tuples", "callable" ]
This is a problem I've come across a lot lately. Google doesn't seem to have an answer so I bring it to the good people of stack overflow. I am looking for a simple way to populate a list with the output of a function. Something like this: ``` fill(random.random(), 3) #=> [0.04095623, 0.39761869, 0.46227642] ``` Her...
How about a [**list comprehension**](http://docs.python.org/tutorial/datastructures.html#list-comprehensions)? ``` [random.random() for x in xrange(3)] ``` Also, in many cases, you need the values just once. In these cases, a [generator expression](http://docs.python.org/reference/expressions.html#generator-expressio...
How do you install PyCairo (Cairo for Python) on Windows?
8,704,407
13
2012-01-02T19:07:51Z
8,704,496
21
2012-01-02T19:16:33Z
[ "python", "windows", "installation", "cairo", "pycairo" ]
I spent hours this afternoon trying to find a straightforward tutorial for installing PyCairo on Windows. The Cairo project itself does not maintain Windows binaries, they must be dowloaded elsehere (e.g. <http://ftp.gnome.org/pub/GNOME/binaries/win32/pycairo/>). The process is also complicated further apparently by ...
You should try windows binary installers from Gohlke repository for [pyCairo](http://www.lfd.uci.edu/~gohlke/pythonlibs/#pycairo) and [py2Cairo](http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygtk). I never used pyCairo myself but took 4 minutes to install and get my first png example file done.
python convert tuple to string
8,704,952
4
2012-01-02T20:19:08Z
8,705,031
14
2012-01-02T20:29:32Z
[ "python", "tuples" ]
Gents, After a mysql select statement, I am left with the following: ``` set([('1@a.com',), ('2@b.net',), ('3@c.com',), ('4@d.com',), ('5@e.com',), ('6@f.net',), ('7@h.net',), ('8@g.com',)]) ``` What I would like to have is a ``` emaillist = "\n".join(queryresult) ``` to in the end, have a string: ``` 1@a.com 2@b....
As long as you're sure you have just one element per tuple: ``` '\n'.join(elem[0] for elem in queryresult) ```
Python's "in" set operator
8,705,378
39
2012-01-02T21:11:09Z
8,705,406
34
2012-01-02T21:14:15Z
[ "python" ]
I'm a little confused about the python in operator for sets. If I have a set in python s and some instance b, is it true that "b in s" means "is there some element x in s such that b == x is true"?
Yes, but it *also* means [`hash(b) == hash(x)`](http://docs.python.org/reference/datamodel.html#object.__hash__), so equality of the items isn't enough to make them the same.