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
How did Python implement the built-in function pow()?
5,246,856
30
2011-03-09T14:01:18Z
10,539,256
19
2012-05-10T17:27:23Z
[ "python", "algorithm", "math" ]
I have to write a program to calculate `a**b % c` where `b` and `c` are both very large numbers. If I just use `a**b % c`, it's really slow. Then I found that the built-in function `pow()` can do this really fast by calling `pow(a, b, c)`. I'm curious to know how does Python implement this? Or where could I find the ...
You might consider the following two implementations for computing `(x ** y) % z` quickly. **In Python:** ``` def pow_mod(x, y, z): "Calculate (x ** y) % z efficiently." number = 1 while y: if y & 1: number = number * x % z y >>= 1 x = x * x % z return number ``` *...
Why does pickle __getstate__ accept as a return value the very instance it required __getstate__ to pickle in the first place?
5,247,250
8
2011-03-09T14:31:46Z
6,162,977
11
2011-05-28T16:43:17Z
[ "python", "pickle" ]
I was going to ask "How to pickle a class that inherits from `dict` and defines `__slots__`". Then I realized the utterly mind-wrenching solution in `class B` below actually works... ``` import pickle class A(dict): __slots__ = ["porridge"] def __init__(self, porridge): self.porridge = porridge class B(A): ...
Maybe I'm a bit late to the party, but this question didn't get an answer that actually explains what's happening, so here we go. Here's a quick summary for those who don't want to read this whole post (it got a bit long...): 1. You don't need to take care of the contained `dict` instance in `__getstate__()` -- `pick...
Python/postgres/psycopg2: getting ID of row just inserted
5,247,685
35
2011-03-09T15:03:47Z
5,247,723
85
2011-03-09T15:06:34Z
[ "python", "postgresql", "psycopg2" ]
I'm using Python and psycopg2 to interface to postgres. When I insert a row... ``` sql_string = "INSERT INTO hundred (name,name_slug,status) VALUES (" sql_string += hundred_name + ", '" + hundred_slug + "', " + status + ");" cursor.execute(sql_string) ``` ... how do I get the ID of t...
``` cursor.execute("INSERT INTO .... RETURNING id") id_of_new_row = cursor.fetchone()[0] ``` And please do not build SQL strings containing values manually. You can (and should!) pass values separately, making it unnecessary to escape and SQL injection impossible: ``` sql_string = "INSERT INTO domes_hundred (name,nam...
Web interface for a twisted application
5,248,825
10
2011-03-09T16:26:55Z
5,314,035
14
2011-03-15T15:32:18Z
[ "python", "twisted", "web-frameworks", "twisted.web" ]
I have a application written in Twisted and I want to add a web interface to control and monitor it. I'll need plenty of dynamic pages that show the current status and configuration, so I hoped for a framework that offers at least a templating language with inheritance and some basic routing. Since I am using Twisted ...
Since Nevow is still down and I didn't want to write routing and support for a templating lib myself, I ended up using Flask. It turned out to be quite easy: ``` # make a Flask app from flask import Flask, render_template, g app = Flask(__name__) @app.route("/") def index(): return render_template("index.html") #...
Fastest way to save and load a large dictionary in Python
5,248,958
10
2011-03-09T16:35:34Z
5,249,210
13
2011-03-09T16:51:25Z
[ "python", "file", "dictionary", "pickle" ]
I have a relatively large dictionary. How do I know the size? well when I save it using `cPickle` the size of the file will grow approx. 400Mb. `cPickle` is supposed to be much faster than `pickle` but loading and saving this file just takes a lot of time. I have a Dual Core laptop 2.6 Ghz with 4GB RAM on a Linux machi...
Use the [protocol=2 option](http://docs.python.org/library/pickle.html#data-stream-format) of cPickle. The default protocol (0) is much slower, and produces much larger files on disk. If you just want to work with a larger dictionary than memory can hold, the [shelve](http://docs.python.org/library/shelve.html) modul...
How do I upload many files at the time to cloud files with Python?
5,249,008
9
2011-03-09T16:39:31Z
5,282,942
7
2011-03-12T13:59:55Z
[ "python", "multithreading", "cloudfiles" ]
I'm using the [cloudfile module](http://packages.python.org/cloudfiles/cloudfiles-module.html) to upload files to rackspace cloud files, using something like this pseudocode: ``` import cloudfiles username = '---' api_key = '---' conn = cloudfiles.get_connection(username, api_key) testcontainer = conn.create_contain...
The `ConnectionPool` class is meant for a multithreading application that ocasionally has to send something to rackspace. That way you can reuse your connection but you don't have to keep 100 connections open if you have 100 threads. You are simply looking for a multithreading/multiprocessing uploader. Here's an exam...
is it possible to find random floats in range [a,b] in python?
5,249,717
2
2011-03-09T17:29:01Z
5,249,780
7
2011-03-09T17:32:46Z
[ "python", "random", "floating-point" ]
I'm trying to generate in python random floats in the range of [0.8,0.9] , but unfortanetly all the tools i found could only generate randoms in the range of [a,b) for floats. ( like `Random.uniform(a,b)` ) Meanwhile , I tried doing something like this : ``` uniform(0.8,0.90000000001) ``` but thats realy bad any id...
The difference between [0.8, 0.9] and [0.8,0.9) is vanishingly small. Given the limitations of binary floating-point, I don't think there even is a difference, since 0.9 can't be precisely represented anyway. Use [0.8,0.9).
How to render an ordered dictionary in django templates?
5,250,276
27
2011-03-09T18:15:21Z
5,250,531
46
2011-03-09T18:38:11Z
[ "python", "django", "django-templates" ]
I'm trying to learning django templates but it's not easy. I have a certain views.py containing a dictionary to be rendered with a template. The dictionary is made of key-value pairs, where key are unique names and values are some values associated to those names. I render the dictionary in the following way: ``` re...
In views.py (Python2): ``` return render_to_response('results.html', {'data': sorted(results_dict.iteritems())}) ``` Or in views.py (Python3): ``` return render_to_response('results.html', {'data': sorted(results_dict.items())}) ``` In template file: ``` {% for key, value in data %} <tr> <td> {...
How to render an ordered dictionary in django templates?
5,250,276
27
2011-03-09T18:15:21Z
30,964,401
9
2015-06-21T12:15:04Z
[ "python", "django", "django-templates" ]
I'm trying to learning django templates but it's not easy. I have a certain views.py containing a dictionary to be rendered with a template. The dictionary is made of key-value pairs, where key are unique names and values are some values associated to those names. I render the dictionary in the following way: ``` re...
Another solution that worked very well for me and I think it's simplier. It uses `OrderedDict()` [more info](http://pymotw.com/2/collections/ordereddict.html) In your `views.py` file add: ``` from collections import OrderedDict def main(request): ord_dict = OrderedDict() ord_dict['2015-06-20'] = {} ord_di...
Difference between open and codecs.open in Python
5,250,744
32
2011-03-09T18:56:27Z
13,181,141
11
2012-11-01T16:14:34Z
[ "python", "codec" ]
There are two ways to open a text file in Python: ``` f = open(filename) ``` And ``` import codecs f = codecs.open(filename, encoding="utf-8") ``` When is `codecs.open` preferable to `open`?
Personally, I *always* use `codecs.open` unless there's a clear identified need to use `open`\*\*. The reason is that there's been so many times when I've been bitten by having utf-8 input sneak into my programs. "Oh, I just know it'll always be ascii" tends to be an assumption that gets broken often. Assuming 'utf-8'...
Difference between open and codecs.open in Python
5,250,744
32
2011-03-09T18:56:27Z
22,288,895
34
2014-03-09T22:13:24Z
[ "python", "codec" ]
There are two ways to open a text file in Python: ``` f = open(filename) ``` And ``` import codecs f = codecs.open(filename, encoding="utf-8") ``` When is `codecs.open` preferable to `open`?
Since Python 2.6, a good practice is to use `io.open()`, which also takes an `encoding` argument. In Python 3, `io.open` is an alias for the `open()` built-in. So `io.open()` works in Python 2.6 and all later versions, including Python 3.4. See docs: <http://docs.python.org/3.4/library/io.html> Now, for the original q...
PIL: enlarge an image
5,251,010
3
2011-03-09T19:19:49Z
5,260,103
8
2011-03-10T13:13:44Z
[ "python", "resize", "transform", "python-imaging-library" ]
I'm having trouble getting PIL to enlarge an image. Large images get scaled down just fine, but small images won't get bigger. ``` # get the ratio of the change in height of this image using the # by dividing the height of the first image s = h / float(image.size[1]) # calculate the change in dimension of the new imag...
For anyone reading this, having the same problem - try it on another machine. I got both ``` im = im.resize(size_tuple) ``` and ``` im = im.transform(size_tuple, Image.EXTENT, (x1,y1,x2,y2) ``` to properly resize files. There must be something wrong with the python installation on my server. Worked fine on my local...
Passing Python array to c++ function with SWIG
5,251,042
6
2011-03-09T19:22:46Z
5,435,410
9
2011-03-25T16:40:41Z
[ "c++", "python", "multidimensional-array", "swig" ]
I have written a good bit of code in python and it works great. But now I'm scaling up the size of the problems that I'm analyzing and python is dreadfully slow. The slow part of the python code is ``` for i in range(0,H,1): x1 = i - length x2 = i + length for j in range(0,W,1): #pri...
You can use arrays as it is described here: [Doc - 5.4.5 Arrays](http://www.swig.org/Doc2.0/SWIGDocumentation.html#SWIG_nn26), the `carray.i` or `std_vector.i` from the SWIG library. I find it easier to work with std::vector from the SWIG library `std_vector.i` to send a python list to a C++ SWIG extension. Though in y...
Using Boto to find to which device and EBS Volume is mounted
5,251,057
10
2011-03-09T19:24:45Z
5,255,017
8
2011-03-10T03:11:13Z
[ "python", "amazon-ec2", "boto", "amazon-ebs" ]
How do I find to which device and EBS Volume is mounted with Python Boto (v2.0) boto.ec2.Volume <https://github.com/boto/boto/blob/master/boto/ec2/volume.py> has some interesting properies e.g. attachment\_state and volume\_state. But no functions for device mapping? boto.manage.volume <https://github.com/boto/boto/b...
It isn't clear if you're running this from the instance itself or externally. If the latter, you will not need the metadata call. Just supply the instance id. ``` from boto.ec2.connection import EC2Connection from boto.utils import get_instance_metadata conn = EC2Connection() m = get_instance_metadata() volumes = [v ...
Using Boto to find to which device and EBS Volume is mounted
5,251,057
10
2011-03-09T19:24:45Z
5,970,539
12
2011-05-11T20:57:44Z
[ "python", "amazon-ec2", "boto", "amazon-ebs" ]
How do I find to which device and EBS Volume is mounted with Python Boto (v2.0) boto.ec2.Volume <https://github.com/boto/boto/blob/master/boto/ec2/volume.py> has some interesting properies e.g. attachment\_state and volume\_state. But no functions for device mapping? boto.manage.volume <https://github.com/boto/boto/b...
I believe attach\_data.device is what your looking for. part of volume. Heres an example, not sure if this is the best way, but it outputs volumeid, instanceid, and attachment\_data something like: ``` Attached Volume ID - Instance ID - Device Name vol-12345678 - i-ab345678 - /dev/sdp vol-12345678 - i-ab345678 - /dev...
determine if a list contains other lists
5,251,663
8
2011-03-09T20:19:37Z
5,251,706
41
2011-03-09T20:23:55Z
[ "python" ]
if I have a list, is there any way to check if it contains any other lists? what i mean to say is, I want to know if a list has this strcuture: `[]` as opposed to this structure `[[]]` so, compare [1,2,3,4] to [1,[2,3],4] this is complicated by the fact that i have a list of strings. well, phihag's solution seems t...
``` any(isinstance(el, list) for el in input_list) ```
Does python's `os.system` ever throw an exception?
5,251,771
7
2011-03-09T20:30:54Z
5,251,837
9
2011-03-09T20:36:51Z
[ "python", "exception", "command-line", "exception-handling", "operating-system" ]
Might the esteemed `os.system` of Python fame throw an exception? If so, which ones?
Short answer: yes: ``` >>> import os >>> os.system(None) TypeError ... ``` Long answer: look here <http://docs.python.org/library/subprocess.html#subprocess-replacements> to see how to avoid using `os.system`.
Specify image filling color when rotating in python with PIL and setting expand argument to true
5,252,170
10
2011-03-09T21:08:11Z
5,253,554
14
2011-03-09T23:20:47Z
[ "python", "image", "colors", "python-imaging-library", "rotation" ]
I'm trying to rotate an image in Python using PIL and having the expand argument to true. It seems that when the background of my image is black, the resulting image saved as a bmp will be a lot smaller than if I have a white background for my image, and then I replace the black due to expand with white. In either case...
If your original image has no alpha layer, you can use an alpha layer as a mask to convert the background to white. When `rotate` creates the "background", it makes it fully transparent. ``` # original image img = Image.open('test.png') # converted to have an alpha layer im2 = img.convert('RGBA') # rotated image rot =...
how to use str.replace() as the function in map()
5,252,834
8
2011-03-09T22:08:33Z
5,252,867
12
2011-03-09T22:12:06Z
[ "python" ]
I have a list of rows returned from an excel sheet. I want to use the replace function on each item in row to replace `'` with `\'` however, this does not work: ``` row = map(replace('\'', "\\'"), row) ``` this just gives an error about replace taking at most 3 arguments but only having 2. is there a way to use rep...
``` map( lambda s: s.replace(...), row ) ``` or use a list comprehension ``` [s.replace(...) for s in row] ```
Convert list of dicts to string
5,253,773
2
2011-03-09T23:46:56Z
5,253,790
9
2011-03-09T23:48:53Z
[ "python", "string", "list", "dictionary" ]
I'm very new to Python, so forgive me if this is easier than it seems to me. I'm being presented with a list of dicts as follows: ``` [{'directMember': 'true', 'memberType': 'User', 'memberId': 'address1@example.com'}, {'directMember': 'true', 'memberType': 'User', 'memberId': 'address2@example.com'}, {'directM...
``` ', '.join(d['memberId'] for d in my_list) ``` Since you said you are new to Python, I'll explain how this works. The [`str.join()`](http://docs.python.org/library/stdtypes.html#str.join) method combines each element of an iterable (like a list), and uses the string that the method is called on as the separator. ...
Python import dll
5,253,854
7
2011-03-09T23:56:19Z
5,253,910
9
2011-03-10T00:03:42Z
[ "python", "dll", "ctypes" ]
How would I import a winDLL into python and be able to use all of its functions? It only needs doubles and strings.
You've tagged the question [ctypes](http://www.python.net/crew/theller/ctypes/) and so it sounds like you already know the answer. The [ctypes tutorial](http://www.python.net/crew/theller/ctypes/tutorial.html) is excellent. Once you've read and understood that you'll be able to do it easily. For example: ``` >>> fro...
Add string in a certain position in Python
5,254,445
48
2011-03-10T01:32:33Z
5,254,455
82
2011-03-10T01:34:44Z
[ "python", "string" ]
Is there any function in Python that I can use to insert a value in a certain position of a string? Something like this: `"3655879ACB6"` then in position 4 add `"-"` to become `"3655-879ACB6"`
No. Python Strings are immutable. ``` >>> s='355879ACB6' >>> s[4:4] = '-' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object does not support item assignment ``` It is, however, possible to create a new string that has the inserted character: ``` >>> s[:4] + '-' + s[4:] ...
Add string in a certain position in Python
5,254,445
48
2011-03-10T01:32:33Z
5,254,480
25
2011-03-10T01:39:02Z
[ "python", "string" ]
Is there any function in Python that I can use to insert a value in a certain position of a string? Something like this: `"3655879ACB6"` then in position 4 add `"-"` to become `"3655-879ACB6"`
This seems very easy: ``` >>> hash = "355879ACB6" >>> hash = hash[:4] + '-' + hash[4:] >>> print hash 3558-79ACB6 ``` However if you like something like a function do as this: ``` def insert_dash(string, index): return string[:index] + '-' + string[index:] print insert_dash("355879ACB6", 5) ```
Add string in a certain position in Python
5,254,445
48
2011-03-10T01:32:33Z
5,254,523
10
2011-03-10T01:48:06Z
[ "python", "string" ]
Is there any function in Python that I can use to insert a value in a certain position of a string? Something like this: `"3655879ACB6"` then in position 4 add `"-"` to become `"3655-879ACB6"`
As strings are immutable another way to do this would be to turn the string into a list, which can then be indexed and modified without any slicing trickery. However, to get the list back to a string you'd have to use `.join()` using an empty string. ``` >>> hash = '355879ACB6' >>> hashlist = list(hash) >>> hashlist.i...
How to check last digit of number
5,254,827
11
2011-03-10T02:36:06Z
5,254,833
15
2011-03-10T02:36:46Z
[ "python" ]
Is there a way to get the last digit of a number. I am trying to find variables that end with "1" like 1,11,21,31,41,etc.. If I use a text variable I can simply put ``` print number[:-1] ``` but it works for variables with text(like "hello) but not with numbers. With numbers I get this error: ``` TypeError: 'int' o...
Remainder when dividing by 10, as in ``` numericVariable % 10 ``` This only works for positive numbers. -12%10 yields 8
How to check last digit of number
5,254,827
11
2011-03-10T02:36:06Z
5,254,835
14
2011-03-10T02:37:00Z
[ "python" ]
Is there a way to get the last digit of a number. I am trying to find variables that end with "1" like 1,11,21,31,41,etc.. If I use a text variable I can simply put ``` print number[:-1] ``` but it works for variables with text(like "hello) but not with numbers. With numbers I get this error: ``` TypeError: 'int' o...
Use the modulus operator with 10: ``` num = 11 if num % 10 == 1: print 'Whee!' ``` This gives the remainder when dividing by 10, which will always be the last digit (when the number is positive).
How to check last digit of number
5,254,827
11
2011-03-10T02:36:06Z
7,789,592
7
2011-10-17T05:07:47Z
[ "python" ]
Is there a way to get the last digit of a number. I am trying to find variables that end with "1" like 1,11,21,31,41,etc.. If I use a text variable I can simply put ``` print number[:-1] ``` but it works for variables with text(like "hello) but not with numbers. With numbers I get this error: ``` TypeError: 'int' o...
So you want to access the digits in a integer like elements in a list; easiest way I can think of is: ``` n = 56789 lastdigit = int(repr(n)[-1]) # > 9 ``` Convert **n** into a string, accessing last element then use int constructor to convert back into integer. For a Floating point number: ``` n = 179.123 fstr = r...
Why does float() fail to convert my string to a float?
5,255,011
6
2011-03-10T03:10:06Z
5,255,025
7
2011-03-10T03:12:18Z
[ "python" ]
my program is giving me an error when it tries to convert a string from a list of strings to a floating point number. The list is read from a line in a CSV text file and then separated into a list. How do I make this work and why is it going wrong? Here are the relevant bits of code: ``` def Main(): srcf = open(bk...
You need to strip the double quotes off the string. This will then you give a legitimate floating point string that float() can convert.
fcntl.flock - how to implement a timeout?
5,255,220
8
2011-03-10T03:45:05Z
5,255,245
7
2011-03-10T03:50:14Z
[ "python", "multithreading" ]
I am using python 2.7 I want to create a wrapper function around fcntl.flock() that will timeout after a set interval: ``` wrapper_function(timeout): ``` I've tried calling on another thread and using thread.join(timeout) but it seems that fcntl.flock() continues blocking: ``` def GetLock(self, timeout): """Ret...
I'm sure there are several ways, but how about using a non-blocking lock? After some n attempts, give up and exit? To use non-blocking lock, include the `fcntl.LOCK_NB` flag, as in: ``` fcntl.flock(self.__lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) ```
fcntl.flock - how to implement a timeout?
5,255,220
8
2011-03-10T03:45:05Z
5,255,473
17
2011-03-10T04:30:30Z
[ "python", "multithreading" ]
I am using python 2.7 I want to create a wrapper function around fcntl.flock() that will timeout after a set interval: ``` wrapper_function(timeout): ``` I've tried calling on another thread and using thread.join(timeout) but it seems that fcntl.flock() continues blocking: ``` def GetLock(self, timeout): """Ret...
Timeouts for system calls are done with signals. Most blocking system calls return with EINTR when a signal happens, so you can use `alarm` to implement timeouts. Here's a context manager that works with most system calls, causing IOError to be raised from a blocking system call if it takes too long. ``` import signa...
How can I disable logging while running unit tests in Python Django?
5,255,657
89
2011-03-10T04:59:55Z
5,255,760
125
2011-03-10T05:14:58Z
[ "python", "django", "unit-testing", "logging" ]
I am using a simple unit test based test runner to test my Django application. My application itself is configured to use a basic logger in settings.py using: ``` logging.basicConfig(level=logging.DEBUG) ``` And in my application code using: ``` logger = logging.getLogger(__name__) logger.setLevel(getattr(settings,...
``` logging.disable(logging.CRITICAL) ``` will disable all logging calls with levels less severe than or equal to `CRITICAL`. Logging can be re-enabled with ``` logging.disable(logging.NOTSET) ```
How can I disable logging while running unit tests in Python Django?
5,255,657
89
2011-03-10T04:59:55Z
7,732,916
31
2011-10-11T21:44:48Z
[ "python", "django", "unit-testing", "logging" ]
I am using a simple unit test based test runner to test my Django application. My application itself is configured to use a basic logger in settings.py using: ``` logging.basicConfig(level=logging.DEBUG) ``` And in my application code using: ``` logger = logging.getLogger(__name__) logger.setLevel(getattr(settings,...
Since you are in Django, you could add these lines to your settings.py: ``` import sys import logging if len(sys.argv) > 1 and sys.argv[1] == 'test': logging.disable(logging.CRITICAL) ``` That way you don't have to add that line in every setUp() on your tests. :) You could also do a couple of handy changes for ...
How can I disable logging while running unit tests in Python Django?
5,255,657
89
2011-03-10T04:59:55Z
25,021,711
15
2014-07-29T17:44:15Z
[ "python", "django", "unit-testing", "logging" ]
I am using a simple unit test based test runner to test my Django application. My application itself is configured to use a basic logger in settings.py using: ``` logging.basicConfig(level=logging.DEBUG) ``` And in my application code using: ``` logger = logging.getLogger(__name__) logger.setLevel(getattr(settings,...
I like Hassek's custom test runner idea. It should be noted that `DjangoTestSuiteRunner` is no longer the default test runner in Django 1.6+, it has been replaced by the `DiscoverRunner`. For default behaviour, the test runner should be more like: ``` import logging from django.test.runner import DiscoverRunner clas...
How can I disable logging while running unit tests in Python Django?
5,255,657
89
2011-03-10T04:59:55Z
32,650,980
9
2015-09-18T11:31:36Z
[ "python", "django", "unit-testing", "logging" ]
I am using a simple unit test based test runner to test my Django application. My application itself is configured to use a basic logger in settings.py using: ``` logging.basicConfig(level=logging.DEBUG) ``` And in my application code using: ``` logger = logging.getLogger(__name__) logger.setLevel(getattr(settings,...
> Is there a simple way to turn off logging in a global way, so that the application specific loggers aren't writing stuff out to the console when I run tests? The other answers prevent "writing stuff out to the console" by globally setting the logging infrastructure to ignore anything. This works but I find it too bl...
python easy_install fails with "assembler for architecture ppc not installed" on Mac OS X
5,256,397
36
2011-03-10T06:47:55Z
5,283,514
78
2011-03-12T15:45:46Z
[ "python", "xcode", "osx", "installation", "ppc" ]
``` bash-3.2$ sudo easy_install appscript Password: Searching for appscript Reading http://pypi.python.org/simple/appscript/ Reading http://appscript.sourceforge.net Best match: appscript 1.0.0 Downloading http://pypi.python.org/packages/source/a/appscript/appscript-1.0.0.tar.gz#md5=6619b637037ea0f391f45870...
This happened for me after having upgraded to XCode 4; I haven't had time to figure out what went wrong during the upgrade (or whether this is the intended behaviour), but the following workaround works for me: ``` sudo env ARCHFLAGS="-arch i386" easy_install whatever ``` The `ARCHFLAGS` trick works with `setup.py` a...
python easy_install fails with "assembler for architecture ppc not installed" on Mac OS X
5,256,397
36
2011-03-10T06:47:55Z
6,315,391
15
2011-06-11T10:33:23Z
[ "python", "xcode", "osx", "installation", "ppc" ]
``` bash-3.2$ sudo easy_install appscript Password: Searching for appscript Reading http://pypi.python.org/simple/appscript/ Reading http://appscript.sourceforge.net Best match: appscript 1.0.0 Downloading http://pypi.python.org/packages/source/a/appscript/appscript-1.0.0.tar.gz#md5=6619b637037ea0f391f45870...
I found another solution [here](http://martinkou.blogspot.com/2011/05/how-to-solve-assembler-for-architecture.html) which solves the problem once and for all. It turns out XCode4 still has the ppc assembler. You just need a symlink to it in the right place: ``` $ sudo ln -s /Developer/Platforms/iPhoneOS.platform/Devel...
Python Four Digits Counter
5,256,428
2
2011-03-10T06:53:38Z
5,256,456
8
2011-03-10T06:56:12Z
[ "python", "counter" ]
How do we use python to generate a four digit counter? ``` range(0,9999) ``` will have 1 digits, 2 digits and 3 digits. We only want 4 digits. i.e. 0000 to 9999 Of course, the simplest Pythonic way.
Format the string to be padded with 0's. To get a list of 0 to 9999 padded with zeroes: ``` ["%04d" % x for x in range(10000)] ``` Same thing works for 5, 6, 7, 8 zeroes, etc. Note that this will give you a list of strings. There's no way to have an integer variable padded with zeroes, so the string is as close as yo...
Python Four Digits Counter
5,256,428
2
2011-03-10T06:53:38Z
5,256,814
9
2011-03-10T07:45:39Z
[ "python", "counter" ]
How do we use python to generate a four digit counter? ``` range(0,9999) ``` will have 1 digits, 2 digits and 3 digits. We only want 4 digits. i.e. 0000 to 9999 Of course, the simplest Pythonic way.
Maybe `str.zfill` could also help you: ``` >>> "1".zfill(4) '0001' ```
How do I create an EC2 image from a running instance using boto?
5,256,665
7
2011-03-10T07:26:39Z
5,260,497
7
2011-03-10T13:51:10Z
[ "python", "amazon-ec2", "boto" ]
I'm trying to create a simple python backup script for my EC2 instances. This script's purpose is to create daily/weekly snapshots of the current machine (see [this question on ServerFault](http://serverfault.com/questions/238083/whats-the-easiest-way-to-auto-backup-an-ec2-instance/244091#244091)). I'm using the [boto]...
You want the "create\_image" method of the EC2Connection object. See the docs [here](http://boto.readthedocs.org/en/latest/ref/ec2.html#boto.ec2.connection.EC2Connection.create_image). You can also ask questions on the [boto-users](http://groups.google.com/group/boto-users) Google Group.
Django - Group By with Date part alone
5,257,128
8
2011-03-10T08:30:32Z
5,257,661
11
2011-03-10T09:26:26Z
[ "python", "django", "django-models", "django-queryset" ]
``` MyModel.objects.filter(created_at__gte='2011-03-09', created_at__lte='2011-03-11').values('created_at','status').annotate(status_count=Count('status')) ``` The above query has the problem with the `created_at` datetime field. Is it possible to tune the above query to ignore the time value and use the date value al...
I am not sure whether Django's ORM can perform a conversion of datetimes to dates in the middle of a query. You could, though, do the query first, get the results, then use the Python `groupby()` function to sort out the rows that are returned. Here is a small example of grouping datetimes by date: ``` from pprint imp...
Deleting a record from database using Python
5,258,326
8
2011-03-10T10:25:54Z
5,258,339
23
2011-03-10T10:27:15Z
[ "python", "django", "django-models", "django-views", "django-queryset" ]
I have created a Django app and tested the application's performance by populating some 10,0000 records. Now i want to delete it using a python script. Can somebody help me in doing this. This is the script i created to populate data into sql db. ``` def dumpdata(): for i in range(2,10): userName = "Bryan"...
[`QuerySet.delete()`](http://docs.djangoproject.com/en/dev/ref/models/querysets/#delete) ``` EmployeeDetails.objects.filter(...).delete() ```
remove special characters from string
5,258,623
10
2011-03-10T10:52:23Z
5,258,952
11
2011-03-10T11:20:40Z
[ "python" ]
i have a string "Mikael Håfström" which contains some special characters how do i remove this using python?
You can use the [`unicodedata`](http://docs.python.org/library/unicodedata.html) module to normalize unicode strings and encode them in their ASCII form like so: ``` >>> import unicodedata >>> source = u'Mikael Håfström' >>> unicodedata.normalize('NFKD', source).encode('ascii', 'ignore') 'Mikael Hafstrom' ``` One n...
Expanding Environment variable in string using python
5,258,647
10
2011-03-10T10:54:56Z
5,258,683
14
2011-03-10T10:57:27Z
[ "python", "posix" ]
I have a string containing an environment variable, e.g. ``` my_path = '$HOME/dir/dir2' ``` I want parse the string, looking up the variable and replacing it in the string: ``` print "HOME =",os.environ['HOME'] my_expanded_path = parse_string(my_path) print "PATH =", my_expanded_path ``` So I should see the output:...
Use : [os.path.expandvars](http://docs.python.org/library/os.path.html#os.path.expandvars)
Django switching, for a block of code, switch the language so translations are done in one language
5,258,715
6
2011-03-10T10:59:51Z
5,263,071
11
2011-03-10T16:59:15Z
[ "python", "django", "internationalization", "translation", "gettext" ]
I have a django project that uses a worker process that sends emails to users. The worker processes listens to a rabbitmq server and gets all the details about the email to send, the template variables, the email address to send to etc. The email body is created with django templates and [render\_to\_string](http://doc...
simplest way to switch language is: ``` from django.utils.translation import activate activate('en') # do smthg activate('pl') # do something in other language ``` be carefull with this as it is changing context for the rest of the execution of this process/thread.
Django switching, for a block of code, switch the language so translations are done in one language
5,258,715
6
2011-03-10T10:59:51Z
10,385,085
11
2012-04-30T14:08:04Z
[ "python", "django", "internationalization", "translation", "gettext" ]
I have a django project that uses a worker process that sends emails to users. The worker processes listens to a rabbitmq server and gets all the details about the email to send, the template variables, the email address to send to etc. The email body is created with django templates and [render\_to\_string](http://doc...
You can force language in a nice way using context manager: ``` class force_lang: def __init__(self, new_lang): self.new_lang = new_lang self.old_lang = translation.get_language() def __enter__(self): translation.activate(self.new_lang) def __exit__(self, type, value, tb): tra...
Django switching, for a block of code, switch the language so translations are done in one language
5,258,715
6
2011-03-10T10:59:51Z
22,944,260
14
2014-04-08T17:33:34Z
[ "python", "django", "internationalization", "translation", "gettext" ]
I have a django project that uses a worker process that sends emails to users. The worker processes listens to a rabbitmq server and gets all the details about the email to send, the template variables, the email address to send to etc. The email body is created with django templates and [render\_to\_string](http://doc...
As @SteveMayne pointed out in comment (but it worth an answer), you can now use the context manager `translation.override` (works with Django 1.6, didn't check with earlier versions): ``` from django.utils import translation print(_("Hello")) # Will print to Hello if default = 'en' # Make a block where the language ...
Check for valid utf8 string in Python
5,259,135
7
2011-03-10T11:37:45Z
5,259,160
15
2011-03-10T11:41:33Z
[ "python", "json", "utf-8", "invalid-characters" ]
I'm reading filenames from file system and I want to send them as JSON encoded array. The problem is that files on file system can be stored in invalid encoding, and I need to handle this situation to omit invalid filenames before passing it to `json.dump`, otherwise it will fail. Is there a way to check that my strin...
How about trying the following? ``` valid_utf8 = True try: filename.decode('utf-8') except UnicodeDecodeError: valid_utf8 = False ``` ... based on an answer to a similar question here: [How to write a check in python to see if file is valid UTF-8?](http://stackoverflow.com/questions/3269293/how-to-write-a-che...
subtract two times in python
5,259,882
46
2011-03-10T12:55:47Z
5,259,921
46
2011-03-10T12:58:56Z
[ "python", "datetime" ]
I have two `datetime.time` values, `exit` and `enter` and I want to do something like: ``` duration = exit - enter ``` However, I get this error: ``` TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time ``` How do I do this correctly? One possible solution is converting the `time` variab...
Try this: ``` from datetime import datetime, date datetime.combine(date.today(), exit) - datetime.combine(date.today(), enter) ``` `combine` builds a datetime, that can be subtracted.
multithreaded blas in python/numpy
5,260,068
35
2011-03-10T13:10:22Z
5,260,509
14
2011-03-10T13:52:06Z
[ "python", "numpy", "scientific-computing", "blas" ]
I am trying to implement a large number of matrix-matrix multiplications in Python. Initially, I assumed that NumPy would use automatically my threaded BLAS libraries since I built it against those libraries. However, when I look at [**top**](http://en.wikipedia.org/wiki/Top_%28software%29) or something else it seems l...
Not all of NumPy uses BLAS, only some functions -- specifically `dot()`, `vdot()`, and `innerproduct()` and several functions from the `numpy.linalg` module. Also note that many NumPy operations are limited by memory bandwidth for large arrays, so an optimised implementation is unlikely to give any improvement. Whether...
multithreaded blas in python/numpy
5,260,068
35
2011-03-10T13:10:22Z
7,645,939
81
2011-10-04T09:41:43Z
[ "python", "numpy", "scientific-computing", "blas" ]
I am trying to implement a large number of matrix-matrix multiplications in Python. Initially, I assumed that NumPy would use automatically my threaded BLAS libraries since I built it against those libraries. However, when I look at [**top**](http://en.wikipedia.org/wiki/Top_%28software%29) or something else it seems l...
*I already posted this in another thread but I think it fits better in this one:* ## UPDATE (30.07.2014): I re-run the the benchmark on our new HPC. Both the hardware as well as the software stack changed from the setup in the original answer. I put the results in a [google spreadsheet](https://docs.google.com/sprea...
Matlab / Octave bwdist() in Python or C
5,260,232
6
2011-03-10T13:26:42Z
5,260,529
7
2011-03-10T13:53:01Z
[ "python", "matlab", "image-processing", "numpy", "scipy" ]
Does anyone know of a Python replacement for Matlab / Octave bwdist() function? This function returns Euclidian distance of each cell to the closest non-zero cell for a given matrix. I saw an Octave C implementation, a pure Matlab implementation, and I was wondering if anyone had to implement this in ANSI C (which does...
While Matlab `bwdist` returns distances to the closest non-zero cell, Python [`distance_transform_edt`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.morphology.distance_transform_edt.html#scipy.ndimage.morphology.distance_transform_edt) returns distances “to the closest background element”. Sci...
read a very very big file with python
5,262,391
2
2011-03-10T16:09:10Z
5,262,453
7
2011-03-10T16:13:11Z
[ "python", "file", "text" ]
What is the best solution to process each line of a text file whose size is about 500 MB? The proposal to which I had thought : ``` def files(mon_fichier): while True: data = mon_fichier.read(1024) if not data: break yield data fichier = open('tonfichier.txt', 'r') for bloc in...
Just using the standard file operations should work as long as you keep away from `readlines` and instead just use `readline`.
read a very very big file with python
5,262,391
2
2011-03-10T16:09:10Z
5,262,569
11
2011-03-10T16:20:56Z
[ "python", "file", "text" ]
What is the best solution to process each line of a text file whose size is about 500 MB? The proposal to which I had thought : ``` def files(mon_fichier): while True: data = mon_fichier.read(1024) if not data: break yield data fichier = open('tonfichier.txt', 'r') for bloc in...
``` with open('myfile.txt') as inf: for line in inf: # do something pass ```
Import statement inside class/function definition - is it a good idea?
5,262,406
20
2011-03-10T16:10:16Z
5,262,512
9
2011-03-10T16:17:36Z
[ "python", "function", "class", "import" ]
I created a module named `util` that provides classes and functions I often use in Python. Some of them need imported features. What are the pros and the cons of importing needed things inside class/function definition? Is it better than `import` at the beginning of a module file? Is it a good idea?
[PEP8](http://www.python.org/dev/peps/pep-0008/), the Python style guide, states that: > Imports are always put at the top of > the file, just after any module > comments and docstrings, and before module globals and constants. Of course this is no hard and fast rule, and imports can go anywhere you want them to. But...
Import statement inside class/function definition - is it a good idea?
5,262,406
20
2011-03-10T16:10:16Z
5,262,532
27
2011-03-10T16:18:38Z
[ "python", "function", "class", "import" ]
I created a module named `util` that provides classes and functions I often use in Python. Some of them need imported features. What are the pros and the cons of importing needed things inside class/function definition? Is it better than `import` at the beginning of a module file? Is it a good idea?
It's the most common style to put *every* import at the top of the file. PEP 8 recommends it, which is a good reason to do it to start with. But that's not a whim, it has advantages (although not critical enough to make everything else a crime). It allows finding all imports at a glance, as opposed to looking through t...
vector< vector <double> > argument with swig and python
5,262,479
3
2011-03-10T16:15:09Z
5,274,100
7
2011-03-11T14:25:32Z
[ "c++", "python", "swig" ]
I'm trying to figure out how to use SWIG to wrap a c++ function that returns 2d vector to python.I have the file functions.h ``` #include <vector> std::vector< std::vector<double> > array_mean(std::vector< std::vector<double> > array) { std::vector< std::vector<double> > mean_array( rows, std::vector<double>(cols...
Your failed to export the inner vector type as well. ``` %module functions %{ #include "functions.h" %} %include "std_vector.i" namespace std { %template(VecDouble) vector<double>; %template(VecVecdouble) vector< vector<double> >; } %include "functions.h" ``` On a side note, generating the -csharp output from SW...
argparse module How to add option without any argument?
5,262,702
50
2011-03-10T16:29:58Z
5,262,769
32
2011-03-10T16:35:12Z
[ "python", "argparse" ]
I have created a script using `argparse`. The script needs to take a configuration file name as an option, and user can specify whether they need to proceed totally the script or only simulate it. The args to be passed: `./script -f config_file -s` or `./script -f config_file`. It's ok for the -f config\_file part, ...
To create an option that needs no value, set the [`action` *[docs]*](http://docs.python.org/dev/library/argparse.html#action) of it to `'store_const'`, `'store_true'` or `'store_false'`. Example: ``` parser.add_argument('-s', '--simulate', action='store_true') ```
argparse module How to add option without any argument?
5,262,702
50
2011-03-10T16:29:58Z
5,271,692
72
2011-03-11T10:25:06Z
[ "python", "argparse" ]
I have created a script using `argparse`. The script needs to take a configuration file name as an option, and user can specify whether they need to proceed totally the script or only simulate it. The args to be passed: `./script -f config_file -s` or `./script -f config_file`. It's ok for the -f config\_file part, ...
As [@Felix Kling suggested](http://stackoverflow.com/questions/5262702/argparse-module-how-to-add-option-without-any-argument/5262769#5262769) use `action='store_true'`: ``` >>> from argparse import ArgumentParser >>> p = ArgumentParser() >>> _ = p.add_argument('-f', '--foo', action='store_true') >>> args = p.parse_ar...
remove colorbar from figure in matplotlib
5,263,034
12
2011-03-10T16:55:03Z
5,265,614
7
2011-03-10T20:37:14Z
[ "python", "matplotlib", "colorbar" ]
This should be easy but I'm having a hard time with it. Basically, I have a subplot in matplotlib that I'm drawing a hexbin plot in every time a function is called, but every time I call the function I get a new colorbar, so what I'd really like to do is update the colorbar. Unfortunately, this doesn't seem to work sin...
Alright, here's my solution. Not terribly elegant, but not a terrible hack either. ``` def foo(self): self.subplot.clear() hb = self.subplot.hexbin(...) if self.cb: self.figure.delaxes(self.figure.axes[1]) self.figure.subplots_adjust(right=0.90) #default right padding self.cb = self.figure.col...
TemplateDoesNotExist on python app-engine django 1.2 while template rendering relative paths
5,263,623
10
2011-03-10T17:46:18Z
5,265,818
15
2011-03-10T20:57:41Z
[ "python", "django", "google-app-engine", "templates" ]
I'm running the 1.4.2 appengine SDK locally on a windows machine. I have an application running Django 0.96. The template rendering is using the django wrapper from ``` google.appengine.ext.webapp.template.render ``` to render templates. I often use a relative path to link my templates e.g ``` {% extends "../templat...
This problem bit me too when I converted from 0.96 to 1.2 Django templates. I was initially pushed to do so when SDK 1.4.2 started issuing the warning that I needed to pick a version, but when I looked into the much-needed improvements in the template language, I was eager to make the change. And then everything broke...
Store a lot of data inside python
5,264,228
6
2011-03-10T18:43:01Z
5,264,275
7
2011-03-10T18:47:32Z
[ "python" ]
Maybe I start will a small introduction for my problem. I'm writing a python program which will be used for post-processing of different physical simulations. Every simulation can create up to 100 GB of output. I deal with different informations (like positions, fields and densities,...) for different time steps. I wou...
I would try using [HDF5](http://en.wikipedia.org/wiki/Hdf5). There are two commonly used Python interfaces, [h5py](http://code.google.com/p/h5py/) and [PyTables](http://www.pytables.org/). While the latter seems to be more widespread, I prefer the former.
Store a lot of data inside python
5,264,228
6
2011-03-10T18:43:01Z
5,264,336
7
2011-03-10T18:52:47Z
[ "python" ]
Maybe I start will a small introduction for my problem. I'm writing a python program which will be used for post-processing of different physical simulations. Every simulation can create up to 100 GB of output. I deal with different informations (like positions, fields and densities,...) for different time steps. I wou...
If you're on a 64-bit operating system, you can use the [mmap](http://docs.python.org/library/mmap.html) module to map that entire file into memory space. Then, reading random bits of the data can be done a lot more quickly since the OS is then responsible for managing your access patterns. Note that you don't actually...
Equation solver in Python
5,264,780
3
2011-03-10T19:27:17Z
5,264,910
9
2011-03-10T19:36:52Z
[ "python", "parsing", "equation-solving" ]
Given a simple equation such as: ``` x = y + z ``` You can get the third variable if you bind the other two (ie: `y = x - z` and `z = x - y`). A straightforward way to put this in code: ``` def solve(args): if 'x' not in args: return args['y'] + args['z'] elif 'z' not in args: return args['x'...
Consider using [Sympy](http://code.google.com/p/sympy/). It includes various tools to solve equations and a lot more. The following is an excerpt from the [docs](http://docs.sympy.org/dev/modules/solvers/solvers.html): ``` >>> from sympy import I, solve >>> from sympy.abc import x, y >>> solve(x**4-1, x) [1, -1, -I,...
Why does scrapy throw an error for me when trying to spider and parse a site?
5,264,829
6
2011-03-10T19:31:36Z
5,275,867
8
2011-03-11T16:55:42Z
[ "python", "screen-scraping", "twisted", "scrapy" ]
The following code ``` class SiteSpider(BaseSpider): name = "some_site.com" allowed_domains = ["some_site.com"] start_urls = [ "some_site.com/something/another/PRODUCT-CATEGORY1_10652_-1__85667", ] rules = ( Rule(SgmlLinkExtractor(allow=('some_site.com/something/another/PRODUCT-CATE...
I needed to change BaseSpider to CrawlSpider. Thanks srapy users! <http://groups.google.com/group/scrapy-users/browse_thread/thread/4adaba51f7bcd0af#> > Hi Bob, > > Perhaps it might work if you change > from BaseSpider to CrawlSpider? The > BaseSpider seems not implement Rule, > see: > > <http://doc.scrapy.org/topics...
Python/numpy: all values in array up to x?
5,265,275
3
2011-03-10T20:06:16Z
5,267,083
10
2011-03-10T23:13:31Z
[ "python", "arrays", "numpy" ]
I have an ordered array like this: `numpy.array([1, 2, 5, 10, 25, 36, 66, 90, 121, 230, 333, 500])` Suppose I want all values up to 60 (if 60 isn't in, i want to stop at the first value greater than 60), so I want `[1, 2, 5, 10, 25, 36, 66]`. If I use `numpy.where()` with <= 60, it stops before 66. My solution ``` f...
there is a specific numpy function to do this, `np.searchsorted`, which is much faster than bisect. ``` a=np.arange(1e7) c=2e6 %timeit bisect.bisect(a,c) 10000 loops, best of 3: 31.6 us per loop %timeit np.searchsorted(a,c) 100000 loops, best of 3: 6.77 us per loop ``` More remarkably ,it has also a specific keyword ...
How to keep submodule names out of the name space of a Python package?
5,265,497
9
2011-03-10T20:25:39Z
8,073,553
8
2011-11-10T00:16:52Z
[ "python", "module", "package" ]
I want the interface of some module to contain a certain number of functions and classes (and nothing else). I could implement all of those in a single file, and would easily get the interface I want. But since there is a lot of code, I'd prefer to split the whole thing up into several files, say ``` mypackage/ __...
If some of the files in a package are indeed implementation details, go ahead and stick an underscore in front of them -- that's what we use them for. For example, if you look in `ctypes` you'll see ``` __init__.py ================================================== """create and manipulate C data types in Python""" ...
where's the rest of ironpython exception?
5,265,511
3
2011-03-10T20:26:34Z
5,266,059
7
2011-03-10T21:20:40Z
[ "python", "exception-handling", "ironpython" ]
I could be wrong, but it seems I'm only getting incomplete stack traces and exception messages when a SystemError is raised in IronPython. I'm doing this: ``` try: with SQLConnection(DATASOURCES[SCHEDULEDB]) as db: db.execute_sql( command + ' ' + ','.join(blo...
Try: ``` import traceback traceback.print_exc() ``` Instead of printing the exception object directly. In Python exception objects don't hold onto the stack trace directly - instead they're part of the trio of items in sys.exc\_info(). You could also do: ``` import System ... except System.Exception, e: ``` and y...
Python: If there are multiple egg versions of the same package installed, how do I import specifically the version I need?
5,265,731
8
2011-03-10T20:47:37Z
5,266,042
16
2011-03-10T21:18:29Z
[ "python", "setuptools", "distutils", "egg" ]
Say, for example that FooPackage-1.1 and FooPackage-1.2 are both installed in dist-packages as eggs. How do I import the one I need?
You can use `pkg_resources` to specify your requirements at import time: ``` import pkg_resources pkg_resources.require('FooPackage==1.2') import FooPackage ``` For example: ``` % easy_install simplejson==2.1.3 % easy_install simplejson==2.1.2 pkg_resources.require('simplejson==2.1.2') import simplejson assert simp...
Best practice for allowing Markdown in Python, while preventing XSS attacks?
5,266,134
19
2011-03-10T21:29:03Z
5,359,237
17
2011-03-19T00:51:25Z
[ "python", "xss", "markdown", "sanitization" ]
I need to let users enter Markdown content to my web app, which has a Python back end. I don’t want to needlessly restrict their entries (e.g. by not allowing *any* HTML, which goes against the spirit and spec of Markdown), but obviously I need to prevent cross-site scripting (XSS) attacks. I can’t be the first on...
I was unable to determine “best practice,” but generally you have three choices when accepting Markdown input: 1. Allow HTML within Markdown content (this is how Markdown originally/officially works, but if treated naïvely, this can invite XSS attacks). 2. Just treat any HTML as plain text, essentially letting yo...
How to see the real SQL query in Python cursor.execute
5,266,430
17
2011-03-10T21:59:45Z
5,266,873
23
2011-03-10T22:52:11Z
[ "python", "sql" ]
I use the following code in Python (with pyodbc for a MS-Access base). ``` cursor.execute("select a from tbl where b=? and c=?", (x, y)) ``` It's Ok but, for maintenance purposes, I need to know the complete and exact SQL string send to the database. Is it possible and how ?
It differs by driver. Here are two examples: ``` import MySQLdb mc = MySQLdb.connect() r = mc.cursor() r.execute('select %s, %s', ("foo", 2)) r._executed "select 'foo', 2" import psycopg2 pc = psycopg2.connect() r = pc.cursor() r.execute('select %s, %s', ('foo', 2)) r.query "select E'foo', 2" ```
high cpu usage in fabric 1.0.0
5,266,851
2
2011-03-10T22:49:42Z
5,354,374
7
2011-03-18T15:40:40Z
[ "python", "fabric" ]
In fabric 0.9, everything runs OK, but in 1.0.0, the following fabric script shows 100% CPU usage in `top`: ``` from fabric.api import run def test(): run("sleep 1000") ``` I'm running the file like this: ``` fab -H localhost ``` Why is this happening?
This is a known issue which will hopefully be addressed in a day or two: <http://code.fabfile.org/issues/show/312>
How do I install PyOpenSSL on Windows 7 64-bit?
5,267,092
14
2011-03-07T22:29:11Z
5,267,133
11
2011-03-10T23:20:32Z
[ "python", "windows-7", "installer", "64bit", "openssl" ]
To get **Scrapy** working on HTTPS, [**I need PyOpenSSL**](http://doc.scrapy.org/intro/install.html), but I can't seem to get this to work. So, is there a 64-bit version available? [**I don't see one...**](https://launchpad.net/pyopenssl) I have installed the 32-bit version but... I currently get this error back from...
Your problem is that PyOpenSSL is not installed. You don't say, but I infer from your question that you have installed a 32 bit version of PyOpenSSL but are using a 64 bit version of Python. That won't work. If you really can't get a 64 bit version of PyOpenSSL, then the simplest, and possibly the only, solution will ...
How do I install PyOpenSSL on Windows 7 64-bit?
5,267,092
14
2011-03-07T22:29:11Z
16,196,983
12
2013-04-24T16:09:04Z
[ "python", "windows-7", "installer", "64bit", "openssl" ]
To get **Scrapy** working on HTTPS, [**I need PyOpenSSL**](http://doc.scrapy.org/intro/install.html), but I can't seem to get this to work. So, is there a 64-bit version available? [**I don't see one...**](https://launchpad.net/pyopenssl) I have installed the 32-bit version but... I currently get this error back from...
Actually, step 9 at this website will resolve your issue. <http://steamforge.net/wiki/index.php/How_to_Install_Scrapy_in_64-bit_Windows_7> EDIT: Including the content from steamforge: ### Notes * Scrapy must be installed with Python 2.5, 2.6, or 2.7 (NOT 3.x) * Python 2.7 (and 3.2) do not load the correct 32-bit co...
Python ctypes argument errors
5,267,434
13
2011-03-10T23:59:10Z
5,267,478
22
2011-03-11T00:05:07Z
[ "python", "dll", "ctypes" ]
I wrote a test dll in C++ to make sure things work before I start using a more important dll that I need. Basically it takes two doubles and adds them, then returns the result. I've been playing around and with other test functions I've gotten returns to work, I just can't pass an argument due to errors. My code is: `...
You probably got the calling conventions mixed up. I'm guessing you have a C function declared something like this: ``` double haloshg_add(double d1, double s2) { return d1+d2; } ``` This will use the C calling convention by default. The simplest approach would be to change the calling convention in your ctypes c...
Why does Python compile modules but not the script being run?
5,268,017
27
2011-03-11T01:27:17Z
5,294,604
21
2011-03-14T04:06:38Z
[ "python" ]
Why does Python compile libraries that are used in a script, but not the script being called itself? For instance, If there is `main.py` and `module.py`, and Python is run by doing `python main.py`, there will be a compiled file `module.pyc` but not one for main. Why? **Edit** Adding bounty. I don't think this has ...
Files are compiled upon import. It isn't a security thing. It is simply that if you import it python saves the output. See [this post](http://effbot.org/zone/python-compile.htm) by Fredrik Lundh on Effbot. ``` >>>import main # main.pyc is created ``` When running a script python will **not** use the \*.pyc file. If y...
Why does Python compile modules but not the script being run?
5,268,017
27
2011-03-11T01:27:17Z
5,321,733
19
2011-03-16T06:19:55Z
[ "python" ]
Why does Python compile libraries that are used in a script, but not the script being called itself? For instance, If there is `main.py` and `module.py`, and Python is run by doing `python main.py`, there will be a compiled file `module.pyc` but not one for main. Why? **Edit** Adding bounty. I don't think this has ...
Nobody seems to want to say this, but I'm pretty sure the answer is simply: there's no solid reason for this behavior. All of the reasons given so far are essentially incorrect: * There's nothing special about the main file. It's loaded as a module, and shows up in `sys.modules` like any other module. Running a main ...
What is the fastest way to check if a class has a function defined?
5,268,404
36
2011-03-11T02:41:57Z
5,268,474
59
2011-03-11T02:54:54Z
[ "python" ]
I'm writing an AI state space search algorithm, and I have a generic class which can be used to quickly implement a search algorithm. A subclass would define the necessary operations, and the algorithm does the rest. Here is where I get stuck: I want to avoid regenerating the parent state over and over again, so I hav...
Yes, use `getattr()` to get the attribute, and `callable()` to verify it is a method: ``` invert_op = getattr(self, "invert_op", None) if callable(invert_op): invert_op(self.path.parent_op) ``` Note that `getattr()` normally throws exception when the attribute doesn't exist. However, if you specify a default valu...
What is the fastest way to check if a class has a function defined?
5,268,404
36
2011-03-11T02:41:57Z
5,268,475
10
2011-03-11T02:54:59Z
[ "python" ]
I'm writing an AI state space search algorithm, and I have a generic class which can be used to quickly implement a search algorithm. A subclass would define the necessary operations, and the algorithm does the rest. Here is where I get stuck: I want to avoid regenerating the parent state over and over again, so I hav...
> Is there a faster way to check to see if the function is not defined than catching an exception? Why are you against that? In most Pythonic cases, it's better to ask forgiveness than permission. ;-) > hasattr is implemented by calling getattr and checking if it raises, which is not what I want. Again, why is that?...
What is a good Django workflow?
5,268,588
16
2011-03-11T03:16:47Z
5,269,553
18
2011-03-11T06:08:56Z
[ "python", "django" ]
I'm a beginner to Python and Django. When starting a new project what do you do first before diving into the code? For example, one could take the following steps: 1. Configure the settings.py file first 2. Configure models.py to lay out data structure 3. Create template files 4. Define the views/pages 5. Syncdb 6. ...
Follow the Agile approach. Finish one small case, **from the start to the end**. From the models to the tests to user experience. Then build on it. Iterate. Thats the right way to software development. To do it efficiently, you need: (don't bother right away, you *will need* it.) Automated schema migration, automate...
What is a good Django workflow?
5,268,588
16
2011-03-11T03:16:47Z
5,272,219
8
2011-03-11T11:17:41Z
[ "python", "django" ]
I'm a beginner to Python and Django. When starting a new project what do you do first before diving into the code? For example, one could take the following steps: 1. Configure the settings.py file first 2. Configure models.py to lay out data structure 3. Create template files 4. Define the views/pages 5. Syncdb 6. ...
> the required steps for a Django application? There are two required steps. Write the settings. Write the urls.py The rest of the steps are optional. > This also serves as a checklist of things to do. Bad policy. You don't need a checklist of Django features. You need a collection of use cases or user stories whi...
Fast 'Record Update' To Binary Files?
5,268,850
3
2011-03-11T04:09:26Z
5,268,894
7
2011-03-11T04:17:26Z
[ "python", "linux", "binary", "numpy" ]
I have 3000 binary files (each of size 40[MB]) of known format (5,000,000 'records' of 'int32,float32' each). they were created using `numpy` tofile() method. A method that I use, `WhichShouldBeUpdated()`, determines which file (out of the 3000) should be updated, and also, which records in this file should be changed...
Since the records are of fixed length you can just open the file and `seek` to the position, which is a multiple of the record size and record offset. To encode the ints and floats as binary you can use [`struct.pack`](http://docs.python.org/library/struct.html?highlight=struct#module-struct). **Update**: Given that th...
Python: Comparing two CSV files and searching for similar items
5,268,929
4
2011-03-11T04:24:19Z
5,269,042
7
2011-03-11T04:46:04Z
[ "python", "csv", "compare" ]
So I've got two CSV files that I'm trying to compare and get the results of the similar items. The first file, hosts.csv is shown below: ``` Path Filename Size Signature C:\ a.txt 14kb 012345 D:\ b.txt 99kb 678910 C:\ c.txt 44kb 111213 ``` The second file, masterlist.cs...
**Edit:** While my solution works correctly, check out Martijn's answer below for a more efficient solution. You can find the documentation for the python CSV module [here](http://docs.python.org/library/csv.html). What you're looking for is something like this: ``` import csv f1 = file('hosts.csv', 'r') f2 = file(...
Python: Comparing two CSV files and searching for similar items
5,268,929
4
2011-03-11T04:24:19Z
23,090,697
8
2014-04-15T17:37:15Z
[ "python", "csv", "compare" ]
So I've got two CSV files that I'm trying to compare and get the results of the similar items. The first file, hosts.csv is shown below: ``` Path Filename Size Signature C:\ a.txt 14kb 012345 D:\ b.txt 99kb 678910 C:\ c.txt 44kb 111213 ``` The second file, masterlist.cs...
The answer by srgerg is terribly inefficient, as it operates in quadratic time; here is a linear time solution instead, using Python 2.6-compatible syntax: ``` import csv with open('masterlist.csv', 'rb') as master: master_indices = dict((r[1], i) for i, r in enumerate(csv.reader(master))) with open('hosts.csv',...
Obtaining module name: x.__module__ vs x.__class__.__module__
5,271,112
3
2011-03-11T09:25:37Z
5,271,269
9
2011-03-11T09:43:03Z
[ "python", "module", "python-module" ]
I want to obtain the module from which a Python object is from. Both ``` x.__module__ ``` and ``` x.__class__.__module__ ``` seem to work. Are these completely redundant? Is there any reason to prefer one over another?
If `x` is a class then `x.__module__` and `x.__class__.__module__` will give you different things: ``` # (Python 3 sample; use 'class Example(object): pass' for Python 2) >>> class Example: pass >>> Example.__module__ '__main__' >>> Example.__class__.__module__ 'builtins' ``` For an instance which doesn't define `__...
Assign multiple variables at once with dynamic variable names
5,272,995
14
2011-03-11T12:41:32Z
5,273,080
11
2011-03-11T12:50:31Z
[ "python", "mass-assignment", "destructuring" ]
I'm aware I can assign multiple variables to multiple values at once with: ``` (foo, bar, baz) = 1, 2, 3 ``` And have foo = 1, bar = 2, and so on. But how could I make the names of the variables more dynamic? Ie, ``` somefunction(data,tupleofnames): (return that each name mapped to a single datum) somefunction...
There are ways to do it, but they're not nice ways, and it's considered bad practice in Python. New variables shouldn't be created by magic. If you want to have a collection of things, use a list, dictionary or set, as appropriate. For example, you could return a dictionary: `{"foo":1, "bar":2, "baz":3}`
Assign multiple variables at once with dynamic variable names
5,272,995
14
2011-03-11T12:41:32Z
5,273,296
9
2011-03-11T13:10:42Z
[ "python", "mass-assignment", "destructuring" ]
I'm aware I can assign multiple variables to multiple values at once with: ``` (foo, bar, baz) = 1, 2, 3 ``` And have foo = 1, bar = 2, and so on. But how could I make the names of the variables more dynamic? Ie, ``` somefunction(data,tupleofnames): (return that each name mapped to a single datum) somefunction...
How about this? ``` def somefunction(data, tupleofnames): length = len(tupleofnames) for i in range(0, length): globals()[tupleofnames[i]] = data[i] ``` Here I assume both data and tupleofnames are lists where tupleofnames is a list of strings. But as Thomas mentioned this is not a good practice. It c...
Split array at value in numpy
5,274,243
5
2011-03-11T14:37:45Z
5,274,601
11
2011-03-11T15:10:28Z
[ "python", "numpy" ]
I have a file containing data in the format: ``` 0.0 x1 0.1 x2 0.2 x3 0.0 x4 0.1 x5 0.2 x6 0.3 x7 ... ``` The data consists of multiple datasets, each starting with 0 in the first column (so x1,x2,x3 would be one set and x4,x5,x6,x7 another one). I need to plot each dataset separately so I need to somehow split the d...
Once you have the data in a long numpy array, just do: ``` import numpy as np A = np.array([[0.0, 1], [0.1, 2], [0.2, 3], [0.0, 4], [0.1, 5], [0.2, 6], [0.3, 7], [0.0, 8], [0.1, 9], [0.2, 10]]) B = np.split(A, np.argwhere(A[:,0] == 0.0).flatten()[1:]) ``` which will give you B containing three arrays `B[0]`, `B[1]` ...
Split array at value in numpy
5,274,243
5
2011-03-11T14:37:45Z
5,274,843
15
2011-03-11T15:28:36Z
[ "python", "numpy" ]
I have a file containing data in the format: ``` 0.0 x1 0.1 x2 0.2 x3 0.0 x4 0.1 x5 0.2 x6 0.3 x7 ... ``` The data consists of multiple datasets, each starting with 0 in the first column (so x1,x2,x3 would be one set and x4,x5,x6,x7 another one). I need to plot each dataset separately so I need to somehow split the d...
I actually liked Benjamin's answer, a slightly shorter solution would be: ``` B= np.split(A, np.where(A[:, 0]== 0.)[0][1:]) ```
Tornado process data in request handler after return
5,274,733
8
2011-03-11T15:21:19Z
12,333,793
8
2012-09-08T19:29:02Z
[ "python", "tornado" ]
In a tornado request handler if I have to call function foo() which doesn't affect what's returned to the user, it makes sense to return result to the user first and then call foo(). Is it possible to do this easily in tornado (or with some third-party package)?
It's extremely easy: ``` class Handler(tornado.web.RequestHandler): def get(self): self.write('response') self.finish() # Connection is now closed foo() ```
Python unpack problem
5,274,997
9
2011-03-11T15:40:43Z
5,275,247
7
2011-03-11T15:59:57Z
[ "python" ]
I have: ``` a, b, c, d, e, f[50], g = unpack('BBBBH50cH', data) ``` The problem is ``` f[50] (too many values to unpack) ``` How do I do what I want?
I think by `f[50]` you are trying to denote "a list of 50 elements"? In Python 3.x you can do `a, b, c, d, e, *f, g` to indicate that you want `f` to contain all the values that don't fit anywhere else (see [this PEP](http://www.python.org/dev/peps/pep-3132/)). In Python 2.x, you will need to write it out explicitly:...
Django or web.py, which is better to build a large website with Python?
5,275,296
16
2011-03-11T16:03:55Z
7,295,093
14
2011-09-03T18:41:53Z
[ "python", "django", "web.py" ]
I'd like to use Python to build a website with more than 100,000 PV each day. Now what I concern is to choose which web framework. I know lots of people use Django, and some people use web.py. Django seems powerful, and I also like the simplicity of web.py. Which framework should I use? (Please introduce the performanc...
In case you haven't started yet, Give both frameworks a try. I started off with Django and moved to web.py. Web.py is not that hard as one might think. In fact, I find it easier to work with than with Django! Just my 2 cents. EDIT: Also, this might help: <http://www.aaronsw.com/weblog/rewritingreddit>
Using beautifulsoup to extract text between line breaks (e.g. <br /> tags)
5,275,359
10
2011-03-11T16:08:52Z
5,275,918
17
2011-03-11T17:00:28Z
[ "python", "html", "html-parsing", "beautifulsoup" ]
I have the following HTML that is within a larger document ``` <br /> Important Text 1 <br /> <br /> Not Important Text <br /> Important Text 2 <br /> Important Text 3 <br /> <br /> Non Important Text <br /> Important Text 4 <br /> ``` I'm currently using BeautifulSoup to obtain other elements within the HTML, but I ...
If you just want any text which is between two `<br />` tags, you could do something like the following: ``` from BeautifulSoup import BeautifulSoup, NavigableString, Tag input = '''<br /> Important Text 1 <br /> <br /> Not Important Text <br /> Important Text 2 <br /> Important Text 3 <br /> <br /> Non Important Tex...
Python Boolean help!
5,275,436
2
2011-03-11T16:16:08Z
5,275,462
11
2011-03-11T16:18:53Z
[ "python", "boolean-operations" ]
I have a code like this: ``` if (X or Y) == ("Cat" or "Dog" or "Fish" or "Bird"): print X, Y ``` It is only working if `X == "Cat"`. Does anyone know my mistake here?
I think you want logic like this: ``` animals = ["Cat", "Dog", "Fish", "Bird"] if X in animals or Y in animals: print X, Y ``` In your code the expression ("Cat" or "Dog" or "Fish" or "Bird") is treated as a logical expression which I'm sure you don't want. As it happens this expression evaluates to "Cat" which e...
Python in Xcode 7
5,276,967
181
2011-03-11T18:40:01Z
5,438,416
245
2011-03-25T21:41:11Z
[ "python", "xcode", "xcode7" ]
How does one create a Python friendly environment in Xcode 7?
I figured it out! The steps make it look like it will take more effort than it actually does. These instructions are for creating a project from scratch. If you have existing Python scripts that you wish to include in this project, you will obviously need to slightly deviate from these instructions. If you find that ...
Python in Xcode 7
5,276,967
181
2011-03-11T18:40:01Z
8,636,301
29
2011-12-26T13:42:07Z
[ "python", "xcode", "xcode7" ]
How does one create a Python friendly environment in Xcode 7?
I've created Xcode 4 templates to simplify the steps provided by [Tyler](http://stackoverflow.com/questions/5276967/python-in-xcode-4/8636301#answer-5438416). The result is [Python Project Template for Xcode 4.](https://github.com/chenhaiteng/Python-Project-Template-for-Xcode-4) Now what you need to do is download t...
Python in Xcode 7
5,276,967
181
2011-03-11T18:40:01Z
32,194,790
9
2015-08-25T02:50:38Z
[ "python", "xcode", "xcode7" ]
How does one create a Python friendly environment in Xcode 7?
**Procedure to get Python Working in XCode 7** **Step 1:** Setup your Project with a External Build System [![enter image description here](http://i.stack.imgur.com/Hy50f.png)](http://i.stack.imgur.com/Hy50f.png) **Step 1.1:** Edit the Project Scheme [![enter image description here](http://i.stack.imgur.com/W8fsK.p...
why use wsgiref simple_server?
5,277,448
5
2011-03-11T19:32:22Z
5,277,617
7
2011-03-11T19:50:41Z
[ "python", "mod-wsgi", "wsgi", "wsgiref" ]
I have a simple webapp to build, and I am just beginning to mess around with mod\_wsgi. In various tutorials, the first hello world app looks something like the following: ``` def application(environ,start_response): response_body = 'Hello World' status = '200 OK' response_headers = [('Content-Type', 'text/p...
I would guess the tutorial assumes you do not have mod\_wsgi set up and running. This way you can run the script from the command line and it will start the `wsgiref` server running the application so that you can test it without having to install Apache and mod\_wsgi.
TypeError: not all arguments converted during string formatting
5,277,679
9
2011-03-11T19:56:14Z
5,277,735
11
2011-03-11T20:02:49Z
[ "python", "mysql" ]
I'm having a bit of trouble loading an CSV file into a mysql database. Here's my code: ``` for q in csvReader: name, price, LastUpdate, today = q co.execute("""INSERT INTO fundata (name, price, LastUpdate) VALUES(name, price, LastUpdate);""",q) ``` I get an error saying TypeError: not all arguments converted ...
If I recall correctly, you should use `%s` with MySQLdb in query to denote positions you want the argument tuple elements to be formatted. This is different from usual `?` placeholders used in most other implementations. ``` for q in csvReader: name, price, LastUpdate, today = q co.execute("INSERT INTO fundata...
Checking if all elements in a list are unique
5,278,122
51
2011-03-11T20:44:28Z
5,278,151
77
2011-03-11T20:47:21Z
[ "python", "algorithm", "list", "unique" ]
What is the best way (best as in the conventional way) of checking whether all elements in a list are unique? My current approach using a `Counter` is: ``` >>> x = [1, 1, 1, 2, 3, 4, 5, 6, 2] >>> counter = Counter(x) >>> for values in counter.itervalues(): if values > 1: # do something ``` Can I...
Not the most efficient, but straight forward and concise: ``` if len(x) > len(set(x)): pass # do something ``` Probably won't make much of a difference for short lists.
Checking if all elements in a list are unique
5,278,122
51
2011-03-11T20:44:28Z
5,278,192
8
2011-03-11T20:50:55Z
[ "python", "algorithm", "list", "unique" ]
What is the best way (best as in the conventional way) of checking whether all elements in a list are unique? My current approach using a `Counter` is: ``` >>> x = [1, 1, 1, 2, 3, 4, 5, 6, 2] >>> counter = Counter(x) >>> for values in counter.itervalues(): if values > 1: # do something ``` Can I...
Alternative to a `set`, you can use a `dict`. ``` len({}.fromkeys(x)) == len(x) ```