title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Non-intrusively unlock file on Windows
1,544,275
<p>Is there a way to unlock a file on Windows with a Python script? The file is exclusively locked by another process. I need a solution without killing or interupting the locking process.</p> <p>I already had a look at <a href="http://code.activestate.com/recipes/65203/" rel="nofollow">portalocker</a>, a portable loc...
1
2009-10-09T14:48:24Z
1,544,333
<p>When backup software can't read locked files, I doubt that you can figure out a way using Python.</p>
0
2009-10-09T14:56:59Z
[ "python", "windows", "file", "winapi", "locking" ]
Non-intrusively unlock file on Windows
1,544,275
<p>Is there a way to unlock a file on Windows with a Python script? The file is exclusively locked by another process. I need a solution without killing or interupting the locking process.</p> <p>I already had a look at <a href="http://code.activestate.com/recipes/65203/" rel="nofollow">portalocker</a>, a portable loc...
1
2009-10-09T14:48:24Z
1,544,567
<p>If you only need to infrequently read the locked file, you might try to use the <a href="http://msdn.microsoft.com/en-us/library/bb968832%28VS.85%29.aspx" rel="nofollow">Volume Shadow Copy Service</a></p>
0
2009-10-09T15:41:07Z
[ "python", "windows", "file", "winapi", "locking" ]
Condense this Python statement without destroying readability
1,544,350
<p>I'm pretty new to Python still, so I'm trying to figure out how to do this and need some help.</p> <p>I use return codes to verify that my internal functions return successfully. For example (from internal library functions):</p> <pre><code>result = some_function(arg1,arg2) if result != OK: return result </code></...
2
2009-10-09T14:59:14Z
1,544,370
<p>Could you use exceptions to indicate failure, rather than return codes? Then most of your <code>if result != OK:</code> statements would simply go away.</p>
10
2009-10-09T15:01:45Z
[ "python" ]
Condense this Python statement without destroying readability
1,544,350
<p>I'm pretty new to Python still, so I'm trying to figure out how to do this and need some help.</p> <p>I use return codes to verify that my internal functions return successfully. For example (from internal library functions):</p> <pre><code>result = some_function(arg1,arg2) if result != OK: return result </code></...
2
2009-10-09T14:59:14Z
1,544,398
<p><a href="http://docs.python.org/glossary.html#term-pythonic" rel="nofollow">pythonic</a>:</p> <blockquote> <p>An idea or piece of code which closely follows the most common idioms of the Python language, rather than implementing code using concepts common to other languages.[...]</p> </blockquote> <p>Does not im...
3
2009-10-09T15:06:10Z
[ "python" ]
Condense this Python statement without destroying readability
1,544,350
<p>I'm pretty new to Python still, so I'm trying to figure out how to do this and need some help.</p> <p>I use return codes to verify that my internal functions return successfully. For example (from internal library functions):</p> <pre><code>result = some_function(arg1,arg2) if result != OK: return result </code></...
2
2009-10-09T14:59:14Z
1,544,584
<p>If you insist on <strong>not using</strong> exceptions, then I would write two lines (one line will be too long here):</p> <pre><code>res = some_function(arg1, arg2) return res if res != OK else ... </code></pre> <p>By the way, I recommend you to come up with some <em>static</em> type of values your function retur...
1
2009-10-09T15:43:09Z
[ "python" ]
Condense this Python statement without destroying readability
1,544,350
<p>I'm pretty new to Python still, so I'm trying to figure out how to do this and need some help.</p> <p>I use return codes to verify that my internal functions return successfully. For example (from internal library functions):</p> <pre><code>result = some_function(arg1,arg2) if result != OK: return result </code></...
2
2009-10-09T14:59:14Z
1,544,637
<p>In addition to exceptions, using a decorator is a good solution to this problem:</p> <pre><code># Create a function that creates a decorator given a value to fail on... def fail_unless(ok_val): def _fail_unless(f): def g(*args, **kwargs): val = f(*args, **kwargs) if val != ok_val: ...
-1
2009-10-09T15:52:43Z
[ "python" ]
Condense this Python statement without destroying readability
1,544,350
<p>I'm pretty new to Python still, so I'm trying to figure out how to do this and need some help.</p> <p>I use return codes to verify that my internal functions return successfully. For example (from internal library functions):</p> <pre><code>result = some_function(arg1,arg2) if result != OK: return result </code></...
2
2009-10-09T14:59:14Z
1,544,682
<p>It sounds as if you want something like..</p> <pre><code>if result = some_function(arg1, arg2): return result </code></pre> <p>This is very deliberately not possible in Python. It's too common a typo to write <code>if a = b</code> instead of <code>if a == b</code>, and allowing this mixes assignment with flow-...
2
2009-10-09T16:01:27Z
[ "python" ]
Which ldap object mapper for python can you recommend?
1,544,535
<p>I have to synchronize two different LDAP servers with different schemas. To make my life easier I'm searching for an object mapper for python like SQLobject/SQLAlchemy, but for LDAP. I found the following packages via pypi and google that might provide such functionality:</p> <ul> <li><p><strong>pumpkin 0.1.0-beta1...
9
2009-10-09T15:35:53Z
1,580,486
<p>If I were you I would either use python-ldap or ldaptor. Python-ldap is a wrapper for OpenLDAP so you may have problems with using it on Windows unless you are able to build from source.</p> <p>LDAPtor, is pure python so you avoid that problem. Also, there is a very well written, and graphical description of ldapto...
4
2009-10-16T21:17:34Z
[ "python", "orm", "ldap" ]
Which ldap object mapper for python can you recommend?
1,544,535
<p>I have to synchronize two different LDAP servers with different schemas. To make my life easier I'm searching for an object mapper for python like SQLobject/SQLAlchemy, but for LDAP. I found the following packages via pypi and google that might provide such functionality:</p> <ul> <li><p><strong>pumpkin 0.1.0-beta1...
9
2009-10-09T15:35:53Z
1,781,544
<p>Giving links to the projects in question would help a lot.</p> <p>Being the developer of <a href="https://launchpad.net/python-ldap-om" rel="nofollow">Python LDAP Object Mapper</a>, I can tell that it is quite dead at the moment. If you (or anybody else) is up for taking it over, you're welcome :)</p>
0
2009-11-23T07:14:13Z
[ "python", "orm", "ldap" ]
Which ldap object mapper for python can you recommend?
1,544,535
<p>I have to synchronize two different LDAP servers with different schemas. To make my life easier I'm searching for an object mapper for python like SQLobject/SQLAlchemy, but for LDAP. I found the following packages via pypi and google that might provide such functionality:</p> <ul> <li><p><strong>pumpkin 0.1.0-beta1...
9
2009-10-09T15:35:53Z
1,959,984
<p>little late maybe...</p> <p>bda.ldap (http://pypi.python.org/pypi/bda.ldap) wraps again python-ldap to a more simple API than python-ldap itself provides.</p> <p>Further it transparently handles query caching of results due to bda.cache (http://pypi.python.org/pypi/bda.cache).</p> <p>Additionally it provides a LD...
2
2009-12-24T22:50:48Z
[ "python", "orm", "ldap" ]
Storing parameters in a class, and how to access them
1,544,672
<p>I'm writing a program that randomly assembles mathematical expressions using the values stored in this class. The operators are stored in a dictionary along with the number of arguements they need. The arguements are stored in a list. (the four x's ensure that the x variable gets chosen often) depth, ratio, method a...
0
2009-10-09T16:00:07Z
1,544,694
<p>What you have there are object properties. You mean to use class variables:</p> <pre><code>class Params(object): atoms =['1.0','2.0','3.0','4.0','5.0','6.0','7.0','8.0','9.0','x','x','x','x'] operators = {'+': 2, '-': 2, '*': 2, '/': 2,'+': 2, '-': 2, '*': 2, '/': 2, '**': 2, '%': 2} depth = 1 ratio...
7
2009-10-09T16:03:20Z
[ "python" ]
Storing parameters in a class, and how to access them
1,544,672
<p>I'm writing a program that randomly assembles mathematical expressions using the values stored in this class. The operators are stored in a dictionary along with the number of arguements they need. The arguements are stored in a list. (the four x's ensure that the x variable gets chosen often) depth, ratio, method a...
0
2009-10-09T16:00:07Z
1,544,729
<p>You can do this in a class, but I'd prefer to just put it in a dictionary. Dictionaries are the all-purpose container type in Python, and they're great for this sort of thing.</p> <pre><code>params = { atoms: ['1.0','2.0','3.0','4.0','5.0','6.0','7.0','8.0','9.0','x','x','x','x'], operators: {'+': 2, '-': 2...
0
2009-10-09T16:12:09Z
[ "python" ]
(i'm close - i think) Python loop through list of subdomains with selenium
1,544,701
<p>starting with a base URL, I'm trying to have selenium loop through a short list of subdomains in csv format (ie: one column of 20 subdomains) and printing the html for each. I'm having trouble figuring it out. Thanks!</p> <pre><code>from selenium import selenium import unittest, time, re, csv, logging subds = csv....
0
2009-10-09T16:05:28Z
1,544,890
<p>You're defining the same function again and again in the body of the class. The class is completely created before <code>unittest.main()</code> starts, so only one test method will remain in the class.</p>
1
2009-10-09T16:45:37Z
[ "python", "selenium", "for-loop" ]
python numpy savetxt
1,544,948
<p>Can someone indicate what I am doing wrong here?</p> <pre><code>import numpy as np a = np.array([1,2,3,4,5],dtype=int) b = np.array(['a','b','c','d','e'],dtype='|S1') np.savetxt('test.txt',zip(a,b),fmt="%i %s") </code></pre> <p>The output is:</p> <pre><code>Traceback (most recent call last): File "loadtxt.py"...
5
2009-10-09T16:56:49Z
1,545,069
<p>I think the problem you are having is that you are passing tuples through the formating string and it can't interpret the tuple with %i. Try using fmt="%s", assuming this is what you are looking for as the output:</p> <pre><code>1 a 2 b 3 c 4 d 5 e </code></pre>
1
2009-10-09T17:20:33Z
[ "python", "numpy" ]
python numpy savetxt
1,544,948
<p>Can someone indicate what I am doing wrong here?</p> <pre><code>import numpy as np a = np.array([1,2,3,4,5],dtype=int) b = np.array(['a','b','c','d','e'],dtype='|S1') np.savetxt('test.txt',zip(a,b),fmt="%i %s") </code></pre> <p>The output is:</p> <pre><code>Traceback (most recent call last): File "loadtxt.py"...
5
2009-10-09T16:56:49Z
1,545,114
<p>You need to construct you array differently:</p> <pre><code>z = np.array(zip([1,2,3,4,5], ['a','b','c','d','e']), dtype=[('int', int), ('str', '|S1')]) np.savetxt('test.txt', z, fmt='%i %s') </code></pre> <p>when you're passing a sequence, <code>savetext</code> performs <a href="http://projects.scipy.org/numpy/bro...
12
2009-10-09T17:31:52Z
[ "python", "numpy" ]
python numpy savetxt
1,544,948
<p>Can someone indicate what I am doing wrong here?</p> <pre><code>import numpy as np a = np.array([1,2,3,4,5],dtype=int) b = np.array(['a','b','c','d','e'],dtype='|S1') np.savetxt('test.txt',zip(a,b),fmt="%i %s") </code></pre> <p>The output is:</p> <pre><code>Traceback (most recent call last): File "loadtxt.py"...
5
2009-10-09T16:56:49Z
1,545,190
<p>If you want to save a CSV file you can also use the function rec2csv (included in matplotlib.mlab)</p> <pre><code>&gt;&gt;&gt; from matplotlib.mlab import rec2csv &gt;&gt;&gt; rec = array([(1.0, 2), (3.0, 4)], dtype=[('x', float), ('y', int)]) &gt;&gt;&gt; rec = array(zip([1,2,3,4,5], ['a','b','c','d','e']), dtype=...
4
2009-10-09T17:53:36Z
[ "python", "numpy" ]
Python one-line "for" expression
1,545,050
<p>I'm not sure if I need a lambda, or something else. But still, I need the following:</p> <p>I have an <code>array = [1,2,3,4,5]</code>. I need to put this array, for instance, into another array. But write it all in one line.</p> <pre><code>for item in array: array2.append(item) </code></pre> <p>I know that t...
8
2009-10-09T17:17:05Z
1,545,056
<pre><code>for item in array: array2.append (item) </code></pre> <p>Or, in this case:</p> <pre><code>array2 += array </code></pre>
8
2009-10-09T17:18:13Z
[ "python", "lambda" ]
Python one-line "for" expression
1,545,050
<p>I'm not sure if I need a lambda, or something else. But still, I need the following:</p> <p>I have an <code>array = [1,2,3,4,5]</code>. I need to put this array, for instance, into another array. But write it all in one line.</p> <pre><code>for item in array: array2.append(item) </code></pre> <p>I know that t...
8
2009-10-09T17:17:05Z
1,545,060
<p>The keyword you're looking for is <a href="http://www.python.org/dev/peps/pep-0202/">list comprehensions</a>:</p> <pre><code>&gt;&gt;&gt; x = [1, 2, 3, 4, 5] &gt;&gt;&gt; y = [2*a for a in x if a % 2 == 1] &gt;&gt;&gt; print(y) [2, 6, 10] </code></pre>
21
2009-10-09T17:19:29Z
[ "python", "lambda" ]
Python one-line "for" expression
1,545,050
<p>I'm not sure if I need a lambda, or something else. But still, I need the following:</p> <p>I have an <code>array = [1,2,3,4,5]</code>. I need to put this array, for instance, into another array. But write it all in one line.</p> <pre><code>for item in array: array2.append(item) </code></pre> <p>I know that t...
8
2009-10-09T17:17:05Z
1,545,066
<p>If you're trying to <em>copy</em> the array:</p> <pre><code>array2 = array[:] </code></pre>
1
2009-10-09T17:20:05Z
[ "python", "lambda" ]
Python one-line "for" expression
1,545,050
<p>I'm not sure if I need a lambda, or something else. But still, I need the following:</p> <p>I have an <code>array = [1,2,3,4,5]</code>. I need to put this array, for instance, into another array. But write it all in one line.</p> <pre><code>for item in array: array2.append(item) </code></pre> <p>I know that t...
8
2009-10-09T17:17:05Z
1,545,075
<p>If you really only need to add the items in one array to another, the '+' operator is already overloaded to do that, incidentally:</p> <pre><code>a1 = [1,2,3,4,5] a2 = [6,7,8,9] a1 + a2 --&gt; [1, 2, 3, 4, 5, 6, 7, 8, 9] </code></pre>
1
2009-10-09T17:21:33Z
[ "python", "lambda" ]
Python one-line "for" expression
1,545,050
<p>I'm not sure if I need a lambda, or something else. But still, I need the following:</p> <p>I have an <code>array = [1,2,3,4,5]</code>. I need to put this array, for instance, into another array. But write it all in one line.</p> <pre><code>for item in array: array2.append(item) </code></pre> <p>I know that t...
8
2009-10-09T17:17:05Z
1,545,124
<p>Even <code>array2.extend(array1)</code> will work.</p>
0
2009-10-09T17:34:51Z
[ "python", "lambda" ]
Django - specify which model manager Django admin should use
1,545,067
<p>I've created a custom Manager for a Django model which returns a QuerySet holding a subset of objects.all(). I need this to be the model's default Manager, since I am also creating a custom tag which will retrieve content from any model (specified by an argument), and needs to use the default Manager for the specifi...
24
2009-10-09T17:20:21Z
1,545,338
<p>You can choose the manager by overriding the <code>queryset</code> method in your ModelAdmin subclass.</p> <pre><code>def get_queryset(self, request): # use our manager, rather than the default one qs = self.model.objects.get_query_set() # we need this from the superclass method ordering = self.ord...
34
2009-10-09T18:23:09Z
[ "python", "django" ]
Django - specify which model manager Django admin should use
1,545,067
<p>I've created a custom Manager for a Django model which returns a QuerySet holding a subset of objects.all(). I need this to be the model's default Manager, since I am also creating a custom tag which will retrieve content from any model (specified by an argument), and needs to use the default Manager for the specifi...
24
2009-10-09T17:20:21Z
17,233,535
<p>Updated code:</p> <pre><code>def get_queryset(self, request): """ Returns a QuerySet of all model instances that can be edited by the admin site. This is used by changelist_view. """ qs = self.model._default_manager.get_queryset() # TODO: this should be handled by some parameter to the Chang...
5
2013-06-21T10:56:39Z
[ "python", "django" ]
Is there a way to get the function a decorator has wrapped?
1,545,178
<p>Suppose I have </p> <pre><code>@someDecorator def func(): '''this function does something''' print 1 </code></pre> <p>Now, the object <code>func</code> is an instance of <code>someDecorator</code>. Is there some way I can access the function it holds, i.e something like <code>func.getInnerFunction()</code>.<...
3
2009-10-09T17:51:55Z
1,545,262
<p>Are you looking for something along these lines?</p> <pre><code>&gt;&gt;&gt; def dec(f): def inner(): print(f.__doc__) return inner &gt;&gt;&gt; @dec def test(): """abc""" print(1) &gt;&gt;&gt; test() abc </code></pre> <p>You're passing function explicitly to the decorator, of course you ca...
1
2009-10-09T18:06:08Z
[ "python", "function", "nested", "decorator" ]
Is there a way to get the function a decorator has wrapped?
1,545,178
<p>Suppose I have </p> <pre><code>@someDecorator def func(): '''this function does something''' print 1 </code></pre> <p>Now, the object <code>func</code> is an instance of <code>someDecorator</code>. Is there some way I can access the function it holds, i.e something like <code>func.getInnerFunction()</code>.<...
3
2009-10-09T17:51:55Z
1,545,282
<p>See functools.wraps: <a href="http://docs.python.org/library/functools.html" rel="nofollow">http://docs.python.org/library/functools.html</a>. The decorator gets the name and doc string of the original function. You use it like this:</p> <pre><code>def decorator(f): @functools.wraps(f) def wrapper(): ...
4
2009-10-09T18:10:06Z
[ "python", "function", "nested", "decorator" ]
Is there a way to get the function a decorator has wrapped?
1,545,178
<p>Suppose I have </p> <pre><code>@someDecorator def func(): '''this function does something''' print 1 </code></pre> <p>Now, the object <code>func</code> is an instance of <code>someDecorator</code>. Is there some way I can access the function it holds, i.e something like <code>func.getInnerFunction()</code>.<...
3
2009-10-09T17:51:55Z
1,545,334
<p>SilentGhost and sri have partial answers for how to deal with this. But the general answer is no: there is no way to get the "wrapped" function out of a decorated function because there is no requirement that the decorator wrap the function in the first place. It may very well have returned an entirely unrelated f...
2
2009-10-09T18:22:10Z
[ "python", "function", "nested", "decorator" ]
Is there a way to get the function a decorator has wrapped?
1,545,178
<p>Suppose I have </p> <pre><code>@someDecorator def func(): '''this function does something''' print 1 </code></pre> <p>Now, the object <code>func</code> is an instance of <code>someDecorator</code>. Is there some way I can access the function it holds, i.e something like <code>func.getInnerFunction()</code>.<...
3
2009-10-09T17:51:55Z
1,546,057
<p>You can attach the wrapped function to the inner function</p> <pre><code>In [1]: def wrapper(f): ...: def inner(): ...: print "inner" ...: inner._orig = f ...: return inner ...: In [2]: @wrapper ...: def foo(): ...: print "foo" ...: ...: In [3]: foo() ...
0
2009-10-09T21:10:01Z
[ "python", "function", "nested", "decorator" ]
Is there a way to get the function a decorator has wrapped?
1,545,178
<p>Suppose I have </p> <pre><code>@someDecorator def func(): '''this function does something''' print 1 </code></pre> <p>Now, the object <code>func</code> is an instance of <code>someDecorator</code>. Is there some way I can access the function it holds, i.e something like <code>func.getInnerFunction()</code>.<...
3
2009-10-09T17:51:55Z
35,407,564
<p>You can try using the <a href="https://pypi.python.org/pypi/undecorated" rel="nofollow">undecorated library</a>:</p> <p>With your example <code>func</code>, you could simply do this to return the original function:</p> <pre><code>undecorated(func) </code></pre>
0
2016-02-15T10:57:52Z
[ "python", "function", "nested", "decorator" ]
UTF-8 In Python logging, how?
1,545,263
<p>I'm trying to log a UTF-8 encoded string to a file using Python's logging package. As a toy example:</p> <pre><code>import logging def logging_test(): handler = logging.FileHandler("/home/ted/logfile.txt", "w", encoding = "UTF-8") formatter = logging.Formatter("%(message)...
23
2009-10-09T18:06:15Z
1,545,315
<p>Try this:</p> <pre><code>import logging def logging_test(): log = open("./logfile.txt", "w") handler = logging.StreamHandler(log) formatter = logging.Formatter("%(message)s") handler.setFormatter(formatter) root_logger = logging.getLogger() root_logger.addHandler(handler) root_logger.se...
1
2009-10-09T18:17:29Z
[ "python", "logging", "unicode" ]
UTF-8 In Python logging, how?
1,545,263
<p>I'm trying to log a UTF-8 encoded string to a file using Python's logging package. As a toy example:</p> <pre><code>import logging def logging_test(): handler = logging.FileHandler("/home/ted/logfile.txt", "w", encoding = "UTF-8") formatter = logging.Formatter("%(message)...
23
2009-10-09T18:06:15Z
1,545,599
<p>Check that you have the latest Python 2.6 - some Unicode bugs were found and fixed since 2.6 came out. For example, on my Ubuntu Jaunty system, I ran your script copied and pasted, removing only the '/home/ted/' prefix from the log file name. Result (copied and pasted from a terminal window):</p> <pre> vinay@eta-ja...
13
2009-10-09T19:14:49Z
[ "python", "logging", "unicode" ]
UTF-8 In Python logging, how?
1,545,263
<p>I'm trying to log a UTF-8 encoded string to a file using Python's logging package. As a toy example:</p> <pre><code>import logging def logging_test(): handler = logging.FileHandler("/home/ted/logfile.txt", "w", encoding = "UTF-8") formatter = logging.Formatter("%(message)...
23
2009-10-09T18:06:15Z
1,545,874
<p>If I understood your problem correctly, the same issue should arise on your system when you do just:</p> <pre><code>str(u'ô') </code></pre> <p>I guess automatic encoding to the locale encoding on Unix will not work until you have enabled locale-aware <code>if</code> branch in the <code>setencoding</code> function...
0
2009-10-09T20:24:30Z
[ "python", "logging", "unicode" ]
UTF-8 In Python logging, how?
1,545,263
<p>I'm trying to log a UTF-8 encoded string to a file using Python's logging package. As a toy example:</p> <pre><code>import logging def logging_test(): handler = logging.FileHandler("/home/ted/logfile.txt", "w", encoding = "UTF-8") formatter = logging.Formatter("%(message)...
23
2009-10-09T18:06:15Z
22,320,208
<p>Having code like:</p> <pre><code>raise Exception(u'щ') </code></pre> <p>Caused:</p> <pre><code> File "/usr/lib/python2.7/logging/__init__.py", line 467, in format s = self._fmt % record.__dict__ UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128) </code></pre...
14
2014-03-11T08:31:51Z
[ "python", "logging", "unicode" ]
Math Expression Evaluation
1,545,403
<p>What is the best way to implement a python program that will take a string and will output its result according to operator precedence (for example: "4+3*5" will output 19). I've googled for ways to solve this problem but they were all too complex, and I'm looking for a (relatively) simple one.</p> <p>clarification...
10
2009-10-09T18:35:41Z
1,545,416
<p>I'm not terribly familiar with Python and any extremely Pythonic methods, but you could look at the <a href="http://en.wikipedia.org/wiki/Interpreter%5Fpattern" rel="nofollow">Interpreter pattern</a>, which is defined in the Gang of Four book. It's designed for processing a "language", and mathematical expressions d...
1
2009-10-09T18:39:03Z
[ "python", "math" ]
Math Expression Evaluation
1,545,403
<p>What is the best way to implement a python program that will take a string and will output its result according to operator precedence (for example: "4+3*5" will output 19). I've googled for ways to solve this problem but they were all too complex, and I'm looking for a (relatively) simple one.</p> <p>clarification...
10
2009-10-09T18:35:41Z
1,545,441
<p>That's what the "eval" function does in Python.</p> <pre><code>result = eval(expression) </code></pre> <p>Beware though it can do a whole lot more, primarily call functions, so to be safe you should make sure it can't access the locals or globals. Also, you can access the builtin methods, including the tricky <str...
1
2009-10-09T18:45:36Z
[ "python", "math" ]
Math Expression Evaluation
1,545,403
<p>What is the best way to implement a python program that will take a string and will output its result according to operator precedence (for example: "4+3*5" will output 19). I've googled for ways to solve this problem but they were all too complex, and I'm looking for a (relatively) simple one.</p> <p>clarification...
10
2009-10-09T18:35:41Z
1,545,518
<p>If you're "academically interested", you want to learn about how to write a parser with operator precedence.</p> <p><a href="http://effbot.org/zone/simple-top-down-parsing.htm">Simple Top-Down Parsing in Python</a> is a nice article that builds an example parser to do exactly what you want to do: Evaluate mathemati...
16
2009-10-09T18:59:59Z
[ "python", "math" ]
Math Expression Evaluation
1,545,403
<p>What is the best way to implement a python program that will take a string and will output its result according to operator precedence (for example: "4+3*5" will output 19). I've googled for ways to solve this problem but they were all too complex, and I'm looking for a (relatively) simple one.</p> <p>clarification...
10
2009-10-09T18:35:41Z
1,545,813
<p>Another possibility is to look at <a href="http://pyparsing.wikispaces.com/" rel="nofollow">Pyparsing</a>, which is a general parser builder. It is more powerful than you need, but it may be faster to implement.</p>
2
2009-10-09T20:08:43Z
[ "python", "math" ]
Math Expression Evaluation
1,545,403
<p>What is the best way to implement a python program that will take a string and will output its result according to operator precedence (for example: "4+3*5" will output 19). I've googled for ways to solve this problem but they were all too complex, and I'm looking for a (relatively) simple one.</p> <p>clarification...
10
2009-10-09T18:35:41Z
4,054,885
<p>The java alternative is here <a href="http://code.google.com/p/expressionoasis/" rel="nofollow">http://code.google.com/p/expressionoasis/</a></p>
0
2010-10-29T18:45:30Z
[ "python", "math" ]
Math Expression Evaluation
1,545,403
<p>What is the best way to implement a python program that will take a string and will output its result according to operator precedence (for example: "4+3*5" will output 19). I've googled for ways to solve this problem but they were all too complex, and I'm looking for a (relatively) simple one.</p> <p>clarification...
10
2009-10-09T18:35:41Z
5,115,749
<p>This receipe gives the proper answer to your problem:</p> <p><a href="http://code.activestate.com/recipes/496746-restricted-safe-eval/" rel="nofollow">http://code.activestate.com/recipes/496746-restricted-safe-eval/</a></p> <p>It allows you to eval limited statement that can not harm your computer or your program....
0
2011-02-25T09:48:23Z
[ "python", "math" ]
Force Python to forego native sqlite3 and use the (installed) latest sqlite3 version
1,545,479
<p>The error message I am trying to get rid of is:</p> <blockquote> <p>AttributeError: 'sqlite3.Connection' object has no attribute 'enable_load_extension'</p> </blockquote> <p>I have 'easy_install'-ed the latest sqlite3 version and python somehow know it is there since sqlite3.version_info produces 3.6.13. In ...
26
2009-10-09T18:53:31Z
1,545,853
<p>You need to look at your Python path and make sure that the sqlite you want is installed in an earlier directory than the built-in sqlite.</p> <p>You can see the path with:</p> <pre><code>import sys print sys.path </code></pre> <p>If you want to find out where a module is from, try:</p> <pre><code>print sqlite3....
3
2009-10-09T20:19:39Z
[ "python", "sqlite", "sqlite3" ]
Force Python to forego native sqlite3 and use the (installed) latest sqlite3 version
1,545,479
<p>The error message I am trying to get rid of is:</p> <blockquote> <p>AttributeError: 'sqlite3.Connection' object has no attribute 'enable_load_extension'</p> </blockquote> <p>I have 'easy_install'-ed the latest sqlite3 version and python somehow know it is there since sqlite3.version_info produces 3.6.13. In ...
26
2009-10-09T18:53:31Z
1,546,162
<p><code>sqlite3</code> support in Python can be a bit confusing. The sqlite database adapter started out as a separate project, <a href="https://github.com/ghaering/pysqlite">pysqlite2</a>, but for Python 2.5 a version of it was incorporated into the Python standard library under the name <a href="http://docs.python.o...
61
2009-10-09T21:36:55Z
[ "python", "sqlite", "sqlite3" ]
Force Python to forego native sqlite3 and use the (installed) latest sqlite3 version
1,545,479
<p>The error message I am trying to get rid of is:</p> <blockquote> <p>AttributeError: 'sqlite3.Connection' object has no attribute 'enable_load_extension'</p> </blockquote> <p>I have 'easy_install'-ed the latest sqlite3 version and python somehow know it is there since sqlite3.version_info produces 3.6.13. In ...
26
2009-10-09T18:53:31Z
8,761,073
<p>I have python 2.7 on a windows machine and the built-in sqlite3.sqlite_version was 3.6.x. By performing the following steps I was able to get it to use sqlite 3.7.9.</p> <ol> <li>Download and unzip the pre-compiled binary DLL ("sqlite-dll-win32-x86-3070900.zip" on <a href="http://www.sqlite.org/download.html">http:...
12
2012-01-06T16:30:22Z
[ "python", "sqlite", "sqlite3" ]
Force Python to forego native sqlite3 and use the (installed) latest sqlite3 version
1,545,479
<p>The error message I am trying to get rid of is:</p> <blockquote> <p>AttributeError: 'sqlite3.Connection' object has no attribute 'enable_load_extension'</p> </blockquote> <p>I have 'easy_install'-ed the latest sqlite3 version and python somehow know it is there since sqlite3.version_info produces 3.6.13. In ...
26
2009-10-09T18:53:31Z
22,231,194
<p>Instead of the standard Python <code>sqlite3</code> module, you might be able to use the <a href="https://github.com/rogerbinns/apsw" rel="nofollow">apsw</a> module, a third-party SQLite module that more closely follows the SQLite API. It includes support for loading extensions, as well as basically anything that i...
3
2014-03-06T17:05:22Z
[ "python", "sqlite", "sqlite3" ]
How to apply Loop to working Python Selenium Script?
1,545,602
<p>I'm trying to figure out how to apply a for-loop to this script and I'm having a lot of trouble. I want to iterate through a list of subdomains which are stored in csv format (ie: one column with 20 subdomains) and print the html for each. They all have the same SourceDomain. Thanks!</p> <pre><code>#Python 2.6 f...
0
2009-10-09T19:15:41Z
1,545,640
<pre><code>#Python 2.6 from selenium import selenium import unittest, time, re, csv, logging class Untitled(unittest.TestCase): def setUp(self): self.verificationErrors = [] self.selenium = selenium("localhost", 4444, "*firefox", "http://www.SourceDomain.com") self.selenium.start() def...
3
2009-10-09T19:27:31Z
[ "python", "list", "csv", "selenium", "loops" ]
Python k-means algorithm
1,545,606
<p>I am looking for Python implementation of k-means algorithm with examples to cluster and cache my database of coordinates.</p>
41
2009-10-09T19:16:13Z
1,545,624
<p>From <a href="http://en.wikipedia.org/wiki/K-means%5Fclustering" rel="nofollow">wikipedia</a>, you could use scipy, <a href="http://docs.scipy.org/doc/scipy/reference/cluster.vq.html" rel="nofollow">K-means clustering an vector quantization</a></p> <p>Or, you could use a Python wrapper for OpenCV, <a href="http://...
5
2009-10-09T19:21:30Z
[ "python", "algorithm", "cluster-analysis", "k-means" ]
Python k-means algorithm
1,545,606
<p>I am looking for Python implementation of k-means algorithm with examples to cluster and cache my database of coordinates.</p>
41
2009-10-09T19:16:13Z
1,545,672
<p>You can also use GDAL, which has many many functions to work with spatial data.</p>
0
2009-10-09T19:35:19Z
[ "python", "algorithm", "cluster-analysis", "k-means" ]
Python k-means algorithm
1,545,606
<p>I am looking for Python implementation of k-means algorithm with examples to cluster and cache my database of coordinates.</p>
41
2009-10-09T19:16:13Z
1,546,313
<p><a href="http://docs.scipy.org/doc/scipy/reference/cluster.html">Scipy's clustering</a> implementations work well, and they include a <a href="http://docs.scipy.org/doc/scipy/reference/cluster.vq.html">k-means</a> implementation.</p> <p>There's also <a href="http://code.google.com/p/scipy-cluster/">scipy-cluster</a...
51
2009-10-09T22:10:57Z
[ "python", "algorithm", "cluster-analysis", "k-means" ]
Python k-means algorithm
1,545,606
<p>I am looking for Python implementation of k-means algorithm with examples to cluster and cache my database of coordinates.</p>
41
2009-10-09T19:16:13Z
2,224,488
<p>SciPy's <a href="http://docs.scipy.org/doc/scipy/reference/cluster.vq.html">kmeans2()</a> has some numerical problems: others have <a href="http://mail.scipy.org/pipermail/scipy-user/2009-February/019777.html">reported</a> error messages such as "Matrix is not positive definite - Cholesky decomposition cannot be com...
27
2010-02-08T20:03:43Z
[ "python", "algorithm", "cluster-analysis", "k-means" ]
Python k-means algorithm
1,545,606
<p>I am looking for Python implementation of k-means algorithm with examples to cluster and cache my database of coordinates.</p>
41
2009-10-09T19:16:13Z
2,605,234
<p>For continuous data, k-means is very easy.</p> <p>You need a list of your means, and for each data point, find the mean its closest to and average the new data point to it. your means will represent the recent salient clusters of points in the input data.</p> <p>I do the averaging continuously, so there is no need...
17
2010-04-09T05:21:50Z
[ "python", "algorithm", "cluster-analysis", "k-means" ]
Python k-means algorithm
1,545,606
<p>I am looking for Python implementation of k-means algorithm with examples to cluster and cache my database of coordinates.</p>
41
2009-10-09T19:16:13Z
6,572,959
<p>(Years later) this kmeans.py under <a href="http://stackoverflow.com/questions/5529625/is-it-possible-to-specify-your-own-distance-function-using-scikits-learn-k-means">is-it-possible-to-specify-your-own-distance-function-using-scikits-learn-k-means</a> is straightforward and reasonably fast; it uses any of the 20-o...
5
2011-07-04T14:43:41Z
[ "python", "algorithm", "cluster-analysis", "k-means" ]
Python k-means algorithm
1,545,606
<p>I am looking for Python implementation of k-means algorithm with examples to cluster and cache my database of coordinates.</p>
41
2009-10-09T19:16:13Z
7,405,341
<p>you can try the scikits-learn implementation: <a href="http://scikit-learn.sourceforge.net/modules/generated/scikits.learn.cluster.KMeans.html" rel="nofollow">http://scikit-learn.sourceforge.net/modules/generated/scikits.learn.cluster.KMeans.html</a></p>
1
2011-09-13T16:35:30Z
[ "python", "algorithm", "cluster-analysis", "k-means" ]
Python k-means algorithm
1,545,606
<p>I am looking for Python implementation of k-means algorithm with examples to cluster and cache my database of coordinates.</p>
41
2009-10-09T19:16:13Z
25,837,866
<p>Python's Pycluster and pyplot can be used for k-means clustering and for visualization of 2D data. A recent blog post <a href="http://remotalks.blogspot.com/2014/08/stock-pricevolume-analysis-using-python.html" rel="nofollow">Stock Price/Volume Analysis Using Python and PyCluster</a> gives an example of clustering u...
-1
2014-09-14T20:47:16Z
[ "python", "algorithm", "cluster-analysis", "k-means" ]
Python k-means algorithm
1,545,606
<p>I am looking for Python implementation of k-means algorithm with examples to cluster and cache my database of coordinates.</p>
41
2009-10-09T19:16:13Z
36,282,082
<p><strong>*This Code K-Means With Pyhon *</strong></p> <pre><code>from math import math from functions import functions class KMEANS: @staticmethod def KMeans(data,classterCount,globalCounter): counter=0 classes=[] cluster =[[]] cluster_index=[] tempClasses=[] for i in range(0,classterCount): globalCounter+=1 clas...
-1
2016-03-29T10:44:55Z
[ "python", "algorithm", "cluster-analysis", "k-means" ]
How do I replace all punctuation in my string with "" in Python?
1,545,655
<p>If my string was:</p> <pre><code>Business -- way's </code></pre> <p>I'd like to turn this into:</p> <pre><code>Business ways </code></pre> <p>ie. replace NON abc/123 into ""</p>
0
2009-10-09T19:32:19Z
1,545,678
<p>Simple regular expression:</p> <pre><code>import re &gt;&gt;&gt; s = "Business -- way's" &gt;&gt;&gt; s = re.sub(r'[^\w\s]', '', s) &gt;&gt;&gt; s "Business ways" </code></pre>
14
2009-10-09T19:36:50Z
[ "python", "regex" ]
How do I replace all punctuation in my string with "" in Python?
1,545,655
<p>If my string was:</p> <pre><code>Business -- way's </code></pre> <p>I'd like to turn this into:</p> <pre><code>Business ways </code></pre> <p>ie. replace NON abc/123 into ""</p>
0
2009-10-09T19:32:19Z
1,545,687
<p>Or, if you don't want to use a regular expression for some reason:</p> <pre><code>''.join([x for x in foo if x.isalpha() or x.isspace()]) </code></pre>
6
2009-10-09T19:40:06Z
[ "python", "regex" ]
How do I replace all punctuation in my string with "" in Python?
1,545,655
<p>If my string was:</p> <pre><code>Business -- way's </code></pre> <p>I'd like to turn this into:</p> <pre><code>Business ways </code></pre> <p>ie. replace NON abc/123 into ""</p>
0
2009-10-09T19:32:19Z
1,545,841
<p>(regular expression) replace</p> <pre><code>[[:punct:]] </code></pre> <p>with '' (if Python supports that).</p> <p>[] is a character class, [::] is posix class syntax. [:punct:] is punctuation, so the character class for all punctuation marks would be [[:punct:]]</p> <p>An alternate way of the same thing is \p ...
-3
2009-10-09T20:16:05Z
[ "python", "regex" ]
Python mechanize doesn't click a button
1,545,698
<p>check the following script:</p> <pre><code>from mechanize import Browser br = Browser() page = br.open('http://scottishladiespool.com/register.php') br.select_form(nr = 5) r = br.click(type = "submit", nr = 0) print r.data #prints username=&amp;password1=&amp;password2=&amp;email=&amp;user_hide_email=1&amp;captc...
1
2009-10-09T19:43:12Z
1,545,819
<p>There is a <code>disabled=disabled</code> attribute on the register button. This prevents the user from clicking and presumably mechanize respects the <code>disabled</code> attribute as well.</p> <p>You'll need to change the source code of that button. Enabling the control means completely removing the <code>disab...
2
2009-10-09T20:10:05Z
[ "python", "mechanize", "clientform" ]
How to replace the quote " and hyphen character in a string with nothing in Python?
1,545,878
<p>I'd like to replace <code>"</code> and <code>-</code></p> <p>with <code>""</code> nothing! make it disappear.</p> <p><code>s = re.sub(r'[^\w\s]', '', s)</code> this makes all punctuation disappear, but I just want those 2 characters. Thanks.</p>
1
2009-10-09T20:25:07Z
1,545,887
<pre><code>re.sub('["-]+', '', s) </code></pre>
2
2009-10-09T20:26:43Z
[ "python", "regex" ]
How to replace the quote " and hyphen character in a string with nothing in Python?
1,545,878
<p>I'd like to replace <code>"</code> and <code>-</code></p> <p>with <code>""</code> nothing! make it disappear.</p> <p><code>s = re.sub(r'[^\w\s]', '', s)</code> this makes all punctuation disappear, but I just want those 2 characters. Thanks.</p>
1
2009-10-09T20:25:07Z
1,545,896
<p>I'm curious as to why you are using a regular expression for this simple string replacement. The only advantage that I can see is that you can do it in one line of code instead of two, but I personally think that a replacement method is clearer than a regex for something like this.</p> <p>The string object has a <c...
6
2009-10-09T20:28:31Z
[ "python", "regex" ]
How to replace the quote " and hyphen character in a string with nothing in Python?
1,545,878
<p>I'd like to replace <code>"</code> and <code>-</code></p> <p>with <code>""</code> nothing! make it disappear.</p> <p><code>s = re.sub(r'[^\w\s]', '', s)</code> this makes all punctuation disappear, but I just want those 2 characters. Thanks.</p>
1
2009-10-09T20:25:07Z
1,545,898
<p><code>re.sub('[-"]', '', s)</code></p>
1
2009-10-09T20:28:44Z
[ "python", "regex" ]
How to replace the quote " and hyphen character in a string with nothing in Python?
1,545,878
<p>I'd like to replace <code>"</code> and <code>-</code></p> <p>with <code>""</code> nothing! make it disappear.</p> <p><code>s = re.sub(r'[^\w\s]', '', s)</code> this makes all punctuation disappear, but I just want those 2 characters. Thanks.</p>
1
2009-10-09T20:25:07Z
1,545,926
<p>In Python 2.6:</p> <pre><code>print 'Hey -- How are "you"?'.translate(None, '-"') </code></pre> <p>Returns: </p> <pre><code>Hey How are you? </code></pre>
0
2009-10-09T20:34:21Z
[ "python", "regex" ]
How to replace the quote " and hyphen character in a string with nothing in Python?
1,545,878
<p>I'd like to replace <code>"</code> and <code>-</code></p> <p>with <code>""</code> nothing! make it disappear.</p> <p><code>s = re.sub(r'[^\w\s]', '', s)</code> this makes all punctuation disappear, but I just want those 2 characters. Thanks.</p>
1
2009-10-09T20:25:07Z
1,545,929
<p>In Python 2.6/2.7, you can use the helpful <code>translate()</code> method on strings. When using <code>None</code> as the first argument, this method has the special behavior of deleting all occurences of any character in the second argument. </p> <pre><code>&gt;&gt;&gt; s = 'No- dashes or "quotes"' &gt;&gt;&gt; s...
2
2009-10-09T20:35:13Z
[ "python", "regex" ]
Cart item management in python Turbogears 2.0
1,545,913
<p>I'm new to python an I decided to give it a try with TG2 by developing a small store. So far I've been loving it, but I'm guessing that my coding parading is still very attached to java's Like for example, the <code>add to cart</code> method in my CartController.</p> <pre><code>def add(self, **kw): pid=kw['pi...
1
2009-10-09T20:31:31Z
1,548,537
<p>Since you are modifying the <code>item</code> object, I don't see any reason why you would have to remove, then append that item to the list. Why do you think you have to?</p> <p>As for making this more pythonic, you might consider something like this:</p> <pre><code>items_by_pid = dict([(item.product.pid, item) ...
3
2009-10-10T17:28:31Z
[ "python", "turbogears2" ]
XML POST REST Request using Python
1,546,041
<p>Does anyone have a simple example of sending an XML POST request to a RESTful API with Python? I am trying to use the urllib2 Python library to "create a new project" in the Harvest API, with no luck. The payload variable is a valid XML document that is a near copy/paste of their documentation (under the Create Ne...
5
2009-10-09T21:05:37Z
1,546,053
<p>It's common to return a 200 response even when a 201 response would strictly be more appropriate. Are you sure that the request isn't correctly processed even if you are getting a 'correct' response?</p>
1
2009-10-09T21:08:55Z
[ "python", "xml", "rest", "post", "harvest" ]
XML POST REST Request using Python
1,546,041
<p>Does anyone have a simple example of sending an XML POST request to a RESTful API with Python? I am trying to use the urllib2 Python library to "create a new project" in the Harvest API, with no luck. The payload variable is a valid XML document that is a near copy/paste of their documentation (under the Create Ne...
5
2009-10-09T21:05:37Z
5,676,794
<p>You're using a local opener everywhere except on the line where you create the response, where you use <code>self.opener</code>, which looks like the problem.</p>
1
2011-04-15T12:34:14Z
[ "python", "xml", "rest", "post", "harvest" ]
web scraping a problem site
1,546,089
<p>I'm trying to scrape some information from a web site, but am having trouble reading the relevant pages. The pages seem to first send a basic setup, then more detailed info. My download attempts only seem to capture the basic setup. I've tried urllib and mechanize so far.</p> <p>Firefox and Chrome have no troubl...
0
2009-10-09T21:16:59Z
1,546,104
<p>The page uses JavaScript to load the data. Firefox and Chrome are only working because you have JavaScript enabled - try disabling it and you'll get a mostly empty page.</p> <p>Python isn't going to be able to do this by itself - your best compromise would be to control a real browser (Internet Explorer is easiest...
2
2009-10-09T21:21:44Z
[ "python", "screen-scraping" ]
web scraping a problem site
1,546,089
<p>I'm trying to scrape some information from a web site, but am having trouble reading the relevant pages. The pages seem to first send a basic setup, then more detailed info. My download attempts only seem to capture the basic setup. I've tried urllib and mechanize so far.</p> <p>Firefox and Chrome have no troubl...
0
2009-10-09T21:16:59Z
1,546,109
<p>The reason why is because it's performing AJAX calls after it loads. You will need to account for searching out those URLs to scrape it's content as well.</p>
0
2009-10-09T21:23:21Z
[ "python", "screen-scraping" ]
web scraping a problem site
1,546,089
<p>I'm trying to scrape some information from a web site, but am having trouble reading the relevant pages. The pages seem to first send a basic setup, then more detailed info. My download attempts only seem to capture the basic setup. I've tried urllib and mechanize so far.</p> <p>Firefox and Chrome have no troubl...
0
2009-10-09T21:16:59Z
1,546,134
<p>As RichieHindle mentioned, your best bet on Windows is to use the WebBrowser class to create an instance of an IE rendering engine and then use that to browse the site.</p> <p>The class gives you full access to the DOM tree, so you can do whatever you want with it.</p> <p><a href="http://msdn.microsoft.com/en-us/l...
0
2009-10-09T21:29:55Z
[ "python", "screen-scraping" ]
web scraping a problem site
1,546,089
<p>I'm trying to scrape some information from a web site, but am having trouble reading the relevant pages. The pages seem to first send a basic setup, then more detailed info. My download attempts only seem to capture the basic setup. I've tried urllib and mechanize so far.</p> <p>Firefox and Chrome have no troubl...
0
2009-10-09T21:16:59Z
1,546,213
<p>Try iMacros. I am very positive it will solve your problem.</p> <p><a href="http://www.iopus.com/imacros/firefox/?ref=fxmoz" rel="nofollow">http://www.iopus.com/imacros/firefox/?ref=fxmoz</a></p>
0
2009-10-09T21:45:18Z
[ "python", "screen-scraping" ]
web scraping a problem site
1,546,089
<p>I'm trying to scrape some information from a web site, but am having trouble reading the relevant pages. The pages seem to first send a basic setup, then more detailed info. My download attempts only seem to capture the basic setup. I've tried urllib and mechanize so far.</p> <p>Firefox and Chrome have no troubl...
0
2009-10-09T21:16:59Z
1,546,280
<p>The website loads the data via ajax. <a href="http://getfirebug.com" rel="nofollow">Firebug</a> shows the ajax calls. For the given page, the data is loaded from <a href="https://personal.vanguard.com/us/JSP/Funds/VGITab/VGIFundOverviewTabContent.jsf?FundIntExt=INT&amp;FundId=0542" rel="nofollow">https://personal.va...
1
2009-10-09T22:00:26Z
[ "python", "screen-scraping" ]
What is needed to add an paperprint-like effect to photos in python?
1,546,205
<p>I want to transform photos in python to look like this:</p> <p><img src="http://media.doctype.com/4b4bb461-1f1f-4c0e-9fc4-b4626e672b27.png" alt="a paper printed-like pic" /> taken from <a href="http://doctype.com" rel="nofollow">doctype.com</a></p> <p>I will use it in django, PIL is installed.</p> <p>How can I ac...
1
2009-10-09T21:43:42Z
1,546,291
<p>This is a combination of several subtle effects. It starts by a nonlinear deformation, and then a tasteful drop shadow is added. There's also a small border. I'd start by drawing one straight, vertical line on the above picture, and then seeing how you would transform to that from the original picture. Then, apply t...
3
2009-10-09T22:04:01Z
[ "python", "django", "image", "python-imaging-library" ]
What is needed to add an paperprint-like effect to photos in python?
1,546,205
<p>I want to transform photos in python to look like this:</p> <p><img src="http://media.doctype.com/4b4bb461-1f1f-4c0e-9fc4-b4626e672b27.png" alt="a paper printed-like pic" /> taken from <a href="http://doctype.com" rel="nofollow">doctype.com</a></p> <p>I will use it in django, PIL is installed.</p> <p>How can I ac...
1
2009-10-09T21:43:42Z
1,546,378
<p>I've had a bit better luck with ImageMagick when it comes to more complex transformations. You would have to install it separately and though there is a python library it doesn't appear well documented so I've just used command line calls.</p> <p>Here is a good <a href="http://www.imagemagick.org/Usage/warping/" r...
2
2009-10-09T22:33:18Z
[ "python", "django", "image", "python-imaging-library" ]
A simple way to remove multiple spaces in a string in Python
1,546,226
<p>Suppose this is the string:</p> <pre><code>The fox jumped over the log. </code></pre> <p>It would result in:</p> <pre><code>The fox jumped over the log. </code></pre> <p>What is the simplest, 1-2 liner that can do this? Without splitting and going into lists...</p>
119
2009-10-09T21:48:37Z
1,546,244
<pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; re.sub(' +',' ','The quick brown fox') 'The quick brown fox' </code></pre>
140
2009-10-09T21:52:29Z
[ "python", "regex", "string" ]
A simple way to remove multiple spaces in a string in Python
1,546,226
<p>Suppose this is the string:</p> <pre><code>The fox jumped over the log. </code></pre> <p>It would result in:</p> <pre><code>The fox jumped over the log. </code></pre> <p>What is the simplest, 1-2 liner that can do this? Without splitting and going into lists...</p>
119
2009-10-09T21:48:37Z
1,546,245
<pre><code>import re s = "The fox jumped over the log." re.sub("\s\s+" , " ", s) </code></pre> <p>or</p> <pre><code>re.sub("\s\s+", " ", s) </code></pre> <p>since the space before comma is listed as a <em>pet peeve</em> in PEP8, as mentioned by moose in the comments.</p>
46
2009-10-09T21:52:30Z
[ "python", "regex", "string" ]
A simple way to remove multiple spaces in a string in Python
1,546,226
<p>Suppose this is the string:</p> <pre><code>The fox jumped over the log. </code></pre> <p>It would result in:</p> <pre><code>The fox jumped over the log. </code></pre> <p>What is the simplest, 1-2 liner that can do this? Without splitting and going into lists...</p>
119
2009-10-09T21:48:37Z
1,546,251
<p>foo is your string:</p> <pre><code>" ".join(foo.split()) </code></pre>
228
2009-10-09T21:52:56Z
[ "python", "regex", "string" ]
A simple way to remove multiple spaces in a string in Python
1,546,226
<p>Suppose this is the string:</p> <pre><code>The fox jumped over the log. </code></pre> <p>It would result in:</p> <pre><code>The fox jumped over the log. </code></pre> <p>What is the simplest, 1-2 liner that can do this? Without splitting and going into lists...</p>
119
2009-10-09T21:48:37Z
1,546,272
<p>Similar to the previous solutions, but more specific: replace two or more spaces with one:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; s = "The fox jumped over the log." &gt;&gt;&gt; re.sub('\s{2,}', ' ', s) 'The fox jumped over the log.' </code></pre>
10
2009-10-09T21:58:27Z
[ "python", "regex", "string" ]
A simple way to remove multiple spaces in a string in Python
1,546,226
<p>Suppose this is the string:</p> <pre><code>The fox jumped over the log. </code></pre> <p>It would result in:</p> <pre><code>The fox jumped over the log. </code></pre> <p>What is the simplest, 1-2 liner that can do this? Without splitting and going into lists...</p>
119
2009-10-09T21:48:37Z
1,546,883
<p>Have to agree with Paul McGuire's comment above. To me, </p> <pre><code> ' '.join(the_string.split()) </code></pre> <p>is vastly preferable to whipping out a regex. My measurements (Linux, Python 2.5) show the split-then-join to be almost 5 times faster than doing the "re.sub(...)", and still 3 times faste...
24
2009-10-10T02:39:51Z
[ "python", "regex", "string" ]
A simple way to remove multiple spaces in a string in Python
1,546,226
<p>Suppose this is the string:</p> <pre><code>The fox jumped over the log. </code></pre> <p>It would result in:</p> <pre><code>The fox jumped over the log. </code></pre> <p>What is the simplest, 1-2 liner that can do this? Without splitting and going into lists...</p>
119
2009-10-09T21:48:37Z
11,647,579
<p>Other alternative</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; str = 'this is a string with multiple spaces and tabs' &gt;&gt;&gt; str = re.sub('[ \t]+' , ' ', str) &gt;&gt;&gt; print str this is a string with multiple spaces and tabs </code></pre>
2
2012-07-25T10:19:34Z
[ "python", "regex", "string" ]
A simple way to remove multiple spaces in a string in Python
1,546,226
<p>Suppose this is the string:</p> <pre><code>The fox jumped over the log. </code></pre> <p>It would result in:</p> <pre><code>The fox jumped over the log. </code></pre> <p>What is the simplest, 1-2 liner that can do this? Without splitting and going into lists...</p>
119
2009-10-09T21:48:37Z
15,913,564
<p>Using regexes with "\s" and doing simple string.split()'s will <em>also</em> remove other whitespace - like newlines, carriage returns, tabs. Unless this is desired, to <strong>only</strong> do <em>multiple spaces</em>, I present these examples.</p> <hr> <p><strong>EDIT:</strong> As I'm wont to do, I slept on thi...
26
2013-04-09T22:16:21Z
[ "python", "regex", "string" ]
A simple way to remove multiple spaces in a string in Python
1,546,226
<p>Suppose this is the string:</p> <pre><code>The fox jumped over the log. </code></pre> <p>It would result in:</p> <pre><code>The fox jumped over the log. </code></pre> <p>What is the simplest, 1-2 liner that can do this? Without splitting and going into lists...</p>
119
2009-10-09T21:48:37Z
26,810,316
<p>If it's whitespace you're dealing with splitting on None will not include empty string in the returned value.</p> <p><a href="https://docs.python.org/2/library/stdtypes.html#str.split" rel="nofollow">https://docs.python.org/2/library/stdtypes.html#str.split</a></p>
0
2014-11-07T21:24:11Z
[ "python", "regex", "string" ]
A simple way to remove multiple spaces in a string in Python
1,546,226
<p>Suppose this is the string:</p> <pre><code>The fox jumped over the log. </code></pre> <p>It would result in:</p> <pre><code>The fox jumped over the log. </code></pre> <p>What is the simplest, 1-2 liner that can do this? Without splitting and going into lists...</p>
119
2009-10-09T21:48:37Z
33,514,861
<p>A simple soultion</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; s="The fox jumped over the log." &gt;&gt;&gt; print re.sub('\s+',' ', s) The fox jumped over the log. </code></pre>
3
2015-11-04T06:11:39Z
[ "python", "regex", "string" ]
A simple way to remove multiple spaces in a string in Python
1,546,226
<p>Suppose this is the string:</p> <pre><code>The fox jumped over the log. </code></pre> <p>It would result in:</p> <pre><code>The fox jumped over the log. </code></pre> <p>What is the simplest, 1-2 liner that can do this? Without splitting and going into lists...</p>
119
2009-10-09T21:48:37Z
35,391,471
<pre><code>string='This is a string full of spaces and taps' string=string.split(' ') while '' in string: string.remove('') string=' '.join(string) print(string) </code></pre> <p><strong>results</strong>:</p> <blockquote> <p>This is a string full of spaces and taps</p> </blockquote>
0
2016-02-14T11:58:36Z
[ "python", "regex", "string" ]
A simple way to remove multiple spaces in a string in Python
1,546,226
<p>Suppose this is the string:</p> <pre><code>The fox jumped over the log. </code></pre> <p>It would result in:</p> <pre><code>The fox jumped over the log. </code></pre> <p>What is the simplest, 1-2 liner that can do this? Without splitting and going into lists...</p>
119
2009-10-09T21:48:37Z
37,510,714
<p>One line of code to remove all extra spaces before, after, and within a sentence: </p> <pre><code>sentence = " The fox jumped over the log. " sentence = ' '.join(filter(None,sentence.split(' '))) </code></pre> <p>Explanation:</p> <ol> <li>Split entire string into list.</li> <li>Filter empty elements from...
1
2016-05-29T13:52:54Z
[ "python", "regex", "string" ]
A simple way to remove multiple spaces in a string in Python
1,546,226
<p>Suppose this is the string:</p> <pre><code>The fox jumped over the log. </code></pre> <p>It would result in:</p> <pre><code>The fox jumped over the log. </code></pre> <p>What is the simplest, 1-2 liner that can do this? Without splitting and going into lists...</p>
119
2009-10-09T21:48:37Z
39,322,245
<p>This also seems to work:</p> <pre><code>while " " in s: s=s.replace(" "," ") </code></pre> <p>Where the variable s represents your string.</p>
0
2016-09-04T23:11:32Z
[ "python", "regex", "string" ]
Using enums in ctypes.Structure
1,546,355
<p>I have a struct I'm accessing via ctypes:</p> <pre><code>struct attrl { char *name; char *resource; char *value; struct attrl *next; enum batch_op op; }; </code></pre> <p>So far I have Python code like:</p> <pre><code># struct attropl class attropl(Structure): pass attrl._fields_ = [ ...
6
2009-10-09T22:25:11Z
1,546,366
<p>Using <code>c_int</code> or <code>c_uint</code> would be fine. Alternatively, there is a <a href="http://code.activestate.com/recipes/576415/" rel="nofollow">recipe in the cookbook</a> for an Enumeration class.</p>
4
2009-10-09T22:29:26Z
[ "python", "enums", "ctypes" ]
Using enums in ctypes.Structure
1,546,355
<p>I have a struct I'm accessing via ctypes:</p> <pre><code>struct attrl { char *name; char *resource; char *value; struct attrl *next; enum batch_op op; }; </code></pre> <p>So far I have Python code like:</p> <pre><code># struct attropl class attropl(Structure): pass attrl._fields_ = [ ...
6
2009-10-09T22:25:11Z
1,546,467
<p>At least for GCC <code>enum</code> is just a simple numeric type. It can be 8-, 16-, 32-, 64-bit or whatever (I have tested it with 64-bit values) as well as <code>signed</code> or <code>unsigned</code>. I guess it cannot exceed <code>long long int</code>, but practically you should check the range of your <code>enu...
7
2009-10-09T23:05:34Z
[ "python", "enums", "ctypes" ]
python: how to send mail with TO, CC and BCC?
1,546,367
<p>I need for testing purposes to populate few hundred email boxes with various messages, and was going to use smtplib for that. But among other things I need to be able to send messages not only TO specific mailboxes, but CC and BCC them as well. It does not look like <a href="http://docs.python.org/library/smtplib.ht...
51
2009-10-09T22:29:46Z
1,546,406
<p>The distinction between TO, CC and BCC occurs only in the text headers. At the SMTP level, everybody is a recipient. </p> <p>TO - There is a TO: header with this recipient's address</p> <p>CC - There is a CC: header with this recipient's address</p> <p>BCC - This recipient isn't mentioned in the headers at all,...
12
2009-10-09T22:41:38Z
[ "python", "email", "testing" ]
python: how to send mail with TO, CC and BCC?
1,546,367
<p>I need for testing purposes to populate few hundred email boxes with various messages, and was going to use smtplib for that. But among other things I need to be able to send messages not only TO specific mailboxes, but CC and BCC them as well. It does not look like <a href="http://docs.python.org/library/smtplib.ht...
51
2009-10-09T22:29:46Z
1,546,410
<p>You can try MIMEText</p> <pre><code>msg = MIMEText('text') msg['to'] = msg['cc'] = </code></pre> <p>then send msg.as_string()</p> <p><a href="http://docs.python.org/library/email-examples.html">http://docs.python.org/library/email-examples.html</a></p>
12
2009-10-09T22:42:55Z
[ "python", "email", "testing" ]
python: how to send mail with TO, CC and BCC?
1,546,367
<p>I need for testing purposes to populate few hundred email boxes with various messages, and was going to use smtplib for that. But among other things I need to be able to send messages not only TO specific mailboxes, but CC and BCC them as well. It does not look like <a href="http://docs.python.org/library/smtplib.ht...
51
2009-10-09T22:29:46Z
1,546,435
<p>Email headers don't matter to the smtp server. Just add the CC and BCC recipients to the toaddrs when you send your email. For CC, add them to the CC header.</p> <pre><code>toaddr = 'buffy@sunnydale.k12.ca.us' cc = ['alexander@sunydale.k12.ca.us','willow@sunnydale.k12.ca.us'] bcc = ['chairman@slayerscouncil.uk'] fr...
85
2009-10-09T22:52:29Z
[ "python", "email", "testing" ]
python: how to send mail with TO, CC and BCC?
1,546,367
<p>I need for testing purposes to populate few hundred email boxes with various messages, and was going to use smtplib for that. But among other things I need to be able to send messages not only TO specific mailboxes, but CC and BCC them as well. It does not look like <a href="http://docs.python.org/library/smtplib.ht...
51
2009-10-09T22:29:46Z
29,627,094
<p>Don't add the bcc header.</p> <p>See this: <a href="http://mail.python.org/pipermail/email-sig/2004-September/000151.html">http://mail.python.org/pipermail/email-sig/2004-September/000151.html</a></p> <p>And this: """Notice that the second argument to sendmail(), the recipients, is passed as a list. You can includ...
7
2015-04-14T12:17:55Z
[ "python", "email", "testing" ]
python: how to send mail with TO, CC and BCC?
1,546,367
<p>I need for testing purposes to populate few hundred email boxes with various messages, and was going to use smtplib for that. But among other things I need to be able to send messages not only TO specific mailboxes, but CC and BCC them as well. It does not look like <a href="http://docs.python.org/library/smtplib.ht...
51
2009-10-09T22:29:46Z
29,936,403
<p>Key thing is to add the recipients as a <em>list of email ids</em> in your sendmail call.</p> <pre><code>import smtplib from email.mime.multipart import MIMEMultipart me = "user63503@gmail.com" to = "someone@gmail.com" cc = "anotherperson@gmail.com,someone@yahoo.com" bcc = "bccperson1@gmail.com,bccperson2@yahoo.co...
6
2015-04-29T06:57:03Z
[ "python", "email", "testing" ]
Parallel Python: How do I supply arguments to 'submit'?
1,546,429
<p>This is only the second question with the parallel-python tag. After looking through the documentation and googling for the subject, I've come here as it's where I've had the best luck with answers and suggestions.</p> <p>The following is the API (I think it's called) that submits all pertinent info to pp.</p> <pr...
5
2009-10-09T22:49:43Z
1,546,601
<p>I think you should be passing in lambda:ks.next() instead of plain old ks</p>
0
2009-10-09T23:56:23Z
[ "python", "parallel-python" ]
Parallel Python: How do I supply arguments to 'submit'?
1,546,429
<p>This is only the second question with the parallel-python tag. After looking through the documentation and googling for the subject, I've come here as it's where I've had the best luck with answers and suggestions.</p> <p>The following is the API (I think it's called) that submits all pertinent info to pp.</p> <pr...
5
2009-10-09T22:49:43Z
1,547,579
<p>interesting - are you doing genetics simulations? i ask because i see 'Chromosome' in there, and I once developed a population genetics simulation using parallel python.</p> <p>your approach looks really complicated. in my parallel python program, i used the following call:</p> <pre><code>job = jobServer.submit( d...
5
2009-10-10T10:23:51Z
[ "python", "parallel-python" ]
localhost django dev server vs. postgres slow on mac os?
1,546,556
<p>Anyone notice slowness from a django dev server running on Mac OS and connecting to a remote (postgres) db? It doesn't seem to be the DNS problem referenced elsewhere. We've got a staging instance running the exact same code on the same remote staging box that's hosting the db, and the performance on that instance i...
2
2009-10-09T23:38:02Z
1,546,620
<p>Two things:</p> <ol> <li>The Django dev server is painfully slow. Any external connections will be restricted by it.</li> <li>The connection to an external database is limited by your machine's local upstream and downstream capabilities (the bottleneck usually being your internet connection).</li> </ol> <p>Any tim...
5
2009-10-10T00:03:10Z
[ "python", "django", "osx", "performance" ]
localhost django dev server vs. postgres slow on mac os?
1,546,556
<p>Anyone notice slowness from a django dev server running on Mac OS and connecting to a remote (postgres) db? It doesn't seem to be the DNS problem referenced elsewhere. We've got a staging instance running the exact same code on the same remote staging box that's hosting the db, and the performance on that instance i...
2
2009-10-09T23:38:02Z
29,394,138
<p>I faced the same problem when I was using replica of my production database in development environment. The problem turned out to to be in <code>django_session</code> table which had a size near Gigabytes. Simplest solution was to clear that table as I did not need to use users session data in development. I used si...
0
2015-04-01T14:56:15Z
[ "python", "django", "osx", "performance" ]
Python: Escaping strings for use in XML
1,546,717
<p>I'm using Python's <code>xml.dom.minidom</code> to create an XML document. (Logical structure -> XML string, not the other way around.)</p> <p>How do I make it escape the strings I provide so they won't be able to mess up the XML?</p>
23
2009-10-10T00:51:10Z
1,546,738
<p>Something like this?</p> <pre><code>&gt;&gt;&gt; from xml.sax.saxutils import escape &gt;&gt;&gt; escape("&lt; &amp; &gt;") '&amp;lt; &amp;amp; &amp;gt;' </code></pre>
55
2009-10-10T01:05:56Z
[ "python", "xml", "security" ]
Python: Escaping strings for use in XML
1,546,717
<p>I'm using Python's <code>xml.dom.minidom</code> to create an XML document. (Logical structure -> XML string, not the other way around.)</p> <p>How do I make it escape the strings I provide so they won't be able to mess up the XML?</p>
23
2009-10-10T00:51:10Z
1,546,747
<p>Do you mean you do something like this:</p> <pre><code>from xml.dom.minidom import Text, Element t = Text() e = Element('p') t.data = '&lt;bar&gt;&lt;a/&gt;&lt;baz spam="eggs"&gt; &amp; blabla &amp;entity;&lt;/&gt;' e.appendChild(t) </code></pre> <p>Then you will get nicely escaped XML string:</p> <pre><code>&g...
10
2009-10-10T01:09:51Z
[ "python", "xml", "security" ]
Python: Escaping strings for use in XML
1,546,717
<p>I'm using Python's <code>xml.dom.minidom</code> to create an XML document. (Logical structure -> XML string, not the other way around.)</p> <p>How do I make it escape the strings I provide so they won't be able to mess up the XML?</p>
23
2009-10-10T00:51:10Z
21,107,835
<p>If you don't want another project import and you already have <code>cgi</code>, you could use this:</p> <pre><code>&gt;&gt;&gt; import cgi &gt;&gt;&gt; cgi.escape("&lt; &amp; &gt;") '&amp;lt; &amp;amp; &amp;gt;' </code></pre> <p>Note however that with this code legibility suffers - you should probably put it in a ...
2
2014-01-14T07:13:19Z
[ "python", "xml", "security" ]
Python: Escaping strings for use in XML
1,546,717
<p>I'm using Python's <code>xml.dom.minidom</code> to create an XML document. (Logical structure -> XML string, not the other way around.)</p> <p>How do I make it escape the strings I provide so they won't be able to mess up the XML?</p>
23
2009-10-10T00:51:10Z
28,703,510
<p>xml.sax.saxutils does not escape quotation characters (")</p> <p>So here is another one:</p> <pre><code>def escape( str ): str = str.replace("&lt;", "&amp;lt;") str = str.replace("&gt;", "&amp;gt;") str = str.replace("&amp;", "&amp;amp;") str = str.replace("\"", "&amp;quot;") return str </code>...
4
2015-02-24T18:30:18Z
[ "python", "xml", "security" ]
Python: Escaping strings for use in XML
1,546,717
<p>I'm using Python's <code>xml.dom.minidom</code> to create an XML document. (Logical structure -> XML string, not the other way around.)</p> <p>How do I make it escape the strings I provide so they won't be able to mess up the XML?</p>
23
2009-10-10T00:51:10Z
35,302,133
<p><code>xml.sax.saxutils.escape</code> only escapes <code>&amp;</code>, <code>&lt;</code>, and <code>&gt;</code> by default, but it does provide an <code>entities</code> parameter to additionally escape other strings:</p> <pre><code>from xml.sax.saxutils import escape def xmlescape(data): return escape(data, ent...
4
2016-02-09T21:02:45Z
[ "python", "xml", "security" ]
Manually giving the twisted (web) network stack a packet to process?
1,546,745
<p>I am running an HTTP server using the twisted framework. Is there any way I can "manually" ask it to process some payload? For example, if I've constructed some Ethernet frame can I ask twisted's reactor to handle it just as if it had just arrived on my network card?</p>
1
2009-10-10T01:09:29Z
1,619,223
<p>What is the use-case?</p> <p>Perhaps you want to create your own <a href="http://twistedmatrix.com/projects/core/documentation/howto/udp.html" rel="nofollow">Datagram Protocol</a></p> <blockquote> <p>At the base, the place where you actually implement the protocol parsing and handling, is the DatagramProto...
0
2009-10-24T21:42:16Z
[ "python", "twisted" ]