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 does one convert a .NET tick to a python datetime?
3,875,806
6
2010-10-06T18:38:59Z
3,875,882
13
2010-10-06T18:47:52Z
[ ".net", "python", "datetime", "timestamp" ]
I have a file with dates and times listed as huge numbers like 634213557000000000. I believe this is a [.NET tick](http://msdn.microsoft.com/en-us/library/system.datetime.ticks.aspx). That's the number of 100 nanosecond increments since midnight on January 1, 1 A.D. What's a good way to read that into a [python datetim...
``` datetime.datetime(1, 1, 1) + datetime.timedelta(microseconds = ticks/10) ``` For your example, this returns ``` datetime.datetime(2010, 9, 29, 11, 15) ```
How to run a code whenever a Tkinter widget value changes?
3,876,229
5
2010-10-06T19:36:47Z
3,883,495
7
2010-10-07T15:57:15Z
[ "python", "events", "tkinter" ]
I'm using Python and `Tkinter`, and I want the equivalent of `onchange` event from other toolkits/languages. I want to run code whenever the user updates the state of some widgets. In my case, I have many `Entry`, `Checkbutton`, `Spinbox` and `Radiobutton` widgets. Whenever any one of these changes, I want to run my c...
How I would solve this in Tcl would be to make sure that the checkbutton, spinbox and radiobutton widgets are all associated with an array variable. I would then put a trace on the array which would cause a function to be called each time that variable is written. Tcl makes this trivial. Unfortunately Tkinter doesn't ...
Python: how to tell if a string represent a statement or an expression?
3,876,231
4
2010-10-06T19:36:53Z
3,876,268
10
2010-10-06T19:44:04Z
[ "python", "expression", "detect" ]
I need to either call exec() or eval() based on an input string "s" If "s" was an expression, after calling eval() I want to print the result if the result was not None If "s" was a statement then simply exec(). If the statement happens to print something then so be it. ``` s = "1 == 2" # user input # --- try: v...
Try to `compile` it as an expression. If it fails then it must be a statement (or just invalid). ``` isstatement= False try: code= compile(s, '<stdin>', 'eval') except SyntaxError: isstatement= True code= compile(s, '<stdin>', 'exec') result= None if isstatement: exec s else: result= eval(s) if r...
Using pyinotify to watch for file creation, but waiting for it to be completely written to disk
3,876,348
6
2010-10-06T19:57:10Z
3,876,474
12
2010-10-06T20:14:05Z
[ "python", "linux", "file", "pyinotify" ]
I'm using pyinotify to watch a folder for when files are created in it. And when certain files are created I want to move them. The problem is that as soon as the file is created (obviously), my program tries to move it, even before it's completely written to disk. Is there a way to make pyinotify wait until a file is...
Have pyinotify react to [IN\_CLOSE\_WRITE](http://pyinotify.sourceforge.net/#The_EventsCodes_Class) events: ``` wm.add_watch(watched_dir, pyinotify.IN_CLOSE_WRITE, proc_fun=MyProcessEvent()) ``` This is from `man 5 incrontab`, but it applies equally well to pyinotify: ``` IN_ACCESS File was accessed (re...
Metaclass to parametrize Inheritance
3,876,921
5
2010-10-06T21:10:26Z
3,877,127
8
2010-10-06T21:43:04Z
[ "c++", "python", "templates", "metaprogramming", "metaclass" ]
I've read some tutorials on Python metaclasses. I've never used one before, but I need one for something relatively simple and all the tutorials seem geared towards much more complex use cases. I basically want to create a template class that has some pre-specified body, but takes its base class as a parameter. Since I...
Doing a reasonably straightforward translation, which doesn't use metaclasses, should do it. Besides being relatively uncomplicated because of this, it'll also work, unchanged for the most part, in both Python 2 & 3. ``` from __future__ import print_function # for Py 2 & 3 compatibility def template(class_T): cl...
How to continue a task when Fabric receives an error
3,876,936
79
2010-10-06T21:11:52Z
3,877,312
124
2010-10-06T22:14:53Z
[ "python", "fabric" ]
When I define a task to run on several remote servers, if the task runs on server one and exits with an error, Fabric will stop and abort the task. But I want to make fabric ignore the error and run the task on the next server. How can I make it do this? For example: ``` $ fab site1_service_gw [site1rpt1] Executing t...
From [the docs](http://fabric-docs.readthedocs.org/en/stable/usage/execution.html#failure-handling): > ... Fabric defaults to a “fail-fast” behavior pattern: if anything goes wrong, such as a remote program returning a nonzero return value or your fabfile’s Python code encountering an exception, execution will h...
How to continue a task when Fabric receives an error
3,876,936
79
2010-10-06T21:11:52Z
8,071,092
13
2011-11-09T20:21:38Z
[ "python", "fabric" ]
When I define a task to run on several remote servers, if the task runs on server one and exits with an error, Fabric will stop and abort the task. But I want to make fabric ignore the error and run the task on the next server. How can I make it do this? For example: ``` $ fab site1_service_gw [site1rpt1] Executing t...
You can also set the entire script's warn\_only setting to be true with ``` def local(): env.warn_only = True ```
How to continue a task when Fabric receives an error
3,876,936
79
2010-10-06T21:11:52Z
8,346,944
7
2011-12-01T19:13:24Z
[ "python", "fabric" ]
When I define a task to run on several remote servers, if the task runs on server one and exits with an error, Fabric will stop and abort the task. But I want to make fabric ignore the error and run the task on the next server. How can I make it do this? For example: ``` $ fab site1_service_gw [site1rpt1] Executing t...
In Fabric 1.3.2 at least, you can recover the exception by catching the `SystemExit` exception. That's helpful if you have more than one command to run in a batch (like a deploy) and want to cleanup if one of them fails.
How to continue a task when Fabric receives an error
3,876,936
79
2010-10-06T21:11:52Z
19,546,026
19
2013-10-23T15:30:33Z
[ "python", "fabric" ]
When I define a task to run on several remote servers, if the task runs on server one and exits with an error, Fabric will stop and abort the task. But I want to make fabric ignore the error and run the task on the next server. How can I make it do this? For example: ``` $ fab site1_service_gw [site1rpt1] Executing t...
As of Fabric 1.5, there is a ContextManager that makes this easier: ``` from fabric.api import sudo, warn_only with warn_only(): sudo('mkdir foo') ``` Update: I re-confirmed that this works in ipython using the following code. ``` from fabric.api import local, warn_only #aborted with SystemExit after 'bad comm...
Running multiple python version
3,877,126
5
2010-10-06T21:43:00Z
3,877,305
8
2010-10-06T22:13:33Z
[ "python", "multiple-versions" ]
I want to run multiple Python version in my box. Is there anything like version manager in Python where I can switch between multiple Python version without having to call the full path of the python binary? I have tried virtualenv and it seems to only cover problems running multiple python libraries version. Thanks f...
When calling python from bash you could try an alias. ``` user@machine:~$ alias python1234='/usr/bin/python2.5' user@machine:~$ python1234 Python 2.5.4 (r254:67916, Jan 20 2010, 21:44:03) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> ``` Let's say you have a script ...
Testing in Python - how to use assertRaises in testing using unittest?
3,877,134
6
2010-10-06T21:44:18Z
3,877,151
9
2010-10-06T21:46:54Z
[ "python", "unit-testing", "testing", "exception-handling" ]
I am trying to do a simple test in Python using unittest, to see if a class throws an exception if it gets an unsuitable input for the constructor. The class looks like this: ``` class SummaryFormula: def __init__( self, summaryFormula): self.atoms = {} for atom in re.finditer( "([A-Z][a-z]{0,2})(\...
Thats because your class requires a parameter while instantiating the object while you are passing ``` ukol1.SummaryFormula() ``` you should have been passing the parameter summaryFormula to it. ``` ukol1.SummaryFormula(someSummaryFormula) ``` Also the confusion is because your class name is SummaryFormula and the...
Testing in Python - how to use assertRaises in testing using unittest?
3,877,134
6
2010-10-06T21:44:18Z
3,877,183
13
2010-10-06T21:52:26Z
[ "python", "unit-testing", "testing", "exception-handling" ]
I am trying to do a simple test in Python using unittest, to see if a class throws an exception if it gets an unsuitable input for the constructor. The class looks like this: ``` class SummaryFormula: def __init__( self, summaryFormula): self.atoms = {} for atom in re.finditer( "([A-Z][a-z]{0,2})(\...
`assertRaises` is a little confusing, because you need to give it the callable, not an expression that makes the call. Change your code to: ``` self.assertRaises(TypeError, ukol1.SummaryFormula, "testtest") ``` In your code, you are invoking the constructor yourself, and it raises an exception about not having enoug...
How to convert an array of strings to an array of floats in numpy?
3,877,209
44
2010-10-06T21:57:33Z
3,877,247
69
2010-10-06T22:04:11Z
[ "python", "numpy" ]
How to get from ``` ["1.1", "2.2", "3.2"] ``` to ``` [1.1, 2.2, 3.2] ``` in NumPy?
Well, if you're reading the data in as a list, just do `np.array(map(float, list_of_strings))` (or equivalently, use a list comprehension). However, if it's already a numpy array of strings, there's a better way. Use `astype()`. ``` import numpy as np x = np.array(['1.1', '2.2', '3.3'], dtype='|S4') y = x.astype(np.f...
Why does id({}) == id({}) and id([]) == id([]) in CPython?
3,877,230
17
2010-10-06T22:00:39Z
3,877,275
24
2010-10-06T22:08:54Z
[ "python", "identity", "cpython", "python-internals" ]
Why does CPython (no clue about other Python implementations) have the following behavior? ``` tuple1 = () tuple2 = () dict1 = {} dict2 = {} list1 = [] list2 = [] # makes sense, tuples are immutable assert(id(tuple1) == ...
CPython is garbage collecting objects as soon as they go out of scope, so the second `[]` is created after the first `[]` is collected. So, most of the time it ends up in the same memory location. This shows what's happening very clearly (the output is likely to be different in other implementations of Python): ``` c...
Why does id({}) == id({}) and id([]) == id([]) in CPython?
3,877,230
17
2010-10-06T22:00:39Z
3,877,276
31
2010-10-06T22:08:56Z
[ "python", "identity", "cpython", "python-internals" ]
Why does CPython (no clue about other Python implementations) have the following behavior? ``` tuple1 = () tuple2 = () dict1 = {} dict2 = {} list1 = [] list2 = [] # makes sense, tuples are immutable assert(id(tuple1) == ...
When you call `id({})`, Python creates a dict and passes it to the `id` function. The `id` function takes its id (its memory location), and throws away the dict. The dict is destroyed. When you do it twice in quick succession (without any other dicts being created in the mean time), the dict Python creates the second t...
Python - question about decimal arithmetic
3,877,299
2
2010-10-06T22:12:55Z
3,877,333
8
2010-10-06T22:17:52Z
[ "python", "decimal", "math" ]
I have 3 questions pertaining to decimal arithmetic in Python, all 3 of which are best asked inline: ### 1) ``` >>> from decimal import getcontext, Decimal >>> getcontext().prec = 6 >>> Decimal('50.567898491579878') * 1 Decimal('50.5679') >>> # How is this a precision of 6? If the decimal counts whole numbers as >>> ...
1. Precision follows [sig figs](http://en.wikipedia.org/wiki/Significant_figures), not fractional digits. The former is more useful in scientific applications. 2. Raw data should never be mangled. Instead it does the mangling when operated upon. 3. This is how it's done.
How best to get map from key list/value list in groovy?
3,877,454
8
2010-10-06T22:44:33Z
3,877,489
9
2010-10-06T22:55:26Z
[ "python", "dictionary", "groovy" ]
In python, I can do the following: ``` keys = [1, 2, 3] values = ['a', 'b', 'c'] d = dict(zip(keys, values)) assert d == {1: 'a', 2: 'b', 3: 'c'} ``` Is there a nice way to construct a map in groovy, starting from a list of keys and a list of values?
Try this: ``` def keys = [1, 2, 3] def values = ['a', 'b', 'c'] def pairs = [keys, values].transpose() def map = [:] pairs.each{ k, v -> map[k] = v } println map ``` Alternatively: ``` def map = [:] pairs.each{ map << (it as MapEntry) } ```
How best to get map from key list/value list in groovy?
3,877,454
8
2010-10-06T22:44:33Z
3,879,166
17
2010-10-07T06:20:57Z
[ "python", "dictionary", "groovy" ]
In python, I can do the following: ``` keys = [1, 2, 3] values = ['a', 'b', 'c'] d = dict(zip(keys, values)) assert d == {1: 'a', 2: 'b', 3: 'c'} ``` Is there a nice way to construct a map in groovy, starting from a list of keys and a list of values?
There's also the `collectEntries` function in Groovy 1.8 (currently in beta) ``` def keys = [1, 2, 3] def values = ['a', 'b', 'c'] [keys,values].transpose().collectEntries { it } ```
deleting rows in numpy array
3,877,491
25
2010-10-06T22:55:34Z
3,878,477
8
2010-10-07T03:33:29Z
[ "python", "numpy", "delete-row" ]
I have an array that might look like this: ``` ANOVAInputMatrixValuesArray = [[ 0.96488889, 0.73641667, 0.67521429, 0.592875, 0.53172222], [ 0.78008333, 0.5938125, 0.481, 0.39883333, 0.]] ``` Notice that one of the rows has a zero value at the end. I want to delete any row that contains a zero, while keeping any row...
Here's a one liner (yes, it is similar to user333700's, but a little more straightforward): ``` >>> import numpy as np >>> arr = np.array([[ 0.96488889, 0.73641667, 0.67521429, 0.592875, 0.53172222], [ 0.78008333, 0.5938125, 0.481, 0.39883333, 0.]]) >>> print arr[arr.all(1)] array([[ 0.96488889, 0.73...
deleting rows in numpy array
3,877,491
25
2010-10-06T22:55:34Z
11,663,150
48
2012-07-26T05:48:21Z
[ "python", "numpy", "delete-row" ]
I have an array that might look like this: ``` ANOVAInputMatrixValuesArray = [[ 0.96488889, 0.73641667, 0.67521429, 0.592875, 0.53172222], [ 0.78008333, 0.5938125, 0.481, 0.39883333, 0.]] ``` Notice that one of the rows has a zero value at the end. I want to delete any row that contains a zero, while keeping any row...
The simplest way to delete rows and columns from arrays is the `numpy.delete` method. Suppose I have the following array `x`: ``` x = array([[1,2,3], [4,5,6], [7,8,9]]) ``` To delete the first row, do this: ``` x = numpy.delete(x, (0), axis=0) ``` To delete the third column, do this: ``` x = numpy...
In Python, can you have variables within triple quotes? If so, how?
3,877,623
26
2010-10-06T23:26:11Z
3,877,637
22
2010-10-06T23:30:07Z
[ "python", "string" ]
This is probably a very simple question for some, but it has me stumped. Can you use variables within python's triple-quotes? In the following example, how do use variables in the text: ``` wash_clothes = 'tuesdays' clean_dishes = 'never' mystring =""" I like to wash clothes on %wash_clothes I like to clean dishes %...
One of the ways : ``` >>> mystring =""" I like to wash clothes on %s ... I like to clean dishes %s ... """ >>> wash_clothes = 'tuesdays' >>> clean_dishes = 'never' >>> >>> print mystring % (wash_clothes, clean_dishes) I like to wash clothes on tuesdays I like to clean dishes never ``` Also look at string formatting...
In Python, can you have variables within triple quotes? If so, how?
3,877,623
26
2010-10-06T23:26:11Z
3,877,647
30
2010-10-06T23:33:21Z
[ "python", "string" ]
This is probably a very simple question for some, but it has me stumped. Can you use variables within python's triple-quotes? In the following example, how do use variables in the text: ``` wash_clothes = 'tuesdays' clean_dishes = 'never' mystring =""" I like to wash clothes on %wash_clothes I like to clean dishes %...
The preferred way of doing this is using [`str.format()`](http://docs.python.org/library/stdtypes.html#str.format) rather than the method using `%`: > This method of string formatting is the new standard in Python 3.0, and should be preferred to the `%` formatting described in String Formatting Operations in new code....
Self-referencing classes in python?
3,877,947
2
2010-10-07T00:47:47Z
3,877,962
7
2010-10-07T00:52:25Z
[ "python", "class" ]
In Python, can you have classes with members that are themselves pointers to members of the type of the same class? For example, in C, you might have the following class for a node in a binary tree: ``` struct node { int data; struct node* left; struct node* right; } ``` How would you equivalently create ...
Python is a dynamic language. Attributes can be bound at (almost) any time with any type. Therefore, the problem you are describing does not exist in Python.
Self-referencing classes in python?
3,877,947
2
2010-10-07T00:47:47Z
3,877,975
7
2010-10-07T00:54:51Z
[ "python", "class" ]
In Python, can you have classes with members that are themselves pointers to members of the type of the same class? For example, in C, you might have the following class for a node in a binary tree: ``` struct node { int data; struct node* left; struct node* right; } ``` How would you equivalently create ...
Emulating a C struct in Python (using str instead of int as the data type): "Declaration": ``` class Node(object): data = None # str left = None # Node object or None right = None # Node object or None ``` Usage: ``` root = Node() root.data = "foo" b = Node() b.data = "bar" root.left = b z = Node() z....
python paramiko
3,878,082
3
2010-10-07T01:28:55Z
3,878,095
14
2010-10-07T01:33:43Z
[ "python", "paramiko" ]
Have installed Paramiko for Python and PyCrypto for Windows 7 machine. ``` import paramiko ssh = paramiko.SSHClient() ``` Tried the above commands but I keep getting this error msg: ``` AttributeError: 'module' object has no attribute 'SSHClient' ``` but this error message goes away if I key in the above comman...
By chance have you called your file `paramiko.py` ? You'll need to name it something else to avoid getting that error.
Tukey five number summary in Python
3,878,245
10
2010-10-07T02:23:43Z
3,878,272
9
2010-10-07T02:30:48Z
[ "python", "statistics", "numpy", "scipy" ]
I have been unable to find this function in any of the standard packages, so I wrote the one below. Before throwing it toward the Cheeseshop, however, does anyone know of an already published version? Alternatively, please suggest any improvements. Thanks. ``` def fivenum(v): """Returns Tukey's five number summary...
I would get rid of these two things: ``` import numpy as np from scipy.stats import scoreatpercentile ``` You should be importing at the module level. This means that users will be aware of missing dependencies as soon as they import your module, rather than when they call the function. ``` try: sum(v) except Ty...
Tukey five number summary in Python
3,878,245
10
2010-10-07T02:23:43Z
13,635,260
21
2012-11-29T21:41:21Z
[ "python", "statistics", "numpy", "scipy" ]
I have been unable to find this function in any of the standard packages, so I wrote the one below. Before throwing it toward the Cheeseshop, however, does anyone know of an already published version? Alternatively, please suggest any improvements. Thanks. ``` def fivenum(v): """Returns Tukey's five number summary...
[`pandas`](http://pandas.pydata.org/) `Series` and `DataFrame` have a `describe` method, which is similar to `R`'s `summary`: ``` In [3]: import numpy as np In [4]: import pandas as pd In [5]: s = pd.Series(np.random.rand(100)) In [6]: s.describe() Out[6]: count 100.000000 mean 0.540376 std 0.29625...
Why are main runnable Python scripts not compiled to pyc files like modules?
3,878,479
22
2010-10-07T03:33:51Z
3,878,510
25
2010-10-07T03:43:15Z
[ "python" ]
I understand that when you import a module, that file is compiled into a `.pyc` file to make it faster? Why is the main file also not compiled to a `.pyc`? Does this slow things down? Would it be better to keep the main file as small as possible then, or does it not matter?
When a module is loaded, the py file is "byte compiled" to pyc files. The time stamp is recorded in pyc files. **This is done not to make it run faster but to load faster.** Hence, it makes sense to "byte compile" modules when you load them. * <http://docs.python.org/tutorial/modules.html#compiled-python-files> [Edit...
How to replace repeated instances of a character with a single instance of that character in python
3,878,555
9
2010-10-07T03:56:54Z
3,878,738
11
2010-10-07T04:42:55Z
[ "python", "string" ]
I want to replace repeated instances of the `"*"` character within a string with a single instance of `"*"`. For example if the string is `"***abc**de*fg******h"`, I want it to get converted to `"*abc*de*fg*h"`. I'm pretty new to python (and programming in general) and tried to use regular expressions and string.repla...
The naive way to do this kind of thing with `re` is ``` re.sub('\*+', '*', text) ``` That replaces runs of 1 or more asterisks with one asterisk. For runs of exactly one asterisk, that is running very hard just to stay still. Much better is to replace runs of **TWO or more** asterisks by a single asterisk: ``` re.su...
Python programs on different Operating Systems
3,878,593
2
2010-10-07T04:10:17Z
3,878,615
9
2010-10-07T04:14:30Z
[ "python" ]
If I write a python script using only python standard libraries, using Python 2.6 will it work on all Operating Systems as long as python 2.6 is installed?
Depends. There are a few parts of the Python standard libraries that are only available on certain platforms. These parts are noted in the Python documentation. You also need to be careful of how you handle things like file paths - using `os.path.join()` and such to make sure paths are formatted in the right way.
Python programs on different Operating Systems
3,878,593
2
2010-10-07T04:10:17Z
3,879,146
7
2010-10-07T06:16:16Z
[ "python" ]
If I write a python script using only python standard libraries, using Python 2.6 will it work on all Operating Systems as long as python 2.6 is installed?
You need to be careful when you are reading binary files. Always use 'rb', 'wb', etc file opening modes. You can get away with 'r' etc on Unix/Linux/etc, but it really matters on Windows. Unintuitively, CSV files are binary. Instructive exercise: work out why this code produces 26 on Windows instead of the 128 that it...
Downloading Mp3 using Python in Windows mangles the song however in Linux it doesn't
3,878,882
3
2010-10-07T05:15:17Z
3,878,887
13
2010-10-07T05:17:08Z
[ "python", "httpwebrequest", "mp3", "web-scraping" ]
I've setup a script to download an mp3 using urllib2 in Python. ``` url = 'example.com' req2 = urllib2.Request(url) response = urllib2.urlopen(req2) #grab the data data = response.read() mp3Name = "song.mp3" song = open(mp3Name, "w") song.write(data) # was data2 song.close() ``` Turns out it was somehow related ...
Try binary file mode. `open(mp3Name, "wb")` You're probably getting line ending translations. The file is binary, yes. It's the mode that wasn't. When a file is opened, it can be set to read as a text file (this is default). When it does this, it will convert line endings to match the platform. On Windows, line ends a...
"Unable to find vcvarsall.bat" error when trying to install qrcode-0.2.1
3,879,014
3
2010-10-07T05:45:17Z
3,879,056
17
2010-10-07T05:55:18Z
[ "python", "installation", "qr-code" ]
Please help me to solve this error ``` C:\Python26\Lib\site-packages\pyqrcode\encoder>python setup.py install running install running bdist_egg running egg_info writing qrcode.egg-info\PKG-INFO writing top-level names to qrcode.egg-info\top_level.txt writing dependency_links to qrcode.egg-info\dependency_links.txt pac...
Distutils does not play well with MS Compiler tool chain. This file is required to setup the environment which will help distutils to use MS compiler tool chains. There are quite a few ways in which this has been made to work. Please look at the following post which may help you. * [Compile Python 2.7 Packages With...
How to create a list or tuple of empty lists in Python?
3,880,037
25
2010-10-07T08:48:41Z
3,880,268
33
2010-10-07T09:20:16Z
[ "memory-management", "python" ]
I need to incrementally fill a list or a tuple of lists. Something that looks like this: ``` result = [] firstTime = True for i in range(x): for j in someListOfElements: if firstTime: result.append([f(j)]) else: result[i].append(j) ``` In order to make it less verbose an mo...
``` result = [list(someListOfElements) for _ in xrange(x)] ``` This will make x distinct lists, each with a copy of `someListOfElements` list (each item in that list is by reference, but the list its in is a copy). If it makes more sense, consider using `copy.deepcopy(someListOfElements)` Generators and list compreh...
how to send the output of pprint module to a log file
3,880,399
26
2010-10-07T09:40:44Z
3,880,431
44
2010-10-07T09:45:43Z
[ "python", "logging" ]
I have the following code: ``` logFile=open('c:\\temp\\mylogfile'+'.txt', 'w') pprint.pprint(dataobject) ``` how can i send the contents of dataobject to the log file on the pretty print format ?
``` pprint.pprint(dataobject, logFile) ``` See [the documentation](http://docs.python.org/library/pprint.html#pprint.pprint)
how to send the output of pprint module to a log file
3,880,399
26
2010-10-07T09:40:44Z
17,839,040
11
2013-07-24T15:53:02Z
[ "python", "logging" ]
I have the following code: ``` logFile=open('c:\\temp\\mylogfile'+'.txt', 'w') pprint.pprint(dataobject) ``` how can i send the contents of dataobject to the log file on the pretty print format ?
Please use `pprint.pformat`, which returns a formated string that can be dumped directly to file. ``` >>> import pprint >>> with open("file_out.txt", "w") as fout: ... fout.write(pprint.pformat(vars(pprint))) ... ``` Reference: <http://docs.python.org/2/library/pprint.html>
closing files properly opened with urllib2.urlopen()
3,880,750
7
2010-10-07T10:31:44Z
3,881,558
8
2010-10-07T12:22:23Z
[ "python", "exception-handling", "urllib2", "pys60" ]
I have following code in a python script ``` try: # send the query request sf = urllib2.urlopen(search_query) search_soup = BeautifulSoup.BeautifulStoneSoup(sf.read()) sf.close() except Exception, err: print("Couldn't get programme information.") print(str(err)) return ``` I'm concerne...
``` finally: if sf: sf.close() ```
closing files properly opened with urllib2.urlopen()
3,880,750
7
2010-10-07T10:31:44Z
14,849,166
13
2013-02-13T08:18:28Z
[ "python", "exception-handling", "urllib2", "pys60" ]
I have following code in a python script ``` try: # send the query request sf = urllib2.urlopen(search_query) search_soup = BeautifulSoup.BeautifulStoneSoup(sf.read()) sf.close() except Exception, err: print("Couldn't get programme information.") print(str(err)) return ``` I'm concerne...
I would use contextlib.closing (in combination with from \_\_future\_\_ import with\_statement for old Python versions): ``` from contextlib import closing with closing(urllib2.urlopen('http://blah')) as sf: search_soup = BeautifulSoup.BeautifulStoneSoup(sf.read()) ``` Or, if you want to avoid the with statement...
Future and stability of IronPython
3,881,418
7
2010-10-07T12:04:19Z
3,882,058
7
2010-10-07T13:23:18Z
[ "python", "ironpython" ]
I am currently looking for a possible way to integrate my C++/C# application with some of my Python scripts. At this point, [IronPython](http://ironpython.codeplex.com/) seems like the way to go. However, before proceeding, I would like to ask the following: * How stable is IronPython right now? Is it ready for produ...
To answer your second question, yes, IronPython will be developed in the future. Right now, there is a "language change moratorium" on CPython, the main branch of Python (see [PEP 3003](http://www.python.org/dev/peps/pep-3003/). The Python folks want CPython, Jython, and other branches of Python development to catch up...
Numpy - add row to array
3,881,453
54
2010-10-07T12:09:13Z
3,881,487
51
2010-10-07T12:14:02Z
[ "python", "arrays", "numpy", "rows" ]
How does one add rows to a numpy array? I have an array A: ``` A = array([[0, 1, 2], [0, 2, 0]]) ``` I wish to add rows to this array from another array X if the first element of each row in X meets a specific condition. Numpy arrays do not have a method 'append' like that of lists, or so it seems. If A and X were...
What is `X`? If it is a 2D-array, how can you then compare its row to a number: `i < 3`? EDIT after OP's comment: ``` A = array([[0, 1, 2], [0, 2, 0]]) X = array([[0, 1, 2], [1, 2, 0], [2, 1, 2], [3, 2, 0]]) ``` add to `A` all rows from `X` where the first element `< 3`: ``` A = vstack((A, X[X[:,0] < 3])) # return...
Numpy - add row to array
3,881,453
54
2010-10-07T12:09:13Z
3,881,504
67
2010-10-07T12:15:51Z
[ "python", "arrays", "numpy", "rows" ]
How does one add rows to a numpy array? I have an array A: ``` A = array([[0, 1, 2], [0, 2, 0]]) ``` I wish to add rows to this array from another array X if the first element of each row in X meets a specific condition. Numpy arrays do not have a method 'append' like that of lists, or so it seems. If A and X were...
well u can do this : ``` newrow = [1,2,3] A = numpy.vstack([A, newrow]) ```
Set python virtualenv in vim
3,881,534
9
2010-10-07T12:19:24Z
4,017,158
13
2010-10-25T17:22:44Z
[ "python", "vim", "virtualenv", "macvim" ]
I use vim for coding and for python coding in particular. Often I want to execute the current buffer with python interpreter. (for example to run unittests), usually I do this with `:!python % <Enter>` This scenatio will work works fine with global python, but I want to run virtualenv python instead. How do I enable v...
Here's what I use (sorry the highlighting is screwy). ``` " Function to activate a virtualenv in the embedded interpreter for " omnicomplete and other things like that. function LoadVirtualEnv(path) let activate_this = a:path . '/bin/activate_this.py' if getftype(a:path) == "dir" && filereadable(activate_this)...
Adding dynamic property to a python object
3,881,895
3
2010-10-07T13:02:14Z
3,882,255
7
2010-10-07T13:46:18Z
[ "python", "dynamic", "properties", "add" ]
``` site = object() mydict = {'name': 'My Site', 'location': 'Zhengjiang'} for key, value in mydict.iteritems(): setattr(site, key, value) print site.a # it doesn't work ``` The above code didn't work. Any suggestion?
The easiest way to populate one `dict` with another is [the `update()` method](http://docs.python.org/library/stdtypes.html#dict.update), so if you extend `object` to ensure your object has a `__dict__` you could try something like this: ``` >>> class Site(object): ... pass ... >>> site = Site() >>> site.__dict__....
Python 2.6 to 2.5 cheat sheet
3,881,980
4
2010-10-07T13:13:38Z
3,882,031
7
2010-10-07T13:19:24Z
[ "python", "python-2.6", "python-2.5", "backport" ]
I've written my code to target Python 2.6.5, but I now need to run it on a cluster that only has 2.5.4, something that wasn't on the horizon when I wrote the code. Backporting the code to 2.5 shouldn't be too hard, but I was wondering if there was either a cheat-sheet or an automated tool that would help me with this. ...
Have you read the [What's New in Python 2.6](http://docs.python.org/whatsnew/2.6.html) document? It describes the 2.5->2.6 direction, but you should be able to figure out the reverse from it. As far as I know, there are no automated tools for 2.6 to 2.5. The only tool I know of is the 2to3 app for going to Python 3.
Stop-word elimination and stemmer in python
3,882,921
3
2010-10-07T14:53:10Z
3,882,948
7
2010-10-07T14:56:33Z
[ "python", "nlp", "stemming", "stop-words" ]
I have a somewhat large document and want to do stop-word elimination and stemming on the words of this document with Python. Does anyone know an of the shelf package for these? If not a code which is fast enough for large documents is also welcome. Thanks
[NLTK](http://www.nltk.org/) supports this.
negative numbers modulo in python
3,883,004
27
2010-10-07T15:00:39Z
3,883,019
48
2010-10-07T15:02:37Z
[ "python", "modulo", "negative-number" ]
I've found some strange behaviour in python regarding negative numbers: ``` >>> a = -5 >>> a % 4 3 ``` Could anyone explain what's going on?
Unlike C or C++, Python's modulo operator (`%`) always return a number having the same sign as the denominator (divisor). Your expression yields 3 because > (-5) % 4 = (-2 × 4 + 3) % 4 = 3. It is chosen over the C behavior because a nonnegative result is often more useful. An example is to compute week days. If today...
negative numbers modulo in python
3,883,004
27
2010-10-07T15:00:39Z
3,883,064
19
2010-10-07T15:06:49Z
[ "python", "modulo", "negative-number" ]
I've found some strange behaviour in python regarding negative numbers: ``` >>> a = -5 >>> a % 4 3 ``` Could anyone explain what's going on?
Here's an explanation from Guido van Rossum: <http://python-history.blogspot.com/2010/08/why-pythons-integer-division-floors.html> Essentially, it's so that a/b = q with remainder r preserves the relationships b\*q + r = a and 0 <= r < b.
How do I read the number of files in a folder using Python?
3,883,138
6
2010-10-07T15:17:14Z
3,883,201
24
2010-10-07T15:23:50Z
[ "python", "file-io" ]
How do I read the number of files in a specific folder using Python? Example code would be awesome!
To count files and directories non-recursively you can use [`os.listdir`](http://docs.python.org/library/os.html#os.listdir) and take its length. To count files and directories recursively you can use [`os.walk`](http://docs.python.org/library/os.html#os.walk) to iterate over the files and subdirectories in the direct...
Using Python code coverage tool for understanding and pruning back source code of a large library
3,883,484
6
2010-10-07T15:56:16Z
3,886,403
8
2010-10-07T22:39:02Z
[ "python", "code-coverage", "reverse-engineering", "code-analysis" ]
My project targets a low-cost and low-resource embedded device. I am dependent on a relatively large and sprawling Python code base, of which my use of its APIs is quite specific. I am keen to prune the code of this library back to its bare minimum, by executing my test suite within a coverage tools like Ned Batchelde...
What you want isn't "test coverage", it is the transitive closure of "can call" from the root of the computation. (In threaded applications, you have to include "can fork"). You want to designate some small set (perhaps only 1) of functions that make up the entry points of your application, and want to trace through a...
Encoding error in Python with Chinese characters
3,883,573
4
2010-10-07T16:05:17Z
3,888,653
8
2010-10-08T07:53:51Z
[ "python", "encoding", "cjk" ]
I'm a beginner having trouble decoding several dozen CSV file with numbers + (Simplified) Chinese characters to UTF-8 in Python 2.7. I do not know the encoding of the input files so I have tried all the possible encodings I am aware of -- GB18030, UTF-7, UTF-8, UTF-16 & UTF-32 (LE & BE). Also, for good measure, GBK an...
""" ... GB18030. I thought this would be the solution because it read through the first few files and decoded them fine.""" -- please explain what you mean. To me, there are TWO criteria for a successful decoding: firstly that raw\_bytes.decode('some\_encoding') didn't fail, secondly that the resultant unicode when dis...
Designing an Python API: Fluent interface or arguments
3,883,907
14
2010-10-07T16:50:39Z
3,884,092
12
2010-10-07T17:13:38Z
[ "python", "interface-design" ]
I'm playing around with a simple port of the [Protovis](http://vis.stanford.edu/protovis/) API to Python. Consider the simple bar chart example, in Javascript: ``` var vis = new pv.Panel() .width(150) .height(150); vis.add(pv.Bar) .data([1, 1.2, 1.7, 1.5, .7, .3]) .width(20) .height(function(d) d...
My vote is anti-chaining, pro-named-params. 1. dot-chaining makes for poor code-intellisense since the empirical prototype is just an empty Panel() or Bar(), you can of course pydoc on it, but in this day and age intellisense is available in most IDEs and a great productivity booster. 2. Chaining makes programatically...
Ruby use case for nil, equivalent to Python None or JavaScript undefined
3,884,004
4
2010-10-07T17:02:34Z
3,884,846
7
2010-10-07T18:50:09Z
[ "javascript", "python", "ruby", null ]
How does Ruby's `nil` manifest in code? For example, in Python you might use None for a default argument when it refers to another argument, but in Ruby you can refer to other arguments in the arg list (see [this question](http://stackoverflow.com/questions/3875943/ruby-default-argument-idiom)). In JS, `undefined` pops...
Ruby's [nil](http://www.ruby-doc.org/core-1.9.3/NilClass.html) and Python's `None` are pretty much equivalent (they represent the absence of value), but people coming from Python may find surprising behaviors. First, Ruby returns `nil` in situations Python raises an exception: Accessing arrays and hashes: ``` [1, 2, ...
Automatically setting class member variables in Python
3,884,612
16
2010-10-07T18:18:35Z
3,884,624
20
2010-10-07T18:20:37Z
[ "python", "constructor" ]
Say, I have the following class in Python ``` class Foo(object): a = None b = None c = None def __init__(self, a = None, b = None, c = None): self.a = a self.b = b self.c = c ``` Is there any way to simplify this process? Whenever I add a new member to class Foo, I'm forced to ...
Please note that ``` class Foo(object): a = None ``` sets a key-value pair in `Foo`'s dict: ``` Foo.__dict__['a']=None ``` while ``` def __init__(self, a = None, b = None, c = None): self.a = a ``` sets a key-value pair in the Foo instance object's dict: ``` foo=Foo() foo.__dict__['a']=a ``` So setting ...
Automatically setting class member variables in Python
3,884,612
16
2010-10-07T18:18:35Z
3,884,679
9
2010-10-07T18:28:27Z
[ "python", "constructor" ]
Say, I have the following class in Python ``` class Foo(object): a = None b = None c = None def __init__(self, a = None, b = None, c = None): self.a = a self.b = b self.c = c ``` Is there any way to simplify this process? Whenever I add a new member to class Foo, I'm forced to ...
There are [elegant](http://stackoverflow.com/questions/1389180/python-automatically-initialize-instance-variables) ways to do this. > Is there any way to simplify this process? Whenever I add a new member to class Foo, I'm forced to modify the constructor. There is also a *crude* way. It will work, but is NOT recomme...
custom methods in python urllib2
3,884,695
3
2010-10-07T18:30:51Z
3,884,771
7
2010-10-07T18:40:14Z
[ "python", "methods", "urllib2" ]
Using urllib2, are we able to use a method other than 'GET' or 'POST' (when data is provided)? I dug into the library and it seems that the decision to use GET or POST is 'conveniently' tied to whether or not data is provided in the request. For example, I want to interact with a CouchDB database which requires metho...
You could subclass urllib2.Request like so (untested) ``` import urllib2 class MyRequest(urllib2.Request): GET = 'get' POST = 'post' PUT = 'put' DELETE = 'delete' def __init__(self, url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None): urllib2...
Multiple authentication options with Tornado
3,885,085
8
2010-10-07T19:16:58Z
3,902,887
11
2010-10-11T00:49:02Z
[ "python", "authentication", "tornado" ]
Just started playing with Tornado and want to offer multiple methods of authentication. Currently my app is working fine with Google's hybrid OpenID/oAuth using tornado.auth.GoogleMixin and the unauthenticated users are automatically sent to Google's auth page. If an unauthenticated user wants to use another option (i...
I think the easiest way to do it would be to change the AuthLoginHandler to something more specific, like GoogleAuthHandler, and create an appropriate route for that: ``` (r"/login/google/", GoogleAuthHandler), (r"/login/facebook/", FacebookAuthHandler), ``` etc. Then simply create links to each authentication provi...
Python - decorator - trying to access the parent class of a method
3,885,459
4
2010-10-07T20:05:02Z
3,885,587
7
2010-10-07T20:24:07Z
[ "python", "decorator" ]
This doesn't work: ``` def register_method(name=None): def decorator(method): # The next line assumes the decorated method is bound (which of course it isn't at this point) cls = method.im_class cls.my_attr = 'FOO BAR' def wrapper(*args, **kwargs): method(*args, **kwargs...
I don't think you can do what you want to do with a decorator (quick edit: with a decorator of the method, anyway). The decorator gets called when the method gets constructed, which is *before* the class is constructed. The reason your code isn't working is because the class doesn't exist when the decorator is called. ...
Implementing Bi-Directional relationships in MongoEngine
3,885,487
15
2010-10-07T20:09:32Z
3,893,926
29
2010-10-08T20:02:19Z
[ "python", "mongodb", "circular-reference", "bidirectional-relation", "mongoengine" ]
I'm building a Django application that uses MongoDB and MongoEngine to store data. To present a simplified version of my problem, say I want to have two classes: User and Page. Each page should associate itself with a user and each user a page. ``` from mongoengine import * class Page(Document): pass class User(...
This is the proper solution: ``` from mongoengine import * class User(Document): name = StringField() page = ReferenceField('Page') class Page(Document): content = StringField() user = ReferenceField(User) ``` Use single quotes ('Page') to denote classes that have not yet been defined.
How to use session on Google app engine
3,885,996
12
2010-10-07T21:24:52Z
3,886,158
20
2010-10-07T21:55:26Z
[ "python", "google-app-engine", "session", "login" ]
I'm building an application using Google app engine with python, and I'm stuck with making sessions. Is there any app that already does that for app engine? Thank you.
I recommend [gae-sessions](http://github.com/dound/gae-sessions/wiki). The source includes demos which show how to use it, including how to integrate with the Users API or RPX/JanRain. Disclaimer: I wrote gae-sessions, but for an informative comparison of it with alternatives, read [this article](http://github.com/dou...
How do I remove the y-axis from a Pylab-generated picture?
3,886,255
5
2010-10-07T22:15:10Z
3,886,272
10
2010-10-07T22:18:10Z
[ "python", "python-imaging-library", "matplotlib" ]
``` import pylab # matplotlib x_list = [1,1,1,1,5,4] y_list = [1,2,3,4,5,4] pylab.plot(x_list, y_list, 'bo') pylab.show() ``` What I want to do is remove the y-axis from the diagram, only keeping the x-axis. And adding more margin to the diagram, we can see that a lot of dots are on the edge of the canvas and don'...
``` ax = pylab.gca() ax.yaxis.set_visible(False) pylab.show() ```
Display array as raster image in python
3,886,281
11
2010-10-07T22:19:04Z
3,886,301
17
2010-10-07T22:21:37Z
[ "python", "image", "image-processing", "numpy" ]
I've got a numpy array in Python and I'd like to display it on-screen as a raster image. What is the simplest way to do this? It doesn't need to be particularly fancy or have a nice interface, all I need to do is to display the contents of the array as a greyscale raster image. I'm trying to transition some of my IDL ...
Depending on your needs, either [matplotlib's `imshow`](http://matplotlib.sourceforge.net/) or [glumpy](http://code.google.com/p/glumpy/) are probably the best options. Matplotlib is infinitely more flexible, but slower (animations in matplotlib can be suprisingly resource intensive even when you do everything right.)...
python: how to get numbers after decimal point?
3,886,402
30
2010-10-07T22:38:47Z
3,886,407
31
2010-10-07T22:40:16Z
[ "python" ]
how do i get the numbers after a decimal point? for example if i have `5.55` how do i get `.55`?
What about: ``` a = 1.3927278749291 b = a - int(a) b >> 0.39272787492910011 ``` Or, using numpy: ``` import numpy a = 1.3927278749291 b = a - numpy.fix(a) ```
python: how to get numbers after decimal point?
3,886,402
30
2010-10-07T22:38:47Z
3,886,408
64
2010-10-07T22:40:19Z
[ "python" ]
how do i get the numbers after a decimal point? for example if i have `5.55` how do i get `.55`?
``` 5.55 % 1 ``` Keep in mind this won't help you with floating point rounding problems. I.e., you may get: ``` 0.550000000001 ``` Or otherwise a little off the 0.55 you are expecting.
python: how to get numbers after decimal point?
3,886,402
30
2010-10-07T22:38:47Z
3,886,439
18
2010-10-07T22:46:35Z
[ "python" ]
how do i get the numbers after a decimal point? for example if i have `5.55` how do i get `.55`?
Using the [`decimal`](http://docs.python.org/library/decimal.html) module from the standard library, you can retain the original precision and avoid floating point rounding issues: ``` >>> from decimal import Decimal >>> Decimal('4.20') % 1 Decimal('0.20') ``` As [kindall](http://stackoverflow.com/users/416467/kindal...
python: how to get numbers after decimal point?
3,886,402
30
2010-10-07T22:38:47Z
23,702,755
30
2014-05-16T18:58:54Z
[ "python" ]
how do i get the numbers after a decimal point? for example if i have `5.55` how do i get `.55`?
Use [modf](https://docs.python.org/2/library/math.html#math.modf): ``` >>> import math >>> frac, whole = math.modf(2.5) >>> frac 0.5 >>> whole 2.0 ```
switch case in python doesn't work; need another pattern
3,886,641
3
2010-10-07T23:22:10Z
3,886,656
9
2010-10-07T23:25:24Z
[ "python", "design-patterns" ]
I need a help with a code here, i wanted to implement the switch case pattern in python so like some tutorial said , i can use a dictionary for that but here is my problem: ``` # type can be either create or update or .. message = { 'create':msg(some_data), 'update':msg(other_data) # c...
``` message = { 'create':msg(some_data or ''), 'update':msg(other_data or '') # can have more } ``` Better yet, to prevent `msg` from being executed just to fill the dict: ``` message = { 'create':(msg,some_data), 'update':(msg,other_data), # can have more ...
switch case in python doesn't work; need another pattern
3,886,641
3
2010-10-07T23:22:10Z
3,887,518
9
2010-10-08T03:34:20Z
[ "python", "design-patterns" ]
I need a help with a code here, i wanted to implement the switch case pattern in python so like some tutorial said , i can use a dictionary for that but here is my problem: ``` # type can be either create or update or .. message = { 'create':msg(some_data), 'update':msg(other_data) # c...
It sounds like you're complicating this more than you need to. You want simple? ``` if mytype == 'create': return msg(some_data) elif mytype == 'update': return msg(other_data) else: return msg(default_data) ``` You don't *have* to use dicts and function references just because you *can*. Sometimes a bori...
Tuple to string
3,886,669
3
2010-10-07T23:28:06Z
3,886,672
9
2010-10-07T23:29:42Z
[ "python" ]
I have a tuple. ``` tst = ([['name', u'bob-21'], ['name', u'john-28']], True) ``` And I want to convert it to a string.. ``` print tst2 "([['name', u'bob-21'], ['name', u'john-28']], True)" ``` what is a good way to do this? Thanks!
``` tst2 = str(tst) ``` E.g.: ``` >>> tst = ([['name', u'bob-21'], ['name', u'john-28']], True) >>> tst2 = str(tst) >>> print tst2 ([['name', u'bob-21'], ['name', u'john-28']], True) >>> repr(tst2) '"([[\'name\', u\'bob-21\'], [\'name\', u\'john-28\']], True)"' ```
Why does initializing a variable via a python default variable keep state across object instantiation?
3,887,079
3
2010-10-08T01:23:24Z
3,887,121
7
2010-10-08T01:36:03Z
[ "python", "arguments" ]
I hit an interesting python bug today in which instantiating a class repeatedly appears to be holding state. In later instantiation calls the variable is already defined. I boiled down the issue into the following class/shell interaction. I realize that this is not the best way to initialize a class variable, but it s...
It is a feature that pretty much all Python users run into once or twice. The main usage is for caches and the likes to avoid repetitive lengthy calculations (simple memoizing, really), although I am sure people have found other uses for it. The reason for this is that the `def` statement only gets executed once, whic...
TypeError: 'NoneType' object is not iterable in Python
3,887,381
46
2010-10-08T02:56:26Z
3,887,385
79
2010-10-08T02:57:22Z
[ "python", "nonetype" ]
What does error `TypeError: 'NoneType' object is not iterable` mean? I am getting it on this Python code: ``` def write_file(data,filename): #creates file and writes list to it with open(filename,'wb') as outfile: writer=csv.writer(outfile) for row in data: ##ABOVE ERROR IS THROWN HERE w...
It means "data" is None.
TypeError: 'NoneType' object is not iterable in Python
3,887,381
46
2010-10-08T02:56:26Z
3,887,391
7
2010-10-08T02:58:55Z
[ "python", "nonetype" ]
What does error `TypeError: 'NoneType' object is not iterable` mean? I am getting it on this Python code: ``` def write_file(data,filename): #creates file and writes list to it with open(filename,'wb') as outfile: writer=csv.writer(outfile) for row in data: ##ABOVE ERROR IS THROWN HERE w...
It means that the data variable is passing None (which is type NoneType), its equivalent for *nothing*. So it can't be iterable as a list, as you are trying to do.
TypeError: 'NoneType' object is not iterable in Python
3,887,381
46
2010-10-08T02:56:26Z
3,888,157
39
2010-10-08T06:22:20Z
[ "python", "nonetype" ]
What does error `TypeError: 'NoneType' object is not iterable` mean? I am getting it on this Python code: ``` def write_file(data,filename): #creates file and writes list to it with open(filename,'wb') as outfile: writer=csv.writer(outfile) for row in data: ##ABOVE ERROR IS THROWN HERE w...
Code: `for row in data:` Error message: `TypeError: 'NoneType' object is not iterable` Which object is it complaining about? Choice of two, `row` and `data`. In `for row in data`, which needs to be iterable? Only `data`. What's the problem with `data`? Its type is `NoneType`. Only `None` has type `NoneType`. So `da...
TypeError: 'NoneType' object is not iterable in Python
3,887,381
46
2010-10-08T02:56:26Z
31,257,927
15
2015-07-07T00:33:28Z
[ "python", "nonetype" ]
What does error `TypeError: 'NoneType' object is not iterable` mean? I am getting it on this Python code: ``` def write_file(data,filename): #creates file and writes list to it with open(filename,'wb') as outfile: writer=csv.writer(outfile) for row in data: ##ABOVE ERROR IS THROWN HERE w...
## How to reproduce this error in python: **Python methods will return NoneType if you expect a tuple from them and fail to return anything to fill them up:** ``` >>> def baz(): ... print("k") ... >>> a, b = baz() k Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'NoneType' obje...
python: how to convert currency to decimal?
3,887,469
11
2010-10-08T03:22:12Z
3,887,483
15
2010-10-08T03:27:13Z
[ "python" ]
i have dollars in a string variable ``` dollars = '$5.99' ``` how do i convert this to a decimal instead of a string so that i can do operations with it like adding dollars to it?
If you'd prefer just an integer number of cents: ``` cents_int = int(round(float(dollars.strip('$'))*100)) ``` If you want a Decimal, just use... ``` from decimal import Decimal dollars_dec = Decimal(dollars.strip('$')) ``` If you know that the dollar sign will always be there, you could use `dollars[1:]` instead o...
python: how to convert currency to decimal?
3,887,469
11
2010-10-08T03:22:12Z
15,207,532
10
2013-03-04T17:36:42Z
[ "python" ]
i have dollars in a string variable ``` dollars = '$5.99' ``` how do i convert this to a decimal instead of a string so that i can do operations with it like adding dollars to it?
Assuming the string stored in the variable `dollars` was generated using python's locale module. A potentially cleaner way to convert it back to float (decimal) is to use the `atof` function from the same module. It should work as long as you use the same `setlocale` parameters in both directions (from currency to stri...
What is the use of related fields in OpenERP?
3,887,675
8
2010-10-08T04:20:55Z
3,893,791
9
2010-10-08T19:42:09Z
[ "python", "openerp" ]
Can someone explain to me something about related fields. For example - * How it was used * How it can be helped * For which kind of scenario I should use fields.related If anybody can provide a small example for real use of fields.related I would appreciate it.
It lets you pull a field from a related table. You can find more details in the [developer book](http://doc.openerp.com/developer/2_5_Objects_Fields_Methods/field_type.html#relational-types), and one example to look at is the `order_partner_id` field of the `sale_order_line` class. In version 5.14, that's at line 806 o...
What is the use of related fields in OpenERP?
3,887,675
8
2010-10-08T04:20:55Z
8,308,931
7
2011-11-29T10:05:37Z
[ "python", "openerp" ]
Can someone explain to me something about related fields. For example - * How it was used * How it can be helped * For which kind of scenario I should use fields.related If anybody can provide a small example for real use of fields.related I would appreciate it.
When using a related field you have to first select which field to be related. For example I'm creating a new module for adding student details. Here the student is actually the partner. So `_rec_name='partner_id'` is taken.In `res.partner` you may have seen the `ref` field. The value in the `ref` field is taken as the...
Passing arguments inside Scrapy spider through lambda callbacks
3,887,968
7
2010-10-08T05:38:31Z
3,888,032
9
2010-10-08T05:55:46Z
[ "python", "lambda", "scrapy" ]
HI, I'm have this short spider code: ``` class TestSpider(CrawlSpider): name = "test" allowed_domains = ["google.com", "yahoo.com"] start_urls = [ "http://google.com" ] def parse2(self, response, i): print "page2, i: ", i # traceback.print_stack() def parse(self, res...
The lambdas are accessing `i` which is being held in closure so they are all referencing the same value (the value of `i` in youre `parse` function when the lambdas are called). A simpler reconstruction of the phenomenon is: ``` >>> def do(x): ... for i in range(x): ... yield lambda: i ... >>> delayed = l...
Passing arguments inside Scrapy spider through lambda callbacks
3,887,968
7
2010-10-08T05:38:31Z
16,632,252
24
2013-05-19T07:07:36Z
[ "python", "lambda", "scrapy" ]
HI, I'm have this short spider code: ``` class TestSpider(CrawlSpider): name = "test" allowed_domains = ["google.com", "yahoo.com"] start_urls = [ "http://google.com" ] def parse2(self, response, i): print "page2, i: ", i # traceback.print_stack() def parse(self, res...
According to the Scrapy documentation using lambda will prevent the libraries Jobs functionality from working (<http://doc.scrapy.org/en/latest/topics/jobs.html>). The Request() and FormRequest() both contain a dictionary named meta which can be used to pass arguments. ``` def some_callback(self, response): somea...
Python - making decorators with optional arguments
3,888,158
32
2010-10-08T06:22:21Z
3,888,245
24
2010-10-08T06:38:25Z
[ "python", "wrapper", "decorator" ]
``` from functools import wraps def foo_register(method_name=None): """Does stuff.""" def decorator(method): if method_name is None: method.gw_method = method.__name__ else: method.gw_method = method_name @wraps(method) def wrapper(*args, **kwargs): ...
Glenn - I had to do it then. I guess I'm glad that there is not a "magic" way to do it. I hate those. So, here's my own answer (method names different than above, but same concept): ``` from functools import wraps def register_gw_method(method_or_name): """Cool!""" def decorator(method): if callable(...
Python - making decorators with optional arguments
3,888,158
32
2010-10-08T06:22:21Z
20,966,822
23
2014-01-07T08:14:24Z
[ "python", "wrapper", "decorator" ]
``` from functools import wraps def foo_register(method_name=None): """Does stuff.""" def decorator(method): if method_name is None: method.gw_method = method.__name__ else: method.gw_method = method_name @wraps(method) def wrapper(*args, **kwargs): ...
Through the help of the answers here and elsewhere and a bunch of trial and error I've found that there is actually a far easier and generic way to make decorators take optional arguments. It does check the args it was called with but there isn't any other way to do it. The key is to **decorate your decorator**. # Ge...
Python - making decorators with optional arguments
3,888,158
32
2010-10-08T06:22:21Z
24,617,244
18
2014-07-07T18:25:18Z
[ "python", "wrapper", "decorator" ]
``` from functools import wraps def foo_register(method_name=None): """Does stuff.""" def decorator(method): if method_name is None: method.gw_method = method.__name__ else: method.gw_method = method_name @wraps(method) def wrapper(*args, **kwargs): ...
The cleanest way I know of for doing this is the following: ``` import functools def decorator(original_function=None, optional_argument1=None, optional_argument2=None, ...): def _decorate(function): @functools.wraps(function) def wrapped_function(*args, **kwargs): ... retu...
How can I get all the request headers in Django?
3,889,769
39
2010-10-08T10:47:10Z
3,889,790
59
2010-10-08T10:51:53Z
[ "python", "django", "http-headers", "httprequest" ]
I need to get all the Django request headers. From what i've read, Django simply dumps everything into the `request.META` variable along with a lot aof other data. What would be the best way to get **all** the headers that the client sent to my Django application? I'm going use these to build a `httplib` request.
According to the [documentation](http://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.META) `request.META` is a "standard Python dictionary containing all available HTTP headers". If you want to get *all* the headers you can simply iterate through the dictionary. Which part of your code t...
How can I get all the request headers in Django?
3,889,769
39
2010-10-08T10:47:10Z
8,976,745
8
2012-01-23T18:33:00Z
[ "python", "django", "http-headers", "httprequest" ]
I need to get all the Django request headers. From what i've read, Django simply dumps everything into the `request.META` variable along with a lot aof other data. What would be the best way to get **all** the headers that the client sent to my Django application? I'm going use these to build a `httplib` request.
This is another way to do it, very similar to **Manoj Govindan**'s answer above: ``` import re regex_http_ = re.compile(r'^HTTP_.+$') regex_content_type = re.compile(r'^CONTENT_TYPE$') regex_content_length = re.compile(r'^CONTENT_LENGTH$') request_headers = {} for header in request.META: if regex_http_...
python code highlighter for publishing in html
3,889,841
5
2010-10-08T11:00:44Z
3,889,878
10
2010-10-08T11:06:26Z
[ "python", "syntax-highlighting" ]
I'm looking for a python code highlighter for publishing as html. I've found this site <http://quickhighlighter.com> that does highlighting really well. However if I try to copy/paste some python code from it to a text file, I get a mess. If you know a better tool, please let me know. Thanks in advance.
[`pygmentize`](http://pygments.org/docs/cmdline/), which handles a lot more languages than just Python and a lot more formats than just HTML.
How is generated the python grammar and how the interpreter understand it
3,890,321
4
2010-10-08T12:11:09Z
3,890,344
8
2010-10-08T12:14:57Z
[ "python", "grammar" ]
I wonder how is generated the grammar of the Python language and how it is understood by the interpreter. In python, the file `graminit.c` seems to implement the grammar, but i don't clearly understand it. More broadly, what are the different ways to generate a grammar and are there differences between how the gramma...
Grammars are generally of the same form: Backus-Naur Form (BNF) is typical. Lexer/parsers can take very different forms. The lexer breaks up the input file into tokens. The parser uses the grammar to see if the stream of tokens is "valid" according to its rules. Usually the outcome is an abstract syntax tree (AST) t...
How do I use num_rows() function in the MySQLDB API for Python?
3,890,517
6
2010-10-08T12:38:10Z
3,890,696
19
2010-10-08T12:59:43Z
[ "python", "mysql" ]
I have this statement ``` cursor = connection.cursor() query = "SELECT * from table" cursor.execute(query) res = cursor.fetchall() ```
``` cursor = connection.cursor() query = "SELECT * from table" cursor.execute(query) print cursor.rowcount ``` According to the [Python Database API Specification v2.0](http://www.python.org/dev/peps/pep-0249/), the `rowcount` attribute of the `cursor` object should return the number of rows that the last query produc...
how does multiplication differ for NumPy Matrix vs Array classes?
3,890,621
94
2010-10-08T12:50:47Z
3,892,639
95
2010-10-08T16:49:23Z
[ "python", "arrays", "numpy", "matrix", "matrix-multiplication" ]
The numpy docs recommend using array instead of matrix for working with matrices. However, unlike octave (which I was using till recently), \* doesn't perform matrix multiplication, you need to use the function matrixmultipy(). I feel this makes the code very unreadable. Does anybody share my views, and has found a so...
The main reason to avoid using the `matrix` class is that a) it's inherently 2-dimensional, and b) there's additional overhead compared to a "normal" numpy array. If all you're doing is linear algebra, then by all means, feel free to use the matrix class... Personally I find it more trouble than it's worth, though. Fo...
how does multiplication differ for NumPy Matrix vs Array classes?
3,890,621
94
2010-10-08T12:50:47Z
18,314,596
54
2013-08-19T13:07:35Z
[ "python", "arrays", "numpy", "matrix", "matrix-multiplication" ]
The numpy docs recommend using array instead of matrix for working with matrices. However, unlike octave (which I was using till recently), \* doesn't perform matrix multiplication, you need to use the function matrixmultipy(). I feel this makes the code very unreadable. Does anybody share my views, and has found a so...
the key things to know for operations on **NumPy** *arrays* versus operations on NumPy *matrices* are: * NumPy matrix is a *subclass* of NumPy array * NumPy array operations are *element-wise* (once broadcasting is accounted for) * NumPy matrix operations follow the ordinary rules of linear algebra some code snippets...
how does multiplication differ for NumPy Matrix vs Array classes?
3,890,621
94
2010-10-08T12:50:47Z
19,146,746
14
2013-10-02T21:01:02Z
[ "python", "arrays", "numpy", "matrix", "matrix-multiplication" ]
The numpy docs recommend using array instead of matrix for working with matrices. However, unlike octave (which I was using till recently), \* doesn't perform matrix multiplication, you need to use the function matrixmultipy(). I feel this makes the code very unreadable. Does anybody share my views, and has found a so...
There is a situation where the dot operator will give different answers when dealing with arrays as with dealing with matrices. For example, suppose the following: ``` >>> a=numpy.array([1, 2, 3]) >>> b=numpy.array([1, 2, 3]) ``` Lets convert them into matrices: ``` >>> am=numpy.mat(a) >>> bm=numpy.mat(b) ``` Now, ...
how does multiplication differ for NumPy Matrix vs Array classes?
3,890,621
94
2010-10-08T12:50:47Z
25,476,540
7
2014-08-24T21:36:10Z
[ "python", "arrays", "numpy", "matrix", "matrix-multiplication" ]
The numpy docs recommend using array instead of matrix for working with matrices. However, unlike octave (which I was using till recently), \* doesn't perform matrix multiplication, you need to use the function matrixmultipy(). I feel this makes the code very unreadable. Does anybody share my views, and has found a so...
In 3.5, Python finally [got a matrix multiplication operator](http://legacy.python.org/dev/peps/pep-0465/). The syntax is `a @ b`.
Django - 404 page displayed for dev web server (http://127.0.0.1:8000/)
3,890,807
6
2010-10-08T13:11:37Z
3,890,892
11
2010-10-08T13:19:49Z
[ "python", "django", "django-models", "django-admin", "django-urls" ]
I am familiarizing myself with Django. I have successfully installed and tested a demo site. I now want to switch on the admin module, to see what happens. The steps I took (granted, some were unnecessary, but I just wanted to make sure I was starting from a clean slate): 1. Edited mysite/settings.py to enable admin...
clearly you are not having any url that handles request to 'http://127.0.0.1:8000/'. To see the admin page visit, 'http://127.0.0.1:8000/admin/' When you have the admin urls ``` # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # (r'^admin/', include(admin....
Select cells randomly from NumPy array - without replacement
3,891,180
13
2010-10-08T13:48:25Z
3,891,224
19
2010-10-08T13:52:26Z
[ "python", "random", "numpy", "shuffle", "sampling" ]
I'm writing some modelling routines in NumPy that need to select cells randomly from a NumPy array and do some processing on them. All cells must be selected without replacement (as in, once a cell has been selected it can't be selected again, but all cells must be selected by the end). I'm transitioning from IDL wher...
How about using `numpy.random.shuffle` or `numpy.random.permutation` if you still need the original array? If you need to change the array in-place than you can create an index array like this: ``` your_array = <some numpy array> index_array = numpy.arange(your_array.size) numpy.random.shuffle(index_array) print you...
how to link python static library with my c++ program
3,891,202
5
2010-10-08T13:50:14Z
3,891,372
8
2010-10-08T14:07:37Z
[ "python" ]
I am implementing a C++ program that uses python/C++ Extensions. As of now I am explicitly linking my program to python static library I compiled. I am wondering is there any way to link my program with system installed python(i mean the default python installation that comes with linux)
Yes. There is a command line utility called `python-config`: ``` Usage: /usr/bin/python-config [--prefix|--exec-prefix|--includes|--libs|--cflags|--ldflags|--help] ``` For linkage purposes, you have to invoke it with `--ldflags` parameter. It will print a list of flags you have to pass to the linker (or `g++`) in ord...
How to connect pyqtSignal between classes in PyQT
3,891,465
13
2010-10-08T14:17:52Z
4,076,977
14
2010-11-02T10:57:49Z
[ "python", "pyqt", "pyqt4" ]
How to connect `pyqtSignal` between two different objects (classes) PROPERLY? I mean best practice. Look what I have done to achieve the goal: The `Thermometer` class is notified when `Pot` increases its temperature: ``` from PyQt4 import QtCore class Pot(QtCore.QObject): temperatureRaisedSignal = QtCore.pyqtSig...
``` from PyQt4 import QtCore class Pot(QtCore.QObject): temperatureRaisedSignal = QtCore.pyqtSignal() def __init__(self, parent=None): QtCore.QObject.__init__(self) self.temperature = 1 def Boil(self): self.temperatureRaisedSignal.emit() self.temperature += 1 class Therm...
Clustering problem
3,891,645
4
2010-10-08T14:40:16Z
3,891,833
7
2010-10-08T15:05:36Z
[ "python", "algorithm", "cluster-analysis", "classification", "nearest-neighbor" ]
I've been tasked to find N clusters containing the most points for a certain data set given that the clusters are bounded by a certain size. Currently, I am attempting to do this by plugging in my data into a kd-tree, iterating over the data and finding its nearest neighbor, and then merging the points if the cluster t...
Check out [scipy.clustering](http://docs.scipy.org/doc/scipy/reference/cluster.html) for a start. Key word searches can then give a lot of info on the different algorithms that are used there. Clustering is a big field, with a lot of research and practical applications, and a number of simple approaches that have been ...
How to raise a warning in Python without stopping (interrupting) the program?
3,891,804
42
2010-10-08T15:01:59Z
3,891,852
43
2010-10-08T15:07:30Z
[ "python", "exception-handling", "error-handling", "warnings" ]
I am dealing with a problem how to raise a Warning in Python without having to let the program crash / stop / interrupt. I use following simple function that only checks if the user passed to it a non-zero number. If the user passes a zero, the program should warn the user, but continue normally. It should work like t...
You shouldn't `raise` the warning, you should be using [`warnings`](http://docs.python.org/library/warnings.html#module-warnings) module. By raising it you're generating error, rather than warning.
How to raise a warning in Python without stopping (interrupting) the program?
3,891,804
42
2010-10-08T15:01:59Z
3,891,890
75
2010-10-08T15:11:33Z
[ "python", "exception-handling", "error-handling", "warnings" ]
I am dealing with a problem how to raise a Warning in Python without having to let the program crash / stop / interrupt. I use following simple function that only checks if the user passed to it a non-zero number. If the user passes a zero, the program should warn the user, but continue normally. It should work like t...
``` import warnings warnings.warn("Warning...........Message") ``` See the python documentation: [here](http://docs.python.org/library/warnings.html#warnings.warn)
Django proxy model and ForeignKey
3,891,880
11
2010-10-08T15:10:13Z
6,988,506
9
2011-08-08T20:59:17Z
[ "python", "django", "django-models" ]
How to make entry.category to be instance of CategoryProxy? See code for details: ``` class Category(models.Model): pass class Entry(models.Model): category = models.ForeignKey(Category) class EntryProxy(Entry): class Meta: proxy = True class CategoryProxy(Category): class Meta: proxy = ...
To switch from a model class to a proxy class without hitting the database: ``` class EntryProxy(Entry): @property def category(self): new_inst = EntryProxy() new_inst.__dict__ = super(EntryProxy, self).category.__dict__ return new_inst ``` edit: the snippet above seems not working on ...
How to test with Python's unittest that a warning has been thrown?
3,892,218
26
2010-10-08T15:51:35Z
3,892,301
21
2010-10-08T16:04:10Z
[ "python", "unit-testing", "exception-handling", "warnings" ]
I have a following function in Python and I want to test with unittest that if the function gets 0 as argument, it throws a warning. I already tried assertRaises, but since I don't raise the warning, that doesn't work. ``` def isZero( i): if i != 0: print "OK" else: warning = Warning...
You can use the `catch_warnings` context manager. Essentially this allows you to mock the warnings handler, so that you can verify details of the warning. See the [official docs](http://docs.python.org/library/warnings.html#testing-warnings) for a fuller explanation and sample test code. ``` import warnings def fxn()...