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
Unexpected Indent error in Python
4,263,485
4
2010-11-24T04:35:36Z
4,263,495
8
2010-11-24T04:37:35Z
[ "python" ]
I have a simple piece of code that I'm not understanding where my error is coming from. The parser is barking at me with an Unexpected Indent on line 5 (the if statement). Does anyone see the problem here? I don't. ``` def gen_fibs(): a, b = 0, 1 while True: a, b = b, a + b if len(str(a)) == 10...
If you just copy+pasted your code, then you used a tab on the line with the `if` statement. Python interprets a tab as 8 spaces and not 4. Don't ever use tabs with python1 :) 1 Or at least don't ever use tabs and spaces mixed. It's highly advisable to use 4 spaces for consistency with the rest of the python universe.
ctypes mouse_events
4,263,608
4
2010-11-24T05:00:45Z
4,263,994
9
2010-11-24T06:22:42Z
[ "python", "ctypes" ]
**ctypes.windll.user32.mouse\_event(3, 0, 0, 0,0)** I'm messing around with mouse positions and stumbled upon this line which from what I understand emulates a mouse click. Does anyone have documentation to similar lines (such as right-click and so on)?
I have a small class that wraps the mouse management. ``` import win32gui, win32api, win32con, ctypes class Mouse: """It simulates the mouse""" MOUSEEVENTF_MOVE = 0x0001 # mouse move MOUSEEVENTF_LEFTDOWN = 0x0002 # left button down MOUSEEVENTF_LEFTUP = 0x0004 # left button up MOUSEEVENTF_RIGHTD...
No speed gains from Cython
4,264,229
21
2010-11-24T07:02:25Z
4,264,777
9
2010-11-24T08:32:10Z
[ "python", "optimization", "numpy", "cython" ]
I am trying to define a function that contains an inner loop for simulating an integral. The problem is speed. Evaluating the function once can take up to 30 seconds on my machine. Since my ultimate goal is to minimize this function, some extra speed would be nice. As such, I have tried to get Cython to work for me, bu...
You could definitely speed up your code by using more of Numpy's capabilities. For instance: ``` cdef np.ndarray[double, ndim=1] S = np.zeros(dtype = "d", shape = J) cdef int j for j in xrange(ns): S += P_i[:,j] ``` would be much faster and legible as ``` S = P_i.sum(axis=1) ``` You also repeat some calculatio...
No speed gains from Cython
4,264,229
21
2010-11-24T07:02:25Z
4,264,946
14
2010-11-24T08:57:31Z
[ "python", "optimization", "numpy", "cython" ]
I am trying to define a function that contains an inner loop for simulating an integral. The problem is speed. Evaluating the function once can take up to 30 seconds on my machine. Since my ultimate goal is to minimize this function, some extra speed would be nice. As such, I have tried to get Cython to work for me, bu...
Cython doesn't offer automatic performance gains, you have to know its internals and check the generated C code. In particular if you want to improve loops performances, you have to avoid calling Python functions in them, which you happen to do a lot in this case (all the `np.` calls are Python calls, slicing, and pro...
No speed gains from Cython
4,264,229
21
2010-11-24T07:02:25Z
4,265,506
22
2010-11-24T10:00:38Z
[ "python", "optimization", "numpy", "cython" ]
I am trying to define a function that contains an inner loop for simulating an integral. The problem is speed. Evaluating the function once can take up to 30 seconds on my machine. Since my ultimate goal is to minimize this function, some extra speed would be nice. As such, I have tried to get Cython to work for me, bu...
Cython can produce an html file to help with this: ``` cython -a MODULE.py ``` This shows each line of source code colored white through various shades of yellow. The darker the yellow color, the more dynamic Python behaviour is still being performed on that line. For each line that contains some yellow, you need to ...
It is possible export table sqlite3 table to csv or similiar?
4,264,379
5
2010-11-24T07:28:13Z
4,264,673
9
2010-11-24T08:15:52Z
[ "python", "sqlite3" ]
It is possible export sqlite3 table to csv or xls format? I'm using python 2.7 and sqlite3.
I knocked this very basic script together using a slightly modified example class from [the docs](http://docs.python.org/library/csv.html); it simply exports an entire table to a CSV file: ``` import sqlite3 import csv, codecs, cStringIO class UnicodeWriter: """ A CSV writer which will write rows to CSV file ...
More Pythonic Way to Run a Process X Times
4,264,634
38
2010-11-24T08:10:24Z
4,264,655
44
2010-11-24T08:13:42Z
[ "python", "loops" ]
Which is more pythonic? **While loop:** ``` count = 0 while count < 50: print "Some thing" count = count + 1 ``` **For loop:** ``` for i in range(50): print "Some thing" ``` Edit: not duplicate because this has answers to determine which is clearer, vs. how to run a range without 'i' -- even though tha...
Personally: ``` for _ in range(50): print "Some thing" ``` if you don't need `i`. If you use Python < 3 and you want to repeat the loop a lot of times, use `xrange` as there is no need to generate the whole list beforehand.
How to upload a file, using Python Mechanize, with a twist :)
4,264,694
3
2010-11-24T08:20:23Z
4,666,348
9
2011-01-12T07:40:03Z
[ "python", "html", "file-upload", "mechanize" ]
Ok I have only been using Mechanize for one day, so be nice :P I would like complete a form including one (or two if possible) file upload style fields. The ones where you click, and it lets you browse for a file. (I want to automate the uploading of a .torrent to a private tracker / site) Now the two issues I have ...
Community: Please fix, I'm a casual passerby who encountered this error and solved it. ``` br.form.add_file(open(filename), 'text/plain', filename, **kwargs) ``` You need to resolve the ambiguity by passing in an extra keyword argument to identify the specific control you want to add the file to. You can add name, id...
Check whether the process is being run as a pipe
4,265,057
8
2010-11-24T09:10:28Z
4,265,081
12
2010-11-24T09:13:12Z
[ "python", "process", "pipe", "stdio" ]
I have a small Python utility which should be run only as a pipe. I want it to print out the help message when it runs stand alone. How can a process know whether it is being used as a pipe. Comparing `sys.stdin` and `sys.__stdin__` does not work.
You can use `isatty`: ``` if sys.stdin.isatty(): ``` It will be `True` if standard input is a tty, which roughly means it's being used directly, outside a pipe.
Python - Round to nearest 05
4,265,546
6
2010-11-24T10:05:18Z
4,265,592
16
2010-11-24T10:10:46Z
[ "python", "rounding" ]
Hvor can I en python do the following rounding: Round to the nearest 05 decimal 7,97 -> 7,95 6,72 -> 6,70 31,06 -> 31,05 36,04 -> 36,05 5,25 -> 5,25 Hope it makes sense.
BTW 7.97 is nearer to 7.95 than 8.00 ``` def round_to(n, precision): correction = 0.5 if n >= 0 else -0.5 return int( n/precision+correction ) * precision def round_to_05(n): return round_to(n, 0.05) ```
Python - Round to nearest 05
4,265,546
6
2010-11-24T10:05:18Z
4,265,619
8
2010-11-24T10:14:02Z
[ "python", "rounding" ]
Hvor can I en python do the following rounding: Round to the nearest 05 decimal 7,97 -> 7,95 6,72 -> 6,70 31,06 -> 31,05 36,04 -> 36,05 5,25 -> 5,25 Hope it makes sense.
``` def round05(number): return (round(number * 20) / 20) ``` Or more generically: ``` def round_to_value(number,roundto): return (round(number / roundto) * roundto) ``` The only problem is [because you're using floats you won't get exactly the answers you want](http://stackoverflow.com/questions/2986150/pyt...
How can I dump raw XML of my request and server's response using suds in python
4,265,602
8
2010-11-24T10:11:43Z
4,266,782
11
2010-11-24T12:31:35Z
[ "python", "soap", "suds" ]
i'm using suds 0.4 and python 2.6, to communicate with remote server. It's WSDL loads perfectly, but any function call returns error. Something is wrong with that server. Now i need to get a dump of soap structure, that is sent to server and it's response, in pure soap either. How can i do that?
Setting the logging for `suds.transport` to debug will get you the sent and received messages. For an interactive session, I find this is good: ``` import logging logging.basicConfig(level=logging.INFO) logging.getLogger('suds.client').setLevel(logging.DEBUG) logging.getLogger('suds.transport').setLevel(logging.DEBUG...
Generate random numbers with a given (numerical) distribution
4,265,988
31
2010-11-24T10:56:51Z
4,266,278
8
2010-11-24T11:32:46Z
[ "python", "module", "random" ]
I have a file with some probabilities for different values e.g.: ``` 1 0.1 2 0.05 3 0.05 4 0.2 5 0.4 6 0.2 ``` I would like to generate random numbers using this distribution. Does an existing module that handles this exist? It's fairly simple to code on your own (build the cumulative density function, generate a ran...
(OK, I know you are asking for shrink-wrap, but maybe those home-grown solutions just weren't succinct enough for your liking. :-) ``` pdf = [(1, 0.1), (2, 0.05), (3, 0.05), (4, 0.2), (5, 0.4), (6, 0.2)] cdf = [(i, sum(p for j,p in pdf if j < i)) for i,_ in pdf] R = max(i for r in [random.random()] for i,c in cdf if c...
Generate random numbers with a given (numerical) distribution
4,265,988
31
2010-11-24T10:56:51Z
4,266,562
16
2010-11-24T12:06:13Z
[ "python", "module", "random" ]
I have a file with some probabilities for different values e.g.: ``` 1 0.1 2 0.05 3 0.05 4 0.2 5 0.4 6 0.2 ``` I would like to generate random numbers using this distribution. Does an existing module that handles this exist? It's fairly simple to code on your own (build the cumulative density function, generate a ran...
An advantage to generating the list using CDF is that you can use binary search. While you need O(n) time and space for preprocessing, you can get k numbers in O(k log n). Since normal Python lists are inefficient, you can use `array` module. If you insist on constant space, you can do the following; O(n) time, O(1) s...
Generate random numbers with a given (numerical) distribution
4,265,988
31
2010-11-24T10:56:51Z
4,266,645
27
2010-11-24T12:15:50Z
[ "python", "module", "random" ]
I have a file with some probabilities for different values e.g.: ``` 1 0.1 2 0.05 3 0.05 4 0.2 5 0.4 6 0.2 ``` I would like to generate random numbers using this distribution. Does an existing module that handles this exist? It's fairly simple to code on your own (build the cumulative density function, generate a ran...
[`scipy.stats.rv_discrete`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.rv_discrete.html) might be what you want. You can supply your probabilities via the `values` parameter. You can then use the `rvs()` method of the distribution object to generate random numbers. As pointed out by Eugene Pakhomo...
Check if a number is rational in Python
4,266,741
7
2010-11-24T12:27:30Z
4,266,844
11
2010-11-24T12:36:34Z
[ "python", "algorithm", "math", "floating-point" ]
I would like to know a good way of checking if a number x is a rational (two integers n,m exist so that x=n/m) in python. In mathematica, this is done by the function ``` Rationalize[6.75] 27/4 ``` I assume this question has an answer for a given accuracy. Is there a common algorithm of obtaining these two integers?
In python >= 2.6 there is a [`as_integer_ratio`](http://docs.python.org/library/stdtypes.html#float.as_integer_ratio) method on floats: ``` >>> a = 6.75 >>> a.as_integer_ratio() (27, 4) >>> import math >>> math.pi.as_integer_ratio() (884279719003555, 281474976710656) ``` However, due to the way floats are defined in ...
Check if a number is rational in Python
4,266,741
7
2010-11-24T12:27:30Z
4,266,999
7
2010-11-24T12:53:44Z
[ "python", "algorithm", "math", "floating-point" ]
I would like to know a good way of checking if a number x is a rational (two integers n,m exist so that x=n/m) in python. In mathematica, this is done by the function ``` Rationalize[6.75] 27/4 ``` I assume this question has an answer for a given accuracy. Is there a common algorithm of obtaining these two integers?
The nature of floating-point numbers means that it makes no sense to *check* if a floating-point number is rational, since all floating-point numbers are really fractions of the form *n* / 2*e*. However, you might well want to know whether there is a *simple* fraction (one with a small denominator rather than a big pow...
Why is int(50)<str(5) in python 2.x?
4,266,918
6
2010-11-24T12:44:47Z
4,266,959
8
2010-11-24T12:49:57Z
[ "python", "comparison", "int", "python-2.x", "string" ]
In python 3, `int(50)<'2'` causes a `TypeError`, and well it should. In python 2.x, however, `int(50)<'2'` returns `True` (this is also the case for other number formats, but `int` exists in both py2 and py3). My question, then, has several parts: 1. Why does Python 2.x (< 3?) allow this behavior? * (And who thought ...
It works like this1. ``` >>> float() == long() == int() < dict() < list() < str() < tuple() True ``` Numbers compare as less than containers. Numeric types are converted to a common type and compared based on their numeric value. Containers are compared by the alphabetic value of their names.2 From the [docs](http:/...
Double-decoding unicode in python
4,267,019
10
2010-11-24T12:56:46Z
4,267,315
15
2010-11-24T13:32:34Z
[ "python", "unicode", "utf-8" ]
I am working against an application that seems keen on returning, what I believe to be, double UTF-8 encoded strings. I send the string `u'XüYß'` encoded using UTF-8, thus becoming `X\u00fcY\u00df` (equal to `X\xc3\xbcY\xc3\x9f`). The server *should* simply echo what I sent it, yet returns the following: `X\xc3\x83...
`ret.decode()` tries implicitly to encode `ret` with the system encoding - in your case ascii. If you explicitly encode the unicode string, you should be fine. There is a builtin encoding that does what you need: ``` >>> u'X\xc3\xbcY\xc3\x9f'.encode('raw_unicode_escape').decode('utf-8') u'X\xfcY\xdf' ``` I'd still t...
Why isn't self being automatically passed to a method that is set on an object after its instantiation?
4,267,459
8
2010-11-24T13:48:52Z
4,267,511
11
2010-11-24T13:53:05Z
[ "python" ]
``` class Person(): pass; def say_hi(self): print 'hii' me=Person() me.say_hi=say_hi me.say_hi() ``` Isn't the self argument automatically passed in python ? why why is calling `me.say_hi()` is giving a stack trace ? ``` Traceback (most recent call last): File "<input>", line 1, in <module> TypeError:...
It's not passed in the way that you are doing it. You would have to do. ``` import types me.say_hi = types.MethodType(say_hi, me, Person) ``` for it to work. When python instantiates a class, it essentially carries out the above procedure for each of the class methods. When you 'monkey-patch' a method onto an obje...
Django. Override save for model
4,269,605
59
2010-11-24T17:21:44Z
4,269,828
57
2010-11-24T17:43:23Z
[ "python", "django" ]
Before saving model I'm re-size a picture. But how can I check if new picture added or just description updated, so I can skip rescaling every time the model is saved? ``` class Model(model.Model): image=models.ImageField(upload_to='folder') thumb=models.ImageField(upload_to='folder') description=models.Ch...
Some thoughts: ``` class Model(model.Model): _image=models.ImageField(upload_to='folder') thumb=models.ImageField(upload_to='folder') description=models.CharField() def set_image(self, val): self._image = val self._image_changed = True # Or put whole logic in here smal...
Django. Override save for model
4,269,605
59
2010-11-24T17:21:44Z
4,269,927
8
2010-11-24T17:51:40Z
[ "python", "django" ]
Before saving model I'm re-size a picture. But how can I check if new picture added or just description updated, so I can skip rescaling every time the model is saved? ``` class Model(model.Model): image=models.ImageField(upload_to='folder') thumb=models.ImageField(upload_to='folder') description=models.Ch...
Check the model's pk field. If it is None, then it is a new object. ``` class Model(model.Model): image=models.ImageField(upload_to='folder') thumb=models.ImageField(upload_to='folder') description=models.CharField() def save(self, *args, **kwargs): if 'form' in kwargs: form=kwarg...
Why avoid while loops?
4,270,167
25
2010-11-24T18:17:22Z
4,270,191
10
2010-11-24T18:20:09Z
[ "python" ]
I'm about 2 weeks deep in my study of Python as an introductory language. I've hit a point in Zed's *"Learn Python the Hard Way"* where he suggests: > Use a while-loop only to loop forever, and that means probably never. This only applies > to Python, other languages are different. I've googled all over this, referen...
It's because in the typical situation where you want to iterate, python can handle it for you. For example: ``` >>> mylist = [1,2,3,4,5,6,7] >>> for item in mylist: ... print item ... 1 2 3 4 5 6 7 ``` Similar example with a dictionary: ``` >>> mydict = {1:'a', 2:'b', 3:'c', 4:'d'} >>> for key in mydict: ... ...
Why avoid while loops?
4,270,167
25
2010-11-24T18:17:22Z
4,270,267
9
2010-11-24T18:31:33Z
[ "python" ]
I'm about 2 weeks deep in my study of Python as an introductory language. I've hit a point in Zed's *"Learn Python the Hard Way"* where he suggests: > Use a while-loop only to loop forever, and that means probably never. This only applies > to Python, other languages are different. I've googled all over this, referen...
Python follows the philosophy of > There should be one-- and preferably > only one --obvious way to do it. (see <https://www.python.org/dev/peps/pep-0020/> for details). And in most cases there is a better way to do iterations in Python than using a while loop. Additionally at least CPython optimizes other kinds of...
Why avoid while loops?
4,270,167
25
2010-11-24T18:17:22Z
4,270,268
23
2010-11-24T18:31:39Z
[ "python" ]
I'm about 2 weeks deep in my study of Python as an introductory language. I've hit a point in Zed's *"Learn Python the Hard Way"* where he suggests: > Use a while-loop only to loop forever, and that means probably never. This only applies > to Python, other languages are different. I've googled all over this, referen...
The advice seems poor to me. When you're iterating over some kind of collection, it is usually *better* to use one of Python's iteration tools, but that doesn't mean that `while` is always wrong. There are lots of cases where you're not iterating over any kind of collection. For example: ``` def gcd(m, n): "Retur...
Should I wait for Django to start supporting Python 3?
4,270,192
7
2010-11-24T18:20:11Z
4,270,238
13
2010-11-24T18:27:21Z
[ "python", "django", "python-3.x" ]
I have a website idea that I'm very excited about, and I love Python. So, I'm interested in using Django. However, I started learning Python in version 3.1, and Django currently only supports various 2.x versions. I've searched for information about when Django will start supporting Python 3.x, and gotten mostly articl...
No. Don't wait. Why? **Pretty much all django libraries are written for Python 2.x**, and if you ever plan on using any of them with Python 3 with the next major release of Django then you'll be waiting not 1 but 3-4 years when everyone starts converting their code. In this time, you could have already mastered djang...
MatPlotLib: Multiple datasets on the same scatter plot
4,270,301
26
2010-11-24T18:35:46Z
4,270,437
43
2010-11-24T18:55:32Z
[ "python", "scipy", "matplotlib" ]
I want to plot multiple data sets on the same scatter plot: ``` cases = scatter(x[:4], y[:4], s=10, c='b', marker="s") controls = scatter(x[4:], y[4:], s=10, c='r', marker="o") show() ``` The above only shows the most recent `scatter()` I've also tried: ``` plt = subplot(111) plt.scatter(x[:4], y[:4], s=10, c='b',...
You need a reference to an `Axes` object to keep drawing on the same subplot. ``` import matplotlib.pyplot as plt x = range(100) y = range(100,200) fig = plt.figure() ax1 = fig.add_subplot(111) ax1.scatter(x[:4], y[:4], s=10, c='b', marker="s", label='first') ax1.scatter(x[40:],y[40:], s=10, c='r', marker="o", label...
How to remove whitespace in BeautifulSoup
4,270,742
6
2010-11-24T19:31:15Z
4,270,898
8
2010-11-24T19:49:03Z
[ "python", "regex", "html-parsing", "beautifulsoup" ]
I have a bunch of HTML I'm parsing with BeautifulSoup and it's been going pretty well except for one minor snag. I want to save the output into a single-lined string, with the following as my current output: ``` <li><span class="plaincharacterwrap break"> Zazzafooky but one two three! ...
Here is how you can do it without regular expressions: ``` >>> html = """ <li><span class="plaincharacterwrap break"> ... Zazzafooky but one two three! ... </span></li> ... <li><span class="plaincharacterwrap break"> ... Zazzafooky2 ... </span>...
What sets up sys.path with Python, and when?
4,271,494
41
2010-11-24T20:57:53Z
4,271,619
18
2010-11-24T21:14:07Z
[ "python", "path" ]
When I run ``` import sys print sys.path ``` on my Mac (Mac OS X 10.6.5, Python 2.6.1), I get the following results. ``` /Library/Python/2.6/site-packages/ply-3.3-py2.6.egg ... /Library/Python/2.6/site-packages/ipython-0.10.1-py2.6.egg /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python26.zip /Syste...
Most of the stuff is set up in Python's `site.py` which is automatically imported when starting the interpreter (unless you start it with the `-S` option). Few paths are set up in the interpreter itself during initialization (you can find out which by starting python with `-S`). Additionally, some frameworks (like Dja...
How can I use Python to get the system hostname?
4,271,740
309
2010-11-24T21:33:23Z
4,271,755
502
2010-11-24T21:36:29Z
[ "python", "hostname" ]
I'm writing a chat program for a local network. I would like be able to identify computers and get the user-set computer name with Python.
Use [`socket`](http://docs.python.org/library/socket.html) and its [`gethostname()`](http://docs.python.org/library/socket.html#socket.gethostname) functionality. This will get the `hostname` of the computer where the Python interpreter is running: ``` import socket print(socket.gethostname()) ```
How can I use Python to get the system hostname?
4,271,740
309
2010-11-24T21:33:23Z
4,271,768
12
2010-11-24T21:37:53Z
[ "python", "hostname" ]
I'm writing a chat program for a local network. I would like be able to identify computers and get the user-set computer name with Python.
If I'm correct, you're looking for the socket.gethostname function: ``` >> import socket >> socket.gethostname() 'terminus' ```
How can I use Python to get the system hostname?
4,271,740
309
2010-11-24T21:33:23Z
4,271,771
7
2010-11-24T21:38:13Z
[ "python", "hostname" ]
I'm writing a chat program for a local network. I would like be able to identify computers and get the user-set computer name with Python.
`socket.gethostname()` could do
How can I use Python to get the system hostname?
4,271,740
309
2010-11-24T21:33:23Z
4,271,873
201
2010-11-24T21:53:48Z
[ "python", "hostname" ]
I'm writing a chat program for a local network. I would like be able to identify computers and get the user-set computer name with Python.
Both of these are pretty portable: ``` import platform platform.node() import socket socket.gethostname() ``` Any solutions using the `HOST` or `HOSTNAME` environment variables are not portable. Even if it works on your system when you run it, it may not work when run in special environments such as cron.
How can I use Python to get the system hostname?
4,271,740
309
2010-11-24T21:33:23Z
8,699,611
27
2012-01-02T10:14:01Z
[ "python", "hostname" ]
I'm writing a chat program for a local network. I would like be able to identify computers and get the user-set computer name with Python.
What about : ``` import platform h = platform.uname()[1] ``` Actually you may want to have a look to all the result in `platform.uname()`
How can I use Python to get the system hostname?
4,271,740
309
2010-11-24T21:33:23Z
10,501,603
41
2012-05-08T15:23:41Z
[ "python", "hostname" ]
I'm writing a chat program for a local network. I would like be able to identify computers and get the user-set computer name with Python.
`os.getenv('HOSTNAME')` and `os.environ['HOSTNAME']` don't always work. In cron jobs and WSDL, HTTP HOSTNAME isn't set. Use this instead: ``` import socket socket.gethostbyaddr(socket.gethostname())[0] ``` It always (even on Windows) returns a fully qualified host name, even if you defined a short alias in */etc/host...
How can I use Python to get the system hostname?
4,271,740
309
2010-11-24T21:33:23Z
15,394,250
37
2013-03-13T19:06:15Z
[ "python", "hostname" ]
I'm writing a chat program for a local network. I would like be able to identify computers and get the user-set computer name with Python.
You will probably load the os module anyway, so another suggestion would be: ``` import os myhost = os.uname()[1] ```
Access django models inside of Scrapy
4,271,975
29
2010-11-24T22:09:42Z
4,274,134
13
2010-11-25T05:54:44Z
[ "python", "django", "scrapy" ]
Is it possible to access my django models inside of a Scrapy pipeline, so that I can save my scraped data straight to my model? I've seen [this](https://scrapy.readthedocs.org/en/latest/topics/djangoitem.html), but I don't really get how to set it up?
Add DJANGO\_SETTINGS\_MODULE env in your scrapy project's settings.py ``` import os os.environ['DJANGO_SETTINGS_MODULE'] = 'your_django_project.settings' ``` Now you can use DjangoItem in your scrapy project. Edit: You have to make sure that the `your_django_project` projects `settings.py` is available in `PYTHONP...
Access django models inside of Scrapy
4,271,975
29
2010-11-24T22:09:42Z
4,305,603
26
2010-11-29T16:10:19Z
[ "python", "django", "scrapy" ]
Is it possible to access my django models inside of a Scrapy pipeline, so that I can save my scraped data straight to my model? I've seen [this](https://scrapy.readthedocs.org/en/latest/topics/djangoitem.html), but I don't really get how to set it up?
If anyone else is having the same problem, this is how I solved it. I added this to my **scrapy** settings.py file: ``` def setup_django_env(path): import imp, os from django.core.management import setup_environ f, filename, desc = imp.find_module('settings', [path]) project = imp.load_module('settin...
Access django models inside of Scrapy
4,271,975
29
2010-11-24T22:09:42Z
9,197,627
20
2012-02-08T16:41:23Z
[ "python", "django", "scrapy" ]
Is it possible to access my django models inside of a Scrapy pipeline, so that I can save my scraped data straight to my model? I've seen [this](https://scrapy.readthedocs.org/en/latest/topics/djangoitem.html), but I don't really get how to set it up?
The opposite solution (setup scrapy in a django management command): ``` # -*- coding: utf-8 -*- # myapp/management/commands/scrapy.py from __future__ import absolute_import from django.core.management.base import BaseCommand class Command(BaseCommand): def run_from_argv(self, argv): self._argv = argv ...
SQLite date storage and conversion
4,272,908
9
2010-11-25T01:04:19Z
4,273,249
14
2010-11-25T02:25:38Z
[ "python", "sqlite" ]
I am having design problems with date storage/retrieval using Python and SQLite. I understand that a SQLite date column stores dates as text in ISO format (ie. `'2010-05-25'`). So when I display a British date (eg. on a web-page) I convert the date using ``` datetime.datetime.strptime(mydate,'%Y-%m-%d').strftime('%d/...
If you set `detect_types=sqlite3.PARSE_DECLTYPES` in `sqlite3.connect`, then the connection will try to convert sqlite data types to Python data types when you draw data out of the database. This is a very good thing since its much nicer to work with datetime objects than random date-like strings which you then have t...
A shorter way to express this? C = A if A else B
4,272,970
3
2010-11-25T01:16:05Z
4,272,993
16
2010-11-25T01:20:14Z
[ "python" ]
I find myself repeating this a lot: ``` val = x if x else y ``` Sometimes `x` goes several levels deep into a class or dictionary so it gets very long: ``` val = obj.elements[0].something if obj.elements[0].something else y ``` It looks ugly and forces me to type a lot more. Any known ways to shorten this? Perhaps ...
The `or` operator returns the first argument that converts to True: ``` val = x or y ``` E.g.: ``` >>> None or 'OK' 'OK' ```
Detect inserted USB on Windows
4,273,252
5
2010-11-25T02:28:05Z
4,274,450
7
2010-11-25T06:56:18Z
[ "python", "windows", "usb" ]
I am currently writing a security tool in python that runs as a daemon on a host computer. Whenever a usb storage device is detected, it will copy all of the files from the usb to some dir on the host computer. Is there any easy way to do this sort of usb detection / interface? Thanks in advance!
Yes, you need to use the [`RegisterDeviceNotification`](http://msdn.microsoft.com/en-us/library/aa363432%28VS.85%29.aspx) Windows API call. As far as I know, there is no Python module that wraps this functionality, so you have to use [`ctypes`](http://python.net/crew/theller/ctypes/) to call this function. Fortunately...
Reversible hash function?
4,273,466
19
2010-11-25T03:18:50Z
4,274,259
12
2010-11-25T06:18:31Z
[ "python", "hash" ]
I need a reversible hash function (obviously the input will be much smaller in size than the output) that maps the input to the output in a random-looking way. Basically, I want a way to transform a number like "123" to a larger number like "9874362483910978", but not in a way that will preserve comparisons, so it must...
What you are asking for *is* encryption. A block cipher in its basic mode of operation, ECB, reversibly maps a input block onto an output block of the same size. The input and output blocks can be interpreted as numbers. For example, AES is a 128 bit block cipher, so it maps an input 128 bit number onto an output 128 ...
Reversible hash function?
4,273,466
19
2010-11-25T03:18:50Z
13,018,842
24
2012-10-22T19:57:27Z
[ "python", "hash" ]
I need a reversible hash function (obviously the input will be much smaller in size than the output) that maps the input to the output in a random-looking way. Basically, I want a way to transform a number like "123" to a larger number like "9874362483910978", but not in a way that will preserve comparisons, so it must...
None of the answers provided seemed particularly useful, given the question. I had the same problem, needing a simple, reversible hash for not-security purposes, and decided to go with bit relocation. The simplest would probably be: ``` def hash(n): return ((0x0000FFFF & n)<<16) + ((0xFFFF0000 & n)>>16) ``` This is...
Get actual disk space
4,274,899
10
2010-11-25T08:12:24Z
7,285,509
8
2011-09-02T15:12:05Z
[ "python" ]
How do I get the actual filesize on disk in python? (the actual size it takes on the harddrive). Thanks.
UNIX only: ``` import os from collections import namedtuple _ntuple_diskusage = namedtuple('usage', 'total used free') def disk_usage(path): """Return disk usage statistics about the given path. Returned valus is a named tuple with attributes 'total', 'used' and 'free', which are the amount of total, us...
Do i need node.js in Python like I would with PHP?
4,276,205
11
2010-11-25T10:52:30Z
4,277,686
9
2010-11-25T13:42:40Z
[ "php", "python", "twisted", "node.js", "nonblocking" ]
I have been using PHP for some time now. And I have been thinking about learning node.js to go along with it to use the non blocking idea for creating an online game or app. There is quite a bit of info on using the two together. Using node as part of the back end of a game could really speed up some aspects of the gam...
While Python can definitely be used for Asynchronous Programming, it doesn't feel natural, even with Twisted, if you compare it to Node.js it just doesn't look or feel *that* nice. Since you're planing on doing a real-time Web Game, you'll most likely will end up using [WebSockets](http://stackoverflow.com/questions/4...
os.walk exclude .svn folders
4,276,255
12
2010-11-25T10:58:31Z
4,276,297
7
2010-11-25T11:03:01Z
[ "python" ]
I got a script that I want to use to change a repeated string throughout a project folder structure. Once changed then I can check this into SVN. However when I run my script it goes into the .svn folders which I want it to ingore. How can I achieve this? Code below, thanks. ``` import os import sys replacement = "ne...
[Err... what?](http://docs.python.org/library/os.html#os.walk) > When topdown is True, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, impose a specific o...
os.walk exclude .svn folders
4,276,255
12
2010-11-25T10:58:31Z
4,276,301
27
2010-11-25T11:03:12Z
[ "python" ]
I got a script that I want to use to change a repeated string throughout a project folder structure. Once changed then I can check this into SVN. However when I run my script it goes into the .svn folders which I want it to ingore. How can I achieve this? Code below, thanks. ``` import os import sys replacement = "ne...
Try this: ``` for root, subFolders, files in os.walk(rootdir): if '.svn' in subFolders: subFolders.remove('.svn') ``` And then continue processing.
declaring a global dynamic variable in python
4,277,056
3
2010-11-25T12:27:41Z
4,277,188
7
2010-11-25T12:44:13Z
[ "python" ]
I'm a python/programming newbie and maybe my question has no sense at all. My problem is that I can't get a variable to be global if it is dynamic, I mean I can do this: ``` def creatingShotInstance(): import movieClass BrokenCristals = movieClass.shot() global BrokenCristals #here I declare BrokenCrist...
Instead of a dynamic global variable, use a dict: ``` movies = {} a = 'BrokenCristals' movies[a] = movieClass.shot() movies[a].set_name(a) # etc ```
declaring a global dynamic variable in python
4,277,056
3
2010-11-25T12:27:41Z
4,277,885
8
2010-11-25T14:05:02Z
[ "python" ]
I'm a python/programming newbie and maybe my question has no sense at all. My problem is that I can't get a variable to be global if it is dynamic, I mean I can do this: ``` def creatingShotInstance(): import movieClass BrokenCristals = movieClass.shot() global BrokenCristals #here I declare BrokenCrist...
For completeness, here's the answer to your original question. But it's almost certainly not what you meant to do -- there are very few cases where modifying the scope's `dict` is the right thing to do. ``` globals()[a] = 'whatever' ```
Python: how to cut off sequences of more than 2 equal characters in a string
4,278,313
5
2010-11-25T14:51:10Z
4,278,385
7
2010-11-25T15:01:37Z
[ "python", "regex", "string" ]
I'm looking for an efficient way to chance a string such that all sequences of more than 2 equal characters are cut off after the first 2. Some input->output examples are: ``` hellooooooooo -> helloo woooohhooooo -> woohhoo ``` I'm currently looping over the characters, but it's a bit slow. Does anyone have another ...
**Edit: after applying helpful comments** ``` import re def ReplaceThreeOrMore(s): # pattern to look for three or more repetitions of any character, including # newlines. pattern = re.compile(r"(.)\1{2,}", re.DOTALL) return pattern.sub(r"\1\1", s) ``` --- *(original response here)* Try something li...
danger of recursive functions
4,278,327
5
2010-11-25T14:53:16Z
4,278,387
7
2010-11-25T15:01:51Z
[ "python", "recursion" ]
Often people say that it's not recommended to use recursive functions in python (recursion depth restrictions, memory consumption, etc) I took a permutation example from [this question](http://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python). ``` def all_perms(str): if len(st...
Recursion is *good* for problems that lend themselves to clean, clear, recursive implementations. But like all programming you must perform some algorithm analysis to understand the performance characteristics. In the case of recursion, besides number of operations you must also estimate the maximum stack depth. Most ...
Python's underlying hash data structure for dictionaries
4,279,358
8
2010-11-25T17:00:49Z
4,279,606
21
2010-11-25T17:32:14Z
[ "python", "algorithm", "performance", "data-structures" ]
I am build a very large dictionary and I am performing many checks to see if a key is in the structure and then adding if it unique or incrementing a counter if it is identical. Python uses a [hash data structure](http://wiki.python.org/moin/DictionaryKeys) to store dictionaries (not to be confused with a cryptographi...
The only way to be sure would be to implement both and check, but my informed guess is that the dictionary will be faster, because a binary search tree has cost O(log(n)) for lookup and insertion, and I think that except under the most pessimal of situations (such as massive hash collisions) the hash table's O(1) looku...
Is there a more pythonic way to find the point in a list which is closest to another point?
4,280,554
11
2010-11-25T20:11:16Z
4,280,573
19
2010-11-25T20:14:25Z
[ "python" ]
I have a list of 2d points, and would like to find the one which is closest to a given point. The code (get\_closest\_point()) below does what I want. But is there a nicer way to do this in python? ``` class Circle(object): def __init__(self, pos): self.position = pos class Point(object): .. def ...
You can use the `key` argument to the `min()` function: Edit: after some consideration, this should be a method of your `Point` class, and i'll fix some other obvious deficiencies: ``` class Point(object): def get_closest_point(self, points): return min(points, key=self.compute_distance_to) ``` or, to do...
list.reverse does not return list?
4,280,691
10
2010-11-25T20:39:31Z
4,280,702
16
2010-11-25T20:40:49Z
[ "python", "functional-programming" ]
The return object is named `None` for `list.reverse()`. So this code fails when I call `solution(k)`. Is there any way I can get around making a temporary? Or how should I do it? ``` fCamel = 'F' bCamel = 'B' gap = ' ' k = ['F', ' ', 'B', 'F'] def solution(formation): return ((formation.index(bCamel) > (len(form...
You can use `reversed(formation)` to return a reverse iterator of `formation`. When you call `formation.reverse()` it does an in place reversal of the list and returns None. EDIT: I see what you are trying to do now, in my opinion it's easier to just do this with a list comprehension: ``` def solution(formation): ...
list.reverse does not return list?
4,280,691
10
2010-11-25T20:39:31Z
18,994,210
8
2013-09-25T00:18:19Z
[ "python", "functional-programming" ]
The return object is named `None` for `list.reverse()`. So this code fails when I call `solution(k)`. Is there any way I can get around making a temporary? Or how should I do it? ``` fCamel = 'F' bCamel = 'B' gap = ' ' k = ['F', ' ', 'B', 'F'] def solution(formation): return ((formation.index(bCamel) > (len(form...
You can use splicing to return the reversed list: ``` l[::-1] ```
Unpicking data pickled in Python 2.5, in Python 3.1 then uncompressing with zlib
4,281,619
7
2010-11-25T23:53:20Z
4,281,802
10
2010-11-26T00:39:20Z
[ "python", "pickle", "zlib" ]
In Python 2.5 I stored data using this code: ``` def GLWriter(file_name, string): import cPickle import zlib data = zlib.compress(str(string)) file = open(file_name, 'w') cPickle.dump(data, file) ``` It worked fine, I was able to read that data by doing that process in reverse. It didn't need to be sec...
The problem is that Python 3 is attempting to convert the pickled Python 2 string into a `str` object, when you really need it to be `bytes`. It does this using the `ascii` codec, which doesn't support all 256 8-bit characters, so you are getting an exception. You can work around this by using the `latin-1` encoding (...
check files for equality
4,283,639
5
2010-11-26T08:32:44Z
4,284,082
8
2010-11-26T09:38:34Z
[ "python", "file", "equality" ]
what's the most elegant way to check to files for equality in Python? Checksum? Bytes comparing? Think files wont' be larger than 100-200 MB
What about `filecmp` module? It can do file comparison in many different ways with different tradeoffs. And even better, it is part of the standard library: <http://docs.python.org/library/filecmp.html>
How to import part of a module in python?
4,283,876
4
2010-11-26T09:08:34Z
4,283,887
9
2010-11-26T09:09:57Z
[ "python", "module", "import" ]
I need to use a python module (available in some library). The module looks like this: ``` class A: def f1(): ... print "Done" ... ``` I need only the functionality of class A. However, when I import the module, the code at bottom (print and others) gets executed. Is there a way to avoid that? Essentially I need...
Yes, sure: ``` from module1 import A ``` Is the general syntax. For example: ``` from datetime import timedelta ``` The code at the bottom should be protected from running at import time by being wrapped like so: ``` if __name__ == "__main__": # Put code that should only run when the module # is used as a stan...
What is the clean way to unittest FileField in django?
4,283,933
25
2010-11-26T09:16:22Z
4,287,271
10
2010-11-26T17:08:04Z
[ "python", "django", "filefield", "django-unittest" ]
I have a model with a FileField. I want to unittest it. django test framework has great ways to manage database and emails. Is there something similar for FileFields? How can I make sure that the unittests are not going to pollute the real application? Thanks in advance PS: My question is almost a duplicate of [Djan...
I normally test filefields in models using doctest ``` >>> from django.core.files import File >>> s = SimpleModel() >>> s.audio_file = File(open("media/testfiles/testaudio.wav")) >>> s.save() >>> ... >>> s.delete() ``` If I need to I also test file uploads with test clients. As for fixtures, I simply copy the files ...
What is the clean way to unittest FileField in django?
4,283,933
25
2010-11-26T09:16:22Z
4,547,203
24
2010-12-28T15:41:35Z
[ "python", "django", "filefield", "django-unittest" ]
I have a model with a FileField. I want to unittest it. django test framework has great ways to manage database and emails. Is there something similar for FileFields? How can I make sure that the unittests are not going to pollute the real application? Thanks in advance PS: My question is almost a duplicate of [Djan...
There are several ways you could tackle this but they're all ugly since unit tests are supposed to be isolated but files are all about durable changes. My unit tests don't run on a system with production data so it's been easy to simply reset the upload directory after each run with something like `git reset --hard`. ...
What is the clean way to unittest FileField in django?
4,283,933
25
2010-11-26T09:16:22Z
20,508,621
37
2013-12-11T01:06:30Z
[ "python", "django", "filefield", "django-unittest" ]
I have a model with a FileField. I want to unittest it. django test framework has great ways to manage database and emails. Is there something similar for FileFields? How can I make sure that the unittests are not going to pollute the real application? Thanks in advance PS: My question is almost a duplicate of [Djan...
Django provides a great way to do this - use a SimpleUploadedFile. ``` from django.core.files.uploadedfile import SimpleUploadedFile my_model.file_field = SimpleUploadedFile('best_file_eva.txt', 'these are the file contents!') ``` It's one of django's magical features-that-don't-show-up-in-the-docs :). However it is...
How can I check the syntax of Python script without executing it?
4,284,313
181
2010-11-26T10:12:50Z
4,284,448
38
2010-11-26T10:29:15Z
[ "python", "syntax-checking" ]
I used to use `perl -c programfile` to check the syntax of a Perl program and then exit without executing it. Is there an equivalent way to do this for a Python script?
You can use these tools: * [PyChecker](http://pychecker.sourceforge.net/) * [Pyflakes](https://github.com/pyflakes/pyflakes) * [Pylint](http://www.logilab.org/857)
How can I check the syntax of Python script without executing it?
4,284,313
181
2010-11-26T10:12:50Z
4,284,526
8
2010-11-26T10:39:11Z
[ "python", "syntax-checking" ]
I used to use `perl -c programfile` to check the syntax of a Perl program and then exit without executing it. Is there an equivalent way to do this for a Python script?
``` import sys filename = sys.argv[1] source = open(filename, 'r').read() + '\n' compile(source, filename, 'exec') ``` Save this as checker.py and run `python checker.py yourpyfile.py`.
How can I check the syntax of Python script without executing it?
4,284,313
181
2010-11-26T10:12:50Z
8,437,597
273
2011-12-08T20:57:16Z
[ "python", "syntax-checking" ]
I used to use `perl -c programfile` to check the syntax of a Perl program and then exit without executing it. Is there an equivalent way to do this for a Python script?
You can check the syntax by compiling it: ``` python -m py_compile script.py ```
Converting lists of tuples to strings Python
4,284,648
14
2010-11-26T10:55:28Z
4,284,697
18
2010-11-26T11:02:32Z
[ "python", "string", "list", "tuples" ]
I've written a function in python that returns a list, for example ``` [(1,1),(2,2),(3,3)] ``` But i want the output as a string so i can replace the comma with another char so the output would be ``` '1@1' '2@2' '3@3' ``` Any easy way around this?:) Thanks for any tips in advance
This looks like a `list` of `tuple`s, where each `tuple` has two elements. ``` ' '.join(['%d@%d' % (t[0],t[1]) for t in l]) ``` Which can of course be simplified to: ``` ' '.join(['%d@%d' % t for t in l]) ``` Or even: ``` ' '.join(map(lambda t: '%d@%d' % t, l)) ``` Where `l` is your original `list`. This generate...
Find gaps in a sequence of Strings
4,284,740
6
2010-11-26T11:09:23Z
4,284,867
9
2010-11-26T11:28:55Z
[ "python" ]
I have got a sequence of strings - `0000001, 0000002, 0000003....` upto 2 million. They are not contiguous. Meaning there are gaps. Say after 0000003 the next string might be 0000006. I need to find out all these gaps. In the above case (0000004, 0000005). This is what I have done so far - ``` gaps = list() total = ...
You could sort the list of ids and then step through it once only: ``` def find_gaps(ids): """Generate the gaps in the list of ids.""" j = 1 for id_i in sorted(ids): while True: id_j = '%07d' % j j += 1 if id_j >= id_i: break yield id_...
Logging from Django under UWSGI
4,284,859
9
2010-11-26T11:27:38Z
6,388,083
10
2011-06-17T15:26:57Z
[ "python", "django", "uwsgi" ]
I am running my django app via uwsgi server and am starting 32 processes -args in my init script are: ``` ARGS="--pidfile ${PIDFILE} --uid ${UID} -s /tmp/${NAME}.sock --pythonpath ${GCS_HOME}/server/src/gcs --master -w wsgi -d ${GCS_HOME}/logs/uwsgi.log -p 32 -z 30" ``` Versions are Python 2.6.5 , Django 1.2.1, uWSGI...
**ANSWER HAS BEEN UPDATED -May 15, 2013 - see bottom for additional logging option** If you want to have a single log file - use syslog, let it handle multiplexing all the inputs into a single file. Having multiple processes appending to a single file is ugly, even with multiprocessing's workarounds. Aside from the a...
parsing nested parentheses in python, grab content by level
4,284,991
9
2010-11-26T11:44:45Z
4,285,211
16
2010-11-26T12:14:49Z
[ "python", "parsing", "parentheses" ]
Apparently this problem comes up fairly often, after reading [Regular expression to detect semi-colon terminated C++ for & while loops](http://stackoverflow.com/questions/524548/regular-expression-to-detect-semi-colon-terminated-c-for-while-loops/524624#524624) and thinking about the problem for a while, i wrote a fu...
You don't make it clear exactly what the specification of your function is, but this behaviour seems wrong to me: ``` >>> ParseNestedParen('(a)(b)(c)', 0) ['a)(b)(c'] >>> nested_paren.ParseNestedParen('(a)(b)(c)', 1) ['b'] >>> nested_paren.ParseNestedParen('(a)(b)(c)', 2) [''] ``` Other comments on your code: * Docs...
Matplotlib: rotating a patch
4,285,103
9
2010-11-26T12:00:08Z
4,891,658
8
2011-02-03T20:58:15Z
[ "python", "matplotlib" ]
I wanted to rotate a Rectangle in matplotlib but when I apply the transformation, the rectangle doesn't show anymore: ``` rect = mpl.patches.Rectangle((0.0120,0),0.1,1000) t = mpl.transforms.Affine2D().rotate_deg(45) rect.set_transform(t) ``` is this a known bug or do I make a mistake?
The patch in the provided code makes it hard to tell what's going on, so I've made a clear demonstration that I worked out from a matplotlib example: ``` import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches import matplotlib as mpl fig = plt.figure() ax = fig.add_subplot(111) r1 = ...
Upper memory limit?
4,285,185
11
2010-11-26T12:11:09Z
4,285,265
13
2010-11-26T12:26:02Z
[ "python", "memory" ]
Is there a limit to memory for python? I've been using a python script to calculate the average values from a file which is a minimum of 150mb big. Depending on the size of the file I sometimes encounter a `MemoryError`. Can more memory be assigned to the python so I don't encounter the error? --- EDIT: Code now be...
You're reading the entire file into memory (`line = u.readlines()`) which will fail of course if the file is too large (and you say that some are up to 20 GB), so that's your problem right there. Better iterate over each line: ``` for current_line in u: do_something_with(current_line) ``` is the recommended appr...
Upper memory limit?
4,285,185
11
2010-11-26T12:11:09Z
4,285,292
8
2010-11-26T12:30:21Z
[ "python", "memory" ]
Is there a limit to memory for python? I've been using a python script to calculate the average values from a file which is a minimum of 150mb big. Depending on the size of the file I sometimes encounter a `MemoryError`. Can more memory be assigned to the python so I don't encounter the error? --- EDIT: Code now be...
Python can use all memory available to its environment. My simple "memory test" crashes on ActiveState Python 2.6 after using about ``` 1959167 [MiB] ``` On jython 2.5 it crashes earlier: ``` 239000 [MiB] ``` probably I can configure Jython to use more memory (it uses limits from JVM) Test app: ``` sl = [] i = 0...
Upper memory limit?
4,285,185
11
2010-11-26T12:11:09Z
4,289,489
15
2010-11-27T00:51:55Z
[ "python", "memory" ]
Is there a limit to memory for python? I've been using a python script to calculate the average values from a file which is a minimum of 150mb big. Depending on the size of the file I sometimes encounter a `MemoryError`. Can more memory be assigned to the python so I don't encounter the error? --- EDIT: Code now be...
*This is my third answer because I misunderstood what your code was doing in my original, and then made a small but crucial mistake in my second -- so hopefully three's a charm.)* As others have pointed out, your `MemoryError` problem is most likely because you're attempting to read the entire contents of huge files i...
how to have a directory dialog in Pyqt
4,286,036
15
2010-11-26T14:19:00Z
4,286,104
23
2010-11-26T14:28:49Z
[ "python", "pyqt" ]
How to have a file dialog that select only directories not files in PyQt? And how do I retrieve the name of the selected directory?
From inside your QDialog/QWidget class, you should be able to do: ``` file = str(QFileDialog.getExistingDirectory(self, "Select Directory")) ```
Django Templates First element of a List
4,286,461
13
2010-11-26T15:19:41Z
4,286,486
36
2010-11-26T15:22:27Z
[ "python", "django", "django-templates", "django-filters" ]
I pass a dictionary to my Django Template, Dictionary & Template is like this - ``` lists[listid] = {'name': l.listname, 'docs': l.userdocs.order_by('-id')} {% for k, v in lists.items %} <ul><li>Count: {{ v.docs.count }}, First: {{ v.docs|first }}</li></ul> {% endfor %} ``` Now `docs` is a list of `userdocs` ty...
You can use the `{% with %}` templatetag for this sort of thing. ``` {% with v.docs|first as first_doc %}{{ first_doc.id }}{% endwith %} ```
Write lines longer than 80 chars in output file [Python]
4,286,544
5
2010-11-26T15:29:17Z
4,286,619
16
2010-11-26T15:42:15Z
[ "python", "file-io", "numpy" ]
I've got a pretty basic question. I'm using Python to calculate an n×12 vector ``` y = numpy.array([V1,V2,V3,V4,V5,V6,V7,V8,V9,V10,V11,V12]) ``` which I append after each loop calculation. My problem is that when I try to save it to a file or print it Python automatically breaks the result in three lines as my outp...
You can use [`numpy.savetxt()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html) to save an array to a text file while controlling the formatting. To print it to the screen, you have different options to control the linewidth. One would be to call ``` numpy.set_printoptions(linewidth=200) ``` t...
Stuck with Python HTTP Server with Basic Authentication using BaseHTTP
4,287,019
8
2010-11-26T16:34:23Z
8,153,189
13
2011-11-16T14:24:34Z
[ "python", "http-authentication", "basehttpserver" ]
I am stuck trying to get a python based webserver to work. I want to do Basic Authentication (sending a 401 header) and authenticating against a list of users. I have no trouble sending the 401 response with "WWW-Authorize" header, I can validate the users response (base64 encoded username & password), however, the lo...
Try this for size: ``` import SimpleHTTPServer import SocketServer from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer class Handler(BaseHTTPRequestHandler): ''' Main class to present webpages and authentication. ''' def do_HEAD(self): print "send header" self.send_response(200) ...
Python Iterators: What does iglob()'s Iterator provide over glob()'s list?
4,287,162
9
2010-11-26T16:53:08Z
4,287,196
12
2010-11-26T16:57:49Z
[ "python", "iterator" ]
Given the piece of code: ``` from glob import glob, iglob for fn in glob('/*'): print fn print '' for fn in iglob('/*'): print fn ``` Reading the [documentation](http://docs.python.org/library/glob.html) for glob I see that glob() returns a basic list of files and iglob an Iterator. However I'm able to ite...
The difference is mentioned in the documentation itself: > Return an iterator which yields the same values as glob() without actually storing them all simultaneously. Basically list will have all the items in memory. Iterator need not, and hence it requires less memory.
Sort list of strings by integer suffix in python
4,287,209
4
2010-11-26T16:59:57Z
4,287,233
10
2010-11-26T17:03:03Z
[ "python" ]
I have a list of strings: ``` [song_1, song_3, song_15, song_16, song_4, song_8] ``` I would like to sort them by the # at the end, unfortunately since the lower numbers aren't "08" and are "8", they are treated as larger than 15 in lexicographical order. I know I have to pass a key to the sort function, I saw this ...
You're close. ``` sorted(the_list, key = lambda x: int(x.split("_")[1])) ``` should do it. This splits on the underscore, takes the second part (i.e. the one after the first underscore), and converts it to integer to use as a key.
Easiest way to perform modular matrix inversion with Python?
4,287,721
14
2010-11-26T18:28:03Z
4,293,123
7
2010-11-27T18:10:28Z
[ "python", "matrix", "number-theory", "matrix-inverse" ]
I'd like to take the modular inverse of a matrix like [[1,2],[3,4]] mod 7 in Python. I've looked at numpy (which does matrix inversion but not modular matrix inversion) and I saw a few number theory packages online, but nothing that seems to do this relatively common procedure (at least, it seems relatively common to m...
Okay...for those who care, I solved my own problem. It took me a while, but I think this works. It's probably not the most elegant, and should include some more error handling, but it works: ``` import numpy import math from numpy import matrix from numpy import linalg def modMatInv(A,p): # Finds the inverse of...
Easiest way to perform modular matrix inversion with Python?
4,287,721
14
2010-11-26T18:28:03Z
6,700,803
11
2011-07-14T22:38:55Z
[ "python", "matrix", "number-theory", "matrix-inverse" ]
I'd like to take the modular inverse of a matrix like [[1,2],[3,4]] mod 7 in Python. I've looked at numpy (which does matrix inversion but not modular matrix inversion) and I saw a few number theory packages online, but nothing that seems to do this relatively common procedure (at least, it seems relatively common to m...
A hackish way to do it for your purposes is to take the regular inverse, which is already implemented in numpy. Now find the determinant, which is implemented in numpy. Now multiply the regular inverse by the determinant, round to integers, and then multiply everything by the determinant's multiplicative inverse (modul...
Downloading videos in flv format from youtube.
4,287,748
11
2010-11-26T18:34:19Z
4,287,778
15
2010-11-26T18:37:45Z
[ "python", "download", "youtube", "urllib2" ]
I cant really understand how youtube serves videos but I have been reading through what I can, it seems like the old method get\_video is now obsolete and can't be used any more so because of this I am asking if there is another pythonic and simple method for collecting youtube videos.
You might have some luck with youtube-dl <http://rg3.github.com/youtube-dl/documentation.html> I'm not sure if there's a good API, but it's written in Python, so theoretically you could do something a little better than Popen :)
How can I list or discover queues on a RabbitMQ exchange using python?
4,287,941
19
2010-11-26T19:06:59Z
4,288,304
12
2010-11-26T20:14:38Z
[ "python", "rabbitmq", "amqp" ]
I need to have a python client that can discover queues on a restarted RabbitMQ server exchange, and then start up a clients to resume consuming messages from each queue. How can I discover queues from some RabbitMQ compatible python api/library?
As far as I know, there isn't any way of doing this. That's nothing to do with Python, but because AMQP doesn't define any method of queue discovery. In any case, in AMQP it's clients (consumers) that declare queues: publishers publish messages to an exchange with a routing key, and consumers determine which queues th...
How can I list or discover queues on a RabbitMQ exchange using python?
4,287,941
19
2010-11-26T19:06:59Z
8,163,144
27
2011-11-17T06:44:27Z
[ "python", "rabbitmq", "amqp" ]
I need to have a python client that can discover queues on a restarted RabbitMQ server exchange, and then start up a clients to resume consuming messages from each queue. How can I discover queues from some RabbitMQ compatible python api/library?
There does not seem to be a direct AMQP-way to manage the server but there is a way you can do it from Python. I would recommend using a *subprocess* module combined with the `rabbitmqctl` command to check the status of the queues. I am assuming that you are running this on Linux. From a command line, running: ``` ra...
How can I list or discover queues on a RabbitMQ exchange using python?
4,287,941
19
2010-11-26T19:06:59Z
21,286,370
11
2014-01-22T14:59:58Z
[ "python", "rabbitmq", "amqp" ]
I need to have a python client that can discover queues on a restarted RabbitMQ server exchange, and then start up a clients to resume consuming messages from each queue. How can I discover queues from some RabbitMQ compatible python api/library?
You can add plugin rabbitmq\_management ``` sudo /usr/lib/rabbitmq/bin/rabbitmq-plugins enable rabbitmq_management sudo service rabbitmq-server restart ``` Then use rest-api ``` import requests def rest_queue_list(user='guest', password='guest', host='localhost', port=15672, virtual_host=None): url = 'http://%s...
How do you do an os.path.join with an array in python?
4,288,792
6
2010-11-26T21:58:37Z
4,288,809
20
2010-11-26T22:01:00Z
[ "python", "join", "path", "operating-system" ]
How do you do an os.path.join with an array in python? Basically, I want to be able to run that command with an array as an argument. Any help is highly appreciated.
By array I assume you mean list. ``` os.path.join(*parts) ``` The \* takes a list (or similar object) and expands it into parameters. Be careful using it, in many situations it will make your code harder to read. But here is makes sense.
What's the difference between %s and %d in Python string formatting?
4,288,973
48
2010-11-26T22:35:16Z
4,288,983
81
2010-11-26T22:36:49Z
[ "python", "string-formatting" ]
I don't understand what `%s` and `%d` do and how they work.
They are used for formatting strings. `%s` acts a placeholder for a string while `%d` acts as a placeholder for a number. Their associated values are passed in via a tuple using the `%` operator. ``` name = 'marcog' number = 42 print '%s %d' % (name, number) ``` will print `marcog 42`. Note that name is a string (%s)...
What's the difference between %s and %d in Python string formatting?
4,288,973
48
2010-11-26T22:35:16Z
4,288,987
9
2010-11-26T22:37:44Z
[ "python", "string-formatting" ]
I don't understand what `%s` and `%d` do and how they work.
%s is used as a placeholder for string values you want inject into a formatted string. %d is used as a placeholder for numeric or decimal values.
What's the difference between %s and %d in Python string formatting?
4,288,973
48
2010-11-26T22:35:16Z
31,279,690
7
2015-07-07T21:33:36Z
[ "python", "string-formatting" ]
I don't understand what `%s` and `%d` do and how they work.
These are placeholders: For example: `'Hi %s I have %d donuts' %('Alice', 42)` This line of code will substitute %s with Alice (str) and %d with 42. Output: `'Hi Alice I have 42 donuts'` This could be achieved with a "+" most of the time. To gain a deeper understanding to your question, you may want to check {} / ....
Python - caching a property to avoid future calculations
4,289,064
4
2010-11-26T22:55:11Z
4,291,260
8
2010-11-27T10:54:27Z
[ "python", "django", "caching", "attributes", "properties" ]
In the following example, `cached_attr` is used to get or set an attribute on a model instance when a database-expensive property (`related_spam` in the example) is called. In the example, I use `cached_spam` to save queries. I put print statements when setting and when getting values so that I could test it out. I tes...
Nothing wrong with your code, as far as it goes. The problem probably isn't there, but in how you use that code. The main thing to realise is that model instances don't have identity. That means that if you instantiate an Egg object somewhere, and a different one somewhere else, even if they refer to the same underlyi...
Python: Extract numbers from a string
4,289,331
146
2010-11-27T00:00:40Z
4,289,348
174
2010-11-27T00:04:21Z
[ "python", "regex", "string", "numbers" ]
I would extract all the numbers contained in a string. Which is the better suited for the purpose, regular expressions or the `isdigit()` method? Example: ``` line = "hello 12 hi 89" ``` Result: ``` [12, 89] ```
I'd use a regexp : ``` >>> import re >>> re.findall(r'\d+', 'hello 42 I\'m a 32 string 30') ['42', '32', '30'] ``` This would also match 42 from `bla42bla`. If you only want numbers delimited by word boundaries (space, period, comma), you can use \b : ``` >>> re.findall(r'\b\d+\b', 'he33llo 42 I\'m a 32 string 30') ...
Python: Extract numbers from a string
4,289,331
146
2010-11-27T00:00:40Z
4,289,415
43
2010-11-27T00:28:48Z
[ "python", "regex", "string", "numbers" ]
I would extract all the numbers contained in a string. Which is the better suited for the purpose, regular expressions or the `isdigit()` method? Example: ``` line = "hello 12 hi 89" ``` Result: ``` [12, 89] ```
I'm assuming you want floats not just integers so I'd do something like this: ``` l = [] for t in s.split(): try: l.append(float(t)) except ValueError: pass ``` Note that some of the other solutions posted here don't work with negative numbers: ``` >>> re.findall(r'\b\d+\b', 'he33llo 42 I\'m ...
Python: Extract numbers from a string
4,289,331
146
2010-11-27T00:00:40Z
4,289,557
159
2010-11-27T01:14:13Z
[ "python", "regex", "string", "numbers" ]
I would extract all the numbers contained in a string. Which is the better suited for the purpose, regular expressions or the `isdigit()` method? Example: ``` line = "hello 12 hi 89" ``` Result: ``` [12, 89] ```
If you only want to extract only positive integers, try the following: ``` >>> str = "h3110 23 cat 444.4 rabbit 11 2 dog" >>> [int(s) for s in str.split() if s.isdigit()] [23, 11, 2] ``` I would argue that this is better than the regex example for three reasons. First, you don't need another module; secondly, it's mo...
Python: Extract numbers from a string
4,289,331
146
2010-11-27T00:00:40Z
29,581,287
30
2015-04-11T18:07:30Z
[ "python", "regex", "string", "numbers" ]
I would extract all the numbers contained in a string. Which is the better suited for the purpose, regular expressions or the `isdigit()` method? Example: ``` line = "hello 12 hi 89" ``` Result: ``` [12, 89] ```
This is more than a bit late, but you can extend the regex expression to account for scientific notation too. ``` >>> ss = ["apple-12.34 ba33na fanc-14.23e-2yapple+45e5+67.56E+3", 'hello X42 I\'m a Y-32.35 string Z30', 'he33llo 42 I\'m a 32 string -30', 'h3110 23 cat 444.4 rabbit 11 2 dog...
Python: Extract numbers from a string
4,289,331
146
2010-11-27T00:00:40Z
36,434,101
8
2016-04-05T18:20:43Z
[ "python", "regex", "string", "numbers" ]
I would extract all the numbers contained in a string. Which is the better suited for the purpose, regular expressions or the `isdigit()` method? Example: ``` line = "hello 12 hi 89" ``` Result: ``` [12, 89] ```
If you know it will be only one number in the string, i.e 'hello 12 hi', you can try filter. For example: ``` In [1]: int(filter(str.isdigit, '200 grams')) Out[1]: 200 In [2]: int(filter(str.isdigit, 'Counters: 55')) Out[2]: 55 In [3]: int(filter(str.isdigit, 'more than 23 times')) Out[3]: 23 ``` But be carefull !!!...
How to speed up string concatenation in Python?
4,289,777
3
2010-11-27T02:19:58Z
4,289,816
7
2010-11-27T02:35:14Z
[ "python" ]
In the code below concatenation is the bottleneck. As you can see i've tried some sophisticated methods to speed this up, but its bloody slow anyway. I would like to know if there is anything i can do to make it faste. BTW both plain and secret are data read from binary file and they are quite big (around 1mb) ``` x ...
Python's lists have O(1) append, at least in the amortized sense. Instead of doing the join in the innermost list, you could build one big list and then join them at the end. This will turn your algorithm from O(N^2) to O(N). It's tough to give you working code without knowing exactly what your setBit() and getBit() fu...
change matplotlib axis settings
4,289,891
9
2010-11-27T02:55:55Z
4,290,393
12
2010-11-27T06:10:46Z
[ "python", "matplotlib", "scipy" ]
How do I get control over the axis settings of a pyplot plot. I have simply done ``` pylab.plot(*self.plot_generator(low, high)) pylab.show() ``` and I get this which is what I want ![alt text](http://i.stack.imgur.com/7fLWz.png) but I want the x axis to be at 0 instead of at the bottom. How would I do tha...
``` # create some data x = np.linspace(-np.pi,np.pi,100) y = np.cos(2.5*x) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(x,y, mfc='orange', mec='orange', marker='.') # using 'spines', new in Matplotlib 1.0 ax.spines['left'].set_position('zero') ax.spines['right'].set_color('none') ax.spines['bottom'].set_posit...
change matplotlib axis settings
4,289,891
9
2010-11-27T02:55:55Z
4,290,402
8
2010-11-27T06:15:11Z
[ "python", "matplotlib", "scipy" ]
How do I get control over the axis settings of a pyplot plot. I have simply done ``` pylab.plot(*self.plot_generator(low, high)) pylab.show() ``` and I get this which is what I want ![alt text](http://i.stack.imgur.com/7fLWz.png) but I want the x axis to be at 0 instead of at the bottom. How would I do tha...
To set start of x-axis to 0: ``` pylab.xlim(xmin=0) ``` To set start of y-axis to 0: ``` pylab.ylim(ymin=0) ``` Put one of these lines (or both if you'd like) after the `pylab.plot` call.
How to repeat last command in python interpreter shell?
4,289,937
60
2010-11-27T03:09:39Z
4,289,945
40
2010-11-27T03:13:25Z
[ "python", "shell", "virtualenv", "interpreter", "python-idle" ]
How do I repeat the last command? The usual keys: Up, Ctrl+Up, Alt-p don't work. They produce nonsensical characters. ``` (ve)[kakarukeys@localhost ve]$ python Python 2.6.6 (r266:84292, Nov 15 2010, 21:48:32) [GCC 4.4.4 20100630 (Red Hat 4.4.4-10)] on linux2 Type "help", "copyright", "credits" or "license" for more i...
I use the following to enable history on python shell. This is my **.pythonstartup** file . PYTHONSTARTUP environment variable is set to this file path. ``` # python startup file import readline import rlcompleter import atexit import os # tab completion readline.parse_and_bind('tab: complete') # history file ...
How to repeat last command in python interpreter shell?
4,289,937
60
2010-11-27T03:09:39Z
12,589,954
71
2012-09-25T19:41:26Z
[ "python", "shell", "virtualenv", "interpreter", "python-idle" ]
How do I repeat the last command? The usual keys: Up, Ctrl+Up, Alt-p don't work. They produce nonsensical characters. ``` (ve)[kakarukeys@localhost ve]$ python Python 2.6.6 (r266:84292, Nov 15 2010, 21:48:32) [GCC 4.4.4 20100630 (Red Hat 4.4.4-10)] on linux2 Type "help", "copyright", "credits" or "license" for more i...
In IDLE, go to Options -> Configure IDLE -> Keys and there select history-next and then history-previous to change the keys. Then click on Get New Keys for Selection and you are ready to choose whatever key combination you want.