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
list
What does the term "blocking" mean in programming?
2,407,589
<p>Could someone provide a layman definition and use case?</p>
17
2010-03-09T08:38:07Z
2,407,601
<p>"Blocking" means that the caller waits until the callee finishes its processing. For instance, a "blocking read" from a socket waits until there is data to return; a "non-blocking" read does not, it just returns an indication (usually a count) of whether there was something read.</p> <p>You hear the term mostly aro...
19
2010-03-09T08:40:07Z
[ "python", "api", "blocking" ]
What does the term "blocking" mean in programming?
2,407,589
<p>Could someone provide a layman definition and use case?</p>
17
2010-03-09T08:38:07Z
2,407,604
<p>In simple words: If you call a function that stops the program from continuing to run until the user has performed some action (or some other action that your program is not controlling), this call is called a blocking call.</p>
3
2010-03-09T08:40:52Z
[ "python", "api", "blocking" ]
How to separate comma separated data from csv file?
2,408,338
<p>I have opened a csv file and I want to sort each string which is comma separated and are in same line:</p> <p>ex:: file : </p> <pre><code>name,sal,dept tom,10000,it </code></pre> <p>o/p :: each string in string variable</p> <p>I have a file which is already open, so I can not use "open" API, I have to use "csv.r...
0
2010-03-09T10:38:41Z
2,408,381
<p>I don't know if I have properly understood your question. You may want to have a look at the <strong>split</strong> function described in the <a href="http://docs.python.org/library/stdtypes.html" rel="nofollow">Python documentation</a> anyway.</p>
0
2010-03-09T10:45:53Z
[ "python" ]
How to separate comma separated data from csv file?
2,408,338
<p>I have opened a csv file and I want to sort each string which is comma separated and are in same line:</p> <p>ex:: file : </p> <pre><code>name,sal,dept tom,10000,it </code></pre> <p>o/p :: each string in string variable</p> <p>I have a file which is already open, so I can not use "open" API, I have to use "csv.r...
0
2010-03-09T10:38:41Z
2,410,224
<p>If the file open for reading is bound to a variable name, say <code>fin</code>; and assuming you're using Python 2.6, and you know the file's not empty (has at least the row with headers):</p> <pre><code> import csv rd = csv.reader(fin) headers = next(rd) for data in rd: ...process data and headers... </code...
2
2010-03-09T15:36:41Z
[ "python" ]
Creating a list of lists with consecutive numbers
2,408,452
<p>I am looking for a convenient way to create a list of lists for which the lists within the list have consecutive numbers. So far I only came up with a very unsatisfying brute-typing force solution (yeah right, I just use python for a few weeks now):</p> <pre><code>block0 = [] ... block4 = [] blocks = [block0,block...
3
2010-03-09T10:59:02Z
2,408,473
<p>It's not clear what consecutive numbers you're talking about, but your code translates into the following idiomatic Python:</p> <pre><code>[[] for _ in range(4)] # use xrange in python-2.x </code></pre>
4
2010-03-09T11:01:32Z
[ "python" ]
Creating a list of lists with consecutive numbers
2,408,452
<p>I am looking for a convenient way to create a list of lists for which the lists within the list have consecutive numbers. So far I only came up with a very unsatisfying brute-typing force solution (yeah right, I just use python for a few weeks now):</p> <pre><code>block0 = [] ... block4 = [] blocks = [block0,block...
3
2010-03-09T10:59:02Z
2,408,487
<p>Don't do it this way. Put it in <code>blocks</code> in the first place:</p> <pre><code>blocks = [ [ ... ], [ ... ], [ ... ], [ ... ] ] </code></pre>
0
2010-03-09T11:03:43Z
[ "python" ]
django python - generic views and cookies
2,408,514
<p>I made in my web a menu using generic_view - simple 'django.views.generic.list_detail.object_list' in urls.py file. I would like to set a cookies each time when user chooses one of element of this list [HttpResponse.set_cookie(...)]. What is the best solution? Should I write function in views.py or have you got more...
0
2010-03-09T11:08:50Z
2,409,891
<p>Generic views are simple views that handle a couple of common cases, for example rendering a template when no view logic is needed. In your case, you want to add functionality to your view (i.e. setting a cookie) so you will need to write your custom view. In addition, you should not add view logic in your urls.py (...
1
2010-03-09T14:52:35Z
[ "python", "django", "django-generic-views" ]
Python nonblocking console input
2,408,560
<p>I am trying to make a simple IRC client in Python (as kind of a project while I learn the language).</p> <p>I have a loop that I use to receive and parse what the IRC server sends me, but if I use <code>raw_input</code> to input stuff, it stops the loop dead in its tracks until I input something (obviously).</p> <...
24
2010-03-09T11:17:05Z
2,409,034
<p>For Windows, console only, use the <a href="http://www.python.org/doc/2.5.2/lib/msvcrt-console.html"><code>msvcrt</code></a> module:</p> <pre><code>import msvcrt num = 0 done = False while not done: print num num += 1 if msvcrt.kbhit(): print "you pressed",msvcrt.getch(),"so now i will quit" ...
23
2010-03-09T12:41:32Z
[ "python", "windows", "input" ]
Python nonblocking console input
2,408,560
<p>I am trying to make a simple IRC client in Python (as kind of a project while I learn the language).</p> <p>I have a loop that I use to receive and parse what the IRC server sends me, but if I use <code>raw_input</code> to input stuff, it stops the loop dead in its tracks until I input something (obviously).</p> <...
24
2010-03-09T11:17:05Z
10,079,805
<p>On Linux, here's a refactoring of mizipzor's code that makes this a little easier, in case you have to use this code in multiple places.</p> <pre><code>import sys import select import tty import termios class NonBlockingConsole(object): def __enter__(self): self.old_settings = termios.tcgetattr(sys.st...
6
2012-04-09T21:00:52Z
[ "python", "windows", "input" ]
Python nonblocking console input
2,408,560
<p>I am trying to make a simple IRC client in Python (as kind of a project while I learn the language).</p> <p>I have a loop that I use to receive and parse what the IRC server sends me, but if I use <code>raw_input</code> to input stuff, it stops the loop dead in its tracks until I input something (obviously).</p> <...
24
2010-03-09T11:17:05Z
19,655,992
<p>Here a solution that runs under linux and windows using a seperate thread:</p> <pre><code>import sys import threading import time import Queue def add_input(input_queue): while True: input_queue.put(sys.stdin.read(1)) def foobar(): input_queue = Queue.Queue() input_thread = threading.Thread(t...
7
2013-10-29T10:45:01Z
[ "python", "windows", "input" ]
Python nonblocking console input
2,408,560
<p>I am trying to make a simple IRC client in Python (as kind of a project while I learn the language).</p> <p>I have a loop that I use to receive and parse what the IRC server sends me, but if I use <code>raw_input</code> to input stuff, it stops the loop dead in its tracks until I input something (obviously).</p> <...
24
2010-03-09T11:17:05Z
22,085,679
<p>This is the most awesome <a href="http://home.wlu.edu/~levys/software/kbhit.py">solution</a><sup>1</sup> I've ever seen. Pasted here in case link goes down:</p> <pre><code>#!/usr/bin/env python ''' A Python class implementing KBHIT, the standard keyboard-interrupt poller. Works transparently on Windows and Posix (L...
11
2014-02-28T03:36:50Z
[ "python", "windows", "input" ]
Python nonblocking console input
2,408,560
<p>I am trying to make a simple IRC client in Python (as kind of a project while I learn the language).</p> <p>I have a loop that I use to receive and parse what the IRC server sends me, but if I use <code>raw_input</code> to input stuff, it stops the loop dead in its tracks until I input something (obviously).</p> <...
24
2010-03-09T11:17:05Z
32,420,329
<p>With python3.3 and above you can use the <code>asyncio</code> module as mentioned in this answer. You will have to re factor your code though to work with <code>asyncio</code>. <a href="http://stackoverflow.com/questions/29081929/prompt-for-user-input-using-python-asyncio-create-server-instance/#answer-29102047">Pro...
1
2015-09-06T05:23:04Z
[ "python", "windows", "input" ]
Why can't I find `len(list)` in Python?
2,408,575
<p>I'm new to Python. I have a method that begins:</p> <pre><code>def foo(self, list): length = len(list) </code></pre> <p>I've called <code>len()</code> successfully in other cases, but here I get:</p> <pre><code>TypeError: object of type 'type' has no len() </code></pre> <p>How do I convince Python that this...
3
2010-03-09T11:18:58Z
2,408,583
<p>Seems like you're calling <code>type()</code> on <code>list</code> which is a type itself. Don't use the name <code>list</code> for your lists because it is a already a built-in type. use <code>L</code> or <code>mylist</code> or whatever and it should work.</p>
2
2010-03-09T11:21:04Z
[ "python" ]
Why can't I find `len(list)` in Python?
2,408,575
<p>I'm new to Python. I have a method that begins:</p> <pre><code>def foo(self, list): length = len(list) </code></pre> <p>I've called <code>len()</code> successfully in other cases, but here I get:</p> <pre><code>TypeError: object of type 'type' has no len() </code></pre> <p>How do I convince Python that this...
3
2010-03-09T11:18:58Z
2,408,584
<p>Because <code>list</code> is the name of the list type.</p> <p>Use a different name.</p> <pre><code>def foo(self, lst): length = len(lst) </code></pre> <p>And make sure you didn't call <code>foo</code> like this:</p> <pre><code>Foo.foo(list) </code></pre>
5
2010-03-09T11:21:06Z
[ "python" ]
Why can't I find `len(list)` in Python?
2,408,575
<p>I'm new to Python. I have a method that begins:</p> <pre><code>def foo(self, list): length = len(list) </code></pre> <p>I've called <code>len()</code> successfully in other cases, but here I get:</p> <pre><code>TypeError: object of type 'type' has no len() </code></pre> <p>How do I convince Python that this...
3
2010-03-09T11:18:58Z
2,408,587
<p>you're shadowing built-in. The value that you're passing to <code>foo</code> method is not a list object, but rather a <code>list</code> type, that doesn't have any length.</p>
5
2010-03-09T11:21:24Z
[ "python" ]
why does python.subprocess hang after proc.communicate()?
2,408,650
<p>I've got an interactive program called <code>my_own_exe</code>. First, it prints out <code>alive</code>, then you input <code>S\n</code> and then it prints out <code>alive</code> again. Finally you input <code>L\n</code>. It does some processing and exits.</p> <p>However, when I call it from the following python sc...
5
2010-03-09T11:35:21Z
2,408,670
<p>From the <a href="http://docs.python.org/library/subprocess#subprocess.Popen.communicate">docs for <code>communicate</code></a>:</p> <blockquote> <p>Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. <strong>Wait for process to terminate.</strong></p> </bloc...
19
2010-03-09T11:38:22Z
[ "python", "subprocess" ]
why does python.subprocess hang after proc.communicate()?
2,408,650
<p>I've got an interactive program called <code>my_own_exe</code>. First, it prints out <code>alive</code>, then you input <code>S\n</code> and then it prints out <code>alive</code> again. Finally you input <code>L\n</code>. It does some processing and exits.</p> <p>However, when I call it from the following python sc...
5
2010-03-09T11:35:21Z
2,408,679
<p><code>communicate()</code> reads data from stdout and stderr <em>until end-of-file is reached</em>. - It waits until your program quits.</p>
2
2010-03-09T11:40:09Z
[ "python", "subprocess" ]
why does python.subprocess hang after proc.communicate()?
2,408,650
<p>I've got an interactive program called <code>my_own_exe</code>. First, it prints out <code>alive</code>, then you input <code>S\n</code> and then it prints out <code>alive</code> again. Finally you input <code>L\n</code>. It does some processing and exits.</p> <p>However, when I call it from the following python sc...
5
2010-03-09T11:35:21Z
39,001,158
<p>comunicate <strong><em>will only run once</em></strong> and then will close the pipe, therefore if you want to send several commands to it you need to send one after the other in the <strong><em>same string</em></strong>.</p> <p>Here is an example that worked for me after <strong><em>MUCH</em></strong> investigatio...
0
2016-08-17T15:50:45Z
[ "python", "subprocess" ]
python unicode implementation (using external programs: cygnative plink ssh rsync)
2,408,695
<p>I have a backup applications in python that needs to work on Windows. It needs UTF compatibility (to be able to backup directories that contain UTF characters like italian accents). The problem is it uses external programs (plink, cygwin, ssh and rsync) and I can't get them working. The prototype is 32 lines long, p...
0
2010-03-09T11:44:42Z
2,408,872
<ul> <li>Don't use <code>shell=True</code>. <strong>EVER</strong>. It needlessy invokes a shell to call your program.</li> <li>Pass the parameters as a list instead of a string.</li> </ul> <p>This example should work, provided the parameters are right and the rsync.exe is in current folder (or <code>PATH</code>):</p> ...
1
2010-03-09T12:16:14Z
[ "python", "utf-8", "cygwin", "rsync", "plink" ]
python unicode implementation (using external programs: cygnative plink ssh rsync)
2,408,695
<p>I have a backup applications in python that needs to work on Windows. It needs UTF compatibility (to be able to backup directories that contain UTF characters like italian accents). The problem is it uses external programs (plink, cygwin, ssh and rsync) and I can't get them working. The prototype is 32 lines long, p...
0
2010-03-09T11:44:42Z
2,409,343
<p>A piece of code that passeth all understanding:</p> <pre><code>if isinstance(obj, unicode): return obj.encode("utf-8") elif isinstance(obj, str): return obj.encode # the above is returning a METHOD *************************** else: return str(obj) </code></pre> <p>What's the point of doctests if yo...
0
2010-03-09T13:35:56Z
[ "python", "utf-8", "cygwin", "rsync", "plink" ]
Suggestions required for generating this logging file structure in django project
2,408,800
<p>Can anyone please suggest how to generate log files having following directory-file structure using python logging in django project. </p> <pre><code>logs/2009-03-09 /errors.log /warnings.log /info.log /emails.log /messages.log logs/2009-03-08 /errors.l...
1
2010-03-09T12:04:42Z
2,415,437
<ol> <li>Set up <code>FileHandler</code> instances with <code>Filter</code> instances which match the criteria for those files.</li> <li>Add the handlers to the root logger.</li> <li>Profit ;-)</li> </ol> <p>See <a href="http://stackoverflow.com/questions/1383254/logging-streamhandler-and-standard-streams">this other ...
3
2010-03-10T08:34:31Z
[ "python", "django", "logging" ]
How can I tell if waiting on Event has timed out?
2,408,882
<pre><code>&gt;&gt;&gt; import threading &gt;&gt;&gt; event = threading.Event() &gt;&gt;&gt; event.set() &gt;&gt;&gt; print event.wait(1) None &gt;&gt;&gt; event.clear() &gt;&gt;&gt; print event.wait(1) None </code></pre> <p>So it basically returns <code>None</code> both when condition was <code>True</code> and <code>...
1
2010-03-09T12:18:13Z
2,408,923
<p>Yes, you're missing next sentence in documentation which writes:</p> <blockquote> <p>Changed in version 2.7: Previously, the method always returned None.</p> </blockquote>
3
2010-03-09T12:23:30Z
[ "python", "events", "multithreading" ]
How can I tell if waiting on Event has timed out?
2,408,882
<pre><code>&gt;&gt;&gt; import threading &gt;&gt;&gt; event = threading.Event() &gt;&gt;&gt; event.set() &gt;&gt;&gt; print event.wait(1) None &gt;&gt;&gt; event.clear() &gt;&gt;&gt; print event.wait(1) None </code></pre> <p>So it basically returns <code>None</code> both when condition was <code>True</code> and <code>...
1
2010-03-09T12:18:13Z
2,408,933
<p>From the <a href="http://docs.python.org/library/threading#threading.Event.wait" rel="nofollow">docs for <code>threading.Event.wait</code></a>:</p> <blockquote> <p>This method returns the internal flag on exit, so it will always return <code>True</code> except if a timeout is given and the operation times out.</p...
2
2010-03-09T12:25:29Z
[ "python", "events", "multithreading" ]
standalone application in python
2,409,168
<p>I wanted to know how can I make standalone application in python. Basically what I am doing right now is I have a template.tex file and my script generate the pdf by giving some input values. So I have to make exe file for windows and same for linux. I can use cx_freeze for creating exe file. But my problem is most ...
1
2010-03-09T13:04:49Z
2,409,207
<p>Sounds like you need a decent installer which can check for latex and if it's not there, install it. If you were feeling really brave you could use that to download Python as well which could avoid the requirement to use py2exe or freeze.</p> <p>I've used the <a href="http://nsis.sourceforge.net/Main_Page" rel="nof...
1
2010-03-09T13:13:20Z
[ "python" ]
standalone application in python
2,409,168
<p>I wanted to know how can I make standalone application in python. Basically what I am doing right now is I have a template.tex file and my script generate the pdf by giving some input values. So I have to make exe file for windows and same for linux. I can use cx_freeze for creating exe file. But my problem is most ...
1
2010-03-09T13:04:49Z
2,409,213
<p>You could write a installer (using NSIS or something) that does two things : </p> <ul> <li>install LateX (or make sure there is an installation of latex available), potentially by calling another installer</li> <li>then install your python script (which can assume latex is now available)</li> </ul>
2
2010-03-09T13:14:17Z
[ "python" ]
Technique to limit number of instances of our application under Terminal Server
2,409,200
<p>I'm looking for simple ways to monitor and limit the number of instances of our application under Terminal Server (2003 and 2008).</p> <p>The purpose of this restriction is to make sure we don't overload our servers. This is an internal administrative requirement - I am not looking for a licensing solution.</p> <p...
2
2010-03-09T13:12:34Z
2,410,065
<p>The various instances of your application need some way to communicate with one another. When an instance starts up, it asks the question, 'how many are already running?'. If there are more than the allowed <code>n</code>, it chooses not to start up.</p> <p>One implementation approach might be to make <code>n</code...
1
2010-03-09T15:16:03Z
[ "python", "terminal-services", "citrix" ]
Technique to limit number of instances of our application under Terminal Server
2,409,200
<p>I'm looking for simple ways to monitor and limit the number of instances of our application under Terminal Server (2003 and 2008).</p> <p>The purpose of this restriction is to make sure we don't overload our servers. This is an internal administrative requirement - I am not looking for a licensing solution.</p> <p...
2
2010-03-09T13:12:34Z
2,431,193
<p>Based on feedback on the Python Win32 API mailing list I'm also considering one of the following techniques:</p> <ol> <li><p>Using Windows Semaphores</p></li> <li><p>Using a pool of Mutexes (offer better recoverability than semaphores)</p></li> <li><p>Using a range of ports </p></li> </ol> <p>Malcolm</p>
0
2010-03-12T07:46:47Z
[ "python", "terminal-services", "citrix" ]
how to get data from csv file in python
2,409,330
<p>I am using csv.reader to read file but it giving me whole file.</p> <pre><code>file_data = self.request.get('file_in'); file_Reader = csv.reader( file_data ); for fields in file_Reader: </code></pre> <p>I want one line at a time and separate data from that line.</p> <pre><code>ex: filedata = name,sal,dept ...
1
2010-03-09T13:33:46Z
2,409,344
<p>This</p> <pre><code>&gt;&gt;&gt; import csv &gt;&gt;&gt; spamReader = csv.reader(open('eggs.csv'), delimiter=' ', quotechar='|') &gt;&gt;&gt; for row in spamReader: ... print ', '.join(row) Spam, Spam, Spam, Spam, Spam, Baked Beans Spam, Lovely Spam, Wonderful Spam </code></pre> <p>Was taken from <a href="http...
1
2010-03-09T13:36:17Z
[ "python" ]
how to get data from csv file in python
2,409,330
<p>I am using csv.reader to read file but it giving me whole file.</p> <pre><code>file_data = self.request.get('file_in'); file_Reader = csv.reader( file_data ); for fields in file_Reader: </code></pre> <p>I want one line at a time and separate data from that line.</p> <pre><code>ex: filedata = name,sal,dept ...
1
2010-03-09T13:33:46Z
2,409,349
<p>Why not do it manually?</p> <pre><code>for line in fd: foo, bar, baz = line.split(";") </code></pre>
0
2010-03-09T13:36:59Z
[ "python" ]
how to get data from csv file in python
2,409,330
<p>I am using csv.reader to read file but it giving me whole file.</p> <pre><code>file_data = self.request.get('file_in'); file_Reader = csv.reader( file_data ); for fields in file_Reader: </code></pre> <p>I want one line at a time and separate data from that line.</p> <pre><code>ex: filedata = name,sal,dept ...
1
2010-03-09T13:33:46Z
2,409,600
<p>It looks like you are trying to pass a string of data directly to csv.reader(). It's expecting an iterable object like a list or filehandle. The docs for the <a href="http://docs.python.org/library/csv.html" rel="nofollow" title="csv module docs">csv module</a> mention this. So you probably want to split the strin...
1
2010-03-09T14:17:21Z
[ "python" ]
seleniumRC: Problems with browser starting on OS X
2,409,353
<p>I am trying to start simple selenium test on OSX (just downloaded the latest version of RC), with a python client driver. But the browser can't start (it crashes).</p> <p>The error which I see in console is </p> <pre><code> 15:33:32.867 INFO - Preparing Firefox profile... dyld: Library not loaded: /System/Libra...
0
2010-03-09T13:38:07Z
2,409,624
<p>It appears as if ImageIO is interfering with the loading of Firefox when it is creating its new Firefox profile on creation.</p> <p>Try create your own firefox profile and then start Selenium RC with the <code>-firefoxProfileTemplate</code> argument</p> <pre><code>java -jar selenium-server.jar -firefoxProfileTempl...
0
2010-03-09T14:19:22Z
[ "python", "selenium", "selenium-rc" ]
Python: How expensive is to create a small list many times?
2,409,472
<p>I encounter the following small annoying dilemma over and over again in Python:</p> <p>Option 1:</p> <p>cleaner but slower(?) if called many times since a_list get re-created for each call of do_something()</p> <pre><code>def do_something(): a_list = ["any", "think", "whatever"] # read something from ...
9
2010-03-09T13:56:31Z
2,409,493
<p>Never create something more than once if you don't have to. This is a simply optimization that can be done on your part and I personally do not find the second example ugly at all.</p> <p>Some may argue not to worry about optimizing little things like this but I feel that something this simple to fix should be don...
4
2010-03-09T13:58:54Z
[ "python" ]
Python: How expensive is to create a small list many times?
2,409,472
<p>I encounter the following small annoying dilemma over and over again in Python:</p> <p>Option 1:</p> <p>cleaner but slower(?) if called many times since a_list get re-created for each call of do_something()</p> <pre><code>def do_something(): a_list = ["any", "think", "whatever"] # read something from ...
9
2010-03-09T13:56:31Z
2,409,502
<p>if your <code>a_list</code> doesn't change, move it out of the function.</p>
3
2010-03-09T14:00:44Z
[ "python" ]
Python: How expensive is to create a small list many times?
2,409,472
<p>I encounter the following small annoying dilemma over and over again in Python:</p> <p>Option 1:</p> <p>cleaner but slower(?) if called many times since a_list get re-created for each call of do_something()</p> <pre><code>def do_something(): a_list = ["any", "think", "whatever"] # read something from ...
9
2010-03-09T13:56:31Z
2,409,506
<p>If the list is never modified, why do you use lists at all?</p> <p>Without knowing your actual requirements, I'd recommend to simply use some if-statements to get rid of the list and the "read something from list" part completely.</p>
0
2010-03-09T14:01:24Z
[ "python" ]
Python: How expensive is to create a small list many times?
2,409,472
<p>I encounter the following small annoying dilemma over and over again in Python:</p> <p>Option 1:</p> <p>cleaner but slower(?) if called many times since a_list get re-created for each call of do_something()</p> <pre><code>def do_something(): a_list = ["any", "think", "whatever"] # read something from ...
9
2010-03-09T13:56:31Z
2,409,514
<p>Option 3: </p> <pre><code>def do_something(a_list = ("any", "think", "whatever")): read something from a_list </code></pre> <p><strong>Option 3 compared to Option 1:</strong></p> <p>Both are equally readable in my opinion (though some seem to think differently in the comments! :-) ). You could even write Opti...
4
2010-03-09T14:02:32Z
[ "python" ]
Python: How expensive is to create a small list many times?
2,409,472
<p>I encounter the following small annoying dilemma over and over again in Python:</p> <p>Option 1:</p> <p>cleaner but slower(?) if called many times since a_list get re-created for each call of do_something()</p> <pre><code>def do_something(): a_list = ["any", "think", "whatever"] # read something from ...
9
2010-03-09T13:56:31Z
2,409,523
<p>What's ugly about it?</p> <p>Are the contents of the list always constants, as in your example? If so: recent versions of Python (since 2.4) will optimise that by evaluating the constant expression and keeping the result but only if it's a tuple. So you could change it to being a tuple. Or you could stop worrying a...
16
2010-03-09T14:03:04Z
[ "python" ]
Python: How expensive is to create a small list many times?
2,409,472
<p>I encounter the following small annoying dilemma over and over again in Python:</p> <p>Option 1:</p> <p>cleaner but slower(?) if called many times since a_list get re-created for each call of do_something()</p> <pre><code>def do_something(): a_list = ["any", "think", "whatever"] # read something from ...
9
2010-03-09T13:56:31Z
2,410,012
<p>Well it seems it comes down to initializing the array in the function or not:</p> <pre><code>import time def fun1(): a = ['any', 'think', 'whatever'] sum = 0 for i in range(100): sum += i def fun2(): sum = 0 for i in range(100): sum += i def...
1
2010-03-09T15:08:37Z
[ "python" ]
Python: How expensive is to create a small list many times?
2,409,472
<p>I encounter the following small annoying dilemma over and over again in Python:</p> <p>Option 1:</p> <p>cleaner but slower(?) if called many times since a_list get re-created for each call of do_something()</p> <pre><code>def do_something(): a_list = ["any", "think", "whatever"] # read something from ...
9
2010-03-09T13:56:31Z
2,410,197
<p>I've worked on automated systems that process 100,000,000+ records a day, where a 1% percent performance improvement is huge. </p> <p>I learned a big lesson working on that system: Faster is better, but only when you know when it's fast enough.</p> <p>A 1% improvement would have been a huge reduction in total pro...
0
2010-03-09T15:32:04Z
[ "python" ]
Python: How expensive is to create a small list many times?
2,409,472
<p>I encounter the following small annoying dilemma over and over again in Python:</p> <p>Option 1:</p> <p>cleaner but slower(?) if called many times since a_list get re-created for each call of do_something()</p> <pre><code>def do_something(): a_list = ["any", "think", "whatever"] # read something from ...
9
2010-03-09T13:56:31Z
2,410,204
<ol> <li>You have some data</li> <li>You have a method associated with it</li> <li>You don't want to keep the data globally just for the sake of optimising the speed of the method unless you have to.</li> </ol> <p>I think this is what classes are for.</p> <pre><code>class Processor: def __init__(this): th...
2
2010-03-09T15:32:43Z
[ "python" ]
How do I do this regex in Python?
2,409,636
<p>Suppose I have a string of text, of all characters Latin-based. With punctuation.</p> <p>How do I "find" all the characters and put <code>&lt;strong&gt;</code> tags around it?</p> <pre><code>hay = The fox jumped up the tree. needle = "umpe" </code></pre> <p>In this case, part of the word "jumped" would be highlig...
2
2010-03-09T14:21:35Z
2,409,667
<p>Your question is not very clear. If you want to highlight the words that have needle in them you can match</p> <pre><code>\b(\w*needle\w*)\b </code></pre> <p>and replace it with</p> <pre><code>&lt;strong&gt;\1&lt;strong&gt; </code></pre>
1
2010-03-09T14:26:01Z
[ "python", "regex" ]
How do I do this regex in Python?
2,409,636
<p>Suppose I have a string of text, of all characters Latin-based. With punctuation.</p> <p>How do I "find" all the characters and put <code>&lt;strong&gt;</code> tags around it?</p> <pre><code>hay = The fox jumped up the tree. needle = "umpe" </code></pre> <p>In this case, part of the word "jumped" would be highlig...
2
2010-03-09T14:21:35Z
2,409,692
<p>Without regex (may be a bit more verbose but also easier to understand):</p> <pre><code>hay = "The fox jumped up the tree." needle = "umpe" print hay.replace(needle, "&lt;strong&gt;%s&lt;strong&gt;" % needle) </code></pre> <p><strong>EDIT after extra specification:</strong> if you want case insensitive replace (w...
4
2010-03-09T14:28:16Z
[ "python", "regex" ]
How do I do this regex in Python?
2,409,636
<p>Suppose I have a string of text, of all characters Latin-based. With punctuation.</p> <p>How do I "find" all the characters and put <code>&lt;strong&gt;</code> tags around it?</p> <pre><code>hay = The fox jumped up the tree. needle = "umpe" </code></pre> <p>In this case, part of the word "jumped" would be highlig...
2
2010-03-09T14:21:35Z
2,409,848
<p>No regex used in this case, but will work for smaller strings.</p> <pre><code>hay = "The fox jumped up the tree." needle = "umpe" hay_lower = hey.lower() found = [] curr_find = hay_lower.find(needle.lower()) found.append(curr_find) hay_list = list(hay) while(curr_find): curr_find = hay_lower.find(needle.lower...
1
2010-03-09T14:48:13Z
[ "python", "regex" ]
How do I do this regex in Python?
2,409,636
<p>Suppose I have a string of text, of all characters Latin-based. With punctuation.</p> <p>How do I "find" all the characters and put <code>&lt;strong&gt;</code> tags around it?</p> <pre><code>hay = The fox jumped up the tree. needle = "umpe" </code></pre> <p>In this case, part of the word "jumped" would be highlig...
2
2010-03-09T14:21:35Z
2,409,855
<p>Using regular expressions on a simple search expression like this is overkill. However, in case you need a more complicated search, I referenced <a href="http://www.python.org/doc/2.5.2/lib/node46.html" rel="nofollow">Python's re module documentation</a> to put together the code below, which I think does what you w...
3
2010-03-09T14:48:51Z
[ "python", "regex" ]
How do I do this regex in Python?
2,409,636
<p>Suppose I have a string of text, of all characters Latin-based. With punctuation.</p> <p>How do I "find" all the characters and put <code>&lt;strong&gt;</code> tags around it?</p> <pre><code>hay = The fox jumped up the tree. needle = "umpe" </code></pre> <p>In this case, part of the word "jumped" would be highlig...
2
2010-03-09T14:21:35Z
2,409,949
<p>This should work:</p> <pre><code>pattern = r'(?P&lt;needle&gt;(umpe))' pat_obj = re.compile(pattern) new_text = pat_obj.sub(r'&lt;strong&gt;\g&lt;needle&gt;&lt;/strong&gt;', hay) </code></pre> <p>The result rendered in HTML: The fox j<strong>umpe</strong>d up the tree.</p> <p>In the snippet above, i've used the r...
1
2010-03-09T15:00:16Z
[ "python", "regex" ]
Python methods on an object - which is better?
2,409,668
<p>Hopefully an easy question. If I have an object and I want to call a method on it which is the better approach, A or B?</p> <pre><code>class foo(object): def bar(): print 'bar' # approach A f = foo() f.bar() # approach B foo().bar() </code></pre>
0
2010-03-09T14:26:08Z
2,409,682
<p>A is more readable. </p> <p>So, A :)</p>
2
2010-03-09T14:27:31Z
[ "python" ]
Python methods on an object - which is better?
2,409,668
<p>Hopefully an easy question. If I have an object and I want to call a method on it which is the better approach, A or B?</p> <pre><code>class foo(object): def bar(): print 'bar' # approach A f = foo() f.bar() # approach B foo().bar() </code></pre>
0
2010-03-09T14:26:08Z
2,409,728
<p>If your sole intent is to call <code>bar()</code> on a <code>foo</code> object, B is okay.</p> <p>But if you actually plan to do something with the object later, you must go with A as B doesn't leave you any references to the created object.</p>
2
2010-03-09T14:31:54Z
[ "python" ]
Python methods on an object - which is better?
2,409,668
<p>Hopefully an easy question. If I have an object and I want to call a method on it which is the better approach, A or B?</p> <pre><code>class foo(object): def bar(): print 'bar' # approach A f = foo() f.bar() # approach B foo().bar() </code></pre>
0
2010-03-09T14:26:08Z
2,409,857
<p>Approach B doesn't keep the object around. If method bar() returns self then you can write:</p> <pre> f = foo().bar() </pre> <p>Personally I like method A. Though I've started making setter functions that return self in order to chain them together like above - I don't think other people consider that pythonic.</p...
1
2010-03-09T14:48:56Z
[ "python" ]
How can I produce student-style graphs using matplotlib?
2,409,774
<p>I am experimenting with matplotlib at the moment. Some time ago I used Excel VBA code to produce images such as the one attached.</p> <p>You will notice it is not presented in a scientific/research style but rather as if produced by a school-student on graph paper - with three different grid-line styles.</p> <p>Is...
6
2010-03-09T14:37:21Z
2,410,136
<p>Yes, you can use <a href="http://matplotlib.sourceforge.net/examples/pylab_examples/spine_placement_demo.html">spines</a> for this.</p> <pre><code>import matplotlib.pyplot as plt from matplotlib.ticker import MultipleLocator, FormatStrFormatter import numpy as np fig = plt.figure(1) ax = fig.add_subplot(111) # se...
8
2010-03-09T15:24:22Z
[ "python", "matplotlib", "wxpython" ]
How can I produce student-style graphs using matplotlib?
2,409,774
<p>I am experimenting with matplotlib at the moment. Some time ago I used Excel VBA code to produce images such as the one attached.</p> <p>You will notice it is not presented in a scientific/research style but rather as if produced by a school-student on graph paper - with three different grid-line styles.</p> <p>Is...
6
2010-03-09T14:37:21Z
2,411,370
<p>Just another thought - I have also tried to do it all with the minor gridlines (apart from anything else it will help my understanding), but it's not enumerating properly, no doubt due to the get_minorticklocs and ax.get_xgridlines. Sorry, and thanks in advance...</p> <p>Geddes</p> <pre><code>import matplotlib.pyp...
1
2010-03-09T18:08:23Z
[ "python", "matplotlib", "wxpython" ]
Should we use Pylons or PHP for our webapp?
2,409,812
<p>My friend and I are planning on building a sort of a forum type of webapp. We've used the major PHP frameworks but we're really thinking about using Python specifically the Pylons framework for our app. Although we're competent PHP programmers, we're somewhat noobs at Python (We could create practical scripts and su...
4
2010-03-09T14:42:54Z
2,409,852
<p>Decide what you want to put your focus on, being productive or learning a new language:</p> <ul> <li>If you want to <strong>learn</strong> Pylons and Python, use Pylon and Python. </li> <li>If you want to <strong>deliver</strong> a stable forum software, use PHP, because that's what you're competent at. </li> </u...
9
2010-03-09T14:48:39Z
[ "php", "python", "pylons" ]
Should we use Pylons or PHP for our webapp?
2,409,812
<p>My friend and I are planning on building a sort of a forum type of webapp. We've used the major PHP frameworks but we're really thinking about using Python specifically the Pylons framework for our app. Although we're competent PHP programmers, we're somewhat noobs at Python (We could create practical scripts and su...
4
2010-03-09T14:42:54Z
2,409,860
<p>I don't know about Pylons but I've been in a similar situation and built a site using Django. I learned enough about Python in an environment that I was familiar with (web apps) that I now go to Python as my first choice.</p>
4
2010-03-09T14:49:18Z
[ "php", "python", "pylons" ]
Should we use Pylons or PHP for our webapp?
2,409,812
<p>My friend and I are planning on building a sort of a forum type of webapp. We've used the major PHP frameworks but we're really thinking about using Python specifically the Pylons framework for our app. Although we're competent PHP programmers, we're somewhat noobs at Python (We could create practical scripts and su...
4
2010-03-09T14:42:54Z
2,409,917
<p>Don't be scared off by imports in python. They're much more common when coding in python than PHP in general, and this is good because your namespace never gets polluted with stuff you aren't expecting, unless you do <code>from foo import *</code> (so don't do that). I think you'll find that the structure pylons g...
5
2010-03-09T14:56:04Z
[ "php", "python", "pylons" ]
Should we use Pylons or PHP for our webapp?
2,409,812
<p>My friend and I are planning on building a sort of a forum type of webapp. We've used the major PHP frameworks but we're really thinking about using Python specifically the Pylons framework for our app. Although we're competent PHP programmers, we're somewhat noobs at Python (We could create practical scripts and su...
4
2010-03-09T14:42:54Z
6,481,796
<p>Many many times have we had this discussion at my job. We use PHP and everyone here would love to switch to python. Even for our new web projects PHP delivers, and since we use it every day that is what we use. Many things in PHP irk me, and I love python, that said Im a big fan of "use the best tool for the job".</...
0
2011-06-26T02:32:52Z
[ "php", "python", "pylons" ]
Where to put the separation between a stateful object and a stateless calculation in Python?
2,410,265
<p>Which of the following code snippets is the most "pythonic"? The calculation is trivial in this example but could be assumed to be complex in real life.</p> <pre><code>class A(object): """Freely mix state and calcs - no good I presume""" def __init__(self, state): self.state = state def calc_wi...
1
2010-03-09T15:41:41Z
2,410,355
<p>I think it depends on your particular project. Is <code>cal_with_state</code> only applicable to this particular class or is the method needs to be shared among many different objects? Do different classes share it?</p> <p>There is nothing more or less pythonic about any of this approaches, use the one that will sa...
1
2010-03-09T15:52:26Z
[ "python" ]
Where to put the separation between a stateful object and a stateless calculation in Python?
2,410,265
<p>Which of the following code snippets is the most "pythonic"? The calculation is trivial in this example but could be assumed to be complex in real life.</p> <pre><code>class A(object): """Freely mix state and calcs - no good I presume""" def __init__(self, state): self.state = state def calc_wi...
1
2010-03-09T15:41:41Z
2,410,357
<p>Personally I would say it depends on resusability. If the calculation is one that might be used with other objects (as it does look to be) then the third example is the most reusable. If the calculation is completely tied to the object or would never be reused then the first example. I'd say the second example is...
0
2010-03-09T15:52:38Z
[ "python" ]
Where to put the separation between a stateful object and a stateless calculation in Python?
2,410,265
<p>Which of the following code snippets is the most "pythonic"? The calculation is trivial in this example but could be assumed to be complex in real life.</p> <pre><code>class A(object): """Freely mix state and calcs - no good I presume""" def __init__(self, state): self.state = state def calc_wi...
1
2010-03-09T15:41:41Z
2,410,359
<p>Factoring out the calculation, whether in a static or global method doesn't offer any benefit <em>with regards to the state awareness</em>. The only slight advantage is that the code explicitly shows which of the object's stateful properties are taken into account in the calculation (show at the level of the functi...
0
2010-03-09T15:52:46Z
[ "python" ]
Where to put the separation between a stateful object and a stateless calculation in Python?
2,410,265
<p>Which of the following code snippets is the most "pythonic"? The calculation is trivial in this example but could be assumed to be complex in real life.</p> <pre><code>class A(object): """Freely mix state and calcs - no good I presume""" def __init__(self, state): self.state = state def calc_wi...
1
2010-03-09T15:41:41Z
2,410,364
<p>What is wrong with A? It does the calculation in one place only and does not modify the state so calc_with_state is a method that does not change state so is a 'simple' behaviour. If the state was complex it stops a large number of parameters being passed into the calculation function.</p> <p>However if the calcula...
0
2010-03-09T15:53:10Z
[ "python" ]
Where to put the separation between a stateful object and a stateless calculation in Python?
2,410,265
<p>Which of the following code snippets is the most "pythonic"? The calculation is trivial in this example but could be assumed to be complex in real life.</p> <pre><code>class A(object): """Freely mix state and calcs - no good I presume""" def __init__(self, state): self.state = state def calc_wi...
1
2010-03-09T15:41:41Z
2,410,372
<p>As written, A, by a longshot. The issue, quite simply, is </p> <blockquote> <p>Flat is better than nested.</p> </blockquote> <p>Look: separating state from calculations is a good design principle, but it doesn't mean what you think, at least not what I can infer you think from this example. We want to make sur...
4
2010-03-09T15:54:00Z
[ "python" ]
Adding up time durations in Python
2,410,454
<p>I would like to add up a series of splits in Python. The times begin as strings like "00:08:30.291". I can't seem to find the right way to use the Python objects or API to make this convenient/elegant. It seems that the time object doesn't use microseconds, so I'm using datetime's strptime to parse the strings, succ...
2
2010-03-09T16:04:54Z
2,410,613
<p>What you're working with is time differences, that's why using <a href="https://docs.python.org/2/library/datetime.html#timedelta-objects" rel="nofollow"><code>datetime.timedelta</code></a> is only appropriate here:</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; d1 = datetime.datetime.strptime("00:08:30.2...
9
2010-03-09T16:26:25Z
[ "python", "datetime", "time" ]
Google OAuth and local dev
2,410,559
<p>i am trying to use Google OAuth to import a user 's contacts. In order to get a consumer and secret key for you app you have to verify your domain at <a href="https://www.google.com/accounts/ManageDomains" rel="nofollow">https://www.google.com/accounts/ManageDomains</a> Google allows you to use only domains without ...
4
2010-03-09T16:19:58Z
2,418,392
<p>well after trial and error i found out that the request 's domain is irrelevant</p>
4
2010-03-10T16:02:58Z
[ "python", "oauth", "google-contacts" ]
Google OAuth and local dev
2,410,559
<p>i am trying to use Google OAuth to import a user 's contacts. In order to get a consumer and secret key for you app you have to verify your domain at <a href="https://www.google.com/accounts/ManageDomains" rel="nofollow">https://www.google.com/accounts/ManageDomains</a> Google allows you to use only domains without ...
4
2010-03-09T16:19:58Z
2,432,861
<p>i just use the official gdata google auth library <a href="http://code.google.com/p/gdata-python-client" rel="nofollow">http://code.google.com/p/gdata-python-client</a></p> <p>Here is some code</p> <pre><code> google_auth_url = None if not current_user.gmail_authorized: google = gdata.contacts.servi...
3
2010-03-12T13:07:44Z
[ "python", "oauth", "google-contacts" ]
How to only pay the dependency penalty for the implementation you use in Python?
2,410,580
<p>I have a fairly simple set of functionality for which I have multiple implementations, e.g., a datastore that could be backed by Redis, MongoDB, or PostgreSQL. How should I structure/write my code so that code that wants to use one of these implementations only needs the dependencies for that implementation, e.g., t...
3
2010-03-09T16:22:28Z
2,410,622
<p><code>import</code> is just another statement, like <code>for</code> or <code>with</code>. Put it in an <code>if</code> statement, possibly behind an abstraction class.</p>
4
2010-03-09T16:27:40Z
[ "python", "import", "dependencies" ]
How to only pay the dependency penalty for the implementation you use in Python?
2,410,580
<p>I have a fairly simple set of functionality for which I have multiple implementations, e.g., a datastore that could be backed by Redis, MongoDB, or PostgreSQL. How should I structure/write my code so that code that wants to use one of these implementations only needs the dependencies for that implementation, e.g., t...
3
2010-03-09T16:22:28Z
2,419,316
<p>Can't you simply put the <code>import</code> statement in the <code>__init__</code> method of each class? Then it won't be run until you try to make an instance:</p> <pre><code>class UnsatisfiedExample(object): def __init__(self): try: import flibbertigibbet except ImportError: ...
5
2010-03-10T18:03:06Z
[ "python", "import", "dependencies" ]
Python - file contents to nested list
2,410,619
<p>I have a file in tab delimited format with trailing newline characters, e.g.,</p> <pre><code>123 abc 456 def 789 ghi </code></pre> <p>I wish to write function to convert the contents of the file into a nested list. To date I have tried:</p> <pre><code>def ls_platform_ann(): keyword = [] for line in ...
3
2010-03-09T16:27:12Z
2,410,645
<p>First off, have a look at the <a href="http://file:///opt/local/share/doc/python26-doc/library/csv.html" rel="nofollow">csv</a> module, it should handle the whitespace for you. You may also want to call <code>strip()</code> on value/entry.</p>
3
2010-03-09T16:31:29Z
[ "python", "file", "list", "newline", "tabs" ]
Python - file contents to nested list
2,410,619
<p>I have a file in tab delimited format with trailing newline characters, e.g.,</p> <pre><code>123 abc 456 def 789 ghi </code></pre> <p>I wish to write function to convert the contents of the file into a nested list. To date I have tried:</p> <pre><code>def ls_platform_ann(): keyword = [] for line in ...
3
2010-03-09T16:27:12Z
2,410,699
<p>You want the <a href="http://docs.python.org/library/csv.html" rel="nofollow"><code>csv</code></a> module.</p> <pre><code>import csv source = "123\tabc\n456\tdef\n789\tghi" lines = source.split("\n") reader = csv.reader(lines, delimiter='\t') print [word for word in [row for row in reader]] </code></pre> <p>Out...
8
2010-03-09T16:38:47Z
[ "python", "file", "list", "newline", "tabs" ]
Python - file contents to nested list
2,410,619
<p>I have a file in tab delimited format with trailing newline characters, e.g.,</p> <pre><code>123 abc 456 def 789 ghi </code></pre> <p>I wish to write function to convert the contents of the file into a nested list. To date I have tried:</p> <pre><code>def ls_platform_ann(): keyword = [] for line in ...
3
2010-03-09T16:27:12Z
2,412,923
<p>Another option that doesn't involve the <a href="http://file///opt/local/share/doc/python26-doc/library/csv.html" rel="nofollow">csv</a> module is:</p> <pre><code>data = [[item.strip() for item in line.rstrip('\r\n').split('\t')] for line in open('input.txt')] </code></pre> <p>As a multiple line statement it would...
3
2010-03-09T22:06:42Z
[ "python", "file", "list", "newline", "tabs" ]
GAE db.Model getting property instead of a string value
2,411,138
<p>I have a db.Model which has a string property on it, email_type. Now I've the values for type defined in a readonly class. When I save this to the datastore I get the string instead of "Register", it also raises a BadValueError. How do I get it to save as a string, not as a property.</p> <p>Here's the (slimmed dow...
0
2010-03-09T17:37:19Z
2,411,293
<p>What happens if you change your EmailTypes class to look like this:</p> <pre><code>class EmailTypes(object): Register = 'Register' NewsLetter = 'NewsLetter' </code></pre> <p>and use it like:</p> <pre><code>e.email_type = EmailTypes.Register </code></pre> <p>Does that make your simplified example work?</p...
3
2010-03-09T18:00:43Z
[ "python", "google-app-engine" ]
pymssql connect function
2,411,203
<p>i have this function pymssql.connect(host="my host",user="my user",password="my pass",database="mydb")</p> <p>I want to read the user and password from the user and put them there is that possible or named arguments lvalue should not be variable and if yes then how could i do that ?</p> <p>i.e is it possible to c...
0
2010-03-09T17:45:17Z
2,411,217
<p>Your question is worded... strangely. Are you having trouble with <a href="http://docs.python.org/tutorial/controlflow.html#default-argument-values" rel="nofollow">setting default arguments</a> in a function definition? </p> <pre><code>&gt;&gt;&gt; def f(arg1="hello", arg2="goodbye"): print "arg1 is", arg1 ...
3
2010-03-09T17:47:55Z
[ "python", "sql-server" ]
pymssql connect function
2,411,203
<p>i have this function pymssql.connect(host="my host",user="my user",password="my pass",database="mydb")</p> <p>I want to read the user and password from the user and put them there is that possible or named arguments lvalue should not be variable and if yes then how could i do that ?</p> <p>i.e is it possible to c...
0
2010-03-09T17:45:17Z
2,411,372
<p>To read input in from the user you can use <code>raw_input</code>.<br> To use the command line arguments of the program you have to <code>import sys</code> and use <code>sys.argv</code></p> <p>for example:</p> <pre><code>import sys myvar = raw_input("please input a var") #prompts the user for a value myvar2 = sys....
0
2010-03-09T18:08:37Z
[ "python", "sql-server" ]
Python Socket Getting Connection Reset
2,411,290
<p>I created a threaded socket listener that stores newly accepted connections in a queue. The socket threads then read from the queue and respond. For some reason, when doing benchmarking with 'ab' (apache benchmark) using a concurrency of 2 or more, I always get a connection reset before it's able to complete the ben...
1
2010-03-09T18:00:16Z
2,413,419
<p>Is there a reason why you're not using SocketServer which comes with Python? This would handle the situation a lot better. If you're looking to do HTTP stuff, the BaseHTTPServer also provides a framework for this. </p>
0
2010-03-09T23:28:53Z
[ "python", "sockets", "multithreading" ]
How to get an item from a set of Queues?
2,411,306
<p>Say there are two empty <code>Queue</code>s. Is there a way to get an item from the queue that gets it first?</p> <p>So I have a queue of high anonymous proxies, queues of anonymous and transparent ones. Some threads may need only high anon. proxies, while others may accept both high anon. and just anon. proxies. T...
0
2010-03-09T18:01:39Z
2,411,355
<p>You could check both queues in turn, each time using a short timeout. That way you would most likely read from the first queue that receives data. However, this solution is prone to race conditions if you will be getting many items on a regular basis.</p> <p>If that is the case, do you have a good reason for not ju...
0
2010-03-09T18:06:35Z
[ "python", "multithreading" ]
How to get an item from a set of Queues?
2,411,306
<p>Say there are two empty <code>Queue</code>s. Is there a way to get an item from the queue that gets it first?</p> <p>So I have a queue of high anonymous proxies, queues of anonymous and transparent ones. Some threads may need only high anon. proxies, while others may accept both high anon. and just anon. proxies. T...
0
2010-03-09T18:01:39Z
2,411,865
<p>If I had this problem (and "polling", i.e. trying each queue alternately with short timeouts, was unacceptable -- it usually is, being very wasteful of CPU time etc), I would tackle it by designing a "multiqueue" object -- one with multiple condition variables, one per "subqueue" and an overall one. A put to any su...
0
2010-03-09T19:17:38Z
[ "python", "multithreading" ]
side effect gotchas in python/numpy? horror stories and narrow escapes wanted
2,411,459
<p>I am considering moving from Matlab to Python/numpy for data analysis and numerical simulations. I have used Matlab (and SML-NJ) for years, and am very comfortable in the functional environment without side effects (barring I/O), but am a little reluctant about the side effects in Python. Can people share their favo...
7
2010-03-09T18:19:54Z
2,411,680
<p>Confusing references to the same (mutable) object with references to separate objects is indeed a "gotcha" (suffered by all non-functional languages, ones which have mutable objects and, of course, references). A frequently seen bug in beginners' Python code is misusing a default value which is mutable, e.g.:</p> ...
9
2010-03-09T18:53:22Z
[ "python", "matlab", "functional-programming", "side-effects" ]
side effect gotchas in python/numpy? horror stories and narrow escapes wanted
2,411,459
<p>I am considering moving from Matlab to Python/numpy for data analysis and numerical simulations. I have used Matlab (and SML-NJ) for years, and am very comfortable in the functional environment without side effects (barring I/O), but am a little reluctant about the side effects in Python. Can people share their favo...
7
2010-03-09T18:19:54Z
15,505,571
<p>I stumbled upon this one recently again, (after years of python) while trying to remove a small dependency on numpy.</p> <p>If you come from matlab you should use and trust <code>numpy</code> functions for mono-type array handling. Along with matplotlib, they are some very convenient packages for a smooth transitio...
0
2013-03-19T16:48:35Z
[ "python", "matlab", "functional-programming", "side-effects" ]
Function to create in-memory zip file and return as http response
2,411,514
<p>I am avoiding the creation of files on disk, this is what I have got so far:</p> <pre><code>def get_zip(request): import zipfile, StringIO i = open('picture.jpg', 'rb').read() o = StringIO.StringIO() zf = zipfile.ZipFile(o, mode='w') zf.writestr('picture.jpg', i) zf.close() o.seek(0) ...
6
2010-03-09T18:28:16Z
2,411,536
<p>Avoiding disk files can slow your server to a crawl, but it will certainly work.</p> <p>You'll exhaust memory if you serve too many of these requests concurrently.</p>
4
2010-03-09T18:32:00Z
[ "python", "zip", "stringio" ]
Function to create in-memory zip file and return as http response
2,411,514
<p>I am avoiding the creation of files on disk, this is what I have got so far:</p> <pre><code>def get_zip(request): import zipfile, StringIO i = open('picture.jpg', 'rb').read() o = StringIO.StringIO() zf = zipfile.ZipFile(o, mode='w') zf.writestr('picture.jpg', i) zf.close() o.seek(0) ...
6
2010-03-09T18:28:16Z
2,411,540
<p>For <code>StringIO</code> you should generally use <code>o.getvalue()</code> to get the result. Also, if you want to add a normal file to the zip file, you can use <code>zf.write('picture.jpg')</code>. You don't need to manually read it.</p>
11
2010-03-09T18:32:21Z
[ "python", "zip", "stringio" ]
Regex - Special alpha characters? - Python
2,411,759
<p>I have a list of simple names such as <code>Márquez</code>,</p> <p>because of the <code>á</code> <code>(?&lt; name &gt;[a-zA-Z]+)</code> doesn't seem to be working!</p> <p>Help would be very much appreciated! </p>
1
2010-03-09T19:04:49Z
2,411,778
<p>you could use </p> <pre><code>\w+ </code></pre> <p>with the unicode flag. I assume there's no risk of having digits or underscore in your names.</p> <pre><code>&gt;&gt;&gt; re.findall('\w+', 'Márquez', re.U) ['Márquez'] </code></pre> <p>You also seem to be missing <code>P</code> after the question mark: <code>...
3
2010-03-09T19:07:28Z
[ "python", "regex", "ascii" ]
Regex - Special alpha characters? - Python
2,411,759
<p>I have a list of simple names such as <code>Márquez</code>,</p> <p>because of the <code>á</code> <code>(?&lt; name &gt;[a-zA-Z]+)</code> doesn't seem to be working!</p> <p>Help would be very much appreciated! </p>
1
2010-03-09T19:04:49Z
2,412,023
<p>For Python &lt; 3 you may want to enable locale:</p> <pre><code>import locale locale.setlocale(locale.LC_ALL, '') </code></pre> <p>And then use <code>re.LOCALE</code> option with your regexpes:</p> <pre><code>re.findall('\w+', 'Márquez', re.LOCALE) </code></pre> <p>Though, probably Unicode is the better way to ...
0
2010-03-09T19:42:04Z
[ "python", "regex", "ascii" ]
Python Socket Send Buffer Vs. Str
2,411,864
<p>I am trying to get a basic server (copied from Beginning Python) to send a str.</p> <p>The error:</p> <pre><code>c.send( "XXX" ) TypeError: must be bytes or buffer, not str </code></pre> <p>It seems to work when pickling an object. All of the examples I found, seem to be able to send a string no problem.</p> <p>...
9
2010-03-09T19:17:38Z
2,411,981
<p>It seems you try to use Python 2.x examples in Python 3 and you hit one of the main differences between those Python version.</p> <p>For Python &lt; 3 'strings' are in fact binary strings and 'unicode objects' are the right text objects (as they can contain any Unicode characters).</p> <p>In Python 3 unicode strin...
18
2010-03-09T19:36:34Z
[ "python", "string", "sockets", "send" ]
Python Socket Send Buffer Vs. Str
2,411,864
<p>I am trying to get a basic server (copied from Beginning Python) to send a str.</p> <p>The error:</p> <pre><code>c.send( "XXX" ) TypeError: must be bytes or buffer, not str </code></pre> <p>It seems to work when pickling an object. All of the examples I found, seem to be able to send a string no problem.</p> <p>...
9
2010-03-09T19:17:38Z
2,412,100
<p>To add to Jacek Konieczny's answer: You can also use <a href="http://docs.python.org/3.1/library/stdtypes.html#str.encode">str.encode()</a> to get bytes from a string. If you have the string in a variable instead of a literal, you can call encode and it will return an equivalent series of bytes.</p>
11
2010-03-09T19:54:27Z
[ "python", "string", "sockets", "send" ]
GUI options with python 3.x
2,411,886
<p>I was wondering what options are available for Python 3.x? I know Tkinter is available as well as qt, but what about the other libraries? Any word on when some of them may be ported over to 3.x?</p>
4
2010-03-09T19:21:44Z
2,412,056
<p>I have heard really good things about WxWidgets <a href="http://www.wxpython.org/" rel="nofollow" title="wxPython"> or wxpython </a> but cant find any word when its going to be compatible. I always liked QT. </p>
1
2010-03-09T19:48:07Z
[ "python", "user-interface", "python-3.x" ]
GUI options with python 3.x
2,411,886
<p>I was wondering what options are available for Python 3.x? I know Tkinter is available as well as qt, but what about the other libraries? Any word on when some of them may be ported over to 3.x?</p>
4
2010-03-09T19:21:44Z
2,412,093
<p>As you can read in the <a href="http://groups.google.com/group/wxpython-users/browse_thread/thread/86f8b2513941d0f4/6d77c3d4ebd0e919?lnk=gst&amp;q=python+3" rel="nofollow">newsgroups</a> of wxPython, people ary trying to port it to Python 3.x but it will take a while.</p> <p>There are also plans to port PyGTK (see ...
1
2010-03-09T19:53:41Z
[ "python", "user-interface", "python-3.x" ]
GUI options with python 3.x
2,411,886
<p>I was wondering what options are available for Python 3.x? I know Tkinter is available as well as qt, but what about the other libraries? Any word on when some of them may be ported over to 3.x?</p>
4
2010-03-09T19:21:44Z
2,412,151
<p>Several recent versions of <a href="http://pypi.python.org/pypi/PyQt/4.6.2" rel="nofollow">PyQt</a> support Python 3 (I'm pointing to the PyPi entry, which is for PyQt 4.6, but there's also a more recent <a href="http://www.riverbankcomputing.co.uk/news/pyqt-47" rel="nofollow">PyQt 4.7</a>). I haven't personally tr...
3
2010-03-09T20:03:13Z
[ "python", "user-interface", "python-3.x" ]
GUI options with python 3.x
2,411,886
<p>I was wondering what options are available for Python 3.x? I know Tkinter is available as well as qt, but what about the other libraries? Any word on when some of them may be ported over to 3.x?</p>
4
2010-03-09T19:21:44Z
29,502,724
<p>I use exclusively Tkinter, and though it's somewhat limited in terms of images, it's remarkably easy to work with and follows the standard easy-to-read Python syntax very nicely. I'm not familiar with other GUI options, but Tkinter is great from my experience.</p>
0
2015-04-07T22:48:05Z
[ "python", "user-interface", "python-3.x" ]
Mercurial Issue when updating
2,412,043
<p>I am trying to do a terminal update and I keep getting this error, no matter what.</p> <p>/Volumes/www/working/.hg/wlock.break /Library/Python/2.6/site-packages/mercurial/dispatch.py:157: DeprecationWarning: use lock.release instead of del lock return -1</p> <p>Any ideas as to what this is?</p> <p>Out of date v...
0
2010-03-09T19:46:01Z
2,413,265
<p>What version of mercurial are you running? It looks like a lot of these (harmless warning) messages have been cleaned up according to the mercurial bug tracker: <a href="http://mercurial.selenic.com/bts/" rel="nofollow">http://mercurial.selenic.com/bts/</a></p>
1
2010-03-09T22:57:12Z
[ "python", "mercurial" ]
Getting information from scripts/command line calls in C#
2,412,141
<p>I've been writing a couple of apps which use C# as the Gui, but under the hood do all the work via scripts (which may be Python, Ruby etc.). </p> <p>To pass information from the script back to the GUI (for example error reporting etc.) I've usually resorted to calling the script via Process and either</p> <ul> <l...
2
2010-03-09T20:01:39Z
2,412,262
<p>Using <code>ProcessStartInfo.RedirectStandardInput</code>, <code>ProcessStartInfo.RedirectStandardOutput</code> and <code>ProcessStartInfo.RedirectStandardError</code> (as well as <code>Process.ExitCode</code>) is perfectly fine, especially when your scripts rigorously follow a certain convention:</p> <ul> <li><str...
4
2010-03-09T20:20:50Z
[ "c#", "python", "ruby", "scripting" ]
Is it possible to delete/remove a wx.aui.AuiManager pane?
2,412,205
<p>I want to remove a pane from the wx.aui.AuiManager.</p> <p>Is it possible?</p>
1
2010-03-09T20:10:12Z
2,417,861
<p>I'm not sure, but this might work:</p> <pre><code>manager.DetachPane(pane) pane.Destroy() manager.Update() </code></pre>
2
2010-03-10T14:59:45Z
[ "python", "wxpython" ]
Is it possible to delete/remove a wx.aui.AuiManager pane?
2,412,205
<p>I want to remove a pane from the wx.aui.AuiManager.</p> <p>Is it possible?</p>
1
2010-03-09T20:10:12Z
28,007,128
<p>I was seeing segfaults due to stale (deleted) panels left in an AuiManager; I cleared them with the following:</p> <pre><code>nbpanes = manager.GetAllPanes() for pane in nbpanes: pane.DestroyOnClose() manager.ClosePane(pane) </code></pre> <p><code>nbpanes</code> is a list of PaneInfo objects</p>
0
2015-01-18T04:25:23Z
[ "python", "wxpython" ]
PyGTK StatusIcon with transparency
2,412,346
<p>I'm trying to create a PyGTK <a href="http://www.pygtk.org/docs/pygtk/class-gtkstatusicon.html" rel="nofollow">StatusIcon</a> with transparent background. I need to draw the contents of the StatusIcon at runtime.</p> <p>StatusIcon wants a <a href="http://www.pygtk.org/docs/pygtk/class-gdkpixbuf.html" rel="nofollow"...
2
2010-03-09T20:33:44Z
2,422,054
<p>You can add transparency to Pixbuf objects with the add_alpha() method. The following line will set zero opacity for the color #ffffff:</p> <pre><code>pixbuf = pixbuf.add_alpha(True, 0xFF, 0xFF, 0xFF) </code></pre> <p>Too easy... :-|</p>
4
2010-03-11T02:00:12Z
[ "python", "pygtk", "alpha-transparency" ]
separating JSS from CSS at plone.htmlhead
2,412,350
<p>I'm using Plone 3.1.7 in a project that needs performance tweaks. One of the tweaks requests that CSS should be at the top of page and the JS should be at the bottom. However both are located at</p> <pre><code>&lt;div tal:replace="structure provider:plone.htmlhead" /&gt; </code></pre> <p>In main_template. How do I...
3
2010-03-09T20:34:22Z
2,421,414
<p>You usually don't have to do this in Plone, as it is set up to trigger the JS asynchronously, so it shouldn't block any rendering (which is what the performance tip is about).</p> <p>If you insert things directly in the template, things may change — but the default setup does the right thing, unless I'm misunders...
1
2010-03-10T23:18:17Z
[ "python", "plone", "plone-3.x" ]
separating JSS from CSS at plone.htmlhead
2,412,350
<p>I'm using Plone 3.1.7 in a project that needs performance tweaks. One of the tweaks requests that CSS should be at the top of page and the JS should be at the bottom. However both are located at</p> <pre><code>&lt;div tal:replace="structure provider:plone.htmlhead" /&gt; </code></pre> <p>In main_template. How do I...
3
2010-03-09T20:34:22Z
2,425,182
<p>My workmates have found the solution:</p> <p>plone.htmlhead is a viewlet registered by the product plone.app.layout that loads other three viewlets:</p> <ul> <li>plone.resourceregistries.styles</li> <li>plone.resourceregistries.scripts</li> <li>plone.resourceregistries.kineticstylesheets</li> </ul> <p>I put the f...
3
2010-03-11T13:22:47Z
[ "python", "plone", "plone-3.x" ]
separating JSS from CSS at plone.htmlhead
2,412,350
<p>I'm using Plone 3.1.7 in a project that needs performance tweaks. One of the tweaks requests that CSS should be at the top of page and the JS should be at the bottom. However both are located at</p> <pre><code>&lt;div tal:replace="structure provider:plone.htmlhead" /&gt; </code></pre> <p>In main_template. How do I...
3
2010-03-09T20:34:22Z
2,460,106
<p>This was a know bug in some recent versions of Products.ResourceRegistries This issue is fixed in the 2.02b release. You can pin that version in your buildout:</p> <pre><code>[versions] ... Products.ResourceRegistries == 2.02b ... </code></pre> <p>then, re-run buildout and this issue goes away.</p>
0
2010-03-17T05:39:57Z
[ "python", "plone", "plone-3.x" ]
separating JSS from CSS at plone.htmlhead
2,412,350
<p>I'm using Plone 3.1.7 in a project that needs performance tweaks. One of the tweaks requests that CSS should be at the top of page and the JS should be at the bottom. However both are located at</p> <pre><code>&lt;div tal:replace="structure provider:plone.htmlhead" /&gt; </code></pre> <p>In main_template. How do I...
3
2010-03-09T20:34:22Z
2,957,846
<p>The suggestion above to replace plone.htmlhead split with 3 viewlets didn't entirely work for me, as I lost the page title (not good for SEO). I assume the page title is also normally included by plone.htmlhead. </p> <p>The better solution seems to be to use the newer Products.ResourceRegistries suggested above, ex...
0
2010-06-02T12:59:41Z
[ "python", "plone", "plone-3.x" ]
separating JSS from CSS at plone.htmlhead
2,412,350
<p>I'm using Plone 3.1.7 in a project that needs performance tweaks. One of the tweaks requests that CSS should be at the top of page and the JS should be at the bottom. However both are located at</p> <pre><code>&lt;div tal:replace="structure provider:plone.htmlhead" /&gt; </code></pre> <p>In main_template. How do I...
3
2010-03-09T20:34:22Z
6,875,550
<p>In the head tag in addition of</p> <pre><code>&lt;div tal:replace="structure provider:plone.resourceregistries.styles" /&gt; </code></pre> <p>I've put </p> <pre><code>&lt;title tal:define="page_title python: context_state.object_title()" tal:content="page_title"&gt;page title&lt;/title&gt; </code></pre> <...
0
2011-07-29T15:38:08Z
[ "python", "plone", "plone-3.x" ]
Serializing a suds object in python
2,412,486
<p>Ok I'm working on getting better with python, so I'm not sure this is the right way to go about what I'm doing to begin with, but here's my current problem...</p> <p>I need to get some information via a SOAP method, and only use part of the information now but store the entire result for future uses (we need to use...
11
2010-03-09T20:54:08Z
2,412,621
<p>Yep, I confirm the explanation I gave in the answer you refer to -- dynamically generated classes are not easily picklable (nor otherwise easily serializable), you need to extract all the state information, pickle <em>that</em> state, and reconstruct the tricky sudsobject on retrieval if you really insist on using i...
5
2010-03-09T21:15:18Z
[ "python", "soap", "pickle", "suds" ]
Serializing a suds object in python
2,412,486
<p>Ok I'm working on getting better with python, so I'm not sure this is the right way to go about what I'm doing to begin with, but here's my current problem...</p> <p>I need to get some information via a SOAP method, and only use part of the information now but store the entire result for future uses (we need to use...
11
2010-03-09T20:54:08Z
14,606,089
<p>I made an implementation of a dummy class for Object intance of suds, and then being able to serialize. The FakeSudsInstance behaves like an original Suds Object instance, see below:</p> <pre><code>from suds.sudsobject import Object as SudsObject class FakeSudsNode(SudsObject): def __init__(self, data): ...
5
2013-01-30T14:14:10Z
[ "python", "soap", "pickle", "suds" ]
Serializing a suds object in python
2,412,486
<p>Ok I'm working on getting better with python, so I'm not sure this is the right way to go about what I'm doing to begin with, but here's my current problem...</p> <p>I need to get some information via a SOAP method, and only use part of the information now but store the entire result for future uses (we need to use...
11
2010-03-09T20:54:08Z
15,678,861
<p>I have been using following approach to convert Suds object into JSON:</p> <pre><code>from suds.sudsobject import asdict def recursive_asdict(d): """Convert Suds object into serializable format.""" out = {} for k, v in asdict(d).iteritems(): if hasattr(v, '__keylist__'): out[k] = re...
27
2013-03-28T10:01:06Z
[ "python", "soap", "pickle", "suds" ]
Serializing a suds object in python
2,412,486
<p>Ok I'm working on getting better with python, so I'm not sure this is the right way to go about what I'm doing to begin with, but here's my current problem...</p> <p>I need to get some information via a SOAP method, and only use part of the information now but store the entire result for future uses (we need to use...
11
2010-03-09T20:54:08Z
34,768,585
<p>I updated the <code>recursive_asdict</code> example <a href="http://stackoverflow.com/questions/2412486/serializing-a-suds-object-in-python/15678861#15678861">above</a> to be compatible with python3 (<code>items</code> instead of <code>iteritems</code>). </p> <pre><code>from suds.sudsobject import asdict from suds....
0
2016-01-13T13:57:07Z
[ "python", "soap", "pickle", "suds" ]
Serializing a suds object in python
2,412,486
<p>Ok I'm working on getting better with python, so I'm not sure this is the right way to go about what I'm doing to begin with, but here's my current problem...</p> <p>I need to get some information via a SOAP method, and only use part of the information now but store the entire result for future uses (we need to use...
11
2010-03-09T20:54:08Z
34,844,428
<p>Here is what I came up with before researching and finding this answer. This actually works well for me on complex suds responses and also on other objects such as <code>__builtins__</code> since the solution is suds agnostic:</p> <pre><code>import datetime def object_to_dict(obj): if isinstance(obj, (str, uni...
0
2016-01-17T22:17:42Z
[ "python", "soap", "pickle", "suds" ]
List of Dicts comparision to match between lists and detect value changes in Python
2,412,562
<p>I have a list of dictionaries that I get back from a web service call,</p> <pre><code>listA = [{'name':'foo', 'val':'x'}, {'name':'bar', 'val':'1'}, {'name':'alice','val':'2'}] </code></pre> <p>I need to compare the results from the previous call to the service and pull out changes. So on the ne...
1
2010-03-09T21:05:51Z
2,412,594
<p>I'd build an auxiliary dict to store <code>listA</code>'s information more sensibly:</p> <pre><code>auxdict = dict((d['name'], d['val']) for d in listA) </code></pre> <p>then the task becomes very easy:</p> <pre><code>changed = [d['name'] for d in listB if d['name'] in auxdict and d['val'] != auxdict[...
6
2010-03-09T21:11:22Z
[ "python", "comparison", "list", "dictionary" ]