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 |
|---|---|---|---|---|---|---|---|---|---|
Add params to given URL in Python | 2,506,379 | <p>Suppose I was given a URL.<br>
It might already have GET parameters (e.g. <code>http://example.com/search?q=question</code>) or it might not (e.g. <code>http://example.com/</code>).</p>
<p>And now I need to add some parameters to it like <code>{'lang':'en','tag':'python'}</code>. In the first case I'm going to have... | 61 | 2010-03-24T09:06:21Z | 2,506,398 | <p>Yes: use <a href="http://docs.python.org/library/urllib.html">urllib</a>.</p>
<p>From the <a href="http://docs.python.org/library/urllib.html#examples">examples</a> in the documentation:</p>
<pre><code>>>> import urllib
>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>>... | 7 | 2010-03-24T09:10:24Z | [
"python",
"url"
] |
Add params to given URL in Python | 2,506,379 | <p>Suppose I was given a URL.<br>
It might already have GET parameters (e.g. <code>http://example.com/search?q=question</code>) or it might not (e.g. <code>http://example.com/</code>).</p>
<p>And now I need to add some parameters to it like <code>{'lang':'en','tag':'python'}</code>. In the first case I'm going to have... | 61 | 2010-03-24T09:06:21Z | 2,506,422 | <p>Use the various <a href="http://docs.python.org/library/urlparse.html" rel="nofollow"><code>urlparse</code></a> functions to tear apart the existing URL, <a href="http://docs.python.org/library/urllib.html#urllib.urlencode" rel="nofollow"><code>urllib.urlencode()</code></a> on the combined dictionary, then <code>url... | 3 | 2010-03-24T09:14:10Z | [
"python",
"url"
] |
Add params to given URL in Python | 2,506,379 | <p>Suppose I was given a URL.<br>
It might already have GET parameters (e.g. <code>http://example.com/search?q=question</code>) or it might not (e.g. <code>http://example.com/</code>).</p>
<p>And now I need to add some parameters to it like <code>{'lang':'en','tag':'python'}</code>. In the first case I'm going to have... | 61 | 2010-03-24T09:06:21Z | 2,506,425 | <p>You want to use URL encoding if the strings can have arbitrary data (for example, characters such as ampersands, slashes, etc. will need to be encoded).</p>
<p>Check out urllib.urlencode:</p>
<pre><code>>>> import urllib
>>> urllib.urlencode({'lang':'en','tag':'python'})
'lang=en&tag=python'
... | 28 | 2010-03-24T09:15:15Z | [
"python",
"url"
] |
Add params to given URL in Python | 2,506,379 | <p>Suppose I was given a URL.<br>
It might already have GET parameters (e.g. <code>http://example.com/search?q=question</code>) or it might not (e.g. <code>http://example.com/</code>).</p>
<p>And now I need to add some parameters to it like <code>{'lang':'en','tag':'python'}</code>. In the first case I'm going to have... | 61 | 2010-03-24T09:06:21Z | 2,506,477 | <p>There are couple quirks with urllib and urlparse modules. Here's working example:</p>
<pre><code>try:
import urlparse
from urllib import urlencode
except: # For Python 3
import urllib.parse as urlparse
from urllib.parse import urlencode
url = "http://stackoverflow.com/search?q=question"
params = {'... | 100 | 2010-03-24T09:23:15Z | [
"python",
"url"
] |
Add params to given URL in Python | 2,506,379 | <p>Suppose I was given a URL.<br>
It might already have GET parameters (e.g. <code>http://example.com/search?q=question</code>) or it might not (e.g. <code>http://example.com/</code>).</p>
<p>And now I need to add some parameters to it like <code>{'lang':'en','tag':'python'}</code>. In the first case I'm going to have... | 61 | 2010-03-24T09:06:21Z | 4,778,023 | <p>In python 2.5</p>
<pre><code>import cgi
import urllib
import urlparse
def add_url_param(url, **params):
n=3
parts = list(urlparse.urlsplit(url))
d = dict(cgi.parse_qsl(parts[n])) # use cgi.parse_qs for list values
d.update(params)
parts[n]=urllib.urlencode(d)
return urlparse.urlunsplit(part... | 1 | 2011-01-24T02:16:06Z | [
"python",
"url"
] |
Add params to given URL in Python | 2,506,379 | <p>Suppose I was given a URL.<br>
It might already have GET parameters (e.g. <code>http://example.com/search?q=question</code>) or it might not (e.g. <code>http://example.com/</code>).</p>
<p>And now I need to add some parameters to it like <code>{'lang':'en','tag':'python'}</code>. In the first case I'm going to have... | 61 | 2010-03-24T09:06:21Z | 9,538,343 | <p>I liked Åukasz version, but since urllib and urllparse functions are somewhat awkward to use in this case, I think it's more straightforward to do something like this:</p>
<pre><code>params = urllib.urlencode(params)
if urlparse.urlparse(url)[4]:
print url + '&' + params
else:
print url + '?' + params... | 4 | 2012-03-02T18:17:26Z | [
"python",
"url"
] |
Add params to given URL in Python | 2,506,379 | <p>Suppose I was given a URL.<br>
It might already have GET parameters (e.g. <code>http://example.com/search?q=question</code>) or it might not (e.g. <code>http://example.com/</code>).</p>
<p>And now I need to add some parameters to it like <code>{'lang':'en','tag':'python'}</code>. In the first case I'm going to have... | 61 | 2010-03-24T09:06:21Z | 11,867,201 | <p>Here is how I implemented it.</p>
<pre><code>import urllib
params = urllib.urlencode({'lang':'en','tag':'python'})
url = ''
if request.GET:
url = request.url + '&' + params
else:
url = request.url + '?' + params
</code></pre>
<p>Worked like a charm. However, I would have liked a more cleaner way to ... | 1 | 2012-08-08T14:50:53Z | [
"python",
"url"
] |
Add params to given URL in Python | 2,506,379 | <p>Suppose I was given a URL.<br>
It might already have GET parameters (e.g. <code>http://example.com/search?q=question</code>) or it might not (e.g. <code>http://example.com/</code>).</p>
<p>And now I need to add some parameters to it like <code>{'lang':'en','tag':'python'}</code>. In the first case I'm going to have... | 61 | 2010-03-24T09:06:21Z | 12,937,121 | <p>Yet another answer:</p>
<pre><code>def addGetParameters(url, newParams):
(scheme, netloc, path, params, query, fragment) = urlparse.urlparse(url)
queryList = urlparse.parse_qsl(query, keep_blank_values=True)
for key in newParams:
queryList.append((key, newParams[key]))
return urlparse.urlunp... | 2 | 2012-10-17T14:51:48Z | [
"python",
"url"
] |
Add params to given URL in Python | 2,506,379 | <p>Suppose I was given a URL.<br>
It might already have GET parameters (e.g. <code>http://example.com/search?q=question</code>) or it might not (e.g. <code>http://example.com/</code>).</p>
<p>And now I need to add some parameters to it like <code>{'lang':'en','tag':'python'}</code>. In the first case I'm going to have... | 61 | 2010-03-24T09:06:21Z | 24,791,840 | <p>You can also use the furl module <a href="https://github.com/gruns/furl">https://github.com/gruns/furl</a></p>
<pre><code>>>> from furl import furl
>>> print furl('http://example.com/search?q=question').add({'lang':'en','tag':'python'}).url
http://example.com/search?q=question&lang=en&tag=... | 9 | 2014-07-16T22:23:57Z | [
"python",
"url"
] |
Add params to given URL in Python | 2,506,379 | <p>Suppose I was given a URL.<br>
It might already have GET parameters (e.g. <code>http://example.com/search?q=question</code>) or it might not (e.g. <code>http://example.com/</code>).</p>
<p>And now I need to add some parameters to it like <code>{'lang':'en','tag':'python'}</code>. In the first case I'm going to have... | 61 | 2010-03-24T09:06:21Z | 25,580,545 | <h2>Why</h2>
<p>I've been not satisfied with all the solutions on this page (<em>come on, where is our favorite copy-paste thing?</em>) so I wrote my own based on answers here. It tries to be complete and more Pythonic. I've added a handler for <strong>dict</strong> and <strong>bool</strong> values in arguments to be ... | 16 | 2014-08-30T08:32:57Z | [
"python",
"url"
] |
Add params to given URL in Python | 2,506,379 | <p>Suppose I was given a URL.<br>
It might already have GET parameters (e.g. <code>http://example.com/search?q=question</code>) or it might not (e.g. <code>http://example.com/</code>).</p>
<p>And now I need to add some parameters to it like <code>{'lang':'en','tag':'python'}</code>. In the first case I'm going to have... | 61 | 2010-03-24T09:06:21Z | 33,924,117 | <p>Based on <a href="http://stackoverflow.com/a/9538343/1113207">this</a> answer, one-liner for simple cases (Python 3 code):</p>
<pre><code>from urllib.parse import urlparse, urlencode
url = "http://stackoverflow.com/search?q=question"
params = {'lang':'en','tag':'python'}
url += ('&' if urlparse(url).query el... | 2 | 2015-11-25T18:39:38Z | [
"python",
"url"
] |
ways to execute python | 2,506,437 | <p>So far to execute a Python program, I'm using </p>
<pre><code>> python file.py
</code></pre>
<p>I want to run the Python script simply using file name, like</p>
<pre><code>> file.py
</code></pre>
<p>similar to shell scripts like</p>
<pre><code>> sh file.sh
> chmod +x file.sh
> ./file.sh
</code>... | 6 | 2010-03-24T09:18:05Z | 2,506,444 | <p>Put this at the top of your Python script:</p>
<pre><code>#!/usr/bin/env python
</code></pre>
<p>The #! part is called a <a href="http://en.wikipedia.org/wiki/Shebang_%28Unix%29">shebang</a>, and the <code>env</code> command will simply locate <code>python</code> on your <code>$PATH</code> and execute the script t... | 17 | 2010-03-24T09:19:06Z | [
"python"
] |
ways to execute python | 2,506,437 | <p>So far to execute a Python program, I'm using </p>
<pre><code>> python file.py
</code></pre>
<p>I want to run the Python script simply using file name, like</p>
<pre><code>> file.py
</code></pre>
<p>similar to shell scripts like</p>
<pre><code>> sh file.sh
> chmod +x file.sh
> ./file.sh
</code>... | 6 | 2010-03-24T09:18:05Z | 2,506,466 | <p>You ca also target the specific location of the python interpreter you wan to use, if you need to specify it (e.g, you're using different versions) Just add to the shebang line (the one starting with #!) the complete path of the interpreter you wan to use, for example</p>
<pre><code>#!/home/user/python2.6/bin/pytho... | 2 | 2010-03-24T09:22:09Z | [
"python"
] |
Python and .exe files, another way | 2,506,857 | <p>How to build exe files from py files (compatible with win32)?</p>
<p>please don't refer to py2exe. that is blocked service in IRI. </p>
<ul>
<li>for Iranians only: do you know how to download something (like py2exe) from blocked sites? especially from sourceforge ande fontforge?</li>
</ul>
| 2 | 2010-03-24T10:30:00Z | 2,506,882 | <p>How about cx_Freeze, is that blocked?</p>
<p>Refer to: <a href="http://cx-freeze.sourceforge.net/" rel="nofollow">http://cx-freeze.sourceforge.net/</a></p>
| 0 | 2010-03-24T10:32:35Z | [
"python",
"py2exe"
] |
Python and .exe files, another way | 2,506,857 | <p>How to build exe files from py files (compatible with win32)?</p>
<p>please don't refer to py2exe. that is blocked service in IRI. </p>
<ul>
<li>for Iranians only: do you know how to download something (like py2exe) from blocked sites? especially from sourceforge ande fontforge?</li>
</ul>
| 2 | 2010-03-24T10:30:00Z | 2,506,885 | <p>Legal issues aside, blocked sites can be accessed (and downloaded from) using any external web proxy.</p>
<p><strong>Edit</strong>: Does this work for you? <a href="http://1.2.hidemyass.com/index.php?q=aHR0cDovL3NvdXJjZWZvcmdlLm5ldA%3D%3D&hl=0" rel="nofollow">Sourceforge.net through hidemyass.com</a>.</p>
| 1 | 2010-03-24T10:33:00Z | [
"python",
"py2exe"
] |
Python and .exe files, another way | 2,506,857 | <p>How to build exe files from py files (compatible with win32)?</p>
<p>please don't refer to py2exe. that is blocked service in IRI. </p>
<ul>
<li>for Iranians only: do you know how to download something (like py2exe) from blocked sites? especially from sourceforge ande fontforge?</li>
</ul>
| 2 | 2010-03-24T10:30:00Z | 2,506,928 | <p>Pick up a mirror like this </p>
<p><a href="http://git.kitsu.ru/mirrors/py2exe.git" rel="nofollow">http://git.kitsu.ru/mirrors/py2exe.git</a></p>
<p>and download it with git clone, and compile it by running setup.py after that.</p>
| 4 | 2010-03-24T10:39:04Z | [
"python",
"py2exe"
] |
Python and .exe files, another way | 2,506,857 | <p>How to build exe files from py files (compatible with win32)?</p>
<p>please don't refer to py2exe. that is blocked service in IRI. </p>
<ul>
<li>for Iranians only: do you know how to download something (like py2exe) from blocked sites? especially from sourceforge ande fontforge?</li>
</ul>
| 2 | 2010-03-24T10:30:00Z | 2,506,930 | <p>How about <a href="http://www.pyinstaller.org/" rel="nofollow">PyInstaller</a> (link to preliminary <a href="http://www.pyinstaller.org/wiki/Python26Win" rel="nofollow">python 2.6 on Windows</a> bin)?</p>
| 3 | 2010-03-24T10:39:38Z | [
"python",
"py2exe"
] |
Why can't my Apache see my media folder? | 2,506,883 | <pre><code>Alias /media/ /home/matt/repos/hello/media
<Directory /home/matt/repos/hello/media>
Options -Indexes
Order deny,allow
Allow from all
</Directory>
WSGIScriptAlias / /home/matt/repos/hello/wsgi/django.wsgi
</code></pre>
<p>/media is my directory. When I go to mydomain.com/media/, it says 403 Forbi... | 1 | 2010-03-24T10:32:47Z | 2,506,900 | <p>You have Indexes disabled, so Apache won't generate a listing of the files when you request the directory /media (instead, it shows the 403 Forbidden error). Try accessing a file directly within there, e.g.: <a href="http://localhost/media/some_image.jpg" rel="nofollow">http://localhost/media/some_image.jpg</a></p>... | 4 | 2010-03-24T10:34:56Z | [
"python",
"linux",
"django",
"apache",
"unix"
] |
Why can't my Apache see my media folder? | 2,506,883 | <pre><code>Alias /media/ /home/matt/repos/hello/media
<Directory /home/matt/repos/hello/media>
Options -Indexes
Order deny,allow
Allow from all
</Directory>
WSGIScriptAlias / /home/matt/repos/hello/wsgi/django.wsgi
</code></pre>
<p>/media is my directory. When I go to mydomain.com/media/, it says 403 Forbi... | 1 | 2010-03-24T10:32:47Z | 2,506,907 | <p>If memory serves me correctly, Apache runs under it's own user account. Are you sure that this account has the correct permissions to that directory?</p>
| 0 | 2010-03-24T10:36:42Z | [
"python",
"linux",
"django",
"apache",
"unix"
] |
Why can't my Apache see my media folder? | 2,506,883 | <pre><code>Alias /media/ /home/matt/repos/hello/media
<Directory /home/matt/repos/hello/media>
Options -Indexes
Order deny,allow
Allow from all
</Directory>
WSGIScriptAlias / /home/matt/repos/hello/wsgi/django.wsgi
</code></pre>
<p>/media is my directory. When I go to mydomain.com/media/, it says 403 Forbi... | 1 | 2010-03-24T10:32:47Z | 2,506,975 | <p>its all about the dash <code>Options -Indexes</code>
and here is a complete editon to yours </p>
<pre><code> Alias /media/ /home/matt/repos/hello/media
<Directory "/home/matt/repos/hello/media">
Options Indexes
AllowOverride all
Order Deny,Allow
Allowfrom all
</Directory
</code></pre>
<p>... | 0 | 2010-03-24T10:48:07Z | [
"python",
"linux",
"django",
"apache",
"unix"
] |
Why can't my Apache see my media folder? | 2,506,883 | <pre><code>Alias /media/ /home/matt/repos/hello/media
<Directory /home/matt/repos/hello/media>
Options -Indexes
Order deny,allow
Allow from all
</Directory>
WSGIScriptAlias / /home/matt/repos/hello/wsgi/django.wsgi
</code></pre>
<p>/media is my directory. When I go to mydomain.com/media/, it says 403 Forbi... | 1 | 2010-03-24T10:32:47Z | 2,507,200 | <p>It looks to me that <code>WSGIScriptAlias / /home/matt/repos/hello/wsgi/django.wsgi</code> tells to apache that everything under / should be handled by the specified WSGI script. This also includes /media. You should tell apache to exclude /media from that rule.</p>
<p>Try adding this to your config file:</p>
<pre... | 3 | 2010-03-24T11:28:05Z | [
"python",
"linux",
"django",
"apache",
"unix"
] |
Why can't my Apache see my media folder? | 2,506,883 | <pre><code>Alias /media/ /home/matt/repos/hello/media
<Directory /home/matt/repos/hello/media>
Options -Indexes
Order deny,allow
Allow from all
</Directory>
WSGIScriptAlias / /home/matt/repos/hello/wsgi/django.wsgi
</code></pre>
<p>/media is my directory. When I go to mydomain.com/media/, it says 403 Forbi... | 1 | 2010-03-24T10:32:47Z | 2,510,646 | <p>I solved it. I missed a trailing slash. after media/</p>
| 1 | 2010-03-24T19:05:35Z | [
"python",
"linux",
"django",
"apache",
"unix"
] |
How do I forward a request to a different url in python | 2,506,932 | <p>I have been looking for the syntax to redirect a special url to a remote server to do some XSS testing. Any ideas?</p>
<pre><code>import SimpleHTTPServer
import SocketServer
class myHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
print self.path
if self.path == '/analog':... | 12 | 2010-03-24T10:40:01Z | 2,507,022 | <p>For a redirect, you have to return a code 301, plus a <code>Location</code> header. Probably you can try something like:</p>
<pre><code>class myHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
self.send_response(301)
self.send_header('Location','http://www.example.com')
... | 11 | 2010-03-24T10:57:21Z | [
"python",
"url",
"redirect",
"simplehttpserver"
] |
How do I forward a request to a different url in python | 2,506,932 | <p>I have been looking for the syntax to redirect a special url to a remote server to do some XSS testing. Any ideas?</p>
<pre><code>import SimpleHTTPServer
import SocketServer
class myHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
print self.path
if self.path == '/analog':... | 12 | 2010-03-24T10:40:01Z | 22,181,914 | <p>This is a complete piece of code to redirect, save this file and run it as a python program. to terminate, ctrl + c.</p>
<pre><code>import SimpleHTTPServer
import SocketServer
class myHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
print self.path
self.send_response(301)
... | 4 | 2014-03-04T20:08:18Z | [
"python",
"url",
"redirect",
"simplehttpserver"
] |
How do I forward a request to a different url in python | 2,506,932 | <p>I have been looking for the syntax to redirect a special url to a remote server to do some XSS testing. Any ideas?</p>
<pre><code>import SimpleHTTPServer
import SocketServer
class myHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
print self.path
if self.path == '/analog':... | 12 | 2010-03-24T10:40:01Z | 26,797,095 | <p>HTTP status code 301 has meaning of the request moved permanently and should be redirected to suggested URI which is set to response header field, location. However, the redirection happens depending on implementation of browsers.</p>
<p>Instead of 301, returning 303 tells the browser the response for the request c... | -1 | 2014-11-07T08:29:49Z | [
"python",
"url",
"redirect",
"simplehttpserver"
] |
String searching algorithm for Chinese characters | 2,506,970 | <p>There is Python code available for normal string searching algorithms, such as Boyer-Moore. I am looking to use this on Chinese characters, but it doesn't seem like the same implementation would work. What would I do in order to make the algorithm work with Chinese characters? I am referring to this:</p>
<p><a href... | 2 | 2010-03-24T10:46:48Z | 2,506,984 | <p>As long as all your text is in unicodes it should work just fine. The algorithm looks sequence-independent, provided each "element" is one sequence-unit in length.</p>
| 3 | 2010-03-24T10:49:32Z | [
"python",
"unicode",
"cjk",
"string-search"
] |
Merging contents of two lists based on a if-loop | 2,507,090 | <p>I have a minor problem while checking for elements in a list:
I have two files with contents something like this</p>
<pre><code>file 1: file2:
47 358 47
48 450 49
49 56 50
</code></pre>
<p>I parsed both files into two lists and used the following code to check </p>
<pre>... | 2 | 2010-03-24T11:06:24Z | 2,507,123 | <p>You could modify your code quite easily:</p>
<pre><code>for i in file_1:
x = None
for j in file_2:
j = j.split()
if i == j[1]:
x = ' '.join(j)
if x is None:
x = ' '.join(['0', i])
</code></pre>
<p>Depending on your inputs, the whole task might be of course simplified... | 1 | 2010-03-24T11:12:08Z | [
"python",
"list",
"loops"
] |
Merging contents of two lists based on a if-loop | 2,507,090 | <p>I have a minor problem while checking for elements in a list:
I have two files with contents something like this</p>
<pre><code>file 1: file2:
47 358 47
48 450 49
49 56 50
</code></pre>
<p>I parsed both files into two lists and used the following code to check </p>
<pre>... | 2 | 2010-03-24T11:06:24Z | 2,507,292 | <pre><code>r1=open('file1').read().split()
r2=open('file2').read().split()
d=dict(zip(r2[1::2],r2[::2]))
output='\n'.join(x in d and d[x]+' '+x or '0 '+x for x in r1)
open('output_file','wb').write(output)
</code></pre>
<p>Test</p>
<pre><code>>>> file1='47\n48\n49\n50'
>>> file2='358 47\n450 49\n... | 2 | 2010-03-24T11:44:27Z | [
"python",
"list",
"loops"
] |
Merging contents of two lists based on a if-loop | 2,507,090 | <p>I have a minor problem while checking for elements in a list:
I have two files with contents something like this</p>
<pre><code>file 1: file2:
47 358 47
48 450 49
49 56 50
</code></pre>
<p>I parsed both files into two lists and used the following code to check </p>
<pre>... | 2 | 2010-03-24T11:06:24Z | 2,508,939 | <p>Here's a readable solution using a dictionary:</p>
<pre><code>d = {}
for k in file1:
d[k] = 0
for line in file2:
v, k = line.split()
d[k] = v
for k in sorted(d):
print d[k], k
</code></pre>
| 1 | 2010-03-24T15:26:58Z | [
"python",
"list",
"loops"
] |
Merging contents of two lists based on a if-loop | 2,507,090 | <p>I have a minor problem while checking for elements in a list:
I have two files with contents something like this</p>
<pre><code>file 1: file2:
47 358 47
48 450 49
49 56 50
</code></pre>
<p>I parsed both files into two lists and used the following code to check </p>
<pre>... | 2 | 2010-03-24T11:06:24Z | 2,513,427 | <p>You can try something like:</p>
<pre><code>l1 = open('file1').read().split()
l2 = [line.split() for line in open('file2')]
for x, y in zip(l1, l2):
if x not in y:
print 0, x
print ' '.join(y)
</code></pre>
<p>but if you follow your logic, the output should be</p>
<pre><code>358 47
0 48
450 49
0 4... | 0 | 2010-03-25T06:13:42Z | [
"python",
"list",
"loops"
] |
Merging contents of two lists based on a if-loop | 2,507,090 | <p>I have a minor problem while checking for elements in a list:
I have two files with contents something like this</p>
<pre><code>file 1: file2:
47 358 47
48 450 49
49 56 50
</code></pre>
<p>I parsed both files into two lists and used the following code to check </p>
<pre>... | 2 | 2010-03-24T11:06:24Z | 2,527,629 | <pre><code>def file_process(filename1, filename2):
# read first file with zeroes as values
with open(filename1) as fp:
adict= dict( (line.rstrip(), 0) for line in fp)
# read second file as "value key"
with open(filename2) as fp:
adict.update(
line.rstrip().partition(" ")[2:... | 0 | 2010-03-27T00:19:27Z | [
"python",
"list",
"loops"
] |
Having trouble scraping an ASP .NET web page | 2,507,280 | <p>I am trying to scrape an ASP.NET website but am having trouble getting the results from a post. I have the following python code and am using httplib2 and BeautifulSoup:</p>
<pre><code>conn = Http()
# do a get first to retrieve important values
page = conn.request(u"http://somepage.com/Search.aspx", "GET")
#event_... | 0 | 2010-03-24T11:42:47Z | 2,507,335 | <p>Well, You need to see first what you have written in the page for get and post, but I hope you are making sure both requests are sending different contents. </p>
<p>here is how you can do that</p>
<pre><code>
if(!IsPostBack)
{
Response.Write("<h1>Get Request</h1>");
}
else
{
Response.Write("<h1>POST Reque... | 0 | 2010-03-24T11:51:54Z | [
"asp.net",
"python"
] |
Having trouble scraping an ASP .NET web page | 2,507,280 | <p>I am trying to scrape an ASP.NET website but am having trouble getting the results from a post. I have the following python code and am using httplib2 and BeautifulSoup:</p>
<pre><code>conn = Http()
# do a get first to retrieve important values
page = conn.request(u"http://somepage.com/Search.aspx", "GET")
#event_... | 0 | 2010-03-24T11:42:47Z | 2,507,350 | <p>This isn't technically an answer, but you could use <a href="http://www.fiddler2.com/fiddler2/" rel="nofollow">Fiddler</a> to examine the difference between what you are sending with your python code, versus what would be sent if you used a web browser to do the post.</p>
<p>I find that usually helps in these types... | 2 | 2010-03-24T11:54:29Z | [
"asp.net",
"python"
] |
increment a variable in django templates | 2,507,284 | <p>All,</p>
<p>How Can we increment a value like the following in django templates, </p>
<pre><code> {{ flag =0 }}
{% for op in options %}
{{op.choices}}<input type="radio" name="template" id="template" value="template{{flag++}}"/>
{% endfor %}
</code></pre>
<p>thanks..</p>
| 11 | 2010-03-24T11:43:18Z | 2,507,305 | <p>I don't think it's intended you should alter data in your templates. For in your specific case, you could instead use the <code>forloop.counter</code> variable.</p>
<p>For example: </p>
<pre><code>{% for op in options %}
{{op.choices}}<input type="radio" name="template" id="template{{forloop.counter}}" value=... | 18 | 2010-03-24T11:47:13Z | [
"python",
"django",
"django-templates"
] |
increment a variable in django templates | 2,507,284 | <p>All,</p>
<p>How Can we increment a value like the following in django templates, </p>
<pre><code> {{ flag =0 }}
{% for op in options %}
{{op.choices}}<input type="radio" name="template" id="template" value="template{{flag++}}"/>
{% endfor %}
</code></pre>
<p>thanks..</p>
| 11 | 2010-03-24T11:43:18Z | 2,507,308 | <p>You explicitly can't do that in a template. Variable assignment is not allowed.</p>
<p>However if all you want is a counter in your loop, you just need to use <code>{{ forloop.counter }}</code>.</p>
| 7 | 2010-03-24T11:47:48Z | [
"python",
"django",
"django-templates"
] |
increment a variable in django templates | 2,507,284 | <p>All,</p>
<p>How Can we increment a value like the following in django templates, </p>
<pre><code> {{ flag =0 }}
{% for op in options %}
{{op.choices}}<input type="radio" name="template" id="template" value="template{{flag++}}"/>
{% endfor %}
</code></pre>
<p>thanks..</p>
| 11 | 2010-03-24T11:43:18Z | 2,511,004 | <p>You might also want to look into having Django <a href="http://docs.djangoproject.com/en/dev/topics/forms/" rel="nofollow">forms</a> produce these values</p>
| 3 | 2010-03-24T20:03:40Z | [
"python",
"django",
"django-templates"
] |
Use BeautifulSoup to extract sibling nodes between two nodes | 2,507,301 | <p>I've got a document like this:</p>
<pre><code><p class="top">I don't want this</p>
<p>I want this</p>
<table>
<!-- ... -->
</table>
<img ... />
<p> and all that stuff too</p>
<p class="end>But not this and nothing after it</p>
</code></p... | 5 | 2010-03-24T11:46:00Z | 2,507,405 | <p><code>node.nextSibling</code> attribute is your solution:</p>
<pre><code>from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)
nextNode = soup.find('p', {'class': 'top'})
while True:
# process
nextNode = nextNode.nextSibling
if getattr(nextNode, 'name', None) == 'p' and nextNode.get('cla... | 8 | 2010-03-24T12:03:45Z | [
"python",
"beautifulsoup"
] |
Detecting Infinite recursion in Python or dynamic languages | 2,507,395 | <p>Recently I tried compiling program something like this with GCC:</p>
<pre><code>int f(int i){
if(i<0){ return 0;}
return f(i-1);
f(100000);
</code></pre>
<p>and it ran just fine. When I inspected the stack frames the compiler optimized the program to use only one frame, by just jumping back to the begin... | 8 | 2010-03-24T12:01:23Z | 2,507,429 | <p>It has nothing to do with the fact that it is a dynamic language or that it is interpreted. <a href="http://en.wikipedia.org/wiki/CPython" rel="nofollow">CPython</a> just doesn't implement <a href="http://en.wikipedia.org/wiki/Tail_recursion" rel="nofollow">Tail Recursion</a> optimization. You may find that JPython ... | 4 | 2010-03-24T12:06:39Z | [
"python",
"gcc",
"compiler-construction"
] |
Detecting Infinite recursion in Python or dynamic languages | 2,507,395 | <p>Recently I tried compiling program something like this with GCC:</p>
<pre><code>int f(int i){
if(i<0){ return 0;}
return f(i-1);
f(100000);
</code></pre>
<p>and it ran just fine. When I inspected the stack frames the compiler optimized the program to use only one frame, by just jumping back to the begin... | 8 | 2010-03-24T12:01:23Z | 2,507,434 | <blockquote>
<p>When I inspected the stack frames the compiler optimized the program to use only one frame, by just jumping back to the beginning of the function and only replacing the arguments to f.</p>
</blockquote>
<p>What you're describing is called "tail recursion". Some compilers/interpreters support it, some... | 6 | 2010-03-24T12:07:39Z | [
"python",
"gcc",
"compiler-construction"
] |
Detecting Infinite recursion in Python or dynamic languages | 2,507,395 | <p>Recently I tried compiling program something like this with GCC:</p>
<pre><code>int f(int i){
if(i<0){ return 0;}
return f(i-1);
f(100000);
</code></pre>
<p>and it ran just fine. When I inspected the stack frames the compiler optimized the program to use only one frame, by just jumping back to the begin... | 8 | 2010-03-24T12:01:23Z | 2,507,436 | <p>The optimisation you're talking about is known as tail call elimination - a recursive call is unfolded into an iterative loop.</p>
<p>There has been some discussion of this, but the current situation is that this will not be added, at least to cpython proper. See <a href="http://neopythonic.blogspot.com/2009/04/ta... | 12 | 2010-03-24T12:07:54Z | [
"python",
"gcc",
"compiler-construction"
] |
C++ Arrays manipulations (python-like operations) | 2,507,422 | <p>I'm trying to figure out the best C++ library/package for array manipulations in a manner of python. Basically I need a simplicity like this:</p>
<pre><code>values = numpy.array(inp.data)
idx1 = numpy.where(values > -2.14)
idx2 = numpy.where(values < 2.0)
res1 = (values[idx1] - diff1)/1000
res2 = (val... | 2 | 2010-03-24T12:05:50Z | 2,507,439 | <p>If I'm not mistaken, numpy is written mostly in C (with a Python wrapper), so you could be able to use it directly from C++ without much effort.</p>
| 1 | 2010-03-24T12:09:01Z | [
"c++",
"python",
"arrays"
] |
C++ Arrays manipulations (python-like operations) | 2,507,422 | <p>I'm trying to figure out the best C++ library/package for array manipulations in a manner of python. Basically I need a simplicity like this:</p>
<pre><code>values = numpy.array(inp.data)
idx1 = numpy.where(values > -2.14)
idx2 = numpy.where(values < 2.0)
res1 = (values[idx1] - diff1)/1000
res2 = (val... | 2 | 2010-03-24T12:05:50Z | 2,507,442 | <p>I suggest you to check the algorithm header.
Also don't work with arrays, you have std::vector or boost(soon to be std)::array.</p>
<p><a href="http://en.wikipedia.org/wiki/Algorithm_%28C%2B%2B%29" rel="nofollow">wikipedia article</a></p>
<p><a href="http://www.cppreference.com/wiki/stl/algorithm/start" rel="nofol... | 4 | 2010-03-24T12:09:05Z | [
"c++",
"python",
"arrays"
] |
C++ Arrays manipulations (python-like operations) | 2,507,422 | <p>I'm trying to figure out the best C++ library/package for array manipulations in a manner of python. Basically I need a simplicity like this:</p>
<pre><code>values = numpy.array(inp.data)
idx1 = numpy.where(values > -2.14)
idx2 = numpy.where(values < 2.0)
res1 = (values[idx1] - diff1)/1000
res2 = (val... | 2 | 2010-03-24T12:05:50Z | 2,507,448 | <p>You should not be using arrays at all. Please sit down and learn about the std::vector class and about iterators and Standard Library algorithms. I strongly suggest reading the book <a href="http://www.josuttis.com/libbook/index.html" rel="nofollow">The C++ Standard Library</a>.</p>
| 5 | 2010-03-24T12:09:42Z | [
"c++",
"python",
"arrays"
] |
C++ Arrays manipulations (python-like operations) | 2,507,422 | <p>I'm trying to figure out the best C++ library/package for array manipulations in a manner of python. Basically I need a simplicity like this:</p>
<pre><code>values = numpy.array(inp.data)
idx1 = numpy.where(values > -2.14)
idx2 = numpy.where(values < 2.0)
res1 = (values[idx1] - diff1)/1000
res2 = (val... | 2 | 2010-03-24T12:05:50Z | 2,507,612 | <p>You can achieve something similar in C++ but you shouldn't use plain C arrays for it.</p>
<p>The easiest way I can see this work would be using a <code>std::set</code> of floats (your code looks like it assumes that the data is sorted in ascending order). You could also use a <code>std::vector</code> of float but y... | 5 | 2010-03-24T12:36:13Z | [
"c++",
"python",
"arrays"
] |
C++ Arrays manipulations (python-like operations) | 2,507,422 | <p>I'm trying to figure out the best C++ library/package for array manipulations in a manner of python. Basically I need a simplicity like this:</p>
<pre><code>values = numpy.array(inp.data)
idx1 = numpy.where(values > -2.14)
idx2 = numpy.where(values < 2.0)
res1 = (values[idx1] - diff1)/1000
res2 = (val... | 2 | 2010-03-24T12:05:50Z | 2,507,737 | <p>If you combine <code>std::vector</code> and <code>boost::lambda</code>, you can come really close to your example:</p>
<pre><code>#include <algorithm>
#include <iostream>
#include <vector>
#include <boost/lambda/lambda.hpp>
using boost::lambda::_1;
int main() {
float ary[10] = { -4, -3... | 1 | 2010-03-24T12:52:09Z | [
"c++",
"python",
"arrays"
] |
Web framework for an application utilizing existing database? | 2,507,463 | <p>A legacy web application written using PHP and utilizing MySql database needs to be rewritten completely. However, the existing database structure must not be changed at all.</p>
<p>I'm looking for suggestions on which framework would be most suitable for this task? Language candidates are Python, PHP, Ruby and Jav... | 1 | 2010-03-24T12:11:18Z | 2,507,479 | <p>Use <a href="http://www.sqlalchemy.org"><code>sqlalchemy</code></a>. On any framework you choose. It can reflect your database as ORM.</p>
| 5 | 2010-03-24T12:13:24Z | [
"java",
"php",
"python",
"ruby"
] |
Web framework for an application utilizing existing database? | 2,507,463 | <p>A legacy web application written using PHP and utilizing MySql database needs to be rewritten completely. However, the existing database structure must not be changed at all.</p>
<p>I'm looking for suggestions on which framework would be most suitable for this task? Language candidates are Python, PHP, Ruby and Jav... | 1 | 2010-03-24T12:11:18Z | 2,507,484 | <p>I suppose that any PHP Framework <em>(I'm a PHP guy, so I will only talk about PHP)</em> could be OK for you ; but you should use one that's well-supported, has a large community, ...</p>
<p>To make things short, I'm thinking about one off this list :</p>
<ul>
<li><a href="http://www.symfony-project.org/" rel="nof... | 2 | 2010-03-24T12:14:26Z | [
"java",
"php",
"python",
"ruby"
] |
Web framework for an application utilizing existing database? | 2,507,463 | <p>A legacy web application written using PHP and utilizing MySql database needs to be rewritten completely. However, the existing database structure must not be changed at all.</p>
<p>I'm looking for suggestions on which framework would be most suitable for this task? Language candidates are Python, PHP, Ruby and Jav... | 1 | 2010-03-24T12:11:18Z | 2,507,492 | <p>I have very good experience with Django. Every time I needed it was up to the task for interfacing with existing database. </p>
<p>Autogenerated models are the start, as MySQL is not the strictest with its schema. Not that it will not work only that usually some of the db restrictions are held in app itself.</p>
| 2 | 2010-03-24T12:16:29Z | [
"java",
"php",
"python",
"ruby"
] |
Web framework for an application utilizing existing database? | 2,507,463 | <p>A legacy web application written using PHP and utilizing MySql database needs to be rewritten completely. However, the existing database structure must not be changed at all.</p>
<p>I'm looking for suggestions on which framework would be most suitable for this task? Language candidates are Python, PHP, Ruby and Jav... | 1 | 2010-03-24T12:11:18Z | 2,507,514 | <p>My first thought would be to use Hibernate and Java, but I may be biased because that is what my experience is in. You generally map your Model classes via Hibernate after you create the database anyway, so it might not be a bad choice.</p>
<p>I'll let it explain itself to you: <a href="http://www.hibernate.org/" r... | 2 | 2010-03-24T12:18:17Z | [
"java",
"php",
"python",
"ruby"
] |
Web framework for an application utilizing existing database? | 2,507,463 | <p>A legacy web application written using PHP and utilizing MySql database needs to be rewritten completely. However, the existing database structure must not be changed at all.</p>
<p>I'm looking for suggestions on which framework would be most suitable for this task? Language candidates are Python, PHP, Ruby and Jav... | 1 | 2010-03-24T12:11:18Z | 2,507,794 | <p>You know, there's a whole Ruby web dev world away from Rails, e.g.:</p>
<ul>
<li><a href="http://www.sinatrarb.com/" rel="nofollow">Sinatra</a></li>
<li><a href="http://ramaze.net/" rel="nofollow">Ramaze</a></li>
<li><a href="http://webby.rubyforge.org/tutorial/" rel="nofollow">Webby</a></li>
</ul>
<p>With such a ... | 0 | 2010-03-24T13:01:17Z | [
"java",
"php",
"python",
"ruby"
] |
Web framework for an application utilizing existing database? | 2,507,463 | <p>A legacy web application written using PHP and utilizing MySql database needs to be rewritten completely. However, the existing database structure must not be changed at all.</p>
<p>I'm looking for suggestions on which framework would be most suitable for this task? Language candidates are Python, PHP, Ruby and Jav... | 1 | 2010-03-24T12:11:18Z | 2,508,613 | <p>Try <a href="http://www.web2py.com/" rel="nofollow">web2py</a>, extremely easy to prototype any webapp, and IMO a bit easier to grasp (overall) than other similar web frameworks, HTH</p>
| 0 | 2010-03-24T14:47:03Z | [
"java",
"php",
"python",
"ruby"
] |
Web framework for an application utilizing existing database? | 2,507,463 | <p>A legacy web application written using PHP and utilizing MySql database needs to be rewritten completely. However, the existing database structure must not be changed at all.</p>
<p>I'm looking for suggestions on which framework would be most suitable for this task? Language candidates are Python, PHP, Ruby and Jav... | 1 | 2010-03-24T12:11:18Z | 2,512,975 | <p>There are no clear cut winners when picking a web framework. Each platform you mentioned has its benefits and drawbacks (cost of hardware, professional support, community support, etc.). Depending on your time table, project requirements, and available hardware resources you are probably going to need some different... | 0 | 2010-03-25T03:53:46Z | [
"java",
"php",
"python",
"ruby"
] |
Web framework for an application utilizing existing database? | 2,507,463 | <p>A legacy web application written using PHP and utilizing MySql database needs to be rewritten completely. However, the existing database structure must not be changed at all.</p>
<p>I'm looking for suggestions on which framework would be most suitable for this task? Language candidates are Python, PHP, Ruby and Jav... | 1 | 2010-03-24T12:11:18Z | 2,556,223 | <p>Iâm currently rebuilding a legacy PHP web application with a MySQL database my self. </p>
<p>The PHP code was kind of spaghetti and is now rewritten in Java as it type safe, promotes well-structured code, has excellent tooling and has superior unit testing capabilities. For database to Java mapping I use Hibernat... | 3 | 2010-03-31T20:27:10Z | [
"java",
"php",
"python",
"ruby"
] |
have you got a py-poppler-qt example? | 2,507,498 | <p>I'm developing an application in PyQt4 that eventually has to open and show PDF files. For this task there is a python library: python-poppler (in various spelling flavours). </p>
<p>The problem is that it is terribly under documented and the only simple working example I found so far uses Python+Gtk+Cairo, while t... | 4 | 2010-03-24T12:17:06Z | 2,739,468 | <p>I know you posted this a month ago, but just in case you're still looking!
There is an example buried deep within an experimental (unused) branch of an app, here is a link to the specific file containing the code. Don't know if it'll help? All the relevant poppler code is self contained within the PdfViewer class at... | 5 | 2010-04-29T17:35:00Z | [
"python",
"qt",
"pyqt4",
"poppler"
] |
How to display locale sensitive time format without seconds in python | 2,507,726 | <p>I can output a locale sensitive time format using <code>strftime('%X')</code>, but this always includes seconds. How might I display this time format without seconds? </p>
<pre><code>>>> import locale
>>> import datetime
>>> locale.setlocale(locale.LC_ALL, 'en_IE.utf-8')
'en_IE.utf-8'
>... | 9 | 2010-03-24T12:50:06Z | 2,507,847 | <p>I would suggest special casing the returned T_FMT as there aren't that many to consider really:</p>
<pre><code>$ for l in $(locale -a | grep utf8); do locale | cut -d= -f1 | LANG=$l xargs locale -kc | grep ^t_fmt=; done | sort -u
t_fmt="%H:%M:%S"
t_fmt="%H.%M.%S"
t_fmt="%Hì %Më¶ %Sì´"
t_fmt="à½à½´à¼à½à½¼à½... | 4 | 2010-03-24T13:08:37Z | [
"python",
"time",
"format",
"locale"
] |
How to display locale sensitive time format without seconds in python | 2,507,726 | <p>I can output a locale sensitive time format using <code>strftime('%X')</code>, but this always includes seconds. How might I display this time format without seconds? </p>
<pre><code>>>> import locale
>>> import datetime
>>> locale.setlocale(locale.LC_ALL, 'en_IE.utf-8')
'en_IE.utf-8'
>... | 9 | 2010-03-24T12:50:06Z | 2,580,346 | <p>This is bad solution. What happens with some new different locale?</p>
<p>Use following: </p>
<pre><code>t.strftime(gettext('%H:%M'))
</code></pre>
<p>Now each translator for each languages would provide suitable format for each string, for
<code>en_US</code> it would be '<code>%I:M %p</code>', for zh_TW: <code>%... | 3 | 2010-04-05T18:49:45Z | [
"python",
"time",
"format",
"locale"
] |
Repeatedly querying xml using python | 2,507,772 | <p>I have some xml documents I need to run queries on. I've created some python scripts (using ElementTree) to do this, since I'm vaguely familiar with using it. </p>
<p>The way it works is I run the scripts several times with different arguments, depending on what I want to find out.</p>
<p>These files can be relati... | 1 | 2010-03-24T12:57:41Z | 2,507,955 | <p>First off, consider using the <code>lxml</code> implementation of <code>ElementTree</code>:<br>
<a href="http://lxml.de/" rel="nofollow">http://lxml.de/</a>
This is a wrapper for libxml2, which I find performs well.</p>
<p>Run python interactively, make multiple queries against the same etree object. <code>ipython<... | 1 | 2010-03-24T13:25:25Z | [
"python",
"xml",
"caching",
"elementtree"
] |
Repeatedly querying xml using python | 2,507,772 | <p>I have some xml documents I need to run queries on. I've created some python scripts (using ElementTree) to do this, since I'm vaguely familiar with using it. </p>
<p>The way it works is I run the scripts several times with different arguments, depending on what I want to find out.</p>
<p>These files can be relati... | 1 | 2010-03-24T12:57:41Z | 2,508,107 | <p>While I second the suggestion to use lxml, you can get a huge performance boost by using the builtin cElementTree.</p>
<pre><code>from xml.etree import cElementTree as ElementTree
</code></pre>
| 2 | 2010-03-24T13:48:24Z | [
"python",
"xml",
"caching",
"elementtree"
] |
Repeatedly querying xml using python | 2,507,772 | <p>I have some xml documents I need to run queries on. I've created some python scripts (using ElementTree) to do this, since I'm vaguely familiar with using it. </p>
<p>The way it works is I run the scripts several times with different arguments, depending on what I want to find out.</p>
<p>These files can be relati... | 1 | 2010-03-24T12:57:41Z | 2,508,146 | <p>Seconding the lxml recommendation, look at this <a href="http://www.ibm.com/developerworks/xml/library/x-hiperfparse/" rel="nofollow">article</a> for how to improve performance by using an iterative (SAX-like) parsing method. It can be a pain at first since it can turn really procedural and messy, but it makes thing... | 1 | 2010-03-24T13:51:50Z | [
"python",
"xml",
"caching",
"elementtree"
] |
python how to check file empty or not | 2,507,808 | <p>I have a text file. How may I check whether the file is empty or not empty?</p>
| 103 | 2010-03-24T13:03:55Z | 2,507,819 | <pre><code>import os
os.path.getsize(fullpathhere) > 0
</code></pre>
| 72 | 2010-03-24T13:05:41Z | [
"python",
"file"
] |
python how to check file empty or not | 2,507,808 | <p>I have a text file. How may I check whether the file is empty or not empty?</p>
| 103 | 2010-03-24T13:03:55Z | 2,507,871 | <pre><code>>>> import os
>>> os.stat("file").st_size == 0
True
</code></pre>
| 114 | 2010-03-24T13:12:31Z | [
"python",
"file"
] |
python how to check file empty or not | 2,507,808 | <p>I have a text file. How may I check whether the file is empty or not empty?</p>
| 103 | 2010-03-24T13:03:55Z | 11,895,272 | <p>if for some reason you already had the file open you could try this:</p>
<pre><code>>>> with open('New Text Document.txt') as my_file:
... # I already have file open at this point.. now what?
... my_file.seek(0) #ensure you're at the start of the file..
... first_char = my_file.read(1) #get the... | 13 | 2012-08-10T03:56:17Z | [
"python",
"file"
] |
python how to check file empty or not | 2,507,808 | <p>I have a text file. How may I check whether the file is empty or not empty?</p>
| 103 | 2010-03-24T13:03:55Z | 15,924,160 | <p>Both <code>getsize()</code> and <code>stat()</code> will throw an exception if the file does not exist. This function will return True/False without throwing:</p>
<pre><code>import os
def is_non_zero_file(fpath):
return os.path.isfile(fpath) and os.path.getsize(fpath) > 0
</code></pre>
| 44 | 2013-04-10T11:08:00Z | [
"python",
"file"
] |
python how to check file empty or not | 2,507,808 | <p>I have a text file. How may I check whether the file is empty or not empty?</p>
| 103 | 2010-03-24T13:03:55Z | 15,926,220 | <p>Ok so I'll combine <a href="http://stackoverflow.com/a/2507871/17772">ghostdog74's answer</a> and the comments, just for fun.</p>
<pre><code>>>> import os
>>> os.stat('c:/pagefile.sys').st_size==0
False
</code></pre>
<p><code>False</code> means a non-empty file.</p>
<p>So let's write a function:... | 6 | 2013-04-10T12:45:03Z | [
"python",
"file"
] |
read only permission in admin interface | 2,508,027 | <p>I saw this post, <a href="http://stackoverflow.com/posts/1348076/revisions">http://stackoverflow.com/posts/1348076/revisions</a> , only at step 3 i'm getting confused, he tells to put 3. Add "get_view_permission" to default model class</p>
<p>but what's the default model class? It doesn't seem to work to me, i get... | 0 | 2010-03-24T13:36:23Z | 2,508,076 | <p>Looks like he means in <code>django/db/models.py</code>.</p>
| 0 | 2010-03-24T13:44:12Z | [
"python",
"django",
"permissions",
"admin"
] |
Getting the previous line in Jython | 2,508,279 | <p>I want to print the line immediately before the searched string. How can I do that?</p>
<p>Lets say my two lines are </p>
<pre><code>AADRG
SDFJGKDFSDF
</code></pre>
<p>and I am searching for <code>SDF</code>. I have found <code>SDFJGKDFSDF</code>, but how can I obtain the previous line <code>AADRG</code>? Does <... | 1 | 2010-03-24T14:09:54Z | 2,508,376 | <pre><code>lastLine = ""
for line in lines:
if line.find("SDF"):
print lastLine
lastLine = line
</code></pre>
<p>or </p>
<pre><code>lines = open("file").readlines()
for line in lines:
if "SDF" in line:
# test for not being the first line of course.
print lines[lines.index(line) - 1]
</code... | 4 | 2010-03-24T14:18:29Z | [
"python"
] |
wxPython & pyGame Assignment | 2,508,352 | <p>I'm actually in need of your help and advice here on my assignment that I am working on. First of all, I was task to do a program that runs langton's ant simulation. For that, I've managed to get the source code (from snippets.dzone.com/posts/show/5143) and edited it accordingly to my requirements. This was done and... | 0 | 2010-03-24T14:16:02Z | 2,508,548 | <p>Here's the page for you: <a href="http://www.pygame.org/wiki/gui" rel="nofollow">pygame GUI discussion</a></p>
<p>To sum it up: Don't use any standard GUI stuff together with pygame. It might work, but it's most definitely gonna annoy you big time. Also on this page, there's a discussion of various different GUI li... | 1 | 2010-03-24T14:39:30Z | [
"python",
"wxpython",
"pygame"
] |
List of dict in Python | 2,508,513 | <p>I've got a list of dict in Python:</p>
<pre><code>dico_cfg = {'name': entry_name, 'ip': entry_ip, 'vendor': combo_vendor, 'stream': combo_stream}
self.list_cfg.append(dico_cfg)
</code></pre>
<p>I append to my list a lot of dict in the same way.</p>
<p>Now I would like to delete one dict and only one dict in this ... | 1 | 2010-03-24T14:36:08Z | 2,508,537 | <p>If you have a reference to a dict, <code>d</code> in the list, you can remove it directly without needing to use an index:</p>
<p><code>list.remove(d)</code></p>
| 0 | 2010-03-24T14:38:44Z | [
"python",
"list",
"dictionary"
] |
List of dict in Python | 2,508,513 | <p>I've got a list of dict in Python:</p>
<pre><code>dico_cfg = {'name': entry_name, 'ip': entry_ip, 'vendor': combo_vendor, 'stream': combo_stream}
self.list_cfg.append(dico_cfg)
</code></pre>
<p>I append to my list a lot of dict in the same way.</p>
<p>Now I would like to delete one dict and only one dict in this ... | 1 | 2010-03-24T14:36:08Z | 2,508,542 | <p>If you have a reference to the dictionary you want to remove, you can try:</p>
<pre><code>self.list_cfg.remove( your_dictionary )
</code></pre>
<p>If you don't have any reference to it, you'll have to try to find it first:</p>
<pre><code>for d in self.list_cfg:
if d['name']=='Some name': # or some other check... | 2 | 2010-03-24T14:39:07Z | [
"python",
"list",
"dictionary"
] |
List of dict in Python | 2,508,513 | <p>I've got a list of dict in Python:</p>
<pre><code>dico_cfg = {'name': entry_name, 'ip': entry_ip, 'vendor': combo_vendor, 'stream': combo_stream}
self.list_cfg.append(dico_cfg)
</code></pre>
<p>I append to my list a lot of dict in the same way.</p>
<p>Now I would like to delete one dict and only one dict in this ... | 1 | 2010-03-24T14:36:08Z | 2,508,556 | <p>A better solution would be to have a dict of dicts instead, indexed by the id attribute. This way, even if you remove a single dict, the other id's still remain the same.</p>
| 8 | 2010-03-24T14:40:51Z | [
"python",
"list",
"dictionary"
] |
List of dict in Python | 2,508,513 | <p>I've got a list of dict in Python:</p>
<pre><code>dico_cfg = {'name': entry_name, 'ip': entry_ip, 'vendor': combo_vendor, 'stream': combo_stream}
self.list_cfg.append(dico_cfg)
</code></pre>
<p>I append to my list a lot of dict in the same way.</p>
<p>Now I would like to delete one dict and only one dict in this ... | 1 | 2010-03-24T14:36:08Z | 2,508,580 | <p>If I get you correctly, you don't want the indices to change when you remove an element from your <code>list</code> of <code>dict</code>s. One solution is to use a <code>dict</code> of <code>dict</code>s instead.</p>
<pre><code>dictOne = {'foo':'bar'}
dictTwo = {'bar':'foo'}
dictOfDicts = {0:dictOne, 1:dictTwo} #an... | 1 | 2010-03-24T14:43:13Z | [
"python",
"list",
"dictionary"
] |
List of dict in Python | 2,508,513 | <p>I've got a list of dict in Python:</p>
<pre><code>dico_cfg = {'name': entry_name, 'ip': entry_ip, 'vendor': combo_vendor, 'stream': combo_stream}
self.list_cfg.append(dico_cfg)
</code></pre>
<p>I append to my list a lot of dict in the same way.</p>
<p>Now I would like to delete one dict and only one dict in this ... | 1 | 2010-03-24T14:36:08Z | 2,508,586 | <p>Identifying the dictionaries with an extra entry, as you suggest, is one viable idea:</p>
<pre><code>dico_cfg = {'name': entry_name, 'ip': entry_ip, 'vendor': combo_vendor,
'stream': combo_stream, 'id': 'dico_cfg'}
self.list_cfg.append(dico_cfg)
</code></pre>
<p>and later</p>
<pre><code>self.list_cfg[... | 1 | 2010-03-24T14:44:14Z | [
"python",
"list",
"dictionary"
] |
Most efficient way to concatenate and rearrange files | 2,508,610 | <p>I am reading from several files, each file is divided into 2 pieces, first a header section of a few thousand lines followed by a body of a few thousand. My problem is I need to concatenate these files into one file where all the headers are on the top followed by the body. </p>
<p>Currently I am using two loops: o... | 2 | 2010-03-24T14:46:45Z | 2,508,736 | <p>How fast would you expect it to be to move 13Gb of data around? This problem is I/O bound and not a problem with Python. To make it faster, do less I/O. Which means that you are either (a) stuck with the speed you've got or (b) should retool later elements of your toolchain to handle the files in-place rather tha... | 2 | 2010-03-24T15:01:56Z | [
"python",
"file",
"concatenation"
] |
Most efficient way to concatenate and rearrange files | 2,508,610 | <p>I am reading from several files, each file is divided into 2 pieces, first a header section of a few thousand lines followed by a body of a few thousand. My problem is I need to concatenate these files into one file where all the headers are on the top followed by the body. </p>
<p>Currently I am using two loops: o... | 2 | 2010-03-24T14:46:45Z | 2,508,737 | <p>You can save the time it takes the 2nd time to skip the headers, as long as you have a reasonable amount of spare disk space: as well as the final file, also open (for 'w+') a temporary file <code>temp_file</code>, and do:</p>
<pre><code>import shutil
hdr_list = []
bod_list = []
dispatch = {True: (hdr_list, final_... | 2 | 2010-03-24T15:01:59Z | [
"python",
"file",
"concatenation"
] |
Most efficient way to concatenate and rearrange files | 2,508,610 | <p>I am reading from several files, each file is divided into 2 pieces, first a header section of a few thousand lines followed by a body of a few thousand. My problem is I need to concatenate these files into one file where all the headers are on the top followed by the body. </p>
<p>Currently I am using two loops: o... | 2 | 2010-03-24T14:46:45Z | 2,508,746 | <p>There are two gross inefficiencies in the code you meant to write (which is not the code presented):</p>
<ol>
<li>You are building up huge lists of header lines in the first major <code>for</code> block instead of just writing them out.</li>
<li>You are skipping the headers of the files again in the second major <c... | 0 | 2010-03-24T15:03:08Z | [
"python",
"file",
"concatenation"
] |
Need to understand Python signals and modules | 2,508,748 | <p>I am trying to get up to speed with Python, trying to replace some C with it. I have run into a problem with sharing data between modules, or more likely my understanding of the whole thing. I have a signal module which simplified is:</p>
<pre><code>import sys, signal
sigterm_caught = False
def SignalHandler(sign... | 3 | 2010-03-24T15:03:25Z | 2,508,775 | <p>You need to add a <code>global</code> statement to the handler:</p>
<pre><code>def SignalHandler(signum, stackframe):
global sigterm_caught
if signum == signal.SIGTERM:
sigterm_caught = True
sys.stdout.write("SIGTERM caught\n")
</code></pre>
<p>The Python compiler, by default, deems each name (like <co... | 7 | 2010-03-24T15:06:39Z | [
"python",
"module",
"signals"
] |
Need to understand Python signals and modules | 2,508,748 | <p>I am trying to get up to speed with Python, trying to replace some C with it. I have run into a problem with sharing data between modules, or more likely my understanding of the whole thing. I have a signal module which simplified is:</p>
<pre><code>import sys, signal
sigterm_caught = False
def SignalHandler(sign... | 3 | 2010-03-24T15:03:25Z | 2,508,778 | <p>If you are <strong>writing</strong> to a global variable, use global:</p>
<pre><code>sigterm_caught = False
def SignalHandler(signum, stackframe):
global sigterm_caught
if signum == signal.SIGTERM:
sigterm_caught = True
sys.stdout.write("SIGTERM caught\n")
</code></pre>
| 3 | 2010-03-24T15:07:06Z | [
"python",
"module",
"signals"
] |
Convert or strip out "illegal" Unicode characters | 2,508,847 | <p>I've got a database in MSSQL that I'm porting to SQLite/Django. I'm using pymssql to connect to the database and save a text field to the local SQLite database.</p>
<p>However for some characters, it explodes. I get complaints like this:</p>
<pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0x97 in po... | 7 | 2010-03-24T15:14:59Z | 2,508,870 | <p>When you decode, just pass 'ignore' to strip those characters</p>
<p>there is some more way of stripping / converting those are</p>
<pre><code>'replace': replace malformed data with a suitable replacement marker, such as '?' or '\ufffd'
'ignore': ignore malformed data and continue without further notice
'backs... | 11 | 2010-03-24T15:18:08Z | [
"python",
"unicode",
"pymssql"
] |
Convert or strip out "illegal" Unicode characters | 2,508,847 | <p>I've got a database in MSSQL that I'm porting to SQLite/Django. I'm using pymssql to connect to the database and save a text field to the local SQLite database.</p>
<p>However for some characters, it explodes. I get complaints like this:</p>
<pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0x97 in po... | 7 | 2010-03-24T15:14:59Z | 2,508,901 | <p>Once you have the string of bytes <code>s</code>, instead of using it as a unicode obj directly, convert it explicitly with the right codec, e.g.:</p>
<pre><code>u = s.decode('latin-1')
</code></pre>
<p>and use <code>u</code> instead of <code>s</code> in the code that follows this point (presumably the part that w... | 11 | 2010-03-24T15:22:13Z | [
"python",
"unicode",
"pymssql"
] |
Python: Convert a string to an integer | 2,508,861 | <p>Does anybody have a quickie for converting an unsafe string to an <code>int</code>?</p>
<p>The string typically comes back as: <code>'234\r\n'</code> or something like that.</p>
<p>In this case I want <code>234</code>. If <code>'-1\r\n'</code>, I want <code>-1</code>. I never want the method to fail but I don't w... | 7 | 2010-03-24T15:17:04Z | 2,508,868 | <p><code>int('243\r\n'.strip())</code></p>
<p>But that won't help you, if something else than a number is passed. Always put try, except and catch <code>ValueError</code>.</p>
<p>Anyway, this also works: <code>int('243\n\r ')</code>, so maybe you don't even need <code>strip</code>.</p>
<p><strong>EDIT</strong>:</p>... | 8 | 2010-03-24T15:18:00Z | [
"python"
] |
Python: Convert a string to an integer | 2,508,861 | <p>Does anybody have a quickie for converting an unsafe string to an <code>int</code>?</p>
<p>The string typically comes back as: <code>'234\r\n'</code> or something like that.</p>
<p>In this case I want <code>234</code>. If <code>'-1\r\n'</code>, I want <code>-1</code>. I never want the method to fail but I don't w... | 7 | 2010-03-24T15:17:04Z | 2,508,894 | <pre><code>try:
x=int("234\r\n".strip())
except ValueError:
x=0
</code></pre>
| 1 | 2010-03-24T15:21:04Z | [
"python"
] |
Python: Convert a string to an integer | 2,508,861 | <p>Does anybody have a quickie for converting an unsafe string to an <code>int</code>?</p>
<p>The string typically comes back as: <code>'234\r\n'</code> or something like that.</p>
<p>In this case I want <code>234</code>. If <code>'-1\r\n'</code>, I want <code>-1</code>. I never want the method to fail but I don't w... | 7 | 2010-03-24T15:17:04Z | 2,508,904 | <p>You could just:</p>
<pre><code>def to_int(unsafe_string):
return int(unsafe_string.strip())
</code></pre>
<p>But it will throw a <code>ValueError</code> if the stripped <code>unsafe_string</code> is not a valid number. You can of course catch the ValueError and do what you like with it.</p>
| 0 | 2010-03-24T15:22:37Z | [
"python"
] |
Python: Convert a string to an integer | 2,508,861 | <p>Does anybody have a quickie for converting an unsafe string to an <code>int</code>?</p>
<p>The string typically comes back as: <code>'234\r\n'</code> or something like that.</p>
<p>In this case I want <code>234</code>. If <code>'-1\r\n'</code>, I want <code>-1</code>. I never want the method to fail but I don't w... | 7 | 2010-03-24T15:17:04Z | 2,508,927 | <pre><code>import re
int(re.sub(r'[^\d-]+', '', your_string))
</code></pre>
<p>This will strip everything except for numbers and the "-" sign. If you can be sure that there won't be ever any excess characters except for whitespace, use gruszczy's method instead. </p>
| 4 | 2010-03-24T15:25:12Z | [
"python"
] |
Python: Convert a string to an integer | 2,508,861 | <p>Does anybody have a quickie for converting an unsafe string to an <code>int</code>?</p>
<p>The string typically comes back as: <code>'234\r\n'</code> or something like that.</p>
<p>In this case I want <code>234</code>. If <code>'-1\r\n'</code>, I want <code>-1</code>. I never want the method to fail but I don't w... | 7 | 2010-03-24T15:17:04Z | 2,508,940 | <p>In this case you do have a way to avoid <code>try</code>/<code>except</code>, although I wouldn't recommend it (assuming your input string is named <code>s</code>, and you're in a function that must return something):</p>
<pre><code>xs = s.strip()
if xs[0:1] in '+-': xs = xs[1:]
if xs.isdigit(): return int(s)
else:... | 16 | 2010-03-24T15:27:00Z | [
"python"
] |
Python: Convert a string to an integer | 2,508,861 | <p>Does anybody have a quickie for converting an unsafe string to an <code>int</code>?</p>
<p>The string typically comes back as: <code>'234\r\n'</code> or something like that.</p>
<p>In this case I want <code>234</code>. If <code>'-1\r\n'</code>, I want <code>-1</code>. I never want the method to fail but I don't w... | 7 | 2010-03-24T15:17:04Z | 2,508,977 | <p>Without knowing what kinds of inputs you are expecting, it's hard to say what is 'enough' to solve this. If you are just worried about trailing newlines, then Xavier Combelle's or gruszczy's answer is enough:</p>
<pre><code>try:
x = int(value)
except ValueError:
x = 0
</code></pre>
<p>If you have to find a... | 0 | 2010-03-24T15:31:47Z | [
"python"
] |
Python: Convert a string to an integer | 2,508,861 | <p>Does anybody have a quickie for converting an unsafe string to an <code>int</code>?</p>
<p>The string typically comes back as: <code>'234\r\n'</code> or something like that.</p>
<p>In this case I want <code>234</code>. If <code>'-1\r\n'</code>, I want <code>-1</code>. I never want the method to fail but I don't w... | 7 | 2010-03-24T15:17:04Z | 2,509,234 | <p>Under Python 3.0 (IDLE) this worked nicely</p>
<blockquote>
<p>strObj = "234\r\n"<br/>
try:<br/>
#a=int(strObj)<br/>
except ValueError:<br/>
#a=-1<br/>
<br/>
print(a)
>>234</p>
</blockquote>
<p><br/></p>
<p>If you're dealing with input you cann... | 0 | 2010-03-24T16:01:58Z | [
"python"
] |
Python: Convert a string to an integer | 2,508,861 | <p>Does anybody have a quickie for converting an unsafe string to an <code>int</code>?</p>
<p>The string typically comes back as: <code>'234\r\n'</code> or something like that.</p>
<p>In this case I want <code>234</code>. If <code>'-1\r\n'</code>, I want <code>-1</code>. I never want the method to fail but I don't w... | 7 | 2010-03-24T15:17:04Z | 22,686,376 | <pre><code>def str_to_int(a):
str_to_int_output=""
for i in range(len(a)):
for b in range(10):
if a[i]==str(b):
str_to_int_output+=a[i]
return int(str_to_int_output)
</code></pre>
<p>fn for "str to float" is a bit more comlicated, but i think i can do it if it is needed.... | 0 | 2014-03-27T11:33:52Z | [
"python"
] |
python urllib2.openurl doesn't work with specific URL (redirect)? | 2,509,073 | <p>I need to download a CSV file, which works fine in browsers using: </p>
<p><a href="http://www.ftse.com/objects/csv_to_csv.jsp?infoCode=100a&theseFilters=&csvAll=&theseColumns=Mw==&theseTitles=&tableTitle=FTSE%20100%20Index%20Constituents&dl=&p_encoded=1&e=.csv" rel="nofollow">http:/... | 1 | 2010-03-24T15:44:53Z | 2,509,522 | <p>urllib2 uses httplib under the hood, so the best way to diagnose this is to turn on http connection debugging. Add this code before you access the url and you should get a nice summary of exactly what http traffic is being generated:</p>
<pre><code>import httplib
httplib.HTTPConnection.debuglevel = 1
</code></pre>
| 1 | 2010-03-24T16:37:26Z | [
"python",
"urllib2"
] |
Restful authentication between two GAE apps | 2,509,205 | <p>I am trying to write a RESTful Google app engine application (Python) that accepts requests only from another GAE that I wrote. I dont like any of the ways that I thought of getting this done, please advise if you know of something better than:</p>
<ul>
<li><p>Get SSL setup, and simply add the credentials on the re... | 0 | 2010-03-24T15:57:54Z | 2,509,490 | <p>Use an <a href="http://docs.python.org/library/hmac.html" rel="nofollow">HMAC</a>. Embed the same secret in each app, and sign requests and responses using the HMAC. Don't forget to include nonces and timestamps to prevent replay attacks!</p>
| 1 | 2010-03-24T16:33:45Z | [
"python",
"google-app-engine",
"rest",
"restful-authentication"
] |
catalogue a list of dictionaries | 2,509,260 | <p>I have a list of dictionaries:</p>
<pre><code>people = [{"name": "Roger", "city": "NY", "age": 20, "sex": "M"},
{"name": "Dan", "city": "Boston", "age": 20, "sex": "M"},
{"name": "Roger", "city": "Boston", "age": 21, "sex": "M"},
{"name": "Dana", "city": "Dallas", "age": 30, "sex": "F"... | 2 | 2010-03-24T16:04:44Z | 2,509,414 | <p>recursively:</p>
<pre><code>import itertools, operator
def catalog(fields,people):
cur_field = operator.itemgetter(fields[0])
groups = itertools.groupby(sorted(people, key=cur_field),cur_field)
if len(fields)==1:
return dict((k,list(v)) for k,v in groups)
else:
return dict((k,catalo... | 8 | 2010-03-24T16:24:00Z | [
"python",
"dictionary",
"nested",
"catalog"
] |
catalogue a list of dictionaries | 2,509,260 | <p>I have a list of dictionaries:</p>
<pre><code>people = [{"name": "Roger", "city": "NY", "age": 20, "sex": "M"},
{"name": "Dan", "city": "Boston", "age": 20, "sex": "M"},
{"name": "Roger", "city": "Boston", "age": 21, "sex": "M"},
{"name": "Dana", "city": "Dallas", "age": 30, "sex": "F"... | 2 | 2010-03-24T16:04:44Z | 2,509,419 | <pre><code>import pprint
people = [{"name": "Roger", "city": "NY", "age": 20, "sex": "M"},
{"name": "Dan", "city": "Boston", "age": 20, "sex": "M"},
{"name": "Roger", "city": "Boston", "age": 21, "sex": "M"},
{"name": "Dana", "city": "Dallas", "age": 30, "sex": "F"}]
fields = ("sex", "age"... | 0 | 2010-03-24T16:24:48Z | [
"python",
"dictionary",
"nested",
"catalog"
] |
catalogue a list of dictionaries | 2,509,260 | <p>I have a list of dictionaries:</p>
<pre><code>people = [{"name": "Roger", "city": "NY", "age": 20, "sex": "M"},
{"name": "Dan", "city": "Boston", "age": 20, "sex": "M"},
{"name": "Roger", "city": "Boston", "age": 21, "sex": "M"},
{"name": "Dana", "city": "Dallas", "age": 30, "sex": "F"... | 2 | 2010-03-24T16:04:44Z | 2,509,493 | <p>Not optimal (could be improved using <code>defaultdict</code>, for instance, but I had Python2.4 installed on my machine), but does the job:</p>
<pre><code>def catalogue(dicts, criteria):
if not criteria:
return dicts
criterion, rest = criteria[0], criteria[1:]
cat = {}
for d in dicts:
... | 0 | 2010-03-24T16:34:01Z | [
"python",
"dictionary",
"nested",
"catalog"
] |
Convert UTF-8 bytes to some other encoding in Python | 2,509,578 | <p>I need to do in Python 2.4 (yes, 2.4 :-( ).</p>
<p>I've got a plain string object, which represents some text encoded with UTF-8. It comes from an external library, which can't be modified.</p>
<p>So, what I think I need to do, is to create an Unicode object using bytes from that source object, and then convert it... | 2 | 2010-03-24T16:43:22Z | 2,509,590 | <pre><code>>>> x.decode('utf8').encode('iso-8859-2')
'Sk\xb3odowski'
</code></pre>
| 9 | 2010-03-24T16:45:01Z | [
"python",
"unicode",
"encoding"
] |
compare two following values in numpy array | 2,509,644 | <p>What is the best way to touch two following values in an numpy array? </p>
<p>example:</p>
<pre><code>npdata = np.array([13,15,20,25])
for i in range( len(npdata) ):
print npdata[i] - npdata[i+1]
</code></pre>
<p>this looks really messed up and additionally needs exception code for the last iteration of the l... | 2 | 2010-03-24T16:50:45Z | 2,509,675 | <p>How about <code>range(len(npdata) - 1)</code> ?</p>
<p>Here's code (using a simple array, but it doesn't matter):</p>
<pre><code>>>> ar = [1, 2, 3, 4, 5]
>>> for i in range(len(ar) - 1):
... print ar[i] + ar[i + 1]
...
3
5
7
9
</code></pre>
<p>As you can see it successfully prints the sums of... | 0 | 2010-03-24T16:55:03Z | [
"python",
"indexing",
"loops",
"numpy",
"iteration"
] |
compare two following values in numpy array | 2,509,644 | <p>What is the best way to touch two following values in an numpy array? </p>
<p>example:</p>
<pre><code>npdata = np.array([13,15,20,25])
for i in range( len(npdata) ):
print npdata[i] - npdata[i+1]
</code></pre>
<p>this looks really messed up and additionally needs exception code for the last iteration of the l... | 2 | 2010-03-24T16:50:45Z | 2,509,695 | <p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ediff1d.html#numpy.ediff1d" rel="nofollow">ediff1d</a> to get differences of consecutive elements. More generally, <code>a[1:] - a[:-1]</code> will give the differences of consecutive elements and can be used with other operators as well.... | 0 | 2010-03-24T16:58:09Z | [
"python",
"indexing",
"loops",
"numpy",
"iteration"
] |
compare two following values in numpy array | 2,509,644 | <p>What is the best way to touch two following values in an numpy array? </p>
<p>example:</p>
<pre><code>npdata = np.array([13,15,20,25])
for i in range( len(npdata) ):
print npdata[i] - npdata[i+1]
</code></pre>
<p>this looks really messed up and additionally needs exception code for the last iteration of the l... | 2 | 2010-03-24T16:50:45Z | 2,509,757 | <p>numpy provides a function <code>diff</code> for this basic use case</p>
<pre><code>>>> import numpy
>>> x = numpy.array([1, 2, 4, 7, 0])
>>> numpy.diff(x)
array([ 1, 2, 3, -7])
</code></pre>
<p>Your snippet computes something closer to <code>-numpy.diff(x)</code>.</p>
| 2 | 2010-03-24T17:05:17Z | [
"python",
"indexing",
"loops",
"numpy",
"iteration"
] |
Python - Nested List to Tab Delimited File? | 2,509,706 | <p>I have a nested list comprising ~30,000 sub-lists, each with three entries, e.g.,</p>
<pre><code>nested_list = [['x', 'y', 'z'], ['a', 'b', 'c']].
</code></pre>
<p>I wish to create a function in order to output this data construct into a tab delimited format, e.g.,</p>
<pre><code>x y z
a b c
</code></... | 5 | 2010-03-24T16:59:25Z | 2,509,721 | <pre><code>>>> nested_list = [['x', 'y', 'z'], ['a', 'b', 'c']]
>>> for line in nested_list:
... print '\t'.join(line)
...
x y z
a b c
>>>
</code></pre>
| 5 | 2010-03-24T17:01:41Z | [
"python",
"list",
"nested",
"tab-delimited"
] |
Python - Nested List to Tab Delimited File? | 2,509,706 | <p>I have a nested list comprising ~30,000 sub-lists, each with three entries, e.g.,</p>
<pre><code>nested_list = [['x', 'y', 'z'], ['a', 'b', 'c']].
</code></pre>
<p>I wish to create a function in order to output this data construct into a tab delimited format, e.g.,</p>
<pre><code>x y z
a b c
</code></... | 5 | 2010-03-24T16:59:25Z | 2,509,732 | <pre><code>>>> print '\n'.join(map('\t'.join,nested_list))
x y z
a b c
>>>
</code></pre>
| 2 | 2010-03-24T17:02:41Z | [
"python",
"list",
"nested",
"tab-delimited"
] |
Python - Nested List to Tab Delimited File? | 2,509,706 | <p>I have a nested list comprising ~30,000 sub-lists, each with three entries, e.g.,</p>
<pre><code>nested_list = [['x', 'y', 'z'], ['a', 'b', 'c']].
</code></pre>
<p>I wish to create a function in order to output this data construct into a tab delimited format, e.g.,</p>
<pre><code>x y z
a b c
</code></... | 5 | 2010-03-24T16:59:25Z | 2,509,735 | <pre><code>out = file("yourfile", "w")
for line in nested_list:
print >> out, "\t".join(line)
</code></pre>
| 1 | 2010-03-24T17:02:48Z | [
"python",
"list",
"nested",
"tab-delimited"
] |
Python - Nested List to Tab Delimited File? | 2,509,706 | <p>I have a nested list comprising ~30,000 sub-lists, each with three entries, e.g.,</p>
<pre><code>nested_list = [['x', 'y', 'z'], ['a', 'b', 'c']].
</code></pre>
<p>I wish to create a function in order to output this data construct into a tab delimited format, e.g.,</p>
<pre><code>x y z
a b c
</code></... | 5 | 2010-03-24T16:59:25Z | 2,509,848 | <pre><code>with open('fname', 'w') as file:
file.writelines('\t'.join(i) + '\n' for i in nested_list)
</code></pre>
| 4 | 2010-03-24T17:15:49Z | [
"python",
"list",
"nested",
"tab-delimited"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.