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
How can I remove all words that end in ":" from a string in Python?
2,589,200
<p>I'm wondering how to remove a dynamic word from a string within Python.</p> <p>It will always have a ":" at the end of the word, and sometimes there's more than one within the string. I'd like to remove all occurrences of "word:".</p> <p>Thanks! :-)</p>
6
2010-04-07T00:13:59Z
2,589,235
<pre><code>[ chunk for chunk in line.split() if not chunk.endswith(":") ] </code></pre> <p>this will create a list. you can join them up afterwards.</p>
0
2010-04-07T00:25:05Z
[ "python", "regex" ]
Command-line input causes SyntaxError
2,589,309
<p>I have a simple Python question that I'm having brain freeze on. This code snippet works. But when I substitue "258 494-3929" with phoneNumber, I get the following error below:</p> <pre><code># Compare phone number phone_pattern = '^\d{3} ?\d{3}-\d{4}$' # phoneNumber = str(input("Please enter a phone number:...
3
2010-04-07T00:43:37Z
2,589,338
<p><code>input()</code> calls <code>eval(raw_input(prompt))</code>, so you want <code>phoneNumber = raw_input("Please enter a phone number: ").strip()</code></p> <p>See also <a href="http://docs.python.org/library/functions.html#input" rel="nofollow">http://docs.python.org/library/functions.html#input</a> and <a href=...
1
2010-04-07T00:49:03Z
[ "python", "input", "command-line", "python-2.x" ]
Command-line input causes SyntaxError
2,589,309
<p>I have a simple Python question that I'm having brain freeze on. This code snippet works. But when I substitue "258 494-3929" with phoneNumber, I get the following error below:</p> <pre><code># Compare phone number phone_pattern = '^\d{3} ?\d{3}-\d{4}$' # phoneNumber = str(input("Please enter a phone number:...
3
2010-04-07T00:43:37Z
2,589,340
<p>You should use <code>raw_input</code> instead of <code>input</code>, and you don't have to call <code>str</code>, because this function returns a string itself:</p> <pre><code>phoneNumber = raw_input("Please enter a phone number: ") </code></pre>
7
2010-04-07T00:49:53Z
[ "python", "input", "command-line", "python-2.x" ]
Command-line input causes SyntaxError
2,589,309
<p>I have a simple Python question that I'm having brain freeze on. This code snippet works. But when I substitue "258 494-3929" with phoneNumber, I get the following error below:</p> <pre><code># Compare phone number phone_pattern = '^\d{3} ?\d{3}-\d{4}$' # phoneNumber = str(input("Please enter a phone number:...
3
2010-04-07T00:43:37Z
2,589,348
<p>The input() function actually <em>evaluates</em> the input that's typed into it:</p> <pre><code>&gt;&gt;&gt; print str(input("input: ")) input: 258238 258238 &gt;&gt;&gt; print str(input("input: ")) input: 3**3 + 4 31 </code></pre> <p>It's trying to evaluate '258 494-3929' which is invalid Python.</p> <p>Use <cod...
4
2010-04-07T00:54:05Z
[ "python", "input", "command-line", "python-2.x" ]
Command-line input causes SyntaxError
2,589,309
<p>I have a simple Python question that I'm having brain freeze on. This code snippet works. But when I substitue "258 494-3929" with phoneNumber, I get the following error below:</p> <pre><code># Compare phone number phone_pattern = '^\d{3} ?\d{3}-\d{4}$' # phoneNumber = str(input("Please enter a phone number:...
3
2010-04-07T00:43:37Z
2,589,720
<p>In Python version 2.x, input() does two things:</p> <ol> <li>Reads a string of data. (You want this.)</li> <li>Then it evaluates the string of data as if it were a Python expression. (This part is causing the error.)</li> </ol> <p>The function raw_input() is better in this situation because it does #1 above but no...
2
2010-04-07T02:53:42Z
[ "python", "input", "command-line", "python-2.x" ]
How do I sort this list in Python, if my date is in a String?
2,589,479
<pre><code>[{'date': '2010-04-01', 'people': 1047, 'hits': 4522}, {'date': '2010-04-03', 'people': 617, 'hits': 2582}, {'date': '2010-04-02', 'people': 736, 'hits': 3277}] </code></pre> <p>Suppose I have this list. How do I sort by "date", which is an item in the dictionary. But, "date" is a string...</p>
7
2010-04-07T01:36:28Z
2,589,484
<pre><code>.sort(key=lambda x: datetime.datetime.strptime(x['date'], '%Y-%m-%d')) </code></pre>
19
2010-04-07T01:38:50Z
[ "python", "list", "dictionary" ]
How do I sort this list in Python, if my date is in a String?
2,589,479
<pre><code>[{'date': '2010-04-01', 'people': 1047, 'hits': 4522}, {'date': '2010-04-03', 'people': 617, 'hits': 2582}, {'date': '2010-04-02', 'people': 736, 'hits': 3277}] </code></pre> <p>Suppose I have this list. How do I sort by "date", which is an item in the dictionary. But, "date" is a string...</p>
7
2010-04-07T01:36:28Z
2,589,490
<pre><code>records = [ {'date': '2010-04-01', 'people': 1047, 'hits': 4522}, {'date': '2010-04-03', 'people': 617, 'hits': 2582}, {'date': '2010-04-02', 'people': 736, 'hits': 3277} ] records.sort(key=lambda x: x['date'].split('-')) </code></pre>
2
2010-04-07T01:40:22Z
[ "python", "list", "dictionary" ]
How do I sort this list in Python, if my date is in a String?
2,589,479
<pre><code>[{'date': '2010-04-01', 'people': 1047, 'hits': 4522}, {'date': '2010-04-03', 'people': 617, 'hits': 2582}, {'date': '2010-04-02', 'people': 736, 'hits': 3277}] </code></pre> <p>Suppose I have this list. How do I sort by "date", which is an item in the dictionary. But, "date" is a string...</p>
7
2010-04-07T01:36:28Z
2,589,499
<p>Fortunately, ISO format dates, which seems to be what you have here, sort perfectly well <em>as strings</em>! So you need nothing fancy:</p> <pre><code>import operator yourlistofdicts.sort(key=operator.itemgetter('date')) </code></pre>
18
2010-04-07T01:41:41Z
[ "python", "list", "dictionary" ]
How do I sort this list in Python, if my date is in a String?
2,589,479
<pre><code>[{'date': '2010-04-01', 'people': 1047, 'hits': 4522}, {'date': '2010-04-03', 'people': 617, 'hits': 2582}, {'date': '2010-04-02', 'people': 736, 'hits': 3277}] </code></pre> <p>Suppose I have this list. How do I sort by "date", which is an item in the dictionary. But, "date" is a string...</p>
7
2010-04-07T01:36:28Z
2,589,529
<p>In python 2.6 you can use soerted w/operator.itemgetter. Since date is YYYY-MM-DD it is sorted even though its a string cause its largest to smallest - i use that format all the time for this reason </p> <pre><code>&gt;&gt;&gt; import operator &gt;&gt;&gt; l = [{'date': '2010-04-01','people': 1047, 'hits': 4522}, ...
3
2010-04-07T01:52:31Z
[ "python", "list", "dictionary" ]
How do I sort this list in Python, if my date is in a String?
2,589,479
<pre><code>[{'date': '2010-04-01', 'people': 1047, 'hits': 4522}, {'date': '2010-04-03', 'people': 617, 'hits': 2582}, {'date': '2010-04-02', 'people': 736, 'hits': 3277}] </code></pre> <p>Suppose I have this list. How do I sort by "date", which is an item in the dictionary. But, "date" is a string...</p>
7
2010-04-07T01:36:28Z
2,589,662
<p>Satoru.Logic's solution is clean and simple. But, per Alex's post, you don't need to manipulate the date string to get the sort order right...so lose the <code>.split('-')</code> </p> <p>This code will suffice:</p> <pre><code>records.sort(key=lambda x:x['date']) </code></pre>
9
2010-04-07T02:37:17Z
[ "python", "list", "dictionary" ]
How to get msn contact list with Python?
2,589,480
<p>How can I get msn contact list with a Python script having username and password?</p>
0
2010-04-07T01:36:56Z
2,589,497
<p>There are <a href="http://blitiri.com.ar/p/msnlib/" rel="nofollow">lots</a> and <a href="http://code.google.com/p/pymsn/" rel="nofollow">lots</a> and <a href="http://twistedmatrix.com/trac/wiki/TwistedWords" rel="nofollow">lots</a> of MSN client modules for Python.</p>
1
2010-04-07T01:41:32Z
[ "python", "msn" ]
Proper way to assert type of variable in Python
2,589,522
<p>In using a function, I wish to ensure that the type of the variables are as expected. How to do it right?</p> <p>Here is an example fake function trying to do just this before going on with its role:</p> <pre><code>def my_print(begin, text, end): """Print 'text' in UPPER between 'begin' and 'end' in lower ...
30
2010-04-07T01:51:10Z
2,589,534
<p>You might want to try this example for version 2.6 of Python.</p> <pre><code>def my_print(text, begin, end): "Print text in UPPER between 'begin' and 'end' in lower." for obj in (text, begin, end): assert isinstance(obj, str), 'Argument of wrong type!' print begin.lower() + begin.upper() + end.l...
7
2010-04-07T01:53:30Z
[ "python", "testing", "assert" ]
Proper way to assert type of variable in Python
2,589,522
<p>In using a function, I wish to ensure that the type of the variables are as expected. How to do it right?</p> <p>Here is an example fake function trying to do just this before going on with its role:</p> <pre><code>def my_print(begin, text, end): """Print 'text' in UPPER between 'begin' and 'end' in lower ...
30
2010-04-07T01:51:10Z
2,589,572
<p>The <a href="http://docs.python.org/library/functions.html#isinstance"><code>isinstance</code></a> built-in is the preferred way if you really must, but even better is to remember Python's motto: "it's easier to ask forgiveness than permission"!-) (It was actually Grace Murray Hopper's favorite motto;-). I.e.:</p>...
31
2010-04-07T02:07:32Z
[ "python", "testing", "assert" ]
Proper way to assert type of variable in Python
2,589,522
<p>In using a function, I wish to ensure that the type of the variables are as expected. How to do it right?</p> <p>Here is an example fake function trying to do just this before going on with its role:</p> <pre><code>def my_print(begin, text, end): """Print 'text' in UPPER between 'begin' and 'end' in lower ...
30
2010-04-07T01:51:10Z
2,589,573
<p>Doing <code>type('')</code> is effectively equivalent to <code>str</code> and <code>types.StringType</code></p> <p>so <code>type('') == str == types.StringType</code> will evaluate to "<code>True</code>"</p> <p>Note that Unicode strings which only contain ASCII will fail if checking types in this way, so you may w...
3
2010-04-07T02:07:32Z
[ "python", "testing", "assert" ]
Creating a method that is simultaneously an instance and class method
2,589,690
<p>In Python, I'd like to be able to create a function that behaves both as a class function and an instance method, but with the ability to change behaviors. The use case for this is for a set of serializable objects and types. As an example:</p> <pre><code>&gt;&gt;&gt; class Thing(object): #... &gt;&gt;&gt; Thin...
13
2010-04-07T02:45:09Z
2,589,706
<p>Sure, you just need to define your own <strong>descriptor</strong> type. There's an excellent tutorial on Python descriptors <a href="http://users.rcn.com/python/download/Descriptor.htm">here</a>.</p>
7
2010-04-07T02:49:00Z
[ "python", "methods" ]
Find full path of the Python interpreter?
2,589,711
<p>How do I find the full path of the currently running Python interpreter from within the currently executing Python script?</p>
144
2010-04-07T02:50:25Z
2,589,722
<p><code>sys.executable</code> contains full path of the currently running Python interpreter.</p> <pre><code>import sys print(sys.executable) </code></pre> <p>which is now <a href="http://docs.python.org/library/sys.html">documented here</a></p>
216
2010-04-07T02:54:34Z
[ "python", "path" ]
Find full path of the Python interpreter?
2,589,711
<p>How do I find the full path of the currently running Python interpreter from within the currently executing Python script?</p>
144
2010-04-07T02:50:25Z
19,622,119
<p>Try the <a href="http://linux.about.com/library/cmd/blcmdl1_whereis.htm" rel="nofollow">whereis</a> command: </p> <pre><code>whereis python </code></pre>
2
2013-10-27T19:00:15Z
[ "python", "path" ]
Find full path of the Python interpreter?
2,589,711
<p>How do I find the full path of the currently running Python interpreter from within the currently executing Python script?</p>
144
2010-04-07T02:50:25Z
27,836,526
<p>Just noting a different way of questionable usefulness, using <a href="https://docs.python.org/3.4/library/os.html#os.environ" rel="nofollow"><code>os.environ</code></a>:</p> <pre><code>import os python_executable_path = os.environ['_'] </code></pre> <p>e.g.</p> <pre><code>$ python -c "import os; print(os.environ...
2
2015-01-08T09:14:45Z
[ "python", "path" ]
How to define and use Python generators appropriately
2,589,812
<p>I want to define a generator from a list that will output the elements one at a time, then use this generator object in an <strong>appropriate manner</strong>. </p> <pre><code>a = ["Hello", "world", "!"] b = (x for x in a) c = next(b, None) while c != None: print c, c = next(b, None) </code></pre> <p>Is th...
1
2010-04-07T03:25:23Z
2,589,826
<p>Why would you use a <code>while</code> loop? In Python, <code>for</code> loops are absolutely designed for this:</p> <pre><code>a = ["Hello", "world", "!"] b = (x for x in a) for c in b: print c, </code></pre> <p>If you are stuck on a <code>while</code> implementation for whatever reason, your current implemen...
7
2010-04-07T03:29:35Z
[ "python", "generator", "while-loop" ]
How to define and use Python generators appropriately
2,589,812
<p>I want to define a generator from a list that will output the elements one at a time, then use this generator object in an <strong>appropriate manner</strong>. </p> <pre><code>a = ["Hello", "world", "!"] b = (x for x in a) c = next(b, None) while c != None: print c, c = next(b, None) </code></pre> <p>Is th...
1
2010-04-07T03:25:23Z
2,590,733
<p>Clarification: you meant <em>generator expressions</em> not <em>generators</em> -- the latter is a function definition that contains at least one <strong><code>yield</code></strong> statement/expression.</p> <p>agreed with the earlier poster... you should be using <strong><code>for</code></strong> loops for almost ...
3
2010-04-07T07:39:48Z
[ "python", "generator", "while-loop" ]
What are the common patterns in web programming?
2,589,932
<p>I have been trying to write my first big web app (more than one cgi file) and as I kept moving forward with the rough prototype, paralelly trying to predict more tasks, this is the todo that got accumulated (In no particular order).</p> <pre><code>* Validations and input sanitizations * Object versioning (to avoid ...
4
2010-04-07T04:06:35Z
2,589,951
<p>The <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller" rel="nofollow">Model-View-Controller (MVC)</a> design pattern: decouples users inputs and the presentation layer from your application data.</p>
3
2010-04-07T04:11:50Z
[ "python", "design-patterns" ]
What are the common patterns in web programming?
2,589,932
<p>I have been trying to write my first big web app (more than one cgi file) and as I kept moving forward with the rough prototype, paralelly trying to predict more tasks, this is the todo that got accumulated (In no particular order).</p> <pre><code>* Validations and input sanitizations * Object versioning (to avoid ...
4
2010-04-07T04:06:35Z
2,590,006
<p>model view controller of course. start with some framework first. in php kohana is good , for python django is good, ruby on rail and so on...</p>
1
2010-04-07T04:30:39Z
[ "python", "design-patterns" ]
What are the common patterns in web programming?
2,589,932
<p>I have been trying to write my first big web app (more than one cgi file) and as I kept moving forward with the rough prototype, paralelly trying to predict more tasks, this is the todo that got accumulated (In no particular order).</p> <pre><code>* Validations and input sanitizations * Object versioning (to avoid ...
4
2010-04-07T04:06:35Z
2,590,009
<p>If this is actually a big web app that will be deployed for general consumption, then I'd add on Rate Limiting.</p>
4
2010-04-07T04:31:14Z
[ "python", "design-patterns" ]
What are the common patterns in web programming?
2,589,932
<p>I have been trying to write my first big web app (more than one cgi file) and as I kept moving forward with the rough prototype, paralelly trying to predict more tasks, this is the todo that got accumulated (In no particular order).</p> <pre><code>* Validations and input sanitizations * Object versioning (to avoid ...
4
2010-04-07T04:06:35Z
2,591,717
<p>Almost all of your list is "Framework".</p> <p>Almost none of that is functionality a user actually sees.</p> <p>My to do list never looks like that. Never.</p> <p>Consequently, I have this advice.</p> <p>STOP.</p> <p>Do this instead.</p> <ol> <li><p>Find a framework that does this. </p></li> <li><p>Focus on...
3
2010-04-07T10:46:48Z
[ "python", "design-patterns" ]
Scipy Negative Distance? What?
2,590,117
<p>I have an input file which contains floating point numbers to 4 decimal place:</p> <pre><code>i.e. 13359 0.0000 0.0000 0.0001 0.0001 0.0002` 0.0003 0.0007 ... </code></pre> <p>(the first is the id). My class uses the <code>loadVectorsFromFile</code> method which multiplies it by 10000 and ...
7
2010-04-07T04:55:50Z
2,590,194
<p>I'm pretty sure that this is because you are using the cosine metric when you are calling fclusterdata. Try using euclidean and see if the error goes away. </p> <p>The cosine metric can go negative if the dot product of two vectors in your set is greater than 1. Since you are using very large numbers and normalizin...
4
2010-04-07T05:18:54Z
[ "python", "scipy" ]
Scipy Negative Distance? What?
2,590,117
<p>I have an input file which contains floating point numbers to 4 decimal place:</p> <pre><code>i.e. 13359 0.0000 0.0000 0.0001 0.0001 0.0002` 0.0003 0.0007 ... </code></pre> <p>(the first is the id). My class uses the <code>loadVectorsFromFile</code> method which multiplies it by 10000 and ...
7
2010-04-07T04:55:50Z
2,590,377
<p>I'm not able to improve the answer of Justin, but another point of note is your data handling.</p> <p>You say you do something like <code>int( float("0.0003") * 10000 )</code> to read the data. But if you do that you'd get not <code>3</code> but <code>2.9999999999999996</code>. That's because the floating point ina...
0
2010-04-07T06:16:05Z
[ "python", "scipy" ]
Scipy Negative Distance? What?
2,590,117
<p>I have an input file which contains floating point numbers to 4 decimal place:</p> <pre><code>i.e. 13359 0.0000 0.0000 0.0001 0.0001 0.0002` 0.0003 0.0007 ... </code></pre> <p>(the first is the id). My class uses the <code>loadVectorsFromFile</code> method which multiplies it by 10000 and ...
7
2010-04-07T04:55:50Z
10,901,549
<p>This is because of floating-point inaccuracy, so some distances between your vectors, instead of being 0, are for example -0.000000000000000002. Use <code>scipy.clip()</code> function to correct the problem. If your distance matrix is <code>dmatr</code>, use <code>numpy.clip(dmatr,0,1,dmatr)</code> and you should be...
4
2012-06-05T16:58:17Z
[ "python", "scipy" ]
Scipy Negative Distance? What?
2,590,117
<p>I have an input file which contains floating point numbers to 4 decimal place:</p> <pre><code>i.e. 13359 0.0000 0.0000 0.0001 0.0001 0.0002` 0.0003 0.0007 ... </code></pre> <p>(the first is the id). My class uses the <code>loadVectorsFromFile</code> method which multiplies it by 10000 and ...
7
2010-04-07T04:55:50Z
31,089,629
<p>"Linkage Z contains negative values". This error also occurs in scipy heirarchical clustering process when any linkage cluster index in linkage matrix is assigned -1. </p> <p>As per my observations, any linkage cluster index gets assigned -1 during the combine processs, when the distance between all pairs of cluste...
1
2015-06-27T14:05:33Z
[ "python", "scipy" ]
Scipy Negative Distance? What?
2,590,117
<p>I have an input file which contains floating point numbers to 4 decimal place:</p> <pre><code>i.e. 13359 0.0000 0.0000 0.0001 0.0001 0.0002` 0.0003 0.0007 ... </code></pre> <p>(the first is the id). My class uses the <code>loadVectorsFromFile</code> method which multiplies it by 10000 and ...
7
2010-04-07T04:55:50Z
35,572,992
<p>I had the same issue. What you can do is rewrite the cosine function. For example:</p> <pre><code>from sklearn.metrics.pairwise import cosine_similarity def mycosine(x1, x2): x1 = x1.reshape(1,-1) x2 = x2.reshape(1,-1) ans = 1 - cosine_similarity(x1, x2) return max(ans[0][0], 0) </code></pre> <p>.....
1
2016-02-23T08:58:48Z
[ "python", "scipy" ]
Histogram in Matplotlib with input file
2,590,328
<p>I wish to make a Histogram in Matplotlib from an input file containing the raw data (.txt). I am facing issues in referring to the input file. I guess it should be a rather small program. Any Matplotlib gurus, any help ? </p> <p>I am not asking for the code, some inputs should put me on the right way ! </p>
5
2010-04-07T06:05:17Z
2,590,381
<p>You can't directly tell matplotlib to make a histogram from an input file - you'll need to open the file yourself and get the data from it. How you'd do that depends on the format of the file - if it's just a file with a number on each line, you can just go through each line, <code>strip()</code> spaces and newlines...
0
2010-04-07T06:17:15Z
[ "python", "matplotlib", "histogram" ]
Histogram in Matplotlib with input file
2,590,328
<p>I wish to make a Histogram in Matplotlib from an input file containing the raw data (.txt). I am facing issues in referring to the input file. I guess it should be a rather small program. Any Matplotlib gurus, any help ? </p> <p>I am not asking for the code, some inputs should put me on the right way ! </p>
5
2010-04-07T06:05:17Z
2,590,548
<p>i would recommend using '<strong>loadtxt</strong>' which is actually in the NumPy library. There are related functions in Matplotlib (csv2rec) but Matplotlib is actually standardizing on loadtxt.</p> <p>Here's how it works:</p> <pre><code>from matplotlib import pyplot as PLT with open('name_of_your_file.csv') as ...
9
2010-04-07T07:00:08Z
[ "python", "matplotlib", "histogram" ]
Eclipse + PyDev: Eclipse telling me that this is an invalid import?
2,590,435
<p>I recently installed twython, a really sleek and awesome twitter API wrapper for Python. I installed it and it works fine from the interpreter, but when I try to import it via Eclipse, it says that twython is an invalid import.</p> <p>How do I "tell" eclipse where twython is so that it will let me import and use it...
2
2010-04-07T06:29:18Z
2,590,469
<p>I believe I have had this problem before - try going into the menu: Window_Preferences and then select Pydev and Interpreter-Python. Then try to click Auto-config - it should update its search paths to include everything installed in Python. If that doesn't work, you should at least be able to manually add the folde...
3
2010-04-07T06:39:04Z
[ "python", "eclipse", "pydev", "twython" ]
Eclipse + PyDev: Eclipse telling me that this is an invalid import?
2,590,435
<p>I recently installed twython, a really sleek and awesome twitter API wrapper for Python. I installed it and it works fine from the interpreter, but when I try to import it via Eclipse, it says that twython is an invalid import.</p> <p>How do I "tell" eclipse where twython is so that it will let me import and use it...
2
2010-04-07T06:29:18Z
2,594,323
<p>Daniel is right. As long as twython went into site-packages then Pydev will find it.</p>
0
2010-04-07T16:50:03Z
[ "python", "eclipse", "pydev", "twython" ]
MySQLdb not INSERTING, _mysql does fine
2,590,480
<p>Okay, I log onto the MySQL command-line client as root. I then open or otherwise run a python app using the MySQLdb module as root. When I check the results using python (IDLE), everything looks fine. When I use the MySQL command-line client, no INSERT has occurred. If I change things around to _mysql instead of MyS...
4
2010-04-07T06:41:23Z
2,590,512
<p>I think they use different autocommit settings. Use commit() after inserting data.</p>
4
2010-04-07T06:50:11Z
[ "python", "mysql" ]
MySQLdb not INSERTING, _mysql does fine
2,590,480
<p>Okay, I log onto the MySQL command-line client as root. I then open or otherwise run a python app using the MySQLdb module as root. When I check the results using python (IDLE), everything looks fine. When I use the MySQL command-line client, no INSERT has occurred. If I change things around to _mysql instead of MyS...
4
2010-04-07T06:41:23Z
2,590,563
<p>You can use <code>db.commit()</code> to submit data or set <code>db.autocommit()</code> after <code>_mysql.connect(...)</code> to autocommit requests.</p>
17
2010-04-07T07:03:36Z
[ "python", "mysql" ]
how to find whether a string is contained in another string
2,590,503
<pre><code>a='1234;5' print a.index('s') </code></pre> <p>the error is :</p> <pre><code>&gt; "D:\Python25\pythonw.exe" "D:\zjm_code\kml\a.py" Traceback (most recent call last): File "D:\zjm_code\kml\a.py", line 4, in &lt;module&gt; print a.index('s') ValueError: substring not found </code></pre> <p>thanks</p...
2
2010-04-07T06:48:26Z
2,590,516
<pre><code>print ('s' in a) # False print ('1234' in a) # True </code></pre> <p>Use <code>find</code> if you need the index as well, but don't want an exception be raised.</p> <pre><code>print a.find('s') # -1 print a.find('1234') # 0 </code></pre>
6
2010-04-07T06:50:48Z
[ "python", "string" ]
how to find whether a string is contained in another string
2,590,503
<pre><code>a='1234;5' print a.index('s') </code></pre> <p>the error is :</p> <pre><code>&gt; "D:\Python25\pythonw.exe" "D:\zjm_code\kml\a.py" Traceback (most recent call last): File "D:\zjm_code\kml\a.py", line 4, in &lt;module&gt; print a.index('s') ValueError: substring not found </code></pre> <p>thanks</p...
2
2010-04-07T06:48:26Z
2,590,519
<p>Try using <code>find()</code> instead - this will tell you where it is in the string:</p> <pre><code>a = '1234;5' index = a.find('s') if index == -1: print "Not found." else: print "Found at index", index </code></pre> <p>If you just want to know <em>whether</em> the string is in there, you can use <code>i...
9
2010-04-07T06:51:34Z
[ "python", "string" ]
how to find whether a string is contained in another string
2,590,503
<pre><code>a='1234;5' print a.index('s') </code></pre> <p>the error is :</p> <pre><code>&gt; "D:\Python25\pythonw.exe" "D:\zjm_code\kml\a.py" Traceback (most recent call last): File "D:\zjm_code\kml\a.py", line 4, in &lt;module&gt; print a.index('s') ValueError: substring not found </code></pre> <p>thanks</p...
2
2010-04-07T06:48:26Z
2,590,550
<p>you can use <code>in</code> operator if you just want to check whether a substring is in a string.</p> <pre><code>if "s" in mystring: print "do something" </code></pre> <p>otherwise, you can use <code>find()</code> and check for -1 (not found) or using <code>index()</code></p>
3
2010-04-07T07:00:23Z
[ "python", "string" ]
how to find whether a string is contained in another string
2,590,503
<pre><code>a='1234;5' print a.index('s') </code></pre> <p>the error is :</p> <pre><code>&gt; "D:\Python25\pythonw.exe" "D:\zjm_code\kml\a.py" Traceback (most recent call last): File "D:\zjm_code\kml\a.py", line 4, in &lt;module&gt; print a.index('s') ValueError: substring not found </code></pre> <p>thanks</p...
2
2010-04-07T06:48:26Z
2,590,666
<p><code>str.find()</code> and <code>str.index()</code> are nearly identical. the biggest difference is that when a string is not found, <code>str.index()</code> throws an error, like the one you got, while <code>str.find()</code> returns -1 as others' have posted.</p> <p>there are 2 sister methods called <code>str.rf...
3
2010-04-07T07:27:00Z
[ "python", "string" ]
How to localize static content in database with Django
2,590,632
<p>My app has tables for languages and countries (actually <a href="http://code.google.com/p/django-countries/" rel="nofollow">django-countries</a> at the moment, but open for suggestions). The tables are populated when I initialize the database and remain static after that. </p> <p>What would be the ideal localizatio...
1
2010-04-07T07:21:31Z
2,590,745
<p>Maybe I'm missing something here, but why just not use [un]gettext, i.e. <code>{% trans lang_from_db %}</code> and <code>_(lang_from_db)</code>?</p> <p>Alternatively, hardcode language names translated in their own language into database, e.g "English", "Svenska", "Suomi", etc.</p>
0
2010-04-07T07:42:39Z
[ "python", "django", "localization" ]
Matplotlib: plotting discrete values
2,590,768
<p>I am trying to plot the following ! </p> <pre><code>from numpy import * from pylab import * import random for x in range(1,500): y = random.randint(1,25000) print(x,y) plot(x,y) show() </code></pre> <p>However, I keep getting a blank graph (?). Just to make sure that the program logic is correct I...
3
2010-04-07T07:48:01Z
2,590,800
<p>First of all, I have sometimes had better success by doing</p> <pre><code>from matplotlib import pyplot </code></pre> <p>instead of using pylab, although this shouldn't make a difference in this case.</p> <p>I think your actual issue might be that points are being plotted but aren't visible. It may work better to...
4
2010-04-07T07:55:07Z
[ "python", "matplotlib", "data-visualization" ]
Cant compile uwsgi under centos (fc10) with python2.6
2,590,870
<p>it`s normally build with python 2.5 BUT i need 2.6! 2.6 normally installed in /opt/python26 and successfully run as python2.6 in console.</p> <p>but </p> <pre><code>python2.6 uwsgiconfig.py --build </code></pre> <p>give me</p> <pre><code>*** uWSGI linking *** /usr/bin/ld: cannot find -lpython2.6 collect2: ld ret...
0
2010-04-07T08:10:12Z
2,592,615
<p>Try:</p> <pre><code>LD_LIBRARY_PATH="/somepath/" python2.6 uwsgiconfig.py --build </code></pre> <p>where <code>somepath</code> is the path to your <code>libpython2.6.so.x</code> file.</p> <p>Respectively update your <code>/etc/ld.so.conf</code> file and add the path to the libraries and run <code>ldconfig</code>....
1
2010-04-07T13:05:40Z
[ "python", "compilation", "wsgi", "uwsgi" ]
Cant compile uwsgi under centos (fc10) with python2.6
2,590,870
<p>it`s normally build with python 2.5 BUT i need 2.6! 2.6 normally installed in /opt/python26 and successfully run as python2.6 in console.</p> <p>but </p> <pre><code>python2.6 uwsgiconfig.py --build </code></pre> <p>give me</p> <pre><code>*** uWSGI linking *** /usr/bin/ld: cannot find -lpython2.6 collect2: ld ret...
0
2010-04-07T08:10:12Z
4,837,978
<p>Edit uwsgiconfig.py and set PYLIB_PATH to the path of the python lib directory.</p>
0
2011-01-29T16:30:38Z
[ "python", "compilation", "wsgi", "uwsgi" ]
Setting A Generator As The Argument Of A PyQt4 Signal
2,590,909
<p>I want to use a generator as the argument passed by a PyQt4 signal, and I am not sure as to the cleanest way. I could just do something like <code>elementChosen=QtCore.pyqtSignal(type((i for i in xrange (i))))</code>, but this just looks ugly. Any suggestions?</p>
1
2010-04-07T08:19:35Z
2,591,247
<p>You can use the <code>types</code> module to make the code look less ugly.</p> <pre><code>from types import GeneratorType elementChosen = QtCore.pyqtSignal(GeneratorType) </code></pre> <p>documentation: <a href="http://docs.python.org/library/types.html" rel="nofollow">http://docs.python.org/library/types.html</a...
1
2010-04-07T09:25:32Z
[ "python", "pyqt4" ]
Find next lower item in a sorted list
2,591,159
<p>let's say I have a sorted list of Floats. Now I'd like to get the index of the next lower item of a given value. The usual for-loop aprroach has a complexity of O(n). Since the list is sorted there must be a way to get the index with O(log n).</p> <p>My O(n) approach:</p> <pre><code>index=0 for i,value in enumerat...
8
2010-04-07T09:10:33Z
2,591,181
<p>You can do a binary search on an array/list to get the index of the object you're looking for and get the index below it to get the lower entry (given that there actually is a lower entry!).</p> <p>See: <a href="http://stackoverflow.com/questions/212358/binary-search-in-python">http://stackoverflow.com/questions/21...
10
2010-04-07T09:14:14Z
[ "python" ]
Find next lower item in a sorted list
2,591,159
<p>let's say I have a sorted list of Floats. Now I'd like to get the index of the next lower item of a given value. The usual for-loop aprroach has a complexity of O(n). Since the list is sorted there must be a way to get the index with O(log n).</p> <p>My O(n) approach:</p> <pre><code>index=0 for i,value in enumerat...
8
2010-04-07T09:10:33Z
2,591,271
<p>To answer part of the question about datatypes: In a general sense, the datatype most appropriate for finding things in O(log n) time (while maintaining O(1) performance on inserts and deletes!) is the binary tree. You can find things in it by making a series of left-right decisions, which is very analogous to how y...
1
2010-04-07T09:28:19Z
[ "python" ]
Find next lower item in a sorted list
2,591,159
<p>let's say I have a sorted list of Floats. Now I'd like to get the index of the next lower item of a given value. The usual for-loop aprroach has a complexity of O(n). Since the list is sorted there must be a way to get the index with O(log n).</p> <p>My O(n) approach:</p> <pre><code>index=0 for i,value in enumerat...
8
2010-04-07T09:10:33Z
2,591,322
<p>How about <a href="http://docs.python.org/library/bisect.html" rel="nofollow">bisect</a>?</p> <pre><code>&gt;&gt;&gt; import bisect &gt;&gt;&gt; float_list = [1.0, 1.3, 2.3, 4.5] &gt;&gt;&gt; i = bisect.bisect_left(float_list, 2.5) &gt;&gt;&gt; index = i - 1 &gt;&gt;&gt; index 2 </code></pre> <p>You might have to ...
12
2010-04-07T09:36:30Z
[ "python" ]
Find next lower item in a sorted list
2,591,159
<p>let's say I have a sorted list of Floats. Now I'd like to get the index of the next lower item of a given value. The usual for-loop aprroach has a complexity of O(n). Since the list is sorted there must be a way to get the index with O(log n).</p> <p>My O(n) approach:</p> <pre><code>index=0 for i,value in enumerat...
8
2010-04-07T09:10:33Z
2,591,334
<p>Use the <a href="http://docs.python.org/library/bisect.html" rel="nofollow">bisect</a> module. The function</p> <pre><code>bisect.bisect_left(mylist, compareValue) </code></pre> <p>returns the proper insertion point for item in list to maintain sorted order.</p>
2
2010-04-07T09:38:50Z
[ "python" ]
Find next lower item in a sorted list
2,591,159
<p>let's say I have a sorted list of Floats. Now I'd like to get the index of the next lower item of a given value. The usual for-loop aprroach has a complexity of O(n). Since the list is sorted there must be a way to get the index with O(log n).</p> <p>My O(n) approach:</p> <pre><code>index=0 for i,value in enumerat...
8
2010-04-07T09:10:33Z
2,709,682
<pre><code>import bisect def next_lower_value(values_list, input_value): index= bisect.bisect_left(values_list, input_value) if index == 0: # there's not a "next lower value" raise NotImplementedError # you must decide what to do here else: return values_list[index - 1] &gt;&gt;&gt; l= [11...
2
2010-04-25T19:50:09Z
[ "python" ]
Find next lower item in a sorted list
2,591,159
<p>let's say I have a sorted list of Floats. Now I'd like to get the index of the next lower item of a given value. The usual for-loop aprroach has a complexity of O(n). Since the list is sorted there must be a way to get the index with O(log n).</p> <p>My O(n) approach:</p> <pre><code>index=0 for i,value in enumerat...
8
2010-04-07T09:10:33Z
22,545,943
<p>If I'm reading this right, the next lower item is the first item in the list that's less than or equal to x. The <a href="http://docs.python.org/2/library/bisect.html#searching-sorted-lists" rel="nofollow">bisect documentation for searching sorted lists</a> gives this function:</p> <pre><code>def find_le(a, x): ...
1
2014-03-20T21:53:35Z
[ "python" ]
How do I write this Django model in SQL?
2,591,360
<p>I want to create a new column. How do I write this in SQL?</p> <pre><code>class mytable(models.Model): created_at = models.DateTimeField(auto_now_add=True) </code></pre>
0
2010-04-07T09:44:52Z
2,591,386
<pre><code>ALTER TABLE mytable ADD created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP; </code></pre>
0
2010-04-07T09:49:11Z
[ "python", "mysql", "database", "django" ]
How do I write this Django model in SQL?
2,591,360
<p>I want to create a new column. How do I write this in SQL?</p> <pre><code>class mytable(models.Model): created_at = models.DateTimeField(auto_now_add=True) </code></pre>
0
2010-04-07T09:44:52Z
2,591,413
<p>If you don't want to use South to manage this automatically - which is highly recommended, by the way - you can easily see what SQL you need by running <code>./manage.py sqlall &lt;appname&gt;</code>. This will show you all the SQL to create the models in your app, so you can find the definition of your new field th...
1
2010-04-07T09:53:46Z
[ "python", "mysql", "database", "django" ]
strip only html anchor tags
2,591,465
<p>i have following code that strip all tags. now i want to strip only anchor tags.</p> <pre><code>x = re.compile(r'&lt;[^&lt;]*?/?&gt;') </code></pre> <p>how to modify so that only anchor tags stripped.</p>
0
2010-04-07T10:03:33Z
2,591,488
<pre><code>x = re.compile(r'&lt;[aA]\&gt;[^&lt;]*?/?&gt;') </code></pre> <p>This will match the 'a' or 'A' followed by a word boundary. Note that it won't clean out the closing tag.</p> <pre><code>x = re.compile(r'&lt;/?[aA]\&gt;[^&lt;]*?/?&gt;') </code></pre> <p>will remove the closing tag as well.</p> <p><b>EDIT:...
1
2010-04-07T10:07:13Z
[ "python", "regex" ]
strip only html anchor tags
2,591,465
<p>i have following code that strip all tags. now i want to strip only anchor tags.</p> <pre><code>x = re.compile(r'&lt;[^&lt;]*?/?&gt;') </code></pre> <p>how to modify so that only anchor tags stripped.</p>
0
2010-04-07T10:03:33Z
2,591,765
<p>I'm not sure if this Python is correct (I'm a PHP guy but am just starting to learn python in my own time).</p> <pre><code>re.sub('&lt;[aA][^&gt;]*&gt;([^&lt;]+)&lt;/[aA]&gt;','\1','&lt;html&gt;&lt;head&gt; .... &lt;/body&gt;&lt;/html&gt;') </code></pre> <p>This won't remove all anchor tags in one shot, so you may...
1
2010-04-07T10:55:38Z
[ "python", "regex" ]
strip only html anchor tags
2,591,465
<p>i have following code that strip all tags. now i want to strip only anchor tags.</p> <pre><code>x = re.compile(r'&lt;[^&lt;]*?/?&gt;') </code></pre> <p>how to modify so that only anchor tags stripped.</p>
0
2010-04-07T10:03:33Z
2,591,862
<blockquote> <p>following code that strip all tags.</p> </blockquote> <p>Not really. <code>&lt;div title="a&gt;b"&gt;</code> is valid HTML and gets mangled. <code>&lt;div title="&lt;" onmouseover="script()" class="&lt;"&gt;"&gt;</code> is invalid HTML but the kind of thing you will often find on real web pages. Your...
5
2010-04-07T11:09:50Z
[ "python", "regex" ]
Getting a specific bit value in a byte string
2,591,483
<p>There is a byte at a specific index in a byte string which represents eight flags; one flag per bit in the byte. If a flag is set, its corresponding bit is 1, otherwise its 0. For example, if I've got</p> <pre><code>b'\x21' </code></pre> <p>the flags would be</p> <pre><code>0001 0101 # Three flags are set at i...
4
2010-04-07T10:06:30Z
2,591,499
<p>Specify bit masks (read about <a href="http://en.wikipedia.org/wiki/Bit_mask" rel="nofollow">bit masks on Wikipedia</a>):</p> <pre><code>FLAG_1 = 1 # 0000 0001 FLAG_2 = 2 # 0000 0010 FLAG_3 = 4 # 0000 0100 ... </code></pre> <p>And then use <code>AND</code> to check whether a bit is set (<code>flags</code> conta...
2
2010-04-07T10:09:17Z
[ "python", "binary", "byte" ]
Getting a specific bit value in a byte string
2,591,483
<p>There is a byte at a specific index in a byte string which represents eight flags; one flag per bit in the byte. If a flag is set, its corresponding bit is 1, otherwise its 0. For example, if I've got</p> <pre><code>b'\x21' </code></pre> <p>the flags would be</p> <pre><code>0001 0101 # Three flags are set at i...
4
2010-04-07T10:06:30Z
2,591,546
<p>x &amp; 1, x &amp; 2, x &amp; 4, x &amp; 8, etc</p> <p>if those are >0 then the bit 1,2,3,4, etc is set</p>
3
2010-04-07T10:16:41Z
[ "python", "binary", "byte" ]
Getting a specific bit value in a byte string
2,591,483
<p>There is a byte at a specific index in a byte string which represents eight flags; one flag per bit in the byte. If a flag is set, its corresponding bit is 1, otherwise its 0. For example, if I've got</p> <pre><code>b'\x21' </code></pre> <p>the flags would be</p> <pre><code>0001 0101 # Three flags are set at i...
4
2010-04-07T10:06:30Z
2,591,555
<p>Typically, the least-significant bit is bit index 0 and the most-significant bit is bit index 7. Using this terminology, we can determine if bit index k is set by taking the bitwise-and with 1 shifted to the left by k. If the bitwise and is non-zero, then that means that index k has a 1; otherwise, index k has a 0. ...
18
2010-04-07T10:17:59Z
[ "python", "binary", "byte" ]
Non-ASCII character Syntax Error in Python while calling URL
2,591,580
<p>How can data can be sent to the server?</p> <p>For example, I have retrieve MAC address, so I want send to the server (e.g. <a href="http://211.21.24.43:8080/data?mac=00-0C-F1-56-98-AD" rel="nofollow">http://211.21.24.43:8080/data?mac=00-0C-F1-56-98-AD</a>)</p> <p>I found this snippet on the Internet:</p> <pre><c...
1
2010-04-07T10:23:06Z
2,591,625
<p>You have copied and pasted code with non-ASCII characters. You have an <code>\xc3</code> character on line 8.</p>
-9
2010-04-07T10:29:29Z
[ "python", "osx" ]
Non-ASCII character Syntax Error in Python while calling URL
2,591,580
<p>How can data can be sent to the server?</p> <p>For example, I have retrieve MAC address, so I want send to the server (e.g. <a href="http://211.21.24.43:8080/data?mac=00-0C-F1-56-98-AD" rel="nofollow">http://211.21.24.43:8080/data?mac=00-0C-F1-56-98-AD</a>)</p> <p>I found this snippet on the Internet:</p> <pre><c...
1
2010-04-07T10:23:06Z
5,307,764
<p>put the encoding at the top of .py file</p> <p>example:</p> <pre><code>#!/usr/bin/env python #coding: utf8 import os ... </code></pre> <p>This probably happened because you copied/pasted some unicode character that is not visible in your text editor.</p>
23
2011-03-15T05:13:22Z
[ "python", "osx" ]
Non-ASCII character Syntax Error in Python while calling URL
2,591,580
<p>How can data can be sent to the server?</p> <p>For example, I have retrieve MAC address, so I want send to the server (e.g. <a href="http://211.21.24.43:8080/data?mac=00-0C-F1-56-98-AD" rel="nofollow">http://211.21.24.43:8080/data?mac=00-0C-F1-56-98-AD</a>)</p> <p>I found this snippet on the Internet:</p> <pre><c...
1
2010-04-07T10:23:06Z
16,037,976
<p>Incorrect characters are probably "comma", or "quotes" on line 8. It probably occurred during the "Ctrl + C", "Ctrl + V". ;) You can try rewrite these characters manually.</p>
1
2013-04-16T13:10:18Z
[ "python", "osx" ]
Non-ASCII character Syntax Error in Python while calling URL
2,591,580
<p>How can data can be sent to the server?</p> <p>For example, I have retrieve MAC address, so I want send to the server (e.g. <a href="http://211.21.24.43:8080/data?mac=00-0C-F1-56-98-AD" rel="nofollow">http://211.21.24.43:8080/data?mac=00-0C-F1-56-98-AD</a>)</p> <p>I found this snippet on the Internet:</p> <pre><c...
1
2010-04-07T10:23:06Z
19,333,516
<p>this solution works for me on Ubuntu.</p> <p>Add the following statement right at the begining, before all import statements.</p> <p># -<em>- coding: utf-8 -</em>-</p> <p>Similar approach for errors with the term '\xe2'.</p>
5
2013-10-12T11:14:04Z
[ "python", "osx" ]
Itertools group by functionality
2,591,621
<p>I want to group by on dict key</p> <pre><code>&gt;&gt;&gt; x [{'a': 10, 'b': 90}, {'a': 20}, {'a': 30}, {'a': 10}] &gt;&gt;&gt; [(name, list(group)) for name, group in groupby(x, lambda p:p['a'])] [(10, [{'a': 10, 'b': 90}]), (20, [{'a': 20}]), (30, [{'a': 30}]), (10, [{'a': 10}])] </code></pre> <p>This must group...
-1
2010-04-07T10:29:02Z
2,591,633
<p><a href="http://docs.python.org/library/itertools.html#itertools.groupby" rel="nofollow">docs say</a>:</p> <blockquote> <p><code>itertools.groupby</code>:<br> It generates a break or new group every time the value of the key function changes (which is why it is usually <strong>necessary to have sorted the data ...
4
2010-04-07T10:30:51Z
[ "python", "itertools" ]
Deploying Django (fastcgi, apache mod_wsgi, uwsgi, gunicorn)
2,591,715
<p>Can someone explain the difference between apache mod_wsgi in daemon mode and django fastcgi in threaded mode. They both use threads for concurrency I think. <strong>Supposing that I'm using nginx as front end to apache mod_wsgi.</strong></p> <p><strong>UPDATE:</strong></p> <p>I'm comparing django built in fastcgi...
15
2010-04-07T10:46:42Z
2,591,927
<p>Neither have to use threads to be able to handle concurrent requests. It depends on how you configure them. You can use multiple processes where each is single threaded if you want.</p> <p>For more background on mod_wsgi process/threading models see:</p> <p><a href="http://code.google.com/p/modwsgi/wiki/ProcessesA...
10
2010-04-07T11:22:10Z
[ "python", "django", "deployment", "fastcgi", "mod-wsgi" ]
Search a variable for an address
2,591,832
<p>I am trying to match information stored in a variable. I have a list of uuid's and ip addresses beside them. The code I have is:</p> <pre><code>r = re.compile(r'urn:uuid:5EEF382F-JSQ9-3c45-D5E0-K15X8M8K76') m = r.match(str(serv)) if m1: print'Found' </code></pre> <p>The string serv contains is:</p> <pre><cod...
0
2010-04-07T11:05:29Z
2,591,873
<pre><code>r = re.compile(r"urn:uuid:5EEF382F-JSQ9-3c45-D5E0-K15X8M8K76:\[u'(.*)'\]") m = r.search(str(serv)) if m: print 'Found', m.group(1) </code></pre>
2
2010-04-07T11:12:07Z
[ "python", "regex" ]
Search a variable for an address
2,591,832
<p>I am trying to match information stored in a variable. I have a list of uuid's and ip addresses beside them. The code I have is:</p> <pre><code>r = re.compile(r'urn:uuid:5EEF382F-JSQ9-3c45-D5E0-K15X8M8K76') m = r.match(str(serv)) if m1: print'Found' </code></pre> <p>The string serv contains is:</p> <pre><cod...
0
2010-04-07T11:05:29Z
2,591,878
<p>your regex is very simple, so much so that there's no need to use regular expression at all.</p> <pre><code>&gt;&gt;&gt; serv=""" ... urn:uuid:7FDS890A-KD9E-3h53-G7E8-BHJSD6789D:[u'http://10.10.10.20:12365/7FDS890A-KD9E-3h53-G7E8-BHJSD6789D/'] ... --------------------------------------------- ... urn:uuid:5EEF382F-...
1
2010-04-07T11:12:56Z
[ "python", "regex" ]
Comparing a time delta in python
2,591,845
<p>I have a variable which is <code>&lt;type 'datetime.timedelta'&gt;</code> and I would like to compare it against certain values. </p> <p>Lets say d produces this <code>datetime.timedelta</code> value <code>0:00:01.782000</code></p> <p>I would like to compare it like this:</p> <pre><code>#if d is greater than 1 mi...
32
2010-04-07T11:07:49Z
2,591,864
<p>You'll have to <a href="http://docs.python.org/library/datetime.html#datetime.timedelta">create a new <code>timedelta</code></a> with the specified amount of time:</p> <pre><code>d &gt; timedelta(minutes=1) </code></pre> <p>Or this slightly more complete script will help elaborate:</p> <pre><code>import datetime ...
47
2010-04-07T11:10:20Z
[ "python", "datetime", "timedelta" ]
Comparing a time delta in python
2,591,845
<p>I have a variable which is <code>&lt;type 'datetime.timedelta'&gt;</code> and I would like to compare it against certain values. </p> <p>Lets say d produces this <code>datetime.timedelta</code> value <code>0:00:01.782000</code></p> <p>I would like to compare it like this:</p> <pre><code>#if d is greater than 1 mi...
32
2010-04-07T11:07:49Z
2,591,875
<p>You just need to create <code>timedelta</code> object from scratch, comparison after that is trivial:</p> <pre><code>&gt;&gt;&gt; a = datetime.timedelta(minutes=1) &gt;&gt;&gt; b = datetime.timedelta(minutes=1, seconds=1) &gt;&gt;&gt; a &lt; b True &gt;&gt;&gt; a &gt; b False </code></pre>
9
2010-04-07T11:12:16Z
[ "python", "datetime", "timedelta" ]
Comparing a time delta in python
2,591,845
<p>I have a variable which is <code>&lt;type 'datetime.timedelta'&gt;</code> and I would like to compare it against certain values. </p> <p>Lets say d produces this <code>datetime.timedelta</code> value <code>0:00:01.782000</code></p> <p>I would like to compare it like this:</p> <pre><code>#if d is greater than 1 mi...
32
2010-04-07T11:07:49Z
16,570,408
<p>Correct me if I'm wrong but I think that you could also use the following:</p> <p>Instead of </p> <pre><code>if elapsed &gt; datetime.timedelta(seconds=1): </code></pre> <p>You could say </p> <pre><code>if elapsed.seconds &gt; 1: </code></pre>
3
2013-05-15T16:30:45Z
[ "python", "datetime", "timedelta" ]
Comparing a time delta in python
2,591,845
<p>I have a variable which is <code>&lt;type 'datetime.timedelta'&gt;</code> and I would like to compare it against certain values. </p> <p>Lets say d produces this <code>datetime.timedelta</code> value <code>0:00:01.782000</code></p> <p>I would like to compare it like this:</p> <pre><code>#if d is greater than 1 mi...
32
2010-04-07T11:07:49Z
36,260,019
<pre><code>if d.total_seconds() &gt; 60: print("elapsed time is greater than 1 minute") </code></pre> <p>but it requires python 2.7+</p>
0
2016-03-28T10:02:59Z
[ "python", "datetime", "timedelta" ]
call a server side python script from javascript
2,591,846
<p>how to call a server side python script from javascript. if test.py is the python script file in server, and if the parameter to be passed to python is another url , then how this can be executed from javascript, how the return string from python script is obtained to the javascript.</p>
3
2010-04-07T11:07:56Z
2,591,895
<p>You can directly call the python script from javascript. You need to use an appropriate server-side technology (asp.net, php, servlet). The best solution will be to create a REST service, by defining a URL, which when called (through ajax for example) will execute the python script and write the output to the body o...
3
2010-04-07T11:15:30Z
[ "javascript", "python" ]
PyPy -- How can it possibly beat CPython?
2,591,879
<p>From the <a href="http://google-opensource.blogspot.com/2010/04/pypy-12-released.html">Google Open Source Blog</a>:</p> <blockquote> <p>PyPy is a reimplementation of Python in Python, using advanced techniques to try to attain better performance than CPython. Many years of hard work have finally paid off....
187
2010-04-07T11:13:02Z
2,591,909
<p>PyPy is implemented in Python, but it implements a JIT compiler to generate native code on the fly.</p> <p>The reason to implement PyPy on top of Python is probably that it is simply a very productive language, especially since the JIT compiler makes the host language's performance somewhat irrelevant.</p>
21
2010-04-07T11:17:56Z
[ "python", "pypy", "language-implementation" ]
PyPy -- How can it possibly beat CPython?
2,591,879
<p>From the <a href="http://google-opensource.blogspot.com/2010/04/pypy-12-released.html">Google Open Source Blog</a>:</p> <blockquote> <p>PyPy is a reimplementation of Python in Python, using advanced techniques to try to attain better performance than CPython. Many years of hard work have finally paid off....
187
2010-04-07T11:13:02Z
2,592,094
<p><strong>Q1. How is this possible?</strong></p> <p>Manual memory management (which is what CPython does with its counting) can be slower than automatic management in some cases. </p> <p>Limitations in the implementation of the CPython interpreter preclude certain optimisations that PyPy can do (eg. fine grained loc...
122
2010-04-07T11:48:51Z
[ "python", "pypy", "language-implementation" ]
PyPy -- How can it possibly beat CPython?
2,591,879
<p>From the <a href="http://google-opensource.blogspot.com/2010/04/pypy-12-released.html">Google Open Source Blog</a>:</p> <blockquote> <p>PyPy is a reimplementation of Python in Python, using advanced techniques to try to attain better performance than CPython. Many years of hard work have finally paid off....
187
2010-04-07T11:13:02Z
4,221,966
<p>PyPy is written in Restricted Python. It does not run on top of the CPython interpreter, as far as I know. Restricted Python is a subset of the Python language. AFAIK, the PyPy interpreter is compiled to machine code, so when installed it does not utilize a python interpreter at runtime.</p> <p>Your question seems ...
11
2010-11-19T03:58:23Z
[ "python", "pypy", "language-implementation" ]
PyPy -- How can it possibly beat CPython?
2,591,879
<p>From the <a href="http://google-opensource.blogspot.com/2010/04/pypy-12-released.html">Google Open Source Blog</a>:</p> <blockquote> <p>PyPy is a reimplementation of Python in Python, using advanced techniques to try to attain better performance than CPython. Many years of hard work have finally paid off....
187
2010-04-07T11:13:02Z
8,797,731
<p>"PyPy is a reimplementation of Python in Python" is a rather misleading way to describe PyPy, IMHO, although it's technically true.</p> <p>There are two major parts of PyPy.</p> <ol> <li>The translation framework</li> <li>The interpreter</li> </ol> <p>The translation framework is a compiler. It compiles <strong>R...
221
2012-01-10T02:07:14Z
[ "python", "pypy", "language-implementation" ]
Python: Converting a tuple to a string
2,592,045
<p>Given this :</p> <pre><code>import os import subprocess def check_server(): cl = subprocess.Popen(["nmap","10.7.1.71"], stdout=subprocess.PIPE) result = cl.communicate() print result check_server() </code></pre> <p>check_server() returns this tuple: </p> <pre><code>('\nStarting Nmap 4.53 ( http://...
0
2010-04-07T11:39:05Z
2,592,052
<p><code>cl.communicate()</code> is still returning a tuple. The assignment <code>result, err = ...</code> has the effect of unpacking the tuple into the variables <code>result</code> (a string) and <code>err</code> (an integer).</p> <p>When you print the tuple, it uses the <code>repr(...)</code> of each element, but ...
6
2010-04-07T11:40:54Z
[ "python", "string", "tuples" ]
Python: Converting a tuple to a string
2,592,045
<p>Given this :</p> <pre><code>import os import subprocess def check_server(): cl = subprocess.Popen(["nmap","10.7.1.71"], stdout=subprocess.PIPE) result = cl.communicate() print result check_server() </code></pre> <p>check_server() returns this tuple: </p> <pre><code>('\nStarting Nmap 4.53 ( http://...
0
2010-04-07T11:39:05Z
2,592,063
<p><code>print</code> is clever. If you pass it a string, it just prints it. If you pass it something else (a tuple in this example) then it prints it's representation (as returned by <code>repr()</code>).</p> <p>The representation of a string has <code>\n</code> where the string contains newlines. The representati...
1
2010-04-07T11:43:18Z
[ "python", "string", "tuples" ]
Python: Converting a tuple to a string
2,592,045
<p>Given this :</p> <pre><code>import os import subprocess def check_server(): cl = subprocess.Popen(["nmap","10.7.1.71"], stdout=subprocess.PIPE) result = cl.communicate() print result check_server() </code></pre> <p>check_server() returns this tuple: </p> <pre><code>('\nStarting Nmap 4.53 ( http://...
0
2010-04-07T11:39:05Z
2,592,075
<p>In both cases <code>cl.communicate()</code> returns a two-element tuple (stdout and stderr of the command if both stdout and stderr are redirected to a PIPE). In first case you assign this tuple to the <code>result</code> variable. When you print it you get a text representation of the tuple. Special characters, lik...
4
2010-04-07T11:44:29Z
[ "python", "string", "tuples" ]
Django User M2M relationship
2,592,187
<p>When trying to syncdb with the following models:</p> <pre><code>class Contact(models.Model): user_from = models.ForeignKey(User,related_name='from_user') user_to = models.ForeignKey(User, related_name='to_user') class Meta: unique_together = (('user_from', 'user_to'),) User.add_to_class('follo...
4
2010-04-07T12:01:21Z
5,293,907
<p>See Carl's answer to this question <a href="http://stackoverflow.com/questions/1036506/django-model-name-clash">Django: Model name clash</a></p>
0
2011-03-14T01:39:45Z
[ "python", "django", "django-models" ]
How to use ';' (semicolon) in urls, using Google Appengine
2,592,540
<p>Using the local dev server, I can use ';' in urls, but as soon as I try the live version hosted by Google, it looks like the ';' and everything afterward is stripped (at least according to <code>request.path_qs</code>).</p> <p>(I would prefer not to encode them if possible, it's much less user friendly if the url c...
2
2010-04-07T12:54:00Z
2,592,595
<p>It is a known issue: <a href="http://code.google.com/p/googleappengine/issues/detail?id=816" rel="nofollow">http://code.google.com/p/googleappengine/issues/detail?id=816</a><br> So I am afraid you need to use a workaround.</p>
3
2010-04-07T13:01:55Z
[ "python", "google-app-engine", "url" ]
How to use ';' (semicolon) in urls, using Google Appengine
2,592,540
<p>Using the local dev server, I can use ';' in urls, but as soon as I try the live version hosted by Google, it looks like the ';' and everything afterward is stripped (at least according to <code>request.path_qs</code>).</p> <p>(I would prefer not to encode them if possible, it's much less user friendly if the url c...
2
2010-04-07T12:54:00Z
5,877,046
<p>Issue816 has now been fixed, semi-colons are usable with appengine.</p>
0
2011-05-03T23:54:06Z
[ "python", "google-app-engine", "url" ]
Rewriting a for loop in pure NumPy to decrease execution time
2,592,696
<p>I <a href="http://stackoverflow.com/questions/2586749/what-is-the-most-platform-and-python-version-independent-way-to-make-a-fast-loop" title="StackOverflow: What is the most platform- and Python-version-independent way to make a fast loop for use in Python?">recently asked about trying to optimise a Python loop for...
7
2010-04-07T13:19:17Z
2,592,846
<p>One obvious thing you can do is replace the line</p> <pre><code>r_test_fast = reshape_vector(r_test) </code></pre> <p>with</p> <pre><code>r_test_fast = r_test.reshape((3,1)) </code></pre> <p>Probably won't make any big difference in performance, but in any case it makes sense to use the numpy builtins instead of...
2
2010-04-07T13:38:17Z
[ "python", "optimization", "numpy", "physics" ]
Rewriting a for loop in pure NumPy to decrease execution time
2,592,696
<p>I <a href="http://stackoverflow.com/questions/2586749/what-is-the-most-platform-and-python-version-independent-way-to-make-a-fast-loop" title="StackOverflow: What is the most platform- and Python-version-independent way to make a fast loop for use in Python?">recently asked about trying to optimise a Python loop for...
7
2010-04-07T13:19:17Z
2,593,663
<p>If you <a href="http://docs.python.org/library/profile.html" rel="nofollow">profile</a> your code, you'll see that 99% of the running time is in <code>calculate_dipole</code> so reducing the time for this looping really won't give a noticeable reduction in execution time. You still need to focus on calculate_dipole ...
2
2010-04-07T15:18:37Z
[ "python", "optimization", "numpy", "physics" ]
What does a b prefix before a python string mean?
2,592,764
<p>In a python source code I stumbled upon I've seen a small <strong>b</strong> before a string like in:</p> <pre><code>b"abcdef" </code></pre> <p>I know about the <strong><code>u</code></strong> prefix signifying a unicode string, and the <strong><code>r</code></strong> prefix for a raw string literal. </p> <p>What...
43
2010-04-07T13:28:36Z
2,592,818
<p>This is Python3 <code>bytes</code> <a href="http://docs.python.org/py3k/reference/lexical_analysis.html#literals">literal</a>. This prefix is absent in Python 2.5 and older (it is equivalent to a plain string of 2.x, while plain string of 3.x is equivalent to a literal with <code>u</code> prefix in 2.x). In Python 2...
35
2010-04-07T13:34:28Z
[ "python", "syntax", "python-3.x", "byte" ]
What does a b prefix before a python string mean?
2,592,764
<p>In a python source code I stumbled upon I've seen a small <strong>b</strong> before a string like in:</p> <pre><code>b"abcdef" </code></pre> <p>I know about the <strong><code>u</code></strong> prefix signifying a unicode string, and the <strong><code>r</code></strong> prefix for a raw string literal. </p> <p>What...
43
2010-04-07T13:28:36Z
24,099,252
<p>The <code>b</code> prefix signifies a <a href="https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals"><code>bytes</code> string literal</a>.</p> <p>If you see it used in Python 3 source code, the expression creates a <a href="https://docs.python.org/3/library/stdtypes.html#bytes"><code...
17
2014-06-07T16:25:37Z
[ "python", "syntax", "python-3.x", "byte" ]
How can I skip the current item and the next in a Python loop?
2,592,798
<p>This might be a really dumb question, however I've looked around online, etc. And have not seen a solid answer.</p> <p>Is there a simple way to do something like this?</p> <pre><code>lines = open('something.txt', 'r').readlines() for line in lines: if line == '!': # force iteration forward twice ...
12
2010-04-07T13:31:53Z
2,592,826
<p>Not very compact:</p> <pre><code>skip = False for line in open('something.txt'): if skip: skip = False continue if line.strip() == '!': skip = True continue </code></pre>
1
2010-04-07T13:35:46Z
[ "python" ]
How can I skip the current item and the next in a Python loop?
2,592,798
<p>This might be a really dumb question, however I've looked around online, etc. And have not seen a solid answer.</p> <p>Is there a simple way to do something like this?</p> <pre><code>lines = open('something.txt', 'r').readlines() for line in lines: if line == '!': # force iteration forward twice ...
12
2010-04-07T13:31:53Z
2,592,845
<p>You could use recursion</p> <pre><code>input = iter( open('something.txt') ) def myFunc( item ): val = iter.next() if( val == '!' ): item.next() return myFunc( item ) #continue on with looping logic </code></pre> <p>Editted post contained the following which actually didn't answer your ...
0
2010-04-07T13:38:05Z
[ "python" ]
How can I skip the current item and the next in a Python loop?
2,592,798
<p>This might be a really dumb question, however I've looked around online, etc. And have not seen a solid answer.</p> <p>Is there a simple way to do something like this?</p> <pre><code>lines = open('something.txt', 'r').readlines() for line in lines: if line == '!': # force iteration forward twice ...
12
2010-04-07T13:31:53Z
2,592,879
<p>Try:</p> <pre><code>lines = iter(open('something.txt', 'r')) for val in lines: if val == "!": lines.next() continue &lt;etc&gt; </code></pre> <p>You may want to catch <code>StopIteration</code> somewhere. It'll occur if the iterator is finished.</p>
22
2010-04-07T13:42:52Z
[ "python" ]
How can I skip the current item and the next in a Python loop?
2,592,798
<p>This might be a really dumb question, however I've looked around online, etc. And have not seen a solid answer.</p> <p>Is there a simple way to do something like this?</p> <pre><code>lines = open('something.txt', 'r').readlines() for line in lines: if line == '!': # force iteration forward twice ...
12
2010-04-07T13:31:53Z
2,592,892
<p>The file.readlines method returns a list of strings, and iterating over a list will not let you modify the iteration in the body of the loop. However if you call iter on the list first then you will get an iterator that you can modify in the loop body:</p> <pre><code>lines = open('something.txt', 'r').readlines() ...
5
2010-04-07T13:44:14Z
[ "python" ]
How can I skip the current item and the next in a Python loop?
2,592,798
<p>This might be a really dumb question, however I've looked around online, etc. And have not seen a solid answer.</p> <p>Is there a simple way to do something like this?</p> <pre><code>lines = open('something.txt', 'r').readlines() for line in lines: if line == '!': # force iteration forward twice ...
12
2010-04-07T13:31:53Z
2,593,100
<p>This is short, pythonic, and works:</p> <pre><code>with open('something.txt', 'r') as f: # or simply f = open('something.txt', 'r') nobang = (line for line in f if line != '!\n') for line in nobang: #... </code></pre> <p>Edit:</p> <p>As many observed, this is not the solution yet. The best I can t...
7
2010-04-07T14:06:55Z
[ "python" ]
How to know if optparse option was passed in the command line or as a default
2,593,257
<p>Using python optparse.py, is there a way to work out whether a specific option value was set from the command line or from the default value. </p> <p>Ideally I would like to have a dict just like defaults, but containing the options actually supplied from command line </p> <p>I know that you could compare the valu...
6
2010-04-07T14:27:43Z
2,593,459
<p>Not knowing you code is impossible to give the better answer, but...</p> <ol> <li><p>simply don't pass defaults to the parser and check for <code>None</code> values. A <code>None</code> value is a default for <code>optparse</code> lib so you can retrieve your own default and act as usually;</p></li> <li><p>extend <...
3
2010-04-07T14:54:23Z
[ "python", "optparse" ]
How to know if optparse option was passed in the command line or as a default
2,593,257
<p>Using python optparse.py, is there a way to work out whether a specific option value was set from the command line or from the default value. </p> <p>Ideally I would like to have a dict just like defaults, but containing the options actually supplied from command line </p> <p>I know that you could compare the valu...
6
2010-04-07T14:27:43Z
11,298,708
<p>In this example <em>v</em> will keep only the options that were passed:</p> <pre><code>v = optparse.Values() options, args = parser.parse_args(values=v) print v.__dict__ </code></pre>
4
2012-07-02T17:55:45Z
[ "python", "optparse" ]
How to know if optparse option was passed in the command line or as a default
2,593,257
<p>Using python optparse.py, is there a way to work out whether a specific option value was set from the command line or from the default value. </p> <p>Ideally I would like to have a dict just like defaults, but containing the options actually supplied from command line </p> <p>I know that you could compare the valu...
6
2010-04-07T14:27:43Z
23,433,897
<pre><code>def is_opt_provided (parser, dest): if any (opt.dest == dest and (opt._long_opts[0] in sys.argv[1:] or opt._short_opts[0] in sys.argv[1:]) for opt in parser._get_all_options()): return True return False </code></pre> <p>Usage:</p> <pre><code>parser = OptionsParser() parser.add_option('-o', ...
1
2014-05-02T17:37:56Z
[ "python", "optparse" ]
Process a set of files from a source directory to a destination directory in Python
2,593,399
<p>Being <em>completely new</em> in python I'm trying to run a command over a set of files in python. The command requires both source and destination file (I'm actually using imagemagick <code>convert</code> as in the example below).</p> <p>I can supply both source and destination directories, however I can't figure ...
2
2010-04-07T14:45:51Z
2,593,486
<p>While not pretty, this will preserve the directory structure of the tree:</p> <pre><code>_, _, subdirs = root.partition(srcdir) destfile = os.path.join(destdir, subdirs[1:], filename) </code></pre>
0
2010-04-07T14:58:24Z
[ "python", "path" ]
Process a set of files from a source directory to a destination directory in Python
2,593,399
<p>Being <em>completely new</em> in python I'm trying to run a command over a set of files in python. The command requires both source and destination file (I'm actually using imagemagick <code>convert</code> as in the example below).</p> <p>I can supply both source and destination directories, however I can't figure ...
2
2010-04-07T14:45:51Z
2,593,614
<p>Change your loop to:</p> <pre><code>for root, dirs, files in os.walk(srcdir): destroot = os.path.join(destdir, root[len(srcdir):]) for adir in dirs: os.makedirs(os.path.join(destroot, adir)) for filename in files: sourceFile = os.path.join(root, filename) destFile = os.path.join(...
2
2010-04-07T15:13:01Z
[ "python", "path" ]
Process a set of files from a source directory to a destination directory in Python
2,593,399
<p>Being <em>completely new</em> in python I'm trying to run a command over a set of files in python. The command requires both source and destination file (I'm actually using imagemagick <code>convert</code> as in the example below).</p> <p>I can supply both source and destination directories, however I can't figure ...
2
2010-04-07T14:45:51Z
2,593,968
<p>There are a few relative path scripts out there that will do what you want -- namely find the relative path between two paths. E.g.:</p> <ul> <li><a href="http://www.voidspace.org.uk/python/pathutils.html" rel="nofollow">http://www.voidspace.org.uk/python/pathutils.html</a> <strong>(relpath method)</strong></li> <...
1
2010-04-07T16:03:00Z
[ "python", "path" ]
How should I write this string-prefix check so that it's idiomatic Python?
2,593,496
<p>I have a couple of lists of items:</p> <pre><code>specials = ['apple', 'banana', 'cherry', ...] smoothies = ['banana-apple', 'mocha mango', ...] </code></pre> <p>I want to make a new list, <code>special_smoothies</code>, consisting of elements in <code>smoothies</code> that start with the elements in <code>specia...
1
2010-04-07T14:59:53Z
2,593,623
<p>There are a couple of ways to do it without an explicit check on <code>specials</code>. But don't do them.</p> <pre><code>if specials: special_smoothies = [x for x in smoothies if any(True for y in specials if x.startswith(y))] else: special_smoothies = smoothies[:] </code></pre>
3
2010-04-07T15:13:51Z
[ "python", "string", "list" ]
How should I write this string-prefix check so that it's idiomatic Python?
2,593,496
<p>I have a couple of lists of items:</p> <pre><code>specials = ['apple', 'banana', 'cherry', ...] smoothies = ['banana-apple', 'mocha mango', ...] </code></pre> <p>I want to make a new list, <code>special_smoothies</code>, consisting of elements in <code>smoothies</code> that start with the elements in <code>specia...
1
2010-04-07T14:59:53Z
2,593,638
<p>Since you want the behavior for empty specials to be different from the natural limit of the behavior for non-empty, you do need to special-case:</p> <pre><code>if specials: specialsmoothies = [x for x in smoothies if any(x.startswith(y) for y in specials)] else: specialsmoothies = l...
4
2010-04-07T15:15:21Z
[ "python", "string", "list" ]
How should I write this string-prefix check so that it's idiomatic Python?
2,593,496
<p>I have a couple of lists of items:</p> <pre><code>specials = ['apple', 'banana', 'cherry', ...] smoothies = ['banana-apple', 'mocha mango', ...] </code></pre> <p>I want to make a new list, <code>special_smoothies</code>, consisting of elements in <code>smoothies</code> that start with the elements in <code>specia...
1
2010-04-07T14:59:53Z
2,593,672
<p>Why complicate things? I think this is the most readable. Alex and Ignacio both give good reasons for not avoiding the <code>else</code> clause.</p> <pre><code>special_smoothies = [] if specials: for smoothy in smoothies: for special in specials: if smoothy.startswith(special): ...
0
2010-04-07T15:20:23Z
[ "python", "string", "list" ]
How should I write this string-prefix check so that it's idiomatic Python?
2,593,496
<p>I have a couple of lists of items:</p> <pre><code>specials = ['apple', 'banana', 'cherry', ...] smoothies = ['banana-apple', 'mocha mango', ...] </code></pre> <p>I want to make a new list, <code>special_smoothies</code>, consisting of elements in <code>smoothies</code> that start with the elements in <code>specia...
1
2010-04-07T14:59:53Z
2,594,612
<p><a href="http://docs.python.org/library/stdtypes.html#str.startswith" rel="nofollow"><code>str.startswith()</code></a> accepts tuple as an argument:</p> <pre><code>if specials: specialsmoothies = [x for x in smoothies if x.startswith(tuple(specials))] else: specialsmoothies = list(smoothies) </code></pre>
1
2010-04-07T17:39:51Z
[ "python", "string", "list" ]