title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
Python error | 966,983 | 2 | 2009-06-08T20:57:48Z | 966,995 | 7 | 2009-06-08T21:00:01Z | [
"python"
] | ```
a=[]
a.append(3)
a.append(7)
for j in range(2,23480):
a[j]=a[j-2]+(j+2)*(j+3)/2
```
When I write this code, it gives an error like this:
```
Traceback (most recent call last):
File "C:/Python26/tcount2.py", line 6, in <module>
a[j]=a[j-2]+(j+2)*(j+3)/2
IndexError: list assignment index out of range
```... | Change this line of code:
```
a[j]=a[j-2]+(j+2)*(j+3)/2
```
to this:
```
a.append(a[j-2] + (j+2)*(j+3)/2)
``` |
python: find out if running in shell or not (e.g. sun grid engine queue) | 967,369 | 6 | 2009-06-08T22:36:56Z | 967,384 | 13 | 2009-06-08T22:39:50Z | [
"python",
"shell",
"terminal",
"stdout"
] | is there a way to find out from within a python program if it was started in a terminal or e.g. in a batch engine like sun grid engine?
the idea is to decide on printing some progress bars and other ascii-interactive stuff, or not.
thanks!
p. | The standard way is `isatty()`.
```
import sys
if sys.stdout.isatty():
print("Interactive")
else:
print("Non-interactive")
``` |
Binary file IO in python, where to start? | 967,652 | 10 | 2009-06-09T00:25:36Z | 967,884 | 9 | 2009-06-09T02:19:37Z | [
"python",
"binary",
"io",
"epub",
"mobipocket"
] | As a self-taught python hobbyist, how would I go about learning to import and export binary files using standard formats?
I'd like to implement a script that takes ePub ebooks (XHTML + CSS in a zip) and converts it to a mobipocket (Palmdoc) format in order to allow the Amazon Kindle to read it (as part of a larger pro... | You should probably start with the [struct](http://docs.python.org/library/struct.html) module, as you pointed to in your question, and of course, open the file as a binary.
Basically you just start at the beginning of the file and pick it apart piece by piece. It's a hassle, but not a huge problem. If the files are c... |
python truncate after a hundreds? | 967,661 | 8 | 2009-06-09T00:29:59Z | 967,666 | 12 | 2009-06-09T00:32:27Z | [
"python",
"truncate"
] | How can truncate an input like 315.15321531321
I want to truncate all the values after the hundredths position so it becomes 315.15
how do i do that? | String formatting under python 2.x should do it for you:
```
>>> print '%.2f' % 315.15321531321
315.15
```
This limits the string representation to just 2 decimal places. Note that if you use `round(315.153215, 2)`, you'll end up with another float value, which is naturally imprecise (or overprecise, depending on how... |
Python Advice for a beginner. Regex, Dictionaries etc? | 968,018 | 3 | 2009-06-09T03:34:33Z | 968,304 | 8 | 2009-06-09T05:32:10Z | [
"python",
"regex",
"dictionary",
"configuration-files"
] | I'm writing my second python script to try and parse the contents of a config file and would like some noob advice. I'm not sure if its best to use regex to parse my script since its multiple lines? I've also been reading about dictionaries and wondered if this would be good practice. I'm not necessarily looking for th... | If you can change the configuration file format, you can directly write your file as a Python file.
### config.py
```
job = {
'Name' : "host.domain.com-foo",
'Client' : "host.domain.com-fd",
'JobDefs' : "DefaultJob",
'FileSet' : "local",
'Write Bootstrap' : "/etc/foo/host.domain.com-foo.bsr",
'Pool' : 'st... |
Calculate the center of a contour/Area | 968,332 | 4 | 2009-06-09T05:39:21Z | 969,506 | 10 | 2009-06-09T11:31:19Z | [
"python",
"image-processing",
"opencv",
"contour"
] | I'm working on a Image-processing chain that seperates a single object by color and contour and then calculates the y-position of this object.
How do I calculate the center of a contour or area with OpenCV?
Opencv links:
* <http://opencv.willowgarage.com/wiki/>
* <http://en.wikipedia.org/wiki/OpenCV> | You can get the center of mass in the y direction by first calculating the [Moments](http://www.cs.indiana.edu/cgi-pub/oleykin/website/OpenCVHelp/ref/OpenCVRef%5FCv.htm#decl%5FcvMoments). Then the center of mass is given by `yc = M01 / M00`, where M01 and M00 are fields in the structure returned by the Moments call.
I... |
How to search help using python console | 969,093 | 6 | 2009-06-09T09:37:17Z | 970,106 | 7 | 2009-06-09T13:30:28Z | [
"python"
] | Is there any way to search for a particular package/function using keywords in the Python console?
For example, I may want to search "pdf" for pdf related tasks. | The `pydoc -k` flag searches the documentation.
```
pydoc -k <keyword>
Search for a keyword in the synopsis lines of all available modules.
```
From a terminal, run..
```
$ pydoc -k pdf
```
..for example:
```
$ pydoc -k pdf
PdfImagePlugin
wx.lib.pdfwin
PIL.PdfImagePlugin
```
It doesn't search the contents o... |
Function parameters hint Eclipse with PyDev | 969,466 | 6 | 2009-06-09T11:20:50Z | 969,483 | 10 | 2009-06-09T11:26:06Z | [
"python",
"eclipse",
"pydev"
] | Seems like newbie's question, but I just can't find the answer. Can I somehow see function parameters hint like in Visual Studio by pressing Ctrl+Shift+Space when cursor is in function call like this:
```
someObj.doSomething("Test", "hello, wold", 4|)
```
where | is my cursor position. Ctrl+Spase shows me that inform... | Try "`CTRL+space`" after a '`,`', not after a parameter.
The function parameters are displayed just after the '`(`' or after a '`,`' + "`CTRL+space`". |
Can I automatically change my PYTHONPATH when activating/deactivating a virtualenv? | 969,553 | 13 | 2009-06-09T11:44:14Z | 969,727 | 19 | 2009-06-09T12:15:34Z | [
"python",
"virtualenv"
] | I would like to have a different PYTHONPATH from my usual in a particular virtualenv. How do I set this up automatically? I realize that it's possible to hack the `bin/activate` file, is there a better/more standard way? | This [django-users post](http://groups.google.com/group/django-users/msg/5316bd02d34b7544) is probably going to help you a lot. It suggests using [virtualenvwrapper](http://www.doughellmann.com/projects/virtualenvwrapper/) to wrap virtualenv, to use the [add2virtualenv](http://www.doughellmann.com/docs/virtualenvwrappe... |
Joining a set of ordered-integer yielding Python iterators | 969,709 | 16 | 2009-06-09T12:11:00Z | 978,816 | 15 | 2009-06-11T00:49:14Z | [
"python",
"join",
"code-golf",
"iterator",
"generator"
] | Here is a seemingly simple problem: given a list of iterators that yield sequences of integers in ascending order, write a concise generator that yields only the integers that appear in every sequence.
After reading a few papers last night, I decided to hack up a completely minimal full text indexer in Python, [as see... | ```
import heapq, itertools
def intersect(*its):
for key, values in itertools.groupby(heapq.merge(*its)):
if len(list(values)) == len(its):
yield key
>>> list(intersect(*postings))
[100, 322]
``` |
What is the most state-of-the-art, pure python, XML parser available? | 970,531 | 5 | 2009-06-09T14:53:34Z | 970,537 | 7 | 2009-06-09T14:54:32Z | [
"python",
"xml",
"google-app-engine",
"jython"
] | Considering that I want to write python code that would run on Google App Engine and also inside jython, C-extensions are not an option. Amara was a nice library, but due to its C-extensions, I can't use it for either of these platforms. | [ElementTree](http://effbot.org/zone/element-index.htm) is very nice. It's also part of [2.5](http://docs.python.org/library/xml.etree.elementtree.html). |
How to strip color codes used by mIRC users? | 970,545 | 6 | 2009-06-09T14:55:08Z | 970,723 | 11 | 2009-06-09T15:17:27Z | [
"python",
"irc"
] | I'm writing a IRC bot in Python using irclib and I'm trying to log the messages on certain channels.
The issue is that some mIRC users and some Bots write using [color codes](http://www.mirc.com/help/color.txt).
Any idea on how i could strip those parts and leave only the clear ascii text message? | Regular expressions are your cleanest bet in my opinion. If you haven't used them before, [this](http://www.diveintopython.org/regular%5Fexpressions/index.html) is a good resource. For the full details on Python's regex library, go [here](http://docs.python.org/library/re.html).
```
import re
regex = re.compile("\x03(... |
How to strip color codes used by mIRC users? | 970,545 | 6 | 2009-06-09T14:55:08Z | 3,504,063 | 7 | 2010-08-17T15:21:24Z | [
"python",
"irc"
] | I'm writing a IRC bot in Python using irclib and I'm trying to log the messages on certain channels.
The issue is that some mIRC users and some Bots write using [color codes](http://www.mirc.com/help/color.txt).
Any idea on how i could strip those parts and leave only the clear ascii text message? | The second-rated and following suggestions are defective, as they look for digits after whatever character, but not after the color code character.
I have improved and combined all posts, with the following consequences:
* we *do* remove the reverse character
* remove color codes *without* leaving digits in the text.... |
Is a file on the same filesystem as another file in python? | 970,742 | 4 | 2009-06-09T15:20:23Z | 970,830 | 10 | 2009-06-09T15:33:38Z | [
"python",
"filesystems"
] | Is there a simple way of finding out if a file is on the same filesystem as another file?
The following command:
```
import shutil
shutil.move('filepatha', 'filepathb')
```
will try and rename the file (if it's on the same filesystem), otherwise it will copy it, then unlink.
I want to find out before calling this c... | Use `os.stat` (on a filename) or `os.fstat` (on a file descriptor). The `st_dev` of the result will be the device number. If they are on the same file system, it will be the same in both.
```
import os
def same_fs(file1, file2):
dev1 = os.stat(file1).st_dev
dev2 = os.stat(file2).st_dev
return dev1 == dev2... |
Threads in Java and Python | 970,909 | 5 | 2009-06-09T15:49:05Z | 970,960 | 12 | 2009-06-09T15:55:02Z | [
"java",
"python",
"multithreading"
] | i have few questions about threads in Python and Java...
1. Is it possible to give priorities to Python threads, as it is in Java?
2. How can I kill, stop, suspend and interrupt thread in Python?
3. Thread groups - what are they really for? Does Python support them too?
4. Synchronization - in Java we use simply keywo... | Assuming we're talking about the classic (CPython) implementation:
1. no, no priorities in Python's threads
2. you can't do any of these things to a thread in Python
3. no thread groups in Python
4. you can use many approaches, such as locks, but the recommended approach is generally to use the Queue module from the s... |
Have csv.reader tell when it is on the last line | 970,983 | 6 | 2009-06-09T15:58:47Z | 971,015 | 10 | 2009-06-09T16:03:43Z | [
"python",
"csv"
] | Apparently some csv output implementation somewhere truncates field separators from the right on the last row and only the last row in the file when the fields are null.
Example input csv, fields 'c' and 'd' are nullable:
```
a|b|c|d
1|2||
1|2|3|4
3|4||
2|3
```
In something like the script below, how can I tell whet... | Basically you only know you've run out *after* you've run out. So you could wrap the `reader` iterator, e.g. as follows:
```
def isLast(itr):
old = itr.next()
for new in itr:
yield False, old
old = new
yield True, old
```
and change your code to:
```
for line_num, (is_last, row) in enumerate(isLast(rea... |
Iterating through a multidimensional array in Python | 971,678 | 21 | 2009-06-09T18:18:06Z | 971,733 | 11 | 2009-06-09T18:29:32Z | [
"python",
"arrays",
"multidimensional-array",
"numpy",
"iteration"
] | I have created a multidimensional array in Python like this:
```
self.cells = np.empty((r,c),dtype=np.object)
```
Now I want to iterate through all elements of my twodimensional array, and I do not care about the order. How do I achieve this? | Just iterate over one dimension, then the other.
```
for row in self.cells:
for cell in row:
do_something(cell)
```
Of course, with only two dimensions, you can compress this down to a single loop using a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions) or gene... |
Iterating through a multidimensional array in Python | 971,678 | 21 | 2009-06-09T18:18:06Z | 971,774 | 34 | 2009-06-09T18:34:53Z | [
"python",
"arrays",
"multidimensional-array",
"numpy",
"iteration"
] | I have created a multidimensional array in Python like this:
```
self.cells = np.empty((r,c),dtype=np.object)
```
Now I want to iterate through all elements of my twodimensional array, and I do not care about the order. How do I achieve this? | It's clear you're using numpy. With numpy you can just do:
```
for cell in self.cells.flat:
do_somethin(cell)
``` |
Iterating through a multidimensional array in Python | 971,678 | 21 | 2009-06-09T18:18:06Z | 4,613,211 | 21 | 2011-01-06T08:56:36Z | [
"python",
"arrays",
"multidimensional-array",
"numpy",
"iteration"
] | I have created a multidimensional array in Python like this:
```
self.cells = np.empty((r,c),dtype=np.object)
```
Now I want to iterate through all elements of my twodimensional array, and I do not care about the order. How do I achieve this? | If you need to change the values of the individual cells then ndenumerate (in numpy) is your friend. Even if you don't it probably still is!
```
for index,value in ndenumerate( self.cells ):
do_something( value )
self.cells[index] = new_value
``` |
Caching values in Python list comprehensions | 971,857 | 4 | 2009-06-09T18:57:40Z | 971,880 | 9 | 2009-06-09T19:01:36Z | [
"python",
"list-comprehension"
] | I'm using the following list comprehension:
```
resources = [obj.get("file") for obj in iterator if obj.get("file") != None]
```
Is there a way to "cache" the value of `obj.get("file")` when it's checked in the if statement so that it doesn't have to call `get` again on obj when it generates the return list? | ```
resources = filter(None, (obj.get("file") for obj in iterator))
```
See the documentation for [filter](http://docs.python.org/library/functions.html#filter) for how to provide your own evaluation function. Passing `None` for the function (as above) filters out all values which aren't true.
If obj.get() returns an... |
spawning process from python | 972,362 | 11 | 2009-06-09T20:38:50Z | 972,383 | 25 | 2009-06-09T20:43:37Z | [
"python",
"process",
"spawn"
] | im spawning a script that runs for a long time from a web app like this:
```
os.spawnle(os.P_NOWAIT, "../bin/producenotify.py", "producenotify.py", "xx",os.environ)
```
the script is spawned successfully and it runs, but till it gets over i am not able to free the port that is used by the web app, or in other words i... | As @mark clarified it's a Linux system, the script could easily make itself fully independent, i.e., a *daemon*, by following this [recipe](http://code.activestate.com/recipes/278731/). (You could also do it in the parent after an `os.fork` and only then `os.exec...` the child process).
Edit: to clarify some details w... |
spawning process from python | 972,362 | 11 | 2009-06-09T20:38:50Z | 972,963 | 11 | 2009-06-09T23:10:20Z | [
"python",
"process",
"spawn"
] | im spawning a script that runs for a long time from a web app like this:
```
os.spawnle(os.P_NOWAIT, "../bin/producenotify.py", "producenotify.py", "xx",os.environ)
```
the script is spawned successfully and it runs, but till it gets over i am not able to free the port that is used by the web app, or in other words i... | You can use the multiprocessing library to spawn processes. A basic example is shown here:
```
from multiprocessing import Process
def f(name):
print 'hello', name
if __name__ == '__main__':
p = Process(target=f, args=('bob',))
p.start()
p.join()
``` |
Python regular expression for multiple tags | 972,749 | 2 | 2009-06-09T22:09:22Z | 972,768 | 11 | 2009-06-09T22:14:02Z | [
"python",
"html",
"regex"
] | I would like to know how to retrieve all results from each `<p>` tag.
```
import re
htmlText = '<p data="5" size="4">item1</p><p size="4">item2</p><p size="4">item3</p>'
print re.match('<p[^>]*size="[0-9]">(.*?)</p>', htmlText).groups()
```
result:
```
('item1', )
```
what I need:
```
('item1', 'item2', 'item3')
`... | For this type of problem, it is recommended to use a DOM parser, not regex.
I've seen [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/) frequently recommended for Python |
Google App Engine and Amazon S3 File Uploads | 972,895 | 6 | 2009-06-09T22:52:13Z | 973,082 | 13 | 2009-06-09T23:57:15Z | [
"python",
"google-app-engine",
"amazon-s3",
"amazon-ec2"
] | I know this has been asked before but there is really not a clear answer. My problem is I built a file upload script for GAE and only found out after, that you can only store files up to aprox. 1MB in the data store. I can stop you right here if you can tell me that if I enable billing the 1MB limit is history but I do... | From the [Amazon S3 documentation](http://docs.amazonwebservices.com/AmazonS3/2006-03-01/UsingHTTPPOST.html):
1. The user opens a web browser and accesses your web page.
2. Your web page contains an HTTP form that contains all the information necessary for the user to upload content to Amazon S3.
3. The user uploads c... |
What is the clojure equivalent of the Python idiom "if __name__ == '__main__'"? | 973,106 | 24 | 2009-06-10T00:07:58Z | 974,286 | 27 | 2009-06-10T08:18:39Z | [
"python",
"lisp",
"clojure",
"idioms"
] | I'm dabbling in clojure and am having a little trouble trying to determine the clojure (and / or Lisp) equivalent of this common python idiom.
The idiom is that at the bottom of a python module there is often a bit of test code, and then a statement which runs the code, for example:
```
# mymodule.py
class MyClass(ob... | It's not idiomatic to run Clojure scripts over and over from the command line. The REPL is a better command line. Clojure being a Lisp, it's common to fire up Clojure and leave the same instance running forever, and interact with it rather than restart it. You can change functions in the running instance one at a time,... |
Running a set of Python scripts in a list | 973,231 | 2 | 2009-06-10T00:56:03Z | 973,256 | 8 | 2009-06-10T01:04:41Z | [
"python"
] | I am working on a Python project that includes a lot of simple example scripts to help new users get used to the system. As well as the source code for each example, I include the output I get on my test machine so users know what to expect when all goes well.
It occured to me that I could use this as a crude form of ... | You could leverage [doctest](http://docs.python.org/library/doctest.html) to help you get this done. Write a method that executes each script, and in the docstring for each method you paste the expected output:
```
def run_example1():
"""
This is example number 1. Running it should give you the following outpu... |
Getting a list of all subdirectories in the current directory | 973,473 | 179 | 2009-06-10T02:48:21Z | 973,488 | 218 | 2009-06-10T02:54:45Z | [
"python",
"directory",
"subdirectory"
] | Is there a way to return a list of all the subdirectories in the current directory in Python?
I know you can do this with files, but I need to get the list of directories instead. | Do you mean immediate subdirectories, or every directory right down the tree?
Either way, you could use [`os.walk`](http://docs.python.org/library/os.html#os.walk) to do this:
```
os.walk(directory)
```
will yield a tuple for each subdirectory. Ths first entry in the 3-tuple is a directory name, so
```
[x[0] for x ... |
Getting a list of all subdirectories in the current directory | 973,473 | 179 | 2009-06-10T02:48:21Z | 973,489 | 23 | 2009-06-10T02:56:09Z | [
"python",
"directory",
"subdirectory"
] | Is there a way to return a list of all the subdirectories in the current directory in Python?
I know you can do this with files, but I need to get the list of directories instead. | If you need a recursive solution that will find all the subdirectories in the subdirectories, use walk as proposed before.
If you only need the current directory's child directories, combine `os.listdir` with `os.path.isdir` |
Getting a list of all subdirectories in the current directory | 973,473 | 179 | 2009-06-10T02:48:21Z | 973,492 | 72 | 2009-06-10T02:57:07Z | [
"python",
"directory",
"subdirectory"
] | Is there a way to return a list of all the subdirectories in the current directory in Python?
I know you can do this with files, but I need to get the list of directories instead. | ```
import os
d='.'
[os.path.join(d,o) for o in os.listdir(d) if os.path.isdir(os.path.join(d,o))]
``` |
Getting a list of all subdirectories in the current directory | 973,473 | 179 | 2009-06-10T02:48:21Z | 19,017,207 | 10 | 2013-09-26T00:08:29Z | [
"python",
"directory",
"subdirectory"
] | Is there a way to return a list of all the subdirectories in the current directory in Python?
I know you can do this with files, but I need to get the list of directories instead. | Implemented this using python-os-walk. (<http://www.pythonforbeginners.com/code-snippets-source-code/python-os-walk/>)
```
import os
print "root prints out directories only from what you specified"
print "dirs prints out sub-directories from root"
print "files prints out all files from root and directories"
print "*" ... |
Getting a list of all subdirectories in the current directory | 973,473 | 179 | 2009-06-10T02:48:21Z | 32,505,092 | 12 | 2015-09-10T14:46:58Z | [
"python",
"directory",
"subdirectory"
] | Is there a way to return a list of all the subdirectories in the current directory in Python?
I know you can do this with files, but I need to get the list of directories instead. | I prefer using filter (<https://docs.python.org/2/library/functions.html#filter>), but this is just a matter of taste.
```
d='.'
filter(lambda x: os.path.isdir(os.path.join(d, x)), os.listdir(d))
``` |
Getting a list of all subdirectories in the current directory | 973,473 | 179 | 2009-06-10T02:48:21Z | 36,426,997 | 11 | 2016-04-05T12:55:54Z | [
"python",
"directory",
"subdirectory"
] | Is there a way to return a list of all the subdirectories in the current directory in Python?
I know you can do this with files, but I need to get the list of directories instead. | You could just use `glob.glob`
```
from glob import glob
glob("/path/to/directory/*/")
```
Don't forget the trailing `/` after the `*`. |
Dynamic Table Creation and ORM mapping in SqlAlchemy | 973,481 | 7 | 2009-06-10T02:51:11Z | 973,567 | 17 | 2009-06-10T03:30:15Z | [
"python",
"database",
"sqlalchemy"
] | I'm fairly new to using relational databases, so I prefer using a good ORM to simplify things. I spent time evaluating different Python ORMs and I think SQLAlchemy is what I need. However, I've come to a mental dead end.
I need to create a new table to go along with each instance of a player I create in my app's playe... | We are absolutely spoiled by SqlAlchemy.
What follows below is taken directly from the [tutorial](http://www.sqlalchemy.org/docs/05/ormtutorial.html),
and is really easy to setup and get working.
And because it is done so often,
Mike Bayer has made this even easier
with the [all-in-one "declarative" method... |
how to integrate ZSH and (i)python? | 973,520 | 9 | 2009-06-10T03:11:55Z | 1,070,597 | 9 | 2009-07-01T18:19:24Z | [
"python",
"shell",
"zsh",
"ipython"
] | I have been in love with `zsh` for a long time, and more recently I have been discovering the advantages of the `ipython` interactive interpreter over `python` itself. Being able to *cd*, to *ls*, to *run* or to *!* is indeed very handy. But now it feels weird to have such a clumsy shell when in ipython, and I wonder h... | I asked this question on the zsh list and this answer worked for me. YMMV.
In genutils.py after the line
> if not debug:
Remove the line:
> stat = os.system(cmd)
Replace it with:
> stat =
> subprocess.call(cmd,shell=True,executable='/bin/zsh')
you see, the problem is that that "!" call uses os.system to run it, ... |
Python library for playing fixed-frequency sound | 974,071 | 22 | 2009-06-10T07:05:02Z | 974,291 | 11 | 2009-06-10T08:20:33Z | [
"python",
"audio",
"mp3",
"frequency"
] | I have a mosquito problem in my house. This wouldn't usually concern a programmers' community; However, I've seen some devices that claim to deter these nasty creatures by playing a 17Khz tone. I would like to do this using my laptop.
One method would be creating an MP3 with a a single, fixed-frequency tone ([This can... | [PyAudiere](http://pypi.python.org/pypi/pyaudiere/) is a simple cross-platform solution for the problem:
```
>>> import audiere
>>> d = audiere.open_device()
>>> t = d.create_tone(17000) # 17 KHz
>>> t.play() # non-blocking call
>>> import time
>>> time.sleep(5)
>>> t.stop()
```
pyaudiere.org is gone. [The site](http... |
Python library for playing fixed-frequency sound | 974,071 | 22 | 2009-06-10T07:05:02Z | 976,848 | 9 | 2009-06-10T16:50:20Z | [
"python",
"audio",
"mp3",
"frequency"
] | I have a mosquito problem in my house. This wouldn't usually concern a programmers' community; However, I've seen some devices that claim to deter these nasty creatures by playing a 17Khz tone. I would like to do this using my laptop.
One method would be creating an MP3 with a a single, fixed-frequency tone ([This can... | The module [winsound](http://docs.python.org/library/winsound.html) is included with Python, so there are no external libraries to install, and it should do what you want (and not much else).
```
import winsound
winsound.Beep(17000, 100)
```
It's very simple and easy, though is only available for Windows.
But:
A... |
How to send a SIGINT to Python from a bash script? | 974,189 | 5 | 2009-06-10T07:46:27Z | 974,229 | 10 | 2009-06-10T08:00:35Z | [
"python",
"bash"
] | I want to launch a background Python job from a bash script and then gracefully kill it with SIGINT. This works fine from the shell, but I can't seem to get it to work in a script.
loop.py:
```
#! /usr/bin/env python
if __name__ == "__main__":
try:
print 'starting loop'
while True:
pas... | You're not registering a signal handler. Try the below. It seems to work fairly reliably. I think the rare exception is when it catches the signal before Python registers the script's handler. Note that KeyboardInterrupt is only supposed to be raised, "when the user hits the interrupt key". I think the fact that it wor... |
How to create single Python dict from a list of dicts by summing values with common keys? | 974,678 | 7 | 2009-06-10T10:01:46Z | 974,692 | 18 | 2009-06-10T10:06:16Z | [
"python"
] | I have a list of dictionaries, e.g:
```
dictList = [
{'a':3, 'b':9, 'c':4},
{'a':9, 'b':24, 'c':99},
{'a':10, 'b':23, 'c':88}
]
```
All the dictionaries have the same keys e.g. *a*, *b*, *c*. I wish to create a single dictionary with the same keys where the values are the sums of the values with the same ... | If all dicts have all keys, you could do this as:
```
>>> dict((key, sum(d[key] for d in dictList)) for key in dictList[0])
{'a': 22, 'b': 56, 'c': 191}
```
**[Edit]** If speed is a big priority, you can also shave off ~20% (though at the cost of some readability) with the following instead:
```
import operator, ite... |
How to create single Python dict from a list of dicts by summing values with common keys? | 974,678 | 7 | 2009-06-10T10:01:46Z | 974,868 | 7 | 2009-06-10T10:52:58Z | [
"python"
] | I have a list of dictionaries, e.g:
```
dictList = [
{'a':3, 'b':9, 'c':4},
{'a':9, 'b':24, 'c':99},
{'a':10, 'b':23, 'c':88}
]
```
All the dictionaries have the same keys e.g. *a*, *b*, *c*. I wish to create a single dictionary with the same keys where the values are the sums of the values with the same ... | Try this.
```
from collections import defaultdict
result = defaultdict(int)
for myDict in dictList:
for k in myDict:
result[k] += myDict[k]
``` |
wget Vs urlretrieve of python | 974,741 | 8 | 2009-06-10T10:18:59Z | 977,311 | 37 | 2009-06-10T18:14:50Z | [
"python",
"urllib2",
"wget"
] | I have a task to download Gbs of data from a website. The data is in form of .gz files, each file being 45mb in size.
The easy way to get the files is use "wget -r -np -A files url". This will donwload data in a recursive format and mirrors the website. The donwload rate is very high 4mb/sec.
But, just to play around... | Probably a unit math error on your part.
Just noticing that [500KB/s (kilobytes) is equal to 4Mb/s (megabits)](http://www.google.com/search?hl=en&rlz=1C1GGLS%5FenUS291US304&q=500%20KB%20in%20Mb&aq=f&oq=&aqi=g1). |
Cleaning up an internal pysqlite connection on object destruction | 974,813 | 5 | 2009-06-10T10:39:34Z | 974,859 | 7 | 2009-06-10T10:51:46Z | [
"python",
"destructor",
"pysqlite"
] | I have an object with an internal database connection that's active throughout its lifetime. At the end of the program's run, the connection has to be committed and closed. So far I've used an explicit `close` method, but this is somewhat cumbersome, especially when exceptions can happen in the calling code.
I'm consi... | Read up on the [with](http://docs.python.org/reference/compound%5Fstmts.html#the-with-statement) statement. You're describing its use case.
You'll need to wrap your connection in a "Context Manager" class that handles the `__enter__` and `__exit__` methods used by the `with` statement.
See [PEP 343](http://www.python... |
Multiply operator applied to list(data structure) | 974,931 | 11 | 2009-06-10T11:06:42Z | 975,024 | 18 | 2009-06-10T11:27:19Z | [
"python",
"python-datamodel"
] | I'm reading [How to think like a computer scientist](http://openbookproject.net/thinkCSpy/) which is an introductory text for "Python Programming".
I want to clarify the behaviour of multiply operator (`*`) when applied to lists.
Consider the function **make\_matrix**
```
def make_matrix(rows, columns):
"""
>>> ma... | EVERYTHING in python are objects, and python never makes copies unless explicity asked to do so.
When you do
```
innerList = [0] * 10
```
you create a list with 10 elements, **all of them refering to the same `int` object *`0`***.
Since integer objects are **immutable**, when you do
```
innerList[1] = 15
```
You ... |
Split an integer into digits to compute an ISBN checksum | 974,952 | 38 | 2009-06-10T11:10:07Z | 974,956 | 66 | 2009-06-10T11:11:07Z | [
"python",
"integer",
"decimal"
] | I'm writing a program which calculates the check digit of an ISBN number. I have to read the user's input (nine digits of an ISBN) into an integer variable, and then multiply the last digit by 2, the second last digit by 3 and so on. How can I "split" the integer into its constituent digits to do this? As this is a bas... | Just create a string out of it.
```
myinteger = 212345
number_string = str(myinteger)
```
That's enough. Now you can iterate over it:
```
for ch in number_string:
print ch # will print each digit in order
```
Or you can slice it:
```
print number_string[:2] # first two digits
print number_string[-3:] # last th... |
Split an integer into digits to compute an ISBN checksum | 974,952 | 38 | 2009-06-10T11:10:07Z | 974,967 | 15 | 2009-06-10T11:12:53Z | [
"python",
"integer",
"decimal"
] | I'm writing a program which calculates the check digit of an ISBN number. I have to read the user's input (nine digits of an ISBN) into an integer variable, and then multiply the last digit by 2, the second last digit by 3 and so on. How can I "split" the integer into its constituent digits to do this? As this is a bas... | ```
list_of_ints = [int(i) for i in str(ISBN)]
```
Will give you a ordered list of ints. Of course, given duck typing, you might as well work with str(ISBN).
Edit: As mentioned in the comments, this list isn't sorted in the sense of being ascending or descending, but it does have a defined order (sets, dictionaries, ... |
Split an integer into digits to compute an ISBN checksum | 974,952 | 38 | 2009-06-10T11:10:07Z | 975,039 | 48 | 2009-06-10T11:30:36Z | [
"python",
"integer",
"decimal"
] | I'm writing a program which calculates the check digit of an ISBN number. I have to read the user's input (nine digits of an ISBN) into an integer variable, and then multiply the last digit by 2, the second last digit by 3 and so on. How can I "split" the integer into its constituent digits to do this? As this is a bas... | ```
while number:
digit = number % 10
# do whatever with digit
# remove last digit from number (as integer)
number //= 10
```
On each iteration of the loop, it removes the last digit from number, assigning it to $digit.
It's in reverse, starts from the last digit, finishes with the first |
Split an integer into digits to compute an ISBN checksum | 974,952 | 38 | 2009-06-10T11:10:07Z | 3,706,468 | 10 | 2010-09-14T06:07:16Z | [
"python",
"integer",
"decimal"
] | I'm writing a program which calculates the check digit of an ISBN number. I have to read the user's input (nine digits of an ISBN) into an integer variable, and then multiply the last digit by 2, the second last digit by 3 and so on. How can I "split" the integer into its constituent digits to do this? As this is a bas... | On Older versions of Python...
```
map(int,str(123))
```
On New Version 3k
```
list(map(int,str(123)))
``` |
Best way to get the name of a button that called an event? | 976,395 | 4 | 2009-06-10T15:34:43Z | 976,691 | 8 | 2009-06-10T16:21:51Z | [
"python",
"user-interface",
"events",
"event-handling",
"wxpython"
] | In the following code (inspired by [this](http://www.daniweb.com/code/snippet508.html) snippet), I use a single event handler `buttonClick` to change the title of the window. Currently, I need to evaluate if the Id of the event corresponds to the Id of the button. If I decide to add 50 buttons instead of 2, this method... | You could give the button a name, and then look at the name in the event handler.
When you make the button
```
b = wx.Button(self, 10, "Default Button", (20, 20))
b.myname = "default button"
self.Bind(wx.EVT_BUTTON, self.OnClick, b)
```
When the button is clicked:
```
def OnClick(self, event):
name = event.GetE... |
Best way to get the name of a button that called an event? | 976,395 | 4 | 2009-06-10T15:34:43Z | 982,887 | 7 | 2009-06-11T18:41:41Z | [
"python",
"user-interface",
"events",
"event-handling",
"wxpython"
] | In the following code (inspired by [this](http://www.daniweb.com/code/snippet508.html) snippet), I use a single event handler `buttonClick` to change the title of the window. Currently, I need to evaluate if the Id of the event corresponds to the Id of the button. If I decide to add 50 buttons instead of 2, this method... | Take advantage of what you can do in a language like Python. You can pass extra arguments to your event callback function, like so.
```
import functools
def __init__(self):
# ...
for i in range(10):
name = 'Button %d' % i
button = wx.Button(parent, -1, name)
func = functools.partial(se... |
Random hash in Python | 976,577 | 40 | 2009-06-10T16:05:02Z | 976,607 | 72 | 2009-06-10T16:09:12Z | [
"python",
"hash",
"md5"
] | What is the **easiest** way to generate a random hash (MD5) in Python? | A md5-hash is just a 128-bit value, so if you want a random one:
```
import random
hash = random.getrandbits(128)
print "hash value: %032x" % hash
```
I don't really see the point, though. Maybe you should elaborate why you need this... |
Random hash in Python | 976,577 | 40 | 2009-06-10T16:05:02Z | 9,011,133 | 7 | 2012-01-25T22:10:22Z | [
"python",
"hash",
"md5"
] | What is the **easiest** way to generate a random hash (MD5) in Python? | Yet another approach. You won't have to format an int to get it.
```
import random
import string
def random_string(length):
pool = string.letters + string.digits
return ''.join(random.choice(pool) for i in xrange(length))
```
Gives you flexibility on the length of the string.
```
>>> random_string(64)
'XTgD... |
Random hash in Python | 976,577 | 40 | 2009-06-10T16:05:02Z | 9,816,388 | 33 | 2012-03-22T04:19:41Z | [
"python",
"hash",
"md5"
] | What is the **easiest** way to generate a random hash (MD5) in Python? | This works for both python 2.x and 3.x
```
import os
import binascii
print(binascii.hexlify(os.urandom(16)))
'4a4d443679ed46f7514ad6dbe3733c3d'
``` |
Random hash in Python | 976,577 | 40 | 2009-06-10T16:05:02Z | 20,060,712 | 28 | 2013-11-19T00:18:52Z | [
"python",
"hash",
"md5"
] | What is the **easiest** way to generate a random hash (MD5) in Python? | I think what you are looking for is a universal unique identifier.Then the module UUID in python is what you are looking for.
```
import uuid
uuid.uuid4().hex
```
UUID4 gives you a random unique identifier that has the same length as a md5 sum. Hex will represent is as an hex string instead of returning a uuid object... |
Shuffling a list of objects in python | 976,882 | 290 | 2009-06-10T16:56:59Z | 976,918 | 485 | 2009-06-10T17:03:37Z | [
"python",
"list",
"random",
"shuffle"
] | I have a list of objects in Python and I want to shuffle them. I thought I could use the `random.shuffle` method, but this seems to fail when the list is of objects. Is there a method for shuffling object or another way around this?
```
import random
class a:
foo = "bar"
a1 = a()
a2 = a()
b = [a1,a2]
print rand... | [`random.shuffle`](https://docs.python.org/library/random.html#random.shuffle) should work. Here's an example, where the objects are lists:
```
from random import shuffle
x = [[i] for i in range(10)]
shuffle(x)
# print x gives [[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]]
# of course your results will vary
```... |
Shuffling a list of objects in python | 976,882 | 290 | 2009-06-10T16:56:59Z | 976,921 | 8 | 2009-06-10T17:04:16Z | [
"python",
"list",
"random",
"shuffle"
] | I have a list of objects in Python and I want to shuffle them. I thought I could use the `random.shuffle` method, but this seems to fail when the list is of objects. Is there a method for shuffling object or another way around this?
```
import random
class a:
foo = "bar"
a1 = a()
a2 = a()
b = [a1,a2]
print rand... | ```
>>> import random
>>> a = ['hi','world','cat','dog']
>>> random.shuffle(a,random.random)
>>> a
['hi', 'cat', 'dog', 'world']
```
It works fine for me. Make sure to set the random method. |
Shuffling a list of objects in python | 976,882 | 290 | 2009-06-10T16:56:59Z | 4,353,542 | 19 | 2010-12-04T12:46:10Z | [
"python",
"list",
"random",
"shuffle"
] | I have a list of objects in Python and I want to shuffle them. I thought I could use the `random.shuffle` method, but this seems to fail when the list is of objects. Is there a method for shuffling object or another way around this?
```
import random
class a:
foo = "bar"
a1 = a()
a2 = a()
b = [a1,a2]
print rand... | ```
#!/usr/bin/python3
import random
s=list(range(5))
random.shuffle(s) # << shuffle before print or assignment
print(s)
# print: [2, 4, 1, 3, 0]
``` |
Shuffling a list of objects in python | 976,882 | 290 | 2009-06-10T16:56:59Z | 12,978,830 | 49 | 2012-10-19T16:50:08Z | [
"python",
"list",
"random",
"shuffle"
] | I have a list of objects in Python and I want to shuffle them. I thought I could use the `random.shuffle` method, but this seems to fail when the list is of objects. Is there a method for shuffling object or another way around this?
```
import random
class a:
foo = "bar"
a1 = a()
a2 = a()
b = [a1,a2]
print rand... | As you learned the in-place shuffling was the problem. I also have problem frequently, and often seem to forget how to copy a list, too. Using `sample(a, len(a))` is the solution.
Here's a simple version using `random.sample()` that returns the shuffled result as a new list.
```
import random
a = range(5)
b = random... |
Shuffling a list of objects in python | 976,882 | 290 | 2009-06-10T16:56:59Z | 27,064,019 | 11 | 2014-11-21T14:49:30Z | [
"python",
"list",
"random",
"shuffle"
] | I have a list of objects in Python and I want to shuffle them. I thought I could use the `random.shuffle` method, but this seems to fail when the list is of objects. Is there a method for shuffling object or another way around this?
```
import random
class a:
foo = "bar"
a1 = a()
a2 = a()
b = [a1,a2]
print rand... | it took me some time to get that too, but the documentation for shuffle is very clear:
> shuffle list x **in place**; return None.
so you shouldn't `print random.shuffle(b)` but `random.shuffle(b)` and than `print b`. |
Comparing 2 .txt files using difflib in Python | 977,491 | 15 | 2009-06-10T18:51:20Z | 977,563 | 23 | 2009-06-10T19:06:00Z | [
"python",
"difflib"
] | I am trying to compare 2 text files and output the first string in the comparison file that does not match but am having difficulty since I am very new to python. Can anybody please give me a sample way to use this module.
When I try something like:
```
result = difflib.SequenceMatcher(None, testFile, comparisonFile)... | For starters, you need to pass strings to difflib.SequenceMatcher, not files:
```
# Like so
difflib.SequenceMatcher(None, str1, str2)
# Or just read the files in
difflib.SequenceMatcher(None, file1.read(), file2.read())
```
That'll fix your error anyway. To get the first non-matching string, I'll direct you to the w... |
Redirecting FORTRAN (called via F2PY) output in Python | 977,840 | 9 | 2009-06-10T19:59:15Z | 978,264 | 14 | 2009-06-10T21:33:26Z | [
"python",
"unix",
"fortran",
"stdout"
] | I'm trying to figure out how to redirect output from some FORTRAN code for which I've generated a Python interface by using F2PY. I've tried:
```
from fortran_code import fortran_function
stdout_holder = sys.stdout
stderr_holder = sys.stderr
sys.stdout = file("/dev/null","w")
fortran_function()
sys.stdout.close()
sys.... | The stdin and stdout fds are being inherited by the C shared library.
```
from fortran_code import fortran_function
import os
print "will run fortran function!"
# open 2 fds
null_fds = [os.open(os.devnull, os.O_RDWR) for x in xrange(2)]
# save the current file descriptors to a tuple
save = os.dup(1), os.dup(2)
# put... |
Vim, Python, and Django autocompletion (pysmell?) | 978,643 | 46 | 2009-06-10T23:35:16Z | 978,778 | 30 | 2009-06-11T00:32:43Z | [
"python",
"django",
"vim"
] | Does anyone know how to set up auto completion to work nicely with python, django, and vim?
I've been trying to use pysmell, but I can't seem to get it set up correctly (or maybe I don't know how it works). Right now, I run pysmell in the django directory (I'm using the trunk) and move the resulting tags to my project... | First off, thank you for asking this question, as it forced me to figure this out myself and it's great!
Here is the page I used as a reference: [PySmell v0.6 released : orestis.gr](http://github.com/orestis/pysmell/tree/v0.6)
1. Install PySmell using the `setup.py install` command.
2. Generate the `PYSMELLTAGS` file... |
Vim, Python, and Django autocompletion (pysmell?) | 978,643 | 46 | 2009-06-10T23:35:16Z | 979,347 | 12 | 2009-06-11T04:43:30Z | [
"python",
"django",
"vim"
] | Does anyone know how to set up auto completion to work nicely with python, django, and vim?
I've been trying to use pysmell, but I can't seem to get it set up correctly (or maybe I don't know how it works). Right now, I run pysmell in the django directory (I'm using the trunk) and move the resulting tags to my project... | 
You can set up VIM with buffers, buffer display, auto complete, even Py Doc display.
[Here you go](http://blog.dispatched.ch/2009/05/24/vim-as-python-ide/) |
Vim, Python, and Django autocompletion (pysmell?) | 978,643 | 46 | 2009-06-10T23:35:16Z | 12,885,498 | 12 | 2012-10-14T19:00:53Z | [
"python",
"django",
"vim"
] | Does anyone know how to set up auto completion to work nicely with python, django, and vim?
I've been trying to use pysmell, but I can't seem to get it set up correctly (or maybe I don't know how it works). Right now, I run pysmell in the django directory (I'm using the trunk) and move the resulting tags to my project... | As I wrote in other places, I developed Jedi. I really think it is far better than all the existing solutions (even PyCharm).
<https://github.com/davidhalter/jedi-vim>
It is built upon pythoncomplete and much much more powerful!
It works for complex code:
And has add... |
Getting all items less than a month old | 979,533 | 14 | 2009-06-11T05:46:51Z | 979,538 | 25 | 2009-06-11T05:50:09Z | [
"python",
"django",
"django-views"
] | Is there a way to get all objects with a date less than a month ago in django.
Something like:
```
items = Item.objects.filter(less than a month old).order_by(...)
``` | What is your definition of a "month"? 30 days? 31 days? Past that, this should do it:
```
from datetime import datetime, timedelta
last_month = datetime.today() - timedelta(days=30)
items = Item.objects.filter(my_date__gte=last_month).order_by(...)
```
Takes advantange of the [gte](http://docs.djangoproject.com/en/de... |
Difference between dir(â¦) and vars(â¦).keys() in Python? | 980,249 | 30 | 2009-06-11T09:46:51Z | 980,276 | 18 | 2009-06-11T09:53:11Z | [
"python"
] | Is there a difference between `dir(â¦)` and `vars(â¦).keys()` in Python?
(I hope there is a difference, because otherwise this would break the "one way to do it" principle... :) | The documentation has this to say about [`dir`](http://docs.python.org/library/functions.html):
> Without arguments, return the list of names in the current local scope. *With an argument, attempt to return a list of valid attributes for that object.*
And this about [`vars`](http://docs.python.org/library/functions.h... |
Difference between dir(â¦) and vars(â¦).keys() in Python? | 980,249 | 30 | 2009-06-11T09:46:51Z | 981,624 | 45 | 2009-06-11T14:57:52Z | [
"python"
] | Is there a difference between `dir(â¦)` and `vars(â¦).keys()` in Python?
(I hope there is a difference, because otherwise this would break the "one way to do it" principle... :) | Python objects store their instance variables in a dictionary that belongs to the object. `vars(x)` returns this dictionary (as does `x.__dict__`). `dir(x)`, on the other hand, returns a dictionary of `x`'s "attributes, its class's attributes, and recursively the attributes of its class's base classes."
When you acces... |
Python: printing floats / modifying the output | 981,189 | 6 | 2009-06-11T13:48:26Z | 981,233 | 9 | 2009-06-11T13:55:55Z | [
"python",
"floating-point"
] | I have a problem which prints out a float variable. What I should get is for example: 104.0625, 119.0, 72.0. I know how to control the number of decimals but how do I control the number of zeros specifically, i.e. when the float is 104.06250000 the program should print 104.0625 but when the float is 119.00000 or 72.000... | How about using the decimal module?
From the [documentation](http://docs.python.org/library/decimal.html):
"The decimal module incorporates a notion of significant places so that 1.30 + 1.20 is 2.50. The trailing zero is kept to indicate significance. This is the customary presentation for monetary applications. For ... |
Can Windows drivers be written in Python? | 981,200 | 10 | 2009-06-11T13:50:06Z | 981,462 | 16 | 2009-06-11T14:32:37Z | [
"python",
"windows",
"drivers"
] | Can Windows drivers be written in Python? | Yes. You cannot create the "classic" kernel-mode drivers. However, starting with XP, Windows offers a [User-Mode Driver Framework](http://www.microsoft.com/whdc/driver/wdf/UMDF.mspx). They can't do everything, obviously - any driver used in booting the OS obviously has to be kernel-mode. But with UMDF, you only need to... |
Using a Django custom model method property in order_by() | 981,375 | 34 | 2009-06-11T14:18:10Z | 981,802 | 54 | 2009-06-11T15:27:12Z | [
"python",
"django",
"django-models"
] | I'm currently learning Django and some of my models have custom methods to get values formatted in a specific way. Is it possible to use the value of one of these custom methods that I've defined as a property in a model with order\_by()?
Here is an example that demonstrates how the property is implemented.
```
class... | No, you can't do that. `order_by` is applied at the database level, but the database can't know anything about your custom Python methods.
You can either use the separate fields to order:
```
Author.objects.order_by('first_name', 'last_name')
```
or do the ordering in Python:
```
sorted(Author.objects.all(), key=la... |
How to tractably solve the assignment optimisation task | 982,127 | 3 | 2009-06-11T16:22:48Z | 982,306 | 19 | 2009-06-11T16:55:18Z | [
"python",
"algorithm",
"optimization",
"dynamic-programming"
] | I'm working on a script that takes the elements from `companies` and pairs them up with the elements of `people`. The goal is to optimize the pairings such that the sum of all pair values is maximized (the value of each individual pairing is precomputed and stored in the dictionary `ctrPairs`).
They're all paired in a... | To all those who wonder about the use of learning theory, this question is a good illustration. The right question is not about a "fast way to bounce between lists and tuples in python" â the reason for the slowness is something deeper.
What you're trying to solve here is known as the [assignment problem](http://en... |
Obfuscate strings in Python | 982,260 | 7 | 2009-06-11T16:47:30Z | 982,310 | 20 | 2009-06-11T16:57:06Z | [
"python",
"linux",
"encryption",
"passwords",
"obfuscation"
] | I have a password string that must be passed to a method. Everything works fine but I don't feel comfortable storing the password in clear text. Is there a way to obfuscate the string or to truly encrypt it? I'm aware that obfuscation can be reverse engineered, but I think I should at least try to cover up the password... | If you just want to prevent casually glancing at a password, you may want to consider encoding/decoding the password to/from [base64](http://docs.python.org/library/base64.html). It's not secure in the least, but the password won't be casually human/robot readable.
```
import base64
# Encode password
encoded_pw = base... |
Finding PI digits using Monte Carlo | 982,381 | 4 | 2009-06-11T17:10:29Z | 982,423 | 8 | 2009-06-11T17:18:03Z | [
"python",
"statistics",
"montecarlo",
"pi"
] | I have tried many algorithms for finding Ï using Monte Carlo.
One of the solutions (in Python) is this:
```
def calc_PI():
n_points = 1000000
hits = 0
for i in range(1, n_points):
x, y = uniform(0.0, 1.0), uniform(0.0, 1.0)
if (x**2 + y**2) <= 1.0:
hits += 1
print "Calc2... | Your fractional error goes by `sqrt(N)/N = 1/sqrt(N)`, So this is a very inefficient way to get a precise estimate. This limit is set by the statistical nature of the measurement and can't be beaten.
You should be able to get about `floor(log_10(N))/2-1` digits of good precision for `N` throws. Maybe `-2` just to be s... |
Finding PI digits using Monte Carlo | 982,381 | 4 | 2009-06-11T17:10:29Z | 982,475 | 14 | 2009-06-11T17:26:25Z | [
"python",
"statistics",
"montecarlo",
"pi"
] | I have tried many algorithms for finding Ï using Monte Carlo.
One of the solutions (in Python) is this:
```
def calc_PI():
n_points = 1000000
hits = 0
for i in range(1, n_points):
x, y = uniform(0.0, 1.0), uniform(0.0, 1.0)
if (x**2 + y**2) <= 1.0:
hits += 1
print "Calc2... | This is a classic example of Monte Carlo. But if you're trying to break the calculation of pi into parallel parts, why not just use an infinite series and let each core take a range, then sum the results as you go?
<http://mathworld.wolfram.com/PiFormulas.html> |
How can I search and replace in XML with Python? | 982,414 | 3 | 2009-06-11T17:16:23Z | 982,493 | 7 | 2009-06-11T17:29:18Z | [
"python",
"xml",
"regex"
] | I am in the middle of making a script for doing translation of xml documents. It's actually pretty cool, the idea is (and it is working) to take an xml file (or a folder of xml files) and open it, parse the xml, get whatever is in between some tags and using the google translate api's translate it and replace the conte... | Don't try to parse XML using regular expressions! [XML is not regular](http://welbog.homeip.net/glue/53/XML-is-not-regular) and therefore regular expressions are not suited to doing this kind of task.
Use an actual XML parser. Many of these are readily available for Python. A quick search has lead me to [this SO quest... |
Mark data as sensitive in python | 982,682 | 17 | 2009-06-11T18:05:47Z | 983,525 | 27 | 2009-06-11T20:39:42Z | [
"python",
"security",
"passwords",
"coredump"
] | I need to store a user's password for a short period of time in memory. How can I do so yet not have such information accidentally disclosed in coredumps or tracebacks? Is there a way to mark a value as "sensitive", so it's not saved anywhere by a debugger? | **Edit**
I have made a solution that uses ctypes (which in turn uses C) to zero memory.
```
import sys
import ctypes
def zerome(string):
location = id(string) + 20
size = sys.getsizeof(string) - 20
memset = ctypes.cdll.msvcrt.memset
# For Linux, use the following. Change the 6 to whatever it is... |
python and sys.argv | 983,201 | 51 | 2009-06-11T19:42:30Z | 983,229 | 32 | 2009-06-11T19:47:14Z | [
"python"
] | ```
if len(sys.argv) < 2:
sys.stderr.write('Usage: sys.argv[0] ')
sys.exit(1)
if not os.path.exists(sys.argv[1]):
sys.stderr.write('ERROR: Database sys.argv[1] was not found!')
sys.exit(1)
```
This is a portion of code I'm working on. The first part I'm trying to say if the user doesn't type `python ... | In Python, you can't just embed arbitrary Python expressions into literal strings and have it substitute the value of the string. You need to either:
```
sys.stderr.write("Usage: " + sys.argv[0])
```
or
```
sys.stderr.write("Usage: %s" % sys.argv[0])
```
Also, you may want to consider using the following syntax of ... |
python and sys.argv | 983,201 | 51 | 2009-06-11T19:42:30Z | 983,355 | 29 | 2009-06-11T20:09:26Z | [
"python"
] | ```
if len(sys.argv) < 2:
sys.stderr.write('Usage: sys.argv[0] ')
sys.exit(1)
if not os.path.exists(sys.argv[1]):
sys.stderr.write('ERROR: Database sys.argv[1] was not found!')
sys.exit(1)
```
This is a portion of code I'm working on. The first part I'm trying to say if the user doesn't type `python ... | I would do it this way:
```
import sys
def main(argv):
if len(argv) < 2:
sys.stderr.write("Usage: %s <database>" % (argv[0],))
return 1
if not os.path.exists(argv[1]):
sys.stderr.write("ERROR: Database %r was not found!" % (argv[1],))
return 1
if __name__ == "__main__":
s... |
python and sys.argv | 983,201 | 51 | 2009-06-11T19:42:30Z | 984,145 | 84 | 2009-06-11T22:41:16Z | [
"python"
] | ```
if len(sys.argv) < 2:
sys.stderr.write('Usage: sys.argv[0] ')
sys.exit(1)
if not os.path.exists(sys.argv[1]):
sys.stderr.write('ERROR: Database sys.argv[1] was not found!')
sys.exit(1)
```
This is a portion of code I'm working on. The first part I'm trying to say if the user doesn't type `python ... | BTW you can pass the error message directly to sys.exit:
```
if len(sys.argv) < 2:
sys.exit('Usage: %s database-name' % sys.argv[0])
if not os.path.exists(sys.argv[1]):
sys.exit('ERROR: Database %s was not found!' % sys.argv[1])
``` |
How do I make python to wait for a pressed key | 983,354 | 229 | 2009-06-11T20:09:19Z | 983,382 | 205 | 2009-06-11T20:11:59Z | [
"python",
"wait",
"keyboard-input"
] | I want my script to wait until the user presses any key.
How do I do that? | One way to do this in Python 2, is to use `raw_input()`:
```
raw_input("Press Enter to continue...")
```
In python3 it's just `input()` |
How do I make python to wait for a pressed key | 983,354 | 229 | 2009-06-11T20:09:19Z | 1,135,035 | 176 | 2009-07-16T01:48:20Z | [
"python",
"wait",
"keyboard-input"
] | I want my script to wait until the user presses any key.
How do I do that? | In Python 3, no `raw_input()` exists. So, just use:
```
input("Press Enter to continue...")
```
This only waits for a user to press enter though, so you might want to use **msvcrt** ((Windows/DOS only) The msvcrt module gives you access to a number of functions in the Microsoft Visual C/C++ Runtime Library (MSVCRT)):... |
How do I make python to wait for a pressed key | 983,354 | 229 | 2009-06-11T20:09:19Z | 5,004,022 | 13 | 2011-02-15T13:09:08Z | [
"python",
"wait",
"keyboard-input"
] | I want my script to wait until the user presses any key.
How do I do that? | The python [manual](http://docs.python.org/faq/library#how-do-i-get-a-single-keypress-at-a-time) provides the following:
```
import termios, fcntl, sys, os
fd = sys.stdin.fileno()
oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetatt... |
How do I make python to wait for a pressed key | 983,354 | 229 | 2009-06-11T20:09:19Z | 6,037,500 | 10 | 2011-05-17T21:42:22Z | [
"python",
"wait",
"keyboard-input"
] | I want my script to wait until the user presses any key.
How do I do that? | I don't know of a platform independent way of doing it, but under Windows, if you use the msvcrt module, you can use its getch function:
```
import msvcrt
c = msvcrt.getch()
print 'you entered', c
```
mscvcrt also includes the non-blocking kbhit() function to see if a key was pressed without waiting (not sure if ther... |
How do I make python to wait for a pressed key | 983,354 | 229 | 2009-06-11T20:09:19Z | 6,599,441 | 27 | 2011-07-06T15:58:39Z | [
"python",
"wait",
"keyboard-input"
] | I want my script to wait until the user presses any key.
How do I do that? | On my linux box, I use the following code. This is similar to the [manual](http://docs.python.org/faq/library#how-do-i-get-a-single-keypress-at-a-time) entry mentioned elsewhere but that code spins in a tight loop where this code doesn't and there are lots of odd corner cases that code doesn't account for that this cod... |
How do I make python to wait for a pressed key | 983,354 | 229 | 2009-06-11T20:09:19Z | 16,933,120 | 15 | 2013-06-05T06:36:48Z | [
"python",
"wait",
"keyboard-input"
] | I want my script to wait until the user presses any key.
How do I do that? | If you are ok with depending on system commands you can use the following:
Linux:
```
os.system('read -s -n 1 -p "Press any key to continue..."')
print
```
Windows:
```
os.system("pause")
``` |
How do I make python to wait for a pressed key | 983,354 | 229 | 2009-06-11T20:09:19Z | 22,151,521 | 11 | 2014-03-03T16:06:30Z | [
"python",
"wait",
"keyboard-input"
] | I want my script to wait until the user presses any key.
How do I do that? | Simply using
```
input("Press Enter to continue...")
```
will cause a SyntaxError: expected EOF while parsing.
Simple fix use:
```
try:
input("Press enter to continue")
except SyntaxError:
pass
``` |
Python JSON encoding | 983,855 | 39 | 2009-06-11T21:37:09Z | 983,879 | 51 | 2009-06-11T21:41:16Z | [
"python",
"json",
"encoding",
"types",
"simplejson"
] | I'm trying to encode data to JSON in Python and I been having a quite a bit of trouble. I believe the problem is simply a misunderstanding.
I'm relatively new to Python and never really got familiar with the various Python data types, so that's most likely what's messing me up.
Currently I am declaring a list, loopin... | Python `lists` translate to JSON `arrays`. What it is giving you is a perfectly valid JSON string that could be used in a Javascript application. To get what you expected, you would need to use a `dict`:
```
>>> json.dumps({'apple': 'cat', 'banana':'dog', 'pear':'fish'})
'{"pear": "fish", "apple": "cat", "banana": "do... |
Python JSON encoding | 983,855 | 39 | 2009-06-11T21:37:09Z | 983,884 | 16 | 2009-06-11T21:41:48Z | [
"python",
"json",
"encoding",
"types",
"simplejson"
] | I'm trying to encode data to JSON in Python and I been having a quite a bit of trouble. I believe the problem is simply a misunderstanding.
I'm relatively new to Python and never really got familiar with the various Python data types, so that's most likely what's messing me up.
Currently I am declaring a list, loopin... | In `simplejson` (or the library `json` in Python 2.6 and later), `loads` takes a JSON string and returns a Python data structure, `dumps` takes a Python data structure and returns a JSON string. JSON string can encode Javascript arrays, not just objects, and a Python list corresponds to a JSON string encoding an array.... |
Python JSON encoding | 983,855 | 39 | 2009-06-11T21:37:09Z | 984,243 | 16 | 2009-06-11T23:07:36Z | [
"python",
"json",
"encoding",
"types",
"simplejson"
] | I'm trying to encode data to JSON in Python and I been having a quite a bit of trouble. I believe the problem is simply a misunderstanding.
I'm relatively new to Python and never really got familiar with the various Python data types, so that's most likely what's messing me up.
Currently I am declaring a list, loopin... | I think you are simply exchanging *dumps* and *loads*.
```
>>> import json
>>> data = [['apple', 'cat'], ['banana', 'dog'], ['pear', 'fish']]
```
The first returns as a (JSON encoded) string its data argument:
```
>>> encoded_str = json.dumps( data )
>>> encoded_str
'[["apple", "cat"], ["banana", "dog"], ["pear", "f... |
Facebook, Django, and Google App Engine | 984,071 | 14 | 2009-06-11T22:20:36Z | 984,140 | 7 | 2009-06-11T22:40:35Z | [
"python",
"django",
"google-app-engine",
"facebook"
] | I'm experimenting with [app-engine-patch](http://code.google.com/p/app-engine-patch/) (Django for GAE) on Google App Engine. And I would like to write a Facebook application. Is it possible to use PyFacebook and its middleware? Or is there some other solution? | I run a system on for social networks and facebook on GAE with back-end in Python, front end in Javascript and Flash. I use mostly client side js libraries to pass data back to the server side datastore. This library for facebook to be exact: <http://code.google.com/p/facebookjsapi/>
There is a reason for this. Most o... |
Formatting date times provided as strings in Django | 984,412 | 7 | 2009-06-12T00:03:53Z | 984,447 | 10 | 2009-06-12T00:14:16Z | [
"python",
"django",
"date",
"time",
"strptime"
] | In my Django application I get times from a webservice, provided as a string, that I use in my templates:
{{date.string}}
This provides me with a date such as:
2009-06-11 17:02:09+0000
These are obviously a bit ugly, and I'd like to present them in a nice format to my users. Django has a great built in date formatt... | You're probably better off parsing the string received from the webservice in your view code, and then passing the datetime.date (or string) to the template for display. The spirit of Django templates is that very little coding work should be done there; they are for presentation only, and that's why they go out of the... |
Correct way of handling exceptions in Python? | 984,526 | 25 | 2009-06-12T00:45:51Z | 984,575 | 12 | 2009-06-12T01:09:53Z | [
"python",
"exception"
] | I have searched for other posts, as I felt this is a rather common problem, but all other Python exception questions I have found didn't reflect my problem.
I will try to be as specific here as I can, so I will give a direct example. And pleeeeease do not post any workarounds for this specific problem. I am not specif... | In general, you want to use as few try blocks as possible, distinguishing failure conditions by the kinds of exceptions they throw. For instance, here's my refactoring of the code you posted:
```
try:
server = smtplib.SMTP(host)
server.login(username, password) # Only runs if the previous line didn't throw
... |
Correct way of handling exceptions in Python? | 984,526 | 25 | 2009-06-12T00:45:51Z | 984,682 | 23 | 2009-06-12T01:53:55Z | [
"python",
"exception"
] | I have searched for other posts, as I felt this is a rather common problem, but all other Python exception questions I have found didn't reflect my problem.
I will try to be as specific here as I can, so I will give a direct example. And pleeeeease do not post any workarounds for this specific problem. I am not specif... | Instead of using the try/except's else block, you could simply return when it errors:
```
def send_message(addr, to, msg):
## Connect to host
try:
server = smtplib.SMTP(host) #can throw an exception
except smtplib.socket.gaierror:
return False
## Login
try:
server.login(use... |
Python Subprocess.Popen from a thread | 984,941 | 18 | 2009-06-12T04:13:25Z | 985,028 | 27 | 2009-06-12T04:39:35Z | [
"python",
"multithreading",
"subprocess",
"rsync"
] | I'm trying to launch an 'rsync' using subprocess module and Popen inside of a thread. After I call the rsync I need to read the output as well. I'm using the communicate method to read the output. The code runs fine when I do not use a thread. It appears that when I use a thread it hangs on the communicate call. Anothe... | You didn't supply any code for us to look at, but here's a sample that does something similar to what you describe:
```
import threading
import subprocess
class MyClass(threading.Thread):
def __init__(self):
self.stdout = None
self.stderr = None
threading.Thread.__init__(self)
def run... |
Is the pickling process deterministic? | 985,294 | 6 | 2009-06-12T06:41:15Z | 985,369 | 7 | 2009-06-12T07:06:00Z | [
"python",
"pickle",
"memoization"
] | Does Pickle always produce the same output for a certain input value? I suppose there could be a gotcha when pickling dictionaries that have the same contents but different insert/delete histories. My goal is to create a "signature" of function arguments, using Pickle and SHA1, for a memoize implementation. | > I suppose there could be a gotcha when pickling dictionaries that have the same contents but different insert/delete histories.
Right:
```
>>> pickle.dumps({1: 0, 9: 0}) == pickle.dumps({9: 0, 1: 0})
False
```
See also: [pickle.dumps not suitable for hashing](http://www.aminus.org/blogs/index.php/2007/11/03/pickle... |
Pythonic way to implement three similar integer range operators? | 985,309 | 2 | 2009-06-12T06:48:02Z | 985,630 | 7 | 2009-06-12T08:39:00Z | [
"python",
"operators"
] | I am working on a circular problem. In this problem, we have objects that are put on a ring of size `MAX`, and are assigned IDs from (0 to MAX-1).
I have three simple functions to test for range inclusions. inRange(i,j,k) tests if i is in the circular interval [j,k[ (Mnemonic is *i inRange(j,k)*). And I have the same ... | Two [Zen of Python](http://www.python.org/dev/peps/pep-0020/ "PEP 20: The Zen of Python") principles leap to mind:
* Simple is better than complex.
* There should be oneâand preferably only oneâobvious way to do it.
# `range`
The Python built-in function `range(start, end)` generates a list from `start` to `end`... |
UTF-8 problem in python when reading chars | 985,486 | 8 | 2009-06-12T07:39:00Z | 985,508 | 14 | 2009-06-12T07:50:00Z | [
"python",
"utf-8"
] | I'm using Python 2.5. What is going on here? What have I misunderstood? How can I fix it?
*in.txt:*
```
Stäckövérfløw
```
*code.py*
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
print """Content-Type: text/plain; charset="UTF-8"\n"""
f = open('in.txt','r')
for line in f:
print line
for i in line:
... | ```
for i in line:
print i,
```
When you read the file, the string you read in is a string of bytes. The for loop iterates over a single byte at a time. This causes problems with a UTF-8 encoded string, where non-ASCII characters are represented by multiple bytes. If you want to work with Unicode objects, where th... |
Locale date formatting in Python | 985,505 | 25 | 2009-06-12T07:48:25Z | 985,517 | 33 | 2009-06-12T07:53:14Z | [
"python",
"date",
"locale"
] | How do I get `datetime.datetime.now()` printed out in the native language?
```
>>> session.deathDate.strftime("%a, %d %b %Y")
'Fri, 12 Jun 2009'
```
I'd like to get the same result but in local language. | You can just set the locale like in this example:
```
>>> import time
>>> print time.strftime("%a, %d %b %Y %H:%M:%S")
Sun, 23 Oct 2005 20:38:56
>>> import locale
>>> locale.setlocale(locale.LC_TIME, "sv_SE") # swedish
'sv_SE'
>>> print time.strftime("%a, %d %b %Y %H:%M:%S")
sön, 23 okt 2005 20:39:15
``` |
Locale date formatting in Python | 985,505 | 25 | 2009-06-12T07:48:25Z | 10,290,840 | 9 | 2012-04-24T02:03:23Z | [
"python",
"date",
"locale"
] | How do I get `datetime.datetime.now()` printed out in the native language?
```
>>> session.deathDate.strftime("%a, %d %b %Y")
'Fri, 12 Jun 2009'
```
I'd like to get the same result but in local language. | Another option is:
```
>>> import locale
>>> import datetime
>>> locale.setlocale(locale.LC_TIME,'')
'es_CR.UTF-8'
>>> date_format = locale.nl_langinfo(locale.D_FMT)
>>> date_format
'%d/%m/%Y'
>>> today = datetime.date.today()
>>> today
datetime.date(2012, 4, 23)
>>> today.strftime(date_format)
'23/04/2012'
``` |
Locale date formatting in Python | 985,505 | 25 | 2009-06-12T07:48:25Z | 26,927,760 | 11 | 2014-11-14T10:22:52Z | [
"python",
"date",
"locale"
] | How do I get `datetime.datetime.now()` printed out in the native language?
```
>>> session.deathDate.strftime("%a, %d %b %Y")
'Fri, 12 Jun 2009'
```
I'd like to get the same result but in local language. | You should use `%x` and `%X` to format the date string in the correct locale. E.g. in Swedish a date is represented as `2014-11-14` instead of `11/14/2014`.
The correct way to get the result as Unicode is:
```
locale.setlocale(locale.LC_ALL, lang)
format_ = datetime.datetime.today().strftime('%a, %x %X')
format_u = f... |
Locale date formatting in Python | 985,505 | 25 | 2009-06-12T07:48:25Z | 32,785,195 | 8 | 2015-09-25T15:04:19Z | [
"python",
"date",
"locale"
] | How do I get `datetime.datetime.now()` printed out in the native language?
```
>>> session.deathDate.strftime("%a, %d %b %Y")
'Fri, 12 Jun 2009'
```
I'd like to get the same result but in local language. | If your application is supposed to support more than one locale then getting localized format of date/time by changing locale (by means of `locale.setlocale()`) is discouraged. For explanation why it's a bad idea see Alex Martelli's [answer](http://stackoverflow.com/a/1551834/95735) to the the question [Using Python lo... |
How do I pass a variable by reference? | 986,006 | 1,460 | 2009-06-12T10:23:51Z | 986,044 | 11 | 2009-06-12T10:39:59Z | [
"python",
"reference",
"pass-by-reference",
"argument-passing"
] | The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original'
```
class PassByReference:
def __init__(self):
self.variable = 'Original'
self.Change(self.variable)
print self.variable
def ... | In this case the variable titled `var` in the method `Change` is assigned a reference to `self.variable`, and you immediately assign a string to `var`. It's no longer pointing to `self.variable`. The following code snippet shows what would happen if you modify the data structure pointed to by `var` and `self.variable`,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.