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
Why does my Python class claim that I have 2 arguments instead of 1?
1,868,685
<pre><code>#! /usr/bin/env python import os import stat import sys class chkup: def set(file): filepermission = os.stat(file) user_read() user_write() user_exec() def user_read(): """Return True if 'file' is readable by us...
5
2009-12-08T17:52:50Z
1,868,710
<p>Since you're treating <code>set</code> as a bound (instance) method of a class, you must explicitly receive the instance as your first argument. It's called "self" by convention.</p> <pre><code>def set(self, file): filepermission = os.stat(file) user_read() user_write() user_exec() </code></pre>
0
2009-12-08T17:55:43Z
[ "python", "class-method" ]
Why does my Python class claim that I have 2 arguments instead of 1?
1,868,685
<pre><code>#! /usr/bin/env python import os import stat import sys class chkup: def set(file): filepermission = os.stat(file) user_read() user_write() user_exec() def user_read(): """Return True if 'file' is readable by us...
5
2009-12-08T17:52:50Z
1,868,712
<p>Because you're not passing the object (generally referred to as <code>self</code>) as the first parameter to your methods. In Python, a call like this:</p> <pre><code>my_obj.do_something(my_other_obj) </code></pre> <p>is essentially desugared into a call like this:</p> <pre><code>MyClass.do_something(my_obj, my_o...
4
2009-12-08T17:55:48Z
[ "python", "class-method" ]
Why does my Python class claim that I have 2 arguments instead of 1?
1,868,685
<pre><code>#! /usr/bin/env python import os import stat import sys class chkup: def set(file): filepermission = os.stat(file) user_read() user_write() user_exec() def user_read(): """Return True if 'file' is readable by us...
5
2009-12-08T17:52:50Z
1,868,746
<p><code>set()</code> is a method of class <code>chkup</code>. When you call <code>i.set(place)</code>, python keeps track of the instance i using the first argument to the method. Generally, every instance method will receive at least one argument, called self, and subsequent arguments follow. You should redefine your...
1
2009-12-08T18:00:18Z
[ "python", "class-method" ]
Why does my Python class claim that I have 2 arguments instead of 1?
1,868,685
<pre><code>#! /usr/bin/env python import os import stat import sys class chkup: def set(file): filepermission = os.stat(file) user_read() user_write() user_exec() def user_read(): """Return True if 'file' is readable by us...
5
2009-12-08T17:52:50Z
1,879,586
<p>in order to define a non-static method you must provide "self" as a first argument like this</p> <p>class chkup:</p> <pre><code> def set(self,file): filepermission = os.stat(file) </code></pre> <p>#this is done to make non static methods,</p> <p>#the call of set() here done by</p> <p>chk=chkup()<...
0
2009-12-10T08:51:13Z
[ "python", "class-method" ]
Why does my Python class claim that I have 2 arguments instead of 1?
1,868,685
<pre><code>#! /usr/bin/env python import os import stat import sys class chkup: def set(file): filepermission = os.stat(file) user_read() user_write() user_exec() def user_read(): """Return True if 'file' is readable by us...
5
2009-12-08T17:52:50Z
1,992,338
<p>Thats because python automatically passes the current object as an argument to all the methods in the class,so when you pass 2 arguments to a function,python appends the third argument which is the current object,the method prototype should consider this</p>
0
2010-01-02T18:25:16Z
[ "python", "class-method" ]
How do I copy an entire directory of files into an existing directory using Python?
1,868,714
<p>Run the following code from a directory that contains a directory named <code>bar</code> (containing one or more files) and a directory named <code>baz</code> (also containing one or more files). Make sure there is not a directory named <code>foo</code>.</p> <pre><code>import shutil shutil.copytree('bar', 'foo') s...
43
2009-12-08T17:56:04Z
1,868,733
<p><a href="http://docs.python.org/library/shutil.html#shutil.copytree">docs explicitly state that destination directory should <strong>not</strong> exist</a>:</p> <blockquote> <p>The destination directory, named by <code>dst</code>, must not already exist; it will be created as well as missing parent directories.</...
6
2009-12-08T17:59:27Z
[ "python", "shutil", "copytree" ]
How do I copy an entire directory of files into an existing directory using Python?
1,868,714
<p>Run the following code from a directory that contains a directory named <code>bar</code> (containing one or more files) and a directory named <code>baz</code> (also containing one or more files). Make sure there is not a directory named <code>foo</code>.</p> <pre><code>import shutil shutil.copytree('bar', 'foo') s...
43
2009-12-08T17:56:04Z
1,868,742
<p>i would assume fastest and simplest way would be have python call the system commands... </p> <p>example..</p> <pre><code>import os cmd = '&lt;command line call&gt;' os.system(cmd) </code></pre> <p>Tar and gzip up the directory.... unzip and untar the directory in the desired place. </p> <p>yah?</p>
1
2009-12-08T18:00:05Z
[ "python", "shutil", "copytree" ]
How do I copy an entire directory of files into an existing directory using Python?
1,868,714
<p>Run the following code from a directory that contains a directory named <code>bar</code> (containing one or more files) and a directory named <code>baz</code> (also containing one or more files). Make sure there is not a directory named <code>foo</code>.</p> <pre><code>import shutil shutil.copytree('bar', 'foo') s...
43
2009-12-08T17:56:04Z
12,514,470
<p>This limitation of the standard <code>shutil.copytree</code> seems arbitrary and annoying. Workaround:</p> <pre><code>def copytree(src, dst, symlinks=False, ignore=None): for item in os.listdir(src): s = os.path.join(src, item) d = os.path.join(dst, item) if os.path.isdir(s): ...
58
2012-09-20T14:10:22Z
[ "python", "shutil", "copytree" ]
How do I copy an entire directory of files into an existing directory using Python?
1,868,714
<p>Run the following code from a directory that contains a directory named <code>bar</code> (containing one or more files) and a directory named <code>baz</code> (also containing one or more files). Make sure there is not a directory named <code>foo</code>.</p> <pre><code>import shutil shutil.copytree('bar', 'foo') s...
43
2009-12-08T17:56:04Z
13,814,557
<p>In slight improvement on atzz's answer to the function where the above function always tries to copy the files from source to destination. </p> <pre><code>def copytree(src, dst, symlinks=False, ignore=None): if not os.path.exists(dst): os.makedirs(dst) for item in os.listdir(src): s = os.pat...
34
2012-12-11T06:04:54Z
[ "python", "shutil", "copytree" ]
How do I copy an entire directory of files into an existing directory using Python?
1,868,714
<p>Run the following code from a directory that contains a directory named <code>bar</code> (containing one or more files) and a directory named <code>baz</code> (also containing one or more files). Make sure there is not a directory named <code>foo</code>.</p> <pre><code>import shutil shutil.copytree('bar', 'foo') s...
43
2009-12-08T17:56:04Z
22,331,852
<p>A merge one inspired by atzz and Mital Vora:</p> <pre><code>#!/usr/bin/python import os import shutil import stat def copytree(src, dst, symlinks = False, ignore = None): if not os.path.exists(dst): os.makedirs(dst) shutil.copystat(src, dst) lst = os.listdir(src) if ignore: excl = ignore(src, lst)...
23
2014-03-11T17:14:16Z
[ "python", "shutil", "copytree" ]
How do I copy an entire directory of files into an existing directory using Python?
1,868,714
<p>Run the following code from a directory that contains a directory named <code>bar</code> (containing one or more files) and a directory named <code>baz</code> (also containing one or more files). Make sure there is not a directory named <code>foo</code>.</p> <pre><code>import shutil shutil.copytree('bar', 'foo') s...
43
2009-12-08T17:56:04Z
24,468,950
<p>Here is my version of the same task::</p> <pre><code>import os, glob, shutil def make_dir(path): if not os.path.isdir(path): os.mkdir(path) def copy_dir(source_item, destination_item): if os.path.isdir(source_item): make_dir(destination_item) sub_items = glob.glob(source_item + '/...
0
2014-06-28T16:45:47Z
[ "python", "shutil", "copytree" ]
How do I copy an entire directory of files into an existing directory using Python?
1,868,714
<p>Run the following code from a directory that contains a directory named <code>bar</code> (containing one or more files) and a directory named <code>baz</code> (also containing one or more files). Make sure there is not a directory named <code>foo</code>.</p> <pre><code>import shutil shutil.copytree('bar', 'foo') s...
43
2009-12-08T17:56:04Z
27,161,799
<p>This is inspired from the original best answer provided by atzz, I just added replace file / folder logic. So it doesn't actually merge, but deletes the existing file/ folder and copies the new one:</p> <pre><code>import shutil import os def copytree(src, dst, symlinks=False, ignore=None): for item in os.listdi...
1
2014-11-27T01:43:32Z
[ "python", "shutil", "copytree" ]
How do I copy an entire directory of files into an existing directory using Python?
1,868,714
<p>Run the following code from a directory that contains a directory named <code>bar</code> (containing one or more files) and a directory named <code>baz</code> (also containing one or more files). Make sure there is not a directory named <code>foo</code>.</p> <pre><code>import shutil shutil.copytree('bar', 'foo') s...
43
2009-12-08T17:56:04Z
31,039,095
<p>Here's a solution that's part of the standard library. </p> <pre><code>from distutils.dir_util import copy_tree copy_tree("/a/b/c", "/x/y/z") </code></pre> <p>See this similar question.</p> <p><a href="http://stackoverflow.com/questions/15034151/copy-directory-contents-into-a-directory-with-python">Copy director...
18
2015-06-24T23:56:31Z
[ "python", "shutil", "copytree" ]
How do I copy an entire directory of files into an existing directory using Python?
1,868,714
<p>Run the following code from a directory that contains a directory named <code>bar</code> (containing one or more files) and a directory named <code>baz</code> (also containing one or more files). Make sure there is not a directory named <code>foo</code>.</p> <pre><code>import shutil shutil.copytree('bar', 'foo') s...
43
2009-12-08T17:56:04Z
35,371,850
<p>Here is a version inspired by this thread that more closely mimics <code>distutils.file_util.copy_file</code>.</p> <p><code>updateonly</code> is a bool if True, will only copy files with modified dates newer than existing files in <code>dst</code> unless listed in <code>forceupdate</code> which will copy regardless...
0
2016-02-12T20:43:38Z
[ "python", "shutil", "copytree" ]
How do I copy an entire directory of files into an existing directory using Python?
1,868,714
<p>Run the following code from a directory that contains a directory named <code>bar</code> (containing one or more files) and a directory named <code>baz</code> (also containing one or more files). Make sure there is not a directory named <code>foo</code>.</p> <pre><code>import shutil shutil.copytree('bar', 'foo') s...
43
2009-12-08T17:56:04Z
38,346,457
<p>The previous solution has some issue that <code>src</code> may overwrite <code>dst</code> without any notification or exception.</p> <p>I add a <code>predict_error</code> method to predict errors before copy.<code>copytree</code> mainly base on Cyrille Pontvieux's version.</p> <p>Using <code>predict_error</code> t...
0
2016-07-13T08:31:04Z
[ "python", "shutil", "copytree" ]
WxPython, Windows Vista 64-bit, and failure
1,868,749
<p>I have Windows Vista 64-bit SP2. I am trying to use wxPython for GUI development with Python, because all my research pointed to that as the way to go. I have downloaded and installed the win64 wxPython. I get the same error every time.</p> <pre><code>Python 2.6 (r26:66721, Oct 2 2008, 11:35:03) [MSC v.1500 32 bit...
1
2009-12-08T18:01:00Z
1,868,792
<p>It looks like you're trying to run 64-bit wxPython on 32-bit Python. You need them both to be for the same architecture.</p>
6
2009-12-08T18:07:38Z
[ "python", "windows-vista", "64bit", "wxpython" ]
Basic easy_install question on python 2.6
1,868,798
<p>I'm trying to install a python api for controlling imagemagick (<a href="http://www.assembla.com/wiki/show/pythonmagickwand" rel="nofollow">this</a>) and followed the instructions.</p> <p>I imported easy_install:</p> <pre><code>import easy_install </code></pre> <p>and then input the line:</p> <pre><code>easy_ins...
0
2009-12-08T18:09:17Z
1,868,821
<p><code>easy_install</code> is a shell command, run at the shell.</p> <p>It's not a python command; it's not run from within Python.</p>
2
2009-12-08T18:12:34Z
[ "python", "imagemagick", "easy-install" ]
Basic easy_install question on python 2.6
1,868,798
<p>I'm trying to install a python api for controlling imagemagick (<a href="http://www.assembla.com/wiki/show/pythonmagickwand" rel="nofollow">this</a>) and followed the instructions.</p> <p>I imported easy_install:</p> <pre><code>import easy_install </code></pre> <p>and then input the line:</p> <pre><code>easy_ins...
0
2009-12-08T18:09:17Z
1,868,823
<p>I believe easy_install is a script that should be run from the command line</p>
1
2009-12-08T18:12:39Z
[ "python", "imagemagick", "easy-install" ]
Basic easy_install question on python 2.6
1,868,798
<p>I'm trying to install a python api for controlling imagemagick (<a href="http://www.assembla.com/wiki/show/pythonmagickwand" rel="nofollow">this</a>) and followed the instructions.</p> <p>I imported easy_install:</p> <pre><code>import easy_install </code></pre> <p>and then input the line:</p> <pre><code>easy_ins...
0
2009-12-08T18:09:17Z
1,868,868
<p>Check <a href="http://peak.telecommunity.com/DevCenter/EasyInstall#using-easy-install" rel="nofollow">http://peak.telecommunity.com/DevCenter/EasyInstall#using-easy-install</a> for a good reference.</p> <p>also, easy_install is run from the command line.</p>
4
2009-12-08T18:19:55Z
[ "python", "imagemagick", "easy-install" ]
Basic easy_install question on python 2.6
1,868,798
<p>I'm trying to install a python api for controlling imagemagick (<a href="http://www.assembla.com/wiki/show/pythonmagickwand" rel="nofollow">this</a>) and followed the instructions.</p> <p>I imported easy_install:</p> <pre><code>import easy_install </code></pre> <p>and then input the line:</p> <pre><code>easy_ins...
0
2009-12-08T18:09:17Z
1,868,995
<p>Typical easy_install usage would be more like "easy_install imagemagick", a package name rather than a pointer to an svn repository. It looks like you can install from <a href="http://bytes.com/topic/python/answers/664977-easy%5Finstall-svn" rel="nofollow">svn via easy_install</a> with the -i flag. Long-term, I'd su...
0
2009-12-08T18:39:00Z
[ "python", "imagemagick", "easy-install" ]
Convert and merge strings into a list in Python
1,868,857
<p>In Python I have four strings that include the formatting of a list:</p> <pre><code>line1 ="['a.b.c','b.c.a','c.d.e']" line2 ="['def','efg']" line3 ="['f']" line4 ="['g']" </code></pre> <p>How do I merge them all so I get a valid Python list such as:</p> <pre><code>SumLine = ['a.b.c','b.c.a','c.d.e','def','efg','...
4
2009-12-08T18:17:58Z
1,868,881
<pre><code>import ast line1 ="['a.b.c','b.c.a','c.d.e']" line2 ="['def','efg']" line3 ="['f']" line4 ="['g']" SumLine = [] for x in (line1, line2, line3, line4): SumLine.extend(ast.literal_eval(x)) print SumLine </code></pre> <p>Don't use the built-in <code>eval</code> unless you have preternatural trust in the ...
11
2009-12-08T18:22:32Z
[ "python", "string", "list" ]
Convert and merge strings into a list in Python
1,868,857
<p>In Python I have four strings that include the formatting of a list:</p> <pre><code>line1 ="['a.b.c','b.c.a','c.d.e']" line2 ="['def','efg']" line3 ="['f']" line4 ="['g']" </code></pre> <p>How do I merge them all so I get a valid Python list such as:</p> <pre><code>SumLine = ['a.b.c','b.c.a','c.d.e','def','efg','...
4
2009-12-08T18:17:58Z
1,868,884
<p>Try <a href="http://docs.python.org/library/functions.html?highlight=eval#eval" rel="nofollow">eval</a>:</p> <pre><code>&gt;&gt;&gt; line1 ="['a.b.c','b.c.a','c.d.e']" &gt;&gt;&gt; line2 ="['def','efg']" &gt;&gt;&gt; line3 ="['f']" &gt;&gt;&gt; line4 ="['g']" &gt;&gt;&gt; eval(line1) + eval(line2) + eval(line3) + e...
1
2009-12-08T18:22:52Z
[ "python", "string", "list" ]
Convert and merge strings into a list in Python
1,868,857
<p>In Python I have four strings that include the formatting of a list:</p> <pre><code>line1 ="['a.b.c','b.c.a','c.d.e']" line2 ="['def','efg']" line3 ="['f']" line4 ="['g']" </code></pre> <p>How do I merge them all so I get a valid Python list such as:</p> <pre><code>SumLine = ['a.b.c','b.c.a','c.d.e','def','efg','...
4
2009-12-08T18:17:58Z
1,868,891
<p>you need to <code>eval</code> them first and then you could sum the results. But I wonder how do you get this strings in the first place?</p>
0
2009-12-08T18:23:35Z
[ "python", "string", "list" ]
Convert and merge strings into a list in Python
1,868,857
<p>In Python I have four strings that include the formatting of a list:</p> <pre><code>line1 ="['a.b.c','b.c.a','c.d.e']" line2 ="['def','efg']" line3 ="['f']" line4 ="['g']" </code></pre> <p>How do I merge them all so I get a valid Python list such as:</p> <pre><code>SumLine = ['a.b.c','b.c.a','c.d.e','def','efg','...
4
2009-12-08T18:17:58Z
1,868,893
<p>The quick and dirty way is to use <code>eval</code>:</p> <pre><code>SumLine = eval(line1) + eval(line2) + eval(line3) + eval(line4) </code></pre> <p>But dont do this if you are getting these strings from someone else (ie user input)</p>
1
2009-12-08T18:23:59Z
[ "python", "string", "list" ]
Convert and merge strings into a list in Python
1,868,857
<p>In Python I have four strings that include the formatting of a list:</p> <pre><code>line1 ="['a.b.c','b.c.a','c.d.e']" line2 ="['def','efg']" line3 ="['f']" line4 ="['g']" </code></pre> <p>How do I merge them all so I get a valid Python list such as:</p> <pre><code>SumLine = ['a.b.c','b.c.a','c.d.e','def','efg','...
4
2009-12-08T18:17:58Z
1,868,903
<p>The simple way is to concetenate the strings to an expression that can be evaulated to give the required result:</p> <pre><code>line1 ="['a.b.c','b.c.a','c.d.e']" line2 ="['def','efg']" line3 ="['f']" line4 ="['g']" lines = [line1, line2, line3, line4] print eval('+'.join(lines)) </code></pre> <p>However this is ...
2
2009-12-08T18:25:10Z
[ "python", "string", "list" ]
Convert and merge strings into a list in Python
1,868,857
<p>In Python I have four strings that include the formatting of a list:</p> <pre><code>line1 ="['a.b.c','b.c.a','c.d.e']" line2 ="['def','efg']" line3 ="['f']" line4 ="['g']" </code></pre> <p>How do I merge them all so I get a valid Python list such as:</p> <pre><code>SumLine = ['a.b.c','b.c.a','c.d.e','def','efg','...
4
2009-12-08T18:17:58Z
1,868,927
<p>Where did you get these strings? Anything short of a real parser will be fragile. Below is what I would recommed, if I had not seen Alex Martelli's brilliant answer before!</p> <p>You may parse them as JSON arrays, but JSON wants to read double-quoted strings, not single quotes. This introduces fragility to the met...
1
2009-12-08T18:28:35Z
[ "python", "string", "list" ]
Removing custom widget from QVBoxLayout
1,869,034
<p>I've got a QFrame with a QVBoxLayout and I'm adding my own custom widgets to the layout to simulate a QListWidget but with more information/functionality in the items. I add the widget to the layout and keep a reference in a member variable (this is Python): </p> <pre><code> self.sv_widgets[purchase.id] = widget ...
1
2009-12-08T18:46:04Z
1,869,082
<p>You can do this:</p> <pre><code>import sip # you'll need this import (no worries, it ships with your pyqt install) sip.delete(self.sv_widgets[purchase.id]) </code></pre> <p><code>sip.delete(obj)</code> <strong>explicitely</strong> calls the destructor on the corresponding C++ object. <code>removeWidget</code> does...
6
2009-12-08T18:54:17Z
[ "python", "qt", "layout", "pyqt" ]
Removing custom widget from QVBoxLayout
1,869,034
<p>I've got a QFrame with a QVBoxLayout and I'm adding my own custom widgets to the layout to simulate a QListWidget but with more information/functionality in the items. I add the widget to the layout and keep a reference in a member variable (this is Python): </p> <pre><code> self.sv_widgets[purchase.id] = widget ...
1
2009-12-08T18:46:04Z
1,884,621
<p>You can also use self.sv_widgets[purchase.id].deleteLater()</p>
1
2009-12-10T22:44:26Z
[ "python", "qt", "layout", "pyqt" ]
Python unable to acquire Oracle environment handle in Apache
1,869,832
<p>I can run my django application using the developer server, but it does not run under apache.<br> The error is:</p> <blockquote> <p>Unable to acquire Oracle environment handle</p> </blockquote> <p>Adding an ORACLE_HOME environment variable pointing to my 10g client did not fix the issue.</p> <p>NOTE: the ORACLE...
0
2009-12-08T21:04:53Z
1,869,938
<p>What is path to where your django application resides?</p> <p>If it's in <em>c:\Program Files (x86)\XXX</em> (as seen on 64-bit Windows), this is a <a href="http://support.microsoft.com/kb/555568" rel="nofollow">known issue</a></p>
0
2009-12-08T21:23:53Z
[ "python", "windows", "oracle10g" ]
Why doesn't my script work, but I can manualy INSERT into mysql?
1,869,835
<pre><code>conn = MySQLdb.connect(host='db1', user='user', passwd='pass', db='db', port=3306) cursor = conn.cursor() count = int(sys.argv[1]) x = 0 while x &lt; count: x += 1 cursor.execute("INSERT INTO auth_group(name) VALUES(%s)", (str(x))) #if I change %s to 'kkkk', it doesn't work either. print st...
5
2009-12-08T21:05:46Z
1,869,861
<p>If there's no particular error message (in other words, it seems to work, but the insert doesn't stick), make sure you commit() after the statement:</p> <pre><code>conn.commit() </code></pre>
14
2009-12-08T21:10:02Z
[ "python", "mysql", "database" ]
Why doesn't my script work, but I can manualy INSERT into mysql?
1,869,835
<pre><code>conn = MySQLdb.connect(host='db1', user='user', passwd='pass', db='db', port=3306) cursor = conn.cursor() count = int(sys.argv[1]) x = 0 while x &lt; count: x += 1 cursor.execute("INSERT INTO auth_group(name) VALUES(%s)", (str(x))) #if I change %s to 'kkkk', it doesn't work either. print st...
5
2009-12-08T21:05:46Z
1,869,878
<p>You have to commit (by issuing a <code>conn.commit()</code>), because autocommit is off by default (and rightfully so).</p>
3
2009-12-08T21:12:19Z
[ "python", "mysql", "database" ]
Why doesn't my script work, but I can manualy INSERT into mysql?
1,869,835
<pre><code>conn = MySQLdb.connect(host='db1', user='user', passwd='pass', db='db', port=3306) cursor = conn.cursor() count = int(sys.argv[1]) x = 0 while x &lt; count: x += 1 cursor.execute("INSERT INTO auth_group(name) VALUES(%s)", (str(x))) #if I change %s to 'kkkk', it doesn't work either. print st...
5
2009-12-08T21:05:46Z
8,881,709
<p>If it happens that none of your data get stored even after commiting, have a look at my answer to this issue: <a href="http://stackoverflow.com/questions/8218870/pymysql-callproc-appears-to-affect-subsequent-selects/8878775#8878775">pymysql callproc() appears to affect subsequent selects</a></p> <p>The basic idea t...
1
2012-01-16T14:54:17Z
[ "python", "mysql", "database" ]
Why is the Python calculated "hashlib.sha1" different from "git hash-object" for a file?
1,869,885
<p>I'm trying to calculate the SHA-1 value of a file. </p> <p>I've fabricated this script:</p> <pre><code>def hashfile(filepath): sha1 = hashlib.sha1() f = open(filepath, 'rb') try: sha1.update(f.read()) finally: f.close() return sha1.hexdigest() </code></pre> <p>For a specific fi...
44
2009-12-08T21:13:58Z
1,869,911
<p>git calculates hashes like this: </p> <pre><code>sha1("blob " + filesize + "\0" + data) </code></pre> <p><a href="http://stackoverflow.com/questions/552659/assigning-git-sha1s-without-git">Reference</a></p>
48
2009-12-08T21:17:52Z
[ "python", "git", "hash" ]
Why is the Python calculated "hashlib.sha1" different from "git hash-object" for a file?
1,869,885
<p>I'm trying to calculate the SHA-1 value of a file. </p> <p>I've fabricated this script:</p> <pre><code>def hashfile(filepath): sha1 = hashlib.sha1() f = open(filepath, 'rb') try: sha1.update(f.read()) finally: f.close() return sha1.hexdigest() </code></pre> <p>For a specific fi...
44
2009-12-08T21:13:58Z
19,711,609
<p>For reference, here's a more concise version:</p> <pre><code>def sha1OfFile(filepath): import hashlib with open(filepath, 'rb') as f: return hashlib.sha1(f.read()).hexdigest() </code></pre> <p>On second thought: although I've never seen it, I think there's potential for <code>f.read()</code> to ret...
31
2013-10-31T16:14:19Z
[ "python", "git", "hash" ]
Recreating Postgres COPY directly in Python?
1,869,973
<p>I have a block of data, currently as a list of n-tuples but the format is pretty flexible, that I'd like to append to a Postgres table - in this case, each n-tuple corresponds to a row in the DB.</p> <p>What I had been doing up to this point is writing these all to a CSV file and then using postgres' COPY to bulk l...
16
2009-12-08T21:30:04Z
1,870,002
<p>If you're using the psycopg2 driver, the cursors provide a <code>copy_to</code> and <code>copy_from</code> function that can read from any file-like object (including a <code>StringIO</code> buffer).</p> <p>There are examples in the files <a href="https://github.com/psycopg/psycopg2/blob/master/examples/copy_from.p...
41
2009-12-08T21:34:56Z
[ "python", "postgresql", "psycopg2" ]
Python String parse
1,870,044
<p>Im working on a data packet retrieval system which will take a packet, and process the various <em>parts</em> of the packet, based on a system of tags [similar to HTML tags]. [text based files only, no binary files].</p> <p>Each part of the packet is contained between two identical tags, and here is a sample packet...
0
2009-12-08T21:41:31Z
1,870,094
<p>Something like this?</p> <pre><code>import re def getPacketContent ( code, packetName ): match = re.search( '&lt;' + packetName + '&gt;(.*?)&lt;' + packetName + '&gt;', code ) return match.group( 1 ) if match else '' # usage code = "&lt;PACKET&gt;&lt;HEAD&gt;&lt;ID&gt;&lt;ID&gt;&lt;SEQ&gt;&lt;SEQ&gt;&lt;FI...
1
2009-12-08T21:49:20Z
[ "python" ]
Python String parse
1,870,044
<p>Im working on a data packet retrieval system which will take a packet, and process the various <em>parts</em> of the packet, based on a system of tags [similar to HTML tags]. [text based files only, no binary files].</p> <p>Each part of the packet is contained between two identical tags, and here is a sample packet...
0
2009-12-08T21:41:31Z
1,870,166
<p>If the packet format effectively uses XML-looking syntax (i.e., if the "closing tags" actually include a slash), the <a href="http://docs.python.org/library/xml.etree.elementtree.html" rel="nofollow"><strong>xml.etree.ElementTree</strong></a> could be used.<br> This libray is part of Python Standard Library, startin...
1
2009-12-08T22:03:11Z
[ "python" ]
Python String parse
1,870,044
<p>Im working on a data packet retrieval system which will take a packet, and process the various <em>parts</em> of the packet, based on a system of tags [similar to HTML tags]. [text based files only, no binary files].</p> <p>Each part of the packet is contained between two identical tags, and here is a sample packet...
0
2009-12-08T21:41:31Z
1,871,037
<p>As mjv points out, there's not the least sense in inventing an XML-like format if you can just use XML.</p> <p>But: If you're going to use XML for your packet format, you need to really use XML for it. You should use an XML library to <em>create</em> your packets, not just to parse them. Otherwise you will come ...
1
2009-12-09T01:14:35Z
[ "python" ]
Render in infinity loop
1,870,140
<p>Question for Python 2.6</p> <p>I would like to create an <em>simple</em> web application which in specified time interval will run a script that modifies the data (in database). My problem is code for <em>infinity loop</em> or some other method to achieve this goal. The script should be run only once by the user. N...
1
2009-12-08T21:59:17Z
1,870,159
<p>i think you'd want to use <a href="http://en.wikipedia.org/wiki/Cron" rel="nofollow">cron</a>. write your script, and have <a href="http://en.wikipedia.org/wiki/Cron" rel="nofollow">cron</a> run it every X minutes / hours.</p> <p>if you really want to do this in Python, you can do something like this:</p> <pre><c...
1
2009-12-08T22:02:39Z
[ "python", "google-app-engine", "cron" ]
Render in infinity loop
1,870,140
<p>Question for Python 2.6</p> <p>I would like to create an <em>simple</em> web application which in specified time interval will run a script that modifies the data (in database). My problem is code for <em>infinity loop</em> or some other method to achieve this goal. The script should be run only once by the user. N...
1
2009-12-08T21:59:17Z
1,870,164
<p>Can you use cron to schedule the job to run at certain intervals? It's usually considered better than infinite loops, and was designed to help solve this sort of problem.</p>
0
2009-12-08T22:02:57Z
[ "python", "google-app-engine", "cron" ]
Render in infinity loop
1,870,140
<p>Question for Python 2.6</p> <p>I would like to create an <em>simple</em> web application which in specified time interval will run a script that modifies the data (in database). My problem is code for <em>infinity loop</em> or some other method to achieve this goal. The script should be run only once by the user. N...
1
2009-12-08T21:59:17Z
1,870,598
<p>There's a very primitive <em>cron</em> in the Python standard library: <a href="http://docs.python.org/library/sched.html" rel="nofollow"><code>import sched</code></a>. There's also <a href="http://docs.python.org/library/threading.html#threading.Timer" rel="nofollow"><code>threading.Timer</code></a>.</p> <p>But a...
0
2009-12-08T23:23:19Z
[ "python", "google-app-engine", "cron" ]
Render in infinity loop
1,870,140
<p>Question for Python 2.6</p> <p>I would like to create an <em>simple</em> web application which in specified time interval will run a script that modifies the data (in database). My problem is code for <em>infinity loop</em> or some other method to achieve this goal. The script should be run only once by the user. N...
1
2009-12-08T21:59:17Z
1,870,637
<p>You mentioned that you're using Google App Engine. You can schedule recurring tasks by placing a <code>cron.yaml</code> file in your application folder. The details are <a href="http://code.google.com/appengine/docs/python/config/cron.html" rel="nofollow">here</a>.</p> <p><strong>Update</strong>: It sounds like y...
4
2009-12-08T23:32:38Z
[ "python", "google-app-engine", "cron" ]
How can I ensure closing all connection in loadbalancer when something fails or hangs?
1,870,251
<p>I'm trying to write a simple load-balancer. It works ok till one of servers (BalanceServer) doesn't close connection then... Client (<em>ReverseProxy</em>) disconnects but the connection in with BalanceServer stays open. I tried to add callback (#3) to <em>ReverseProxy.connectionLost</em> to close the connection wit...
2
2009-12-08T22:16:26Z
4,361,651
<p>You may want to look at <code>twisted.internet.protocols.portforward</code> for an example of hooking up two connections and then disconnecting them. Or just use <a href="https://launchpad.net/txloadbalancer" rel="nofollow">txloadbalancer</a> and don't even write your own code.</p> <p>However, <code>loseConnection...
1
2010-12-05T22:26:13Z
[ "python", "timeout", "twisted", "reverse-proxy", "load-balancing" ]
SQL Alchemy default value function for simulating autoincrement within a unique group of parent-child records
1,870,364
<p>I have a small problem that I think should be easily handled by SQL Alchemy but I can't seem to get it right. I have two tables with one being a parent table and the other a child table. For each child record it needs a unique ID but only with the context of the unique parent record.</p> <p>I am using the Declara...
3
2009-12-08T22:33:21Z
1,873,491
<p>So, what you're trying to achieve is have each set of CategoryItems with a different CategoryUniqueName have their CategoryId auto-incremented separately?</p> <p>If that's right, your current approach (get the current max of CategoryId in the subset of CategoryItems you're adding to) is broken. It has an intrinsic ...
0
2009-12-09T12:05:44Z
[ "python", "sqlalchemy", "primary-key", "auto-increment", "declarative" ]
SQL Alchemy default value function for simulating autoincrement within a unique group of parent-child records
1,870,364
<p>I have a small problem that I think should be easily handled by SQL Alchemy but I can't seem to get it right. I have two tables with one being a parent table and the other a child table. For each child record it needs a unique ID but only with the context of the unique parent record.</p> <p>I am using the Declara...
3
2009-12-08T22:33:21Z
1,879,934
<p>I see 3 ways to go:</p> <ol> <li>The most obvious and well documented. Create a mapper extension with <code>before_insert()</code> hook replacing inserted parameter.</li> <li>Pass function as <code>default</code> argument. This function is called with <code>context</code> parameter with all data you need: <code>con...
3
2009-12-10T09:53:56Z
[ "python", "sqlalchemy", "primary-key", "auto-increment", "declarative" ]
SQL Alchemy default value function for simulating autoincrement within a unique group of parent-child records
1,870,364
<p>I have a small problem that I think should be easily handled by SQL Alchemy but I can't seem to get it right. I have two tables with one being a parent table and the other a child table. For each child record it needs a unique ID but only with the context of the unique parent record.</p> <p>I am using the Declara...
3
2009-12-08T22:33:21Z
1,883,195
<p>Thanks for the insight Denis, you are spot on. I played with both options 1 and 2 and they work very nicely. The context parameter was the key for option 2. I didn't realize it was being passed automatically. One thing I did note was option 1 would introduce a race condition even in the context of a single user ...
1
2009-12-10T18:55:49Z
[ "python", "sqlalchemy", "primary-key", "auto-increment", "declarative" ]
skip an element in zip
1,870,372
<p>I have two files that are <code>zipped</code> with something like the following:</p> <pre><code>for line in zip(open(file1), open(file2)): # do-something </code></pre> <p>Unfortunately, now file2 has changed, and there is an additional line at the beginning. Yes, I could get rid of that manually (or with an ad...
0
2009-12-08T22:34:43Z
1,870,395
<p>Take a look at <a href="http://docs.python.org/library/itertools.html" rel="nofollow">itertools</a>:</p> <pre><code>for line in itertools.izip( open(file1), itertools.islice(open(file2), 1, None) ): # do something </code></pre> <p><strong>Edit:</strong> changed from zip to the itertools.izip functi...
2
2009-12-08T22:39:51Z
[ "python" ]
skip an element in zip
1,870,372
<p>I have two files that are <code>zipped</code> with something like the following:</p> <pre><code>for line in zip(open(file1), open(file2)): # do-something </code></pre> <p>Unfortunately, now file2 has changed, and there is an additional line at the beginning. Yes, I could get rid of that manually (or with an ad...
0
2009-12-08T22:34:43Z
1,870,416
<pre><code>f1 = open(file1) f2 = open(file2) f2.next() # Skip the first line of file2 (used to be readline() - thanks, Alex) for line in zip(f1, f2): # do-something </code></pre>
1
2009-12-08T22:43:07Z
[ "python" ]
skip an element in zip
1,870,372
<p>I have two files that are <code>zipped</code> with something like the following:</p> <pre><code>for line in zip(open(file1), open(file2)): # do-something </code></pre> <p>Unfortunately, now file2 has changed, and there is an additional line at the beginning. Yes, I could get rid of that manually (or with an ad...
0
2009-12-08T22:34:43Z
1,870,431
<p><code>open</code> gives you an iterator, so it's not "subscriptable" but it can easily be advanced by one (with the <code>next</code> builtin in 2.6 or better, the <code>.next()</code> method in older Python versions -- I'm assuming 2.6 or better here).</p> <p>So where you'd like to say:</p> <pre><code>for line in...
4
2009-12-08T22:46:46Z
[ "python" ]
Python to generate output ready for Excel
1,870,383
<p>I have a Python script gathering info from some remote network devices. The output can be maybe 20 to 1000 lines of text. This then goes into excel on my local PC for now.</p> <p>Now access to this Linux device is convoluted, a citrix session to a remote windows server then ssh to the Linux device half way around t...
0
2009-12-08T22:36:28Z
1,870,410
<p>CSV is more robust than your current format under "copy and paste transfer" -- spaces and tabs can easily get confused, commas and doublequotes aren't. And the Python standard library's <a href="http://docs.python.org/library/csv.html?highlight=csv#module-csv" rel="nofollow">csv</a> module makes it pretty easy to s...
7
2009-12-08T22:42:14Z
[ "python", "xml", "excel", "csv" ]
Python to generate output ready for Excel
1,870,383
<p>I have a Python script gathering info from some remote network devices. The output can be maybe 20 to 1000 lines of text. This then goes into excel on my local PC for now.</p> <p>Now access to this Linux device is convoluted, a citrix session to a remote windows server then ssh to the Linux device half way around t...
0
2009-12-08T22:36:28Z
1,870,411
<p>Reformat it as CSV. It's dead easy to do, is fairly human readable, and can be read by loads of pieces of spreadsheet software.</p>
0
2009-12-08T22:42:19Z
[ "python", "xml", "excel", "csv" ]
Python to generate output ready for Excel
1,870,383
<p>I have a Python script gathering info from some remote network devices. The output can be maybe 20 to 1000 lines of text. This then goes into excel on my local PC for now.</p> <p>Now access to this Linux device is convoluted, a citrix session to a remote windows server then ssh to the Linux device half way around t...
0
2009-12-08T22:36:28Z
1,870,421
<p>Are you sure copy-paste is the only way? If you can interactively ssh to the Linux device, then you can also ssh plus run a command plus redirect the output. So:</p> <pre><code>ssh remote-linux-box command-to-run &gt;output-file </code></pre> <p>This doesn't involve any manual copy and paste at all.</p>
0
2009-12-08T22:43:42Z
[ "python", "xml", "excel", "csv" ]
Recognizing newline characters in Python
1,870,435
<p>So I would like to grab stdout from a subprocess and then write the output to a file using python. </p> <p>The problem I'm having is the stdout from the subprocess loses the formatting, it contains \n's where there are newlines. I would like to write the output to a file with formatting intact, meaning instead of o...
1
2009-12-08T22:47:10Z
1,870,466
<p>Don't call <code>repr()</code>, ie. just call</p> <pre><code>f.write(stdout_value) </code></pre>
3
2009-12-08T22:52:19Z
[ "python", "formatting" ]
Recognizing newline characters in Python
1,870,435
<p>So I would like to grab stdout from a subprocess and then write the output to a file using python. </p> <p>The problem I'm having is the stdout from the subprocess loses the formatting, it contains \n's where there are newlines. I would like to write the output to a file with formatting intact, meaning instead of o...
1
2009-12-08T22:47:10Z
1,870,468
<p>Why <code>repr</code>? That turns a object into its representation, which for strings means converting things like <code>chr(10)</code> (newline) into <code>'\n'</code>.</p>
1
2009-12-08T22:52:36Z
[ "python", "formatting" ]
Recognizing newline characters in Python
1,870,435
<p>So I would like to grab stdout from a subprocess and then write the output to a file using python. </p> <p>The problem I'm having is the stdout from the subprocess loses the formatting, it contains \n's where there are newlines. I would like to write the output to a file with formatting intact, meaning instead of o...
1
2009-12-08T22:47:10Z
1,870,477
<p>The <code>repr</code> (which doubles up the "escapes", i.e. backslash characters) is what's causing you to "lose formatting" -- why are you doing that at all? And btw the <code>str</code> call is totally redundant (innocuous, but totally useless -- why have it there?!).</p>
0
2009-12-08T22:54:01Z
[ "python", "formatting" ]
unhexlify in objective c
1,870,475
<p>is there something like Python's <code>unhexlify</code> for objc / cocoa?</p> <pre> >>> from binascii import unhexlify >>> help(unhexlify) Help on built-in function unhexlify in module binascii: unhexlify(...) a2b_hex(hexstr) -> s; Binary data of hexadecimal representation. hexstr must contain an even number of h...
2
2009-12-08T22:53:35Z
1,870,521
<p>Edit: I didn't grok what unhexlify does. I still don't grok why it might be useful (commenters?). </p> <p>You would have to pick off the hex characters two at a time, convert them to an int, and spit out the characters. </p> <pre><code>char *hex = "abc123d35d"; NSData *data = [NSData dataWithBytesNoCopy:hex lengt...
3
2009-12-08T23:07:20Z
[ "iphone", "python", "cocoa-touch" ]
unhexlify in objective c
1,870,475
<p>is there something like Python's <code>unhexlify</code> for objc / cocoa?</p> <pre> >>> from binascii import unhexlify >>> help(unhexlify) Help on built-in function unhexlify in module binascii: unhexlify(...) a2b_hex(hexstr) -> s; Binary data of hexadecimal representation. hexstr must contain an even number of h...
2
2009-12-08T22:53:35Z
1,870,779
<p>Here is some very rough, naive, inefficient, and insecure code that implements <code>unhexlify</code>. It's main limitation is that it doesn't check that <code>hexstr</code> contains only hex digits. But this should be enough to get you started.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #inc...
2
2009-12-09T00:07:47Z
[ "iphone", "python", "cocoa-touch" ]
unhexlify in objective c
1,870,475
<p>is there something like Python's <code>unhexlify</code> for objc / cocoa?</p> <pre> >>> from binascii import unhexlify >>> help(unhexlify) Help on built-in function unhexlify in module binascii: unhexlify(...) a2b_hex(hexstr) -> s; Binary data of hexadecimal representation. hexstr must contain an even number of h...
2
2009-12-08T22:53:35Z
1,875,096
<p>How about just the <a href="http://www.cplusplus.com/reference/clibrary/cstdlib/strtol/" rel="nofollow"><code>strtol</code></a> function?</p> <p>It'd be something like this:</p> <pre><code>NSString * abc = @"abc"; NSInteger intVal = strtol([abc cStringUsingEncoding:NSASCIIStringEncoding], nil, 16); NSLog(@"%lld", ...
0
2009-12-09T16:33:12Z
[ "iphone", "python", "cocoa-touch" ]
Quickly alphabetize a large file via python
1,870,541
<pre><code>#!/usr/bin/python import random import string appendToFile = open("appendedFile", "a" ) # Generator for i in range(1, 100000): chars = "".join( [random.choice(string.letters) for i in xrange(15)] ) chars2 = "".join( [random.choice(string.letters) for i in xrange(15)] ) appendToFile.write(ch...
5
2009-12-08T23:12:03Z
1,870,548
<p>The obvious first approach is simply to use the built-in sort feature in Python. Is this not what you had in mind? If not, why? With only 100,000 lines of random text, the built-in sort would be very fast.</p> <pre><code>lst = open("appendedFile", "rt").readlines() lst.sort(key=str.lower) </code></pre> <p>Done....
8
2009-12-08T23:15:12Z
[ "python", "file", "order", "alphabetical" ]
Quickly alphabetize a large file via python
1,870,541
<pre><code>#!/usr/bin/python import random import string appendToFile = open("appendedFile", "a" ) # Generator for i in range(1, 100000): chars = "".join( [random.choice(string.letters) for i in xrange(15)] ) chars2 = "".join( [random.choice(string.letters) for i in xrange(15)] ) appendToFile.write(ch...
5
2009-12-08T23:12:03Z
1,870,581
<p>Try this (case insensitive):</p> <pre><code>l=file(appendedFile).readlines() l.sort(key=lambda x:x.lower()) </code></pre> <p>For these kinds of sizes optimalisation is not really necessary (timings on my slow machine ;-):</p> <pre><code>christophe@orion:~$ time python -c "l=file('appendedFile').readlines();l.sort...
1
2009-12-08T23:20:49Z
[ "python", "file", "order", "alphabetical" ]
Quickly alphabetize a large file via python
1,870,541
<pre><code>#!/usr/bin/python import random import string appendToFile = open("appendedFile", "a" ) # Generator for i in range(1, 100000): chars = "".join( [random.choice(string.letters) for i in xrange(15)] ) chars2 = "".join( [random.choice(string.letters) for i in xrange(15)] ) appendToFile.write(ch...
5
2009-12-08T23:12:03Z
1,870,582
<p>This is very fast (under 1 second on my computer). It uses a case-insensitive sort, which is assume what you mean by "case is irrelevant"?</p> <pre><code>#!/usr/bin/python appendToFile = open("appendedFile", "r") sortToFile = open("sortedFile", "w") for line in sorted(appendToFile, key = str.lower): sortToFil...
5
2009-12-08T23:20:50Z
[ "python", "file", "order", "alphabetical" ]
Python SequenceMatcher Overhead - 100% CPU utilization and very slow processing
1,870,646
<p>I am using difflib to compare files in two directories (versions from consecutive years). First, i am using filecmp to find files that have changed and then iteratively using difflib.SequenceMatcher to compare them and generate a html diff as explained <a href="http://stackoverflow.com/questions/774316/python-diffli...
1
2009-12-08T23:35:44Z
1,870,676
<p>My answer is a different approach to the problem altogether: Try using a version-control system like git to investigate how the directory changed over the years.</p> <p>Make a repository out of the first directory, then replace the contents with the next year's directory and commit that as a change. (or move the ....
3
2009-12-08T23:43:18Z
[ "python", "difflib" ]
In Python, how do I refer to an identifier by its absolute fully-qualified name?
1,870,718
<p>I have a project with a directory structure that looks like:</p> <pre> /foo/baz/__init__.py /bar/foo.py /bar/splat.py </pre> <p>Problem is, <code>/bar/splat.py</code> refers to the <code>foo.baz</code> module. This fails with the error <code>No module named baz</code> because it's trying to search for this module...
0
2009-12-08T23:54:53Z
1,870,733
<p>In Python 2.5 and 2.6,</p> <pre><code>from __future__ import absolute_import </code></pre> <p>should change Python's <code>import</code> behavior to do what you want (if the very root, /, is on <code>sys.path</code> of course;-). This becomes the normal Python behavior in 2.7 (not released yet, but an early alpha...
4
2009-12-08T23:57:50Z
[ "python", "namespaces" ]
efficient way to compress a numpy array (python)
1,870,871
<p>I am looking for an efficient way to compress a numpy array. I have an array like: <code>dtype=[(name, (np.str_,8), (job, (np.str_,8), (income, np.uint32)]</code> (my favourite example).</p> <p>if I'm doing something like this: <code>my_array.compress(my_array['income'] &gt; 10000)</code> I'm getting a new array wi...
4
2009-12-09T00:31:55Z
1,870,918
<p>It's not quite as nice as what you'd like, but I think you can do:</p> <pre><code>mask = my_array['job'] == 'this' for condition in ['that', 'other']: mask = numpy.logical_or(mask,my_array['job'] == condition) selected_array = my_array[mask] </code></pre>
1
2009-12-09T00:44:11Z
[ "python", "filter", "numpy", "compression" ]
efficient way to compress a numpy array (python)
1,870,871
<p>I am looking for an efficient way to compress a numpy array. I have an array like: <code>dtype=[(name, (np.str_,8), (job, (np.str_,8), (income, np.uint32)]</code> (my favourite example).</p> <p>if I'm doing something like this: <code>my_array.compress(my_array['income'] &gt; 10000)</code> I'm getting a new array wi...
4
2009-12-09T00:31:55Z
1,881,464
<p>If you're looking for a numpy-only solution, I don't think you'll get it. Still, although it does lots of work under the covers, consider whether the <a href="http://pypi.python.org/pypi/tabular/" rel="nofollow">tabular</a> package might be able to do what you want in a less "ugly" fashion. I'm not sure you'll get...
0
2009-12-10T14:51:17Z
[ "python", "filter", "numpy", "compression" ]
efficient way to compress a numpy array (python)
1,870,871
<p>I am looking for an efficient way to compress a numpy array. I have an array like: <code>dtype=[(name, (np.str_,8), (job, (np.str_,8), (income, np.uint32)]</code> (my favourite example).</p> <p>if I'm doing something like this: <code>my_array.compress(my_array['income'] &gt; 10000)</code> I'm getting a new array wi...
4
2009-12-09T00:31:55Z
3,987,901
<p>The best way to compress a numpy array is to use pytables. It is the defacto standard when it comes to handling a large amount of numerical data.</p> <pre><code>import tables as t hdf5_file = t.openFile('outfile.hdf5') hdf5_file.createArray ...... hdf5_file.close() </code></pre>
1
2010-10-21T13:26:22Z
[ "python", "filter", "numpy", "compression" ]
python regular expression across multiple lines
1,870,954
<p>I'm gathering some info from some cisco devices using python and pexpect, and had a lot of success with REs to extract pesky little items. I'm afraid i've hit the wall on this. Some switches stack together, I have identified this in the script and used a separate routine to parse the data. If the switch is stacked y...
1
2009-12-09T00:52:02Z
1,870,977
<pre><code>x="""Top Assembly Part Number : 800-25858-06 Top Assembly Revision Number : A0 Version ID : V08 CLEI Code Number : COMDE10BRA Hardware Board Revision Number : 0x01 Switch Ports Model SW Version SW Image ------ ----- ----- ...
2
2009-12-09T00:57:41Z
[ "python", "regex" ]
python regular expression across multiple lines
1,870,954
<p>I'm gathering some info from some cisco devices using python and pexpect, and had a lot of success with REs to extract pesky little items. I'm afraid i've hit the wall on this. Some switches stack together, I have identified this in the script and used a separate routine to parse the data. If the switch is stacked y...
1
2009-12-09T00:52:02Z
1,870,990
<p>To have <code>.</code> match any character, including a newline, compile your RE with <a href="http://docs.python.org/library/re.html?highlight=re.dotall#re.DOTALL">re.DOTALL</a> among the options (remember, if you have multiple options, use <code>|</code>, the bit-or operator, between them, in order to combine them...
8
2009-12-09T01:01:34Z
[ "python", "regex" ]
Debugging Django/Python on Dreamhost
1,871,252
<p>Debugging Django on Dreamhost is proving quite the challenge. To my knowledge, print statements aren't available, and neither are logs... any suggestions?</p>
1
2009-12-09T02:28:19Z
1,871,258
<p>Have you tried the <a href="http://pypi.python.org/pypi/django-debug-toolbar/0.8.1" rel="nofollow">Django Debug Toolbar</a>?</p> <p>For a summary of the features, watch the <a href="http://robhudson.github.com/django-debug-toolbar/" rel="nofollow">video here</a>.</p>
1
2009-12-09T02:30:59Z
[ "python", "django", "debugging", "dreamhost" ]
Debugging Django/Python on Dreamhost
1,871,252
<p>Debugging Django on Dreamhost is proving quite the challenge. To my knowledge, print statements aren't available, and neither are logs... any suggestions?</p>
1
2009-12-09T02:28:19Z
1,871,616
<p>The <a href="http://pypi.python.org/pypi/django-debug-toolbar/0.8.1" rel="nofollow">Django Debug Toolbar</a>, as already mentioned, is damn useful.</p> <p>But as long as Django is running in <a href="http://docs.djangoproject.com/en/dev/ref/settings/#debug" rel="nofollow">debug mode</a>, the brute force method equi...
3
2009-12-09T04:40:02Z
[ "python", "django", "debugging", "dreamhost" ]
Dictionary (same value, different key)
1,871,296
<p>Newbie Alert:</p> <p>I'm new to Python and when I'm basically adding values to a dict, I find that when I'm printing the whole dictionary, I get the same value of something for all keys of a specific key.</p> <p>Seems like a pointer issue?</p> <p>Here's a snippet when using the event-based XML parser (SAX):</p> ...
0
2009-12-09T02:43:55Z
1,871,302
<p>You'll get the value <code>self</code> for every single entry in <code>self.mapping</code>, of course, since that's the only value you ever <strong>store</strong> there. Did you rather mean to take a copy/snapshot of <code>self</code> or some of its attributes at that point, then have <code>self</code> change befor...
4
2009-12-09T02:46:21Z
[ "python", "dictionary" ]
Dictionary (same value, different key)
1,871,296
<p>Newbie Alert:</p> <p>I'm new to Python and when I'm basically adding values to a dict, I find that when I'm printing the whole dictionary, I get the same value of something for all keys of a specific key.</p> <p>Seems like a pointer issue?</p> <p>Here's a snippet when using the event-based XML parser (SAX):</p> ...
0
2009-12-09T02:43:55Z
1,871,312
<p>If I understand what you're saying, then this is probably expected behaviour. When you make an assignment in Python, you're just assigning the <em>reference</em> (sort of like a pointer). When you do:</p> <pre><code>self.mapping[self.Id] = self </code></pre> <p>then future changes to <code>self</code> will be refl...
2
2009-12-09T02:49:36Z
[ "python", "dictionary" ]
Python ctypes: initializing c_char_p()
1,871,375
<p>I wrote a simple C++ program to illustrate my problem:</p> <pre><code>extern "C"{ int test(int, char*); } int test(int i, char* var){ if (i == 1){ strcpy(var,"hi"); } return 1; } </code></pre> <p>I compile this into an so. From python I call:</p> <pre><code>from ctypes import * libso = CDL...
1
2009-12-09T03:15:34Z
1,871,382
<p>I am guessing python is reusing the same buffer for all 5 passes. once you set it to "hi", you never set it back to "bye" You can do something like this:</p> <pre><code>extern "C"{ int test(int, char*); } int test(int i, char* var){ if (i == 1){ strcpy(var,"hi"); } else { strcpy(var, "b...
2
2009-12-09T03:17:30Z
[ "c++", "python", "ctypes", "shared-objects" ]
Python ctypes: initializing c_char_p()
1,871,375
<p>I wrote a simple C++ program to illustrate my problem:</p> <pre><code>extern "C"{ int test(int, char*); } int test(int i, char* var){ if (i == 1){ strcpy(var,"hi"); } return 1; } </code></pre> <p>I compile this into an so. From python I call:</p> <pre><code>from ctypes import * libso = CDL...
1
2009-12-09T03:15:34Z
1,871,409
<p>The string which you initialized with the characters <code>"bye"</code>, and whose address you keep taking and assigning to <code>charP</code>, does not get re-initialized after the first time.</p> <p>Follow the advice <a href="http://docs.python.org/library/ctypes.html?highlight=c%5Fchar%5Fp#fundamental-data-types...
7
2009-12-09T03:25:22Z
[ "c++", "python", "ctypes", "shared-objects" ]
How can I convert JSON to CSV?
1,871,524
<p>I have a JSON file that I want to covert to a CSV file. How can I do this with Python?</p> <p>I tried:</p> <pre><code>import json import csv f = open('data.json') data = json.load(f) f.close() f = open('data.csv') csv_file = csv.writer(f) for item in data: f.writerow(item) f.close() </code></pre> <p>However...
62
2009-12-09T04:06:37Z
1,871,557
<p>This code should work for you, assuming that your JSON data is in a file called <code>data.json</code>.</p> <pre><code>import json import csv with open("data.json") as file: data = json.load(file) with open("data.csv", "w") as file: csv_file = csv.writer(file) for item in data: csv_file.writer...
17
2009-12-09T04:23:05Z
[ "python", "json", "csv" ]
How can I convert JSON to CSV?
1,871,524
<p>I have a JSON file that I want to covert to a CSV file. How can I do this with Python?</p> <p>I tried:</p> <pre><code>import json import csv f = open('data.json') data = json.load(f) f.close() f = open('data.csv') csv_file = csv.writer(f) for item in data: f.writerow(item) f.close() </code></pre> <p>However...
62
2009-12-09T04:06:37Z
1,871,568
<p>JSON can represent a wide variety of data structures -- a JS "object" is roughly like a Python dict (with string keys), a JS "array" roughly like a Python list, and you can nest them as long as the final "leaf" elements are numbers or strings.</p> <p>CSV can essentially represent only a 2-D table -- optionally with...
29
2009-12-09T04:27:25Z
[ "python", "json", "csv" ]
How can I convert JSON to CSV?
1,871,524
<p>I have a JSON file that I want to covert to a CSV file. How can I do this with Python?</p> <p>I tried:</p> <pre><code>import json import csv f = open('data.json') data = json.load(f) f.close() f = open('data.csv') csv_file = csv.writer(f) for item in data: f.writerow(item) f.close() </code></pre> <p>However...
62
2009-12-09T04:06:37Z
1,872,081
<p>I am not sure this question is solved already or not, but let me paste what I have done for reference.</p> <p>First, your JSON has nested objects, so it normally cannot be directly converted to CSV. You need to change that to something like this:</p> <pre><code>{ "pk": 22, "model": "auth.permission", "...
51
2009-12-09T06:56:38Z
[ "python", "json", "csv" ]
How can I convert JSON to CSV?
1,871,524
<p>I have a JSON file that I want to covert to a CSV file. How can I do this with Python?</p> <p>I tried:</p> <pre><code>import json import csv f = open('data.json') data = json.load(f) f.close() f = open('data.csv') csv_file = csv.writer(f) for item in data: f.writerow(item) f.close() </code></pre> <p>However...
62
2009-12-09T04:06:37Z
6,083,329
<p>I was having trouble with <a href="http://stackoverflow.com/a/1871557/233467">Dan's proposed solution</a>, but this worked for me:</p> <pre><code>import json import csv f = open('test.json') data = json.load(f) f.close() f=csv.writer(open('test.csv','wb+')) for item in data: f.writerow([item['pk'], item['mode...
3
2011-05-21T17:30:00Z
[ "python", "json", "csv" ]
How can I convert JSON to CSV?
1,871,524
<p>I have a JSON file that I want to covert to a CSV file. How can I do this with Python?</p> <p>I tried:</p> <pre><code>import json import csv f = open('data.json') data = json.load(f) f.close() f = open('data.csv') csv_file = csv.writer(f) for item in data: f.writerow(item) f.close() </code></pre> <p>However...
62
2009-12-09T04:06:37Z
12,738,863
<p>A generic solution which translates any json list of <em>flat</em> objects to csv.</p> <p>Pass the input.json file as first argument on command line.</p> <pre><code>import csv, json, sys input = open(sys.argv[1]) data = json.load(input) input.close() output = csv.writer(sys.stdout) output.writerow(data[0].keys(...
16
2012-10-05T02:55:35Z
[ "python", "json", "csv" ]
How can I convert JSON to CSV?
1,871,524
<p>I have a JSON file that I want to covert to a CSV file. How can I do this with Python?</p> <p>I tried:</p> <pre><code>import json import csv f = open('data.json') data = json.load(f) f.close() f = open('data.csv') csv_file = csv.writer(f) for item in data: f.writerow(item) f.close() </code></pre> <p>However...
62
2009-12-09T04:06:37Z
21,679,973
<p>Since the data appears to be in a dictionary format, it would appear that you should actually use csv.DictWriter() to actually output the lines with the appropriate header information. This should allow the conversion to be handled somewhat easier. The fieldnames parameter would then set up the order properly while ...
0
2014-02-10T14:34:19Z
[ "python", "json", "csv" ]
How can I convert JSON to CSV?
1,871,524
<p>I have a JSON file that I want to covert to a CSV file. How can I do this with Python?</p> <p>I tried:</p> <pre><code>import json import csv f = open('data.json') data = json.load(f) f.close() f = open('data.csv') csv_file = csv.writer(f) for item in data: f.writerow(item) f.close() </code></pre> <p>However...
62
2009-12-09T04:06:37Z
21,842,560
<p>As mentioned in the previous answers the difficulty in converting json to csv is because a json file can contain nested dictionaries and therefore be a multidimensional data structure verses a csv which is a 2D data structure. However, a good way to turn a multidimensional structure to a csv is to have multiple csvs...
3
2014-02-18T01:19:24Z
[ "python", "json", "csv" ]
How can I convert JSON to CSV?
1,871,524
<p>I have a JSON file that I want to covert to a CSV file. How can I do this with Python?</p> <p>I tried:</p> <pre><code>import json import csv f = open('data.json') data = json.load(f) f.close() f = open('data.csv') csv_file = csv.writer(f) for item in data: f.writerow(item) f.close() </code></pre> <p>However...
62
2009-12-09T04:06:37Z
28,246,154
<p>I am assuming that your JSON file will decode into a list of dictionaries. First we need a function which will flatten the JSON objects: </p> <pre><code>def flattenjson( b, delim ): val = {} for i in b.keys(): if isinstance( b[i], dict ): get = flattenjson( b[i], delim ) for ...
28
2015-01-30T23:11:27Z
[ "python", "json", "csv" ]
How can I convert JSON to CSV?
1,871,524
<p>I have a JSON file that I want to covert to a CSV file. How can I do this with Python?</p> <p>I tried:</p> <pre><code>import json import csv f = open('data.json') data = json.load(f) f.close() f = open('data.csv') csv_file = csv.writer(f) for item in data: f.writerow(item) f.close() </code></pre> <p>However...
62
2009-12-09T04:06:37Z
36,818,582
<p>This works relatively well. It flattens the json to write it to a csv file. Nested elements are managed :)</p> <p>That's for python 3</p> <pre><code>import json o = json.loads('your json string') # Be careful, o must be a list, each of its objects will make a line of the csv. def flatten(o, k='/'): global l,...
1
2016-04-24T02:17:23Z
[ "python", "json", "csv" ]
How can I convert JSON to CSV?
1,871,524
<p>I have a JSON file that I want to covert to a CSV file. How can I do this with Python?</p> <p>I tried:</p> <pre><code>import json import csv f = open('data.json') data = json.load(f) f.close() f = open('data.csv') csv_file = csv.writer(f) for item in data: f.writerow(item) f.close() </code></pre> <p>However...
62
2009-12-09T04:06:37Z
37,307,324
<p>With the <code>pandas</code> <a href="http://pandas.pydata.org/pandas-docs/stable/index.html">library</a>, <strong>this is as easy as using two commands!</strong></p> <pre><code>pandas.read_json() </code></pre> <p>To convert a JSON string to a pandas object (either a series or dataframe). Then, assuming the resul...
5
2016-05-18T18:19:22Z
[ "python", "json", "csv" ]
How can I convert JSON to CSV?
1,871,524
<p>I have a JSON file that I want to covert to a CSV file. How can I do this with Python?</p> <p>I tried:</p> <pre><code>import json import csv f = open('data.json') data = json.load(f) f.close() f = open('data.csv') csv_file = csv.writer(f) for item in data: f.writerow(item) f.close() </code></pre> <p>However...
62
2009-12-09T04:06:37Z
38,328,234
<p>Modified Alec McGail's answer to support JSON with lists inside</p> <pre><code> def flattenjson(self, mp, delim="|"): ret = [] if isinstance(mp, dict): for k in mp.keys(): csvs = self.flattenjson(mp[k], delim) for...
0
2016-07-12T11:56:02Z
[ "python", "json", "csv" ]
Euclidean distance between points in two different Numpy arrays, not within
1,871,536
<p>I have two arrays of <em>x</em>-<em>y</em> coordinates, and I would like to find the minimum Euclidean distance between <em>each</em> point in one array with <em>all</em> the points in the other array. The arrays are not necessarily the same size. For example:</p> <pre><code>xy1=numpy.array( [[ 243, 3173], [ 525...
26
2009-12-09T04:11:16Z
1,871,595
<p>For what you're trying to do:</p> <pre><code>dists = numpy.sqrt((xy1[:, 0, numpy.newaxis] - xy2[:, 0])**2 + (xy1[:, 1, numpy.newaxis - xy2[:, 1])**2) mindist = numpy.min(dists, axis=1) minid = numpy.argmin(dists, axis=1) </code></pre> <p><em>Edit</em>: Instead of calling <code>sqrt</code>, doing squares, etc., you...
3
2009-12-09T04:34:52Z
[ "python", "numpy", "euclidean-distance" ]
Euclidean distance between points in two different Numpy arrays, not within
1,871,536
<p>I have two arrays of <em>x</em>-<em>y</em> coordinates, and I would like to find the minimum Euclidean distance between <em>each</em> point in one array with <em>all</em> the points in the other array. The arrays are not necessarily the same size. For example:</p> <pre><code>xy1=numpy.array( [[ 243, 3173], [ 525...
26
2009-12-09T04:11:16Z
1,871,630
<p>To compute the m by p matrix of distances, this should work:</p> <pre><code>&gt;&gt;&gt; def distances(xy1, xy2): ... d0 = numpy.subtract.outer(xy1[:,0], xy2[:,0]) ... d1 = numpy.subtract.outer(xy1[:,1], xy2[:,1]) ... return numpy.hypot(d0, d1) </code></pre> <p>the <code>.outer</code> calls make two such mat...
20
2009-12-09T04:44:54Z
[ "python", "numpy", "euclidean-distance" ]
Euclidean distance between points in two different Numpy arrays, not within
1,871,536
<p>I have two arrays of <em>x</em>-<em>y</em> coordinates, and I would like to find the minimum Euclidean distance between <em>each</em> point in one array with <em>all</em> the points in the other array. The arrays are not necessarily the same size. For example:</p> <pre><code>xy1=numpy.array( [[ 243, 3173], [ 525...
26
2009-12-09T04:11:16Z
3,127,955
<p>(Months later) <code>scipy.spatial.distance.cdist( X, Y )</code> gives all pairs of distances, for X and Y 2 dim, 3 dim ...<br> It also does 22 different norms, detailed <a href="http://docs.scipy.org/doc/scipy/reference/spatial.distance.html">here</a> .</p> <pre><code># cdist example: (nx,dim) (ny,dim) -&gt; (nx,n...
31
2010-06-27T16:22:18Z
[ "python", "numpy", "euclidean-distance" ]
Python: Determine if running inside virtualenv
1,871,549
<p>Is it possible to determine if the current script is running inside a virtualenv environment?</p>
84
2009-12-09T04:18:47Z
1,883,251
<p>AFAIK the most reliable way to check for this (and the way that is used internally in virtualenv and in pip) is to check for the existence of <code>sys.real_prefix</code>:</p> <pre><code>import sys if hasattr(sys, 'real_prefix'): #... </code></pre> <p>Inside a virtualenv, <code>sys.prefix</code> points to the...
97
2009-12-10T19:07:58Z
[ "python", "virtualenv" ]
Python: Determine if running inside virtualenv
1,871,549
<p>Is it possible to determine if the current script is running inside a virtualenv environment?</p>
84
2009-12-09T04:18:47Z
10,743,097
<p>According to the virtualenv pep at <a href="http://www.python.org/dev/peps/pep-0405/#specification">http://www.python.org/dev/peps/pep-0405/#specification</a> you can just use sys.prefix instead os.environ['VIRTUAL_ENV'].</p> <p>the sys.real_prefix does not exist in my virtualenv and same with sys.base_prefix.</p>
12
2012-05-24T18:15:59Z
[ "python", "virtualenv" ]
Python: Determine if running inside virtualenv
1,871,549
<p>Is it possible to determine if the current script is running inside a virtualenv environment?</p>
84
2009-12-09T04:18:47Z
28,388,115
<p>Using $VIRTUAL_ENV variable indeed will check if we are inside virtual environment, but the issue might be with deactivate function that not clear this variable when we leave virtualenv.</p>
8
2015-02-07T22:17:31Z
[ "python", "virtualenv" ]
Python: Determine if running inside virtualenv
1,871,549
<p>Is it possible to determine if the current script is running inside a virtualenv environment?</p>
84
2009-12-09T04:18:47Z
38,939,054
<p>Try using <code>pip -V</code> (notice capital V)</p> <p>If you are running the virtual env. it'll show the path to the env.'s location.</p>
5
2016-08-14T04:12:16Z
[ "python", "virtualenv" ]
Python: Determine if running inside virtualenv
1,871,549
<p>Is it possible to determine if the current script is running inside a virtualenv environment?</p>
84
2009-12-09T04:18:47Z
40,099,080
<p>I routinely use several Anaconda-installed virtual environments (venv). This code snippet/examples enables you to determine whether or not you are in a venv (or your system environment), and to also require a specific venv for your script.</p> <h3>ADD TO PYTHON SCRIPT (code snippet):</h3> <pre><code># -----------...
0
2016-10-18T03:35:08Z
[ "python", "virtualenv" ]
Python: Determine if running inside virtualenv
1,871,549
<p>Is it possible to determine if the current script is running inside a virtualenv environment?</p>
84
2009-12-09T04:18:47Z
40,109,916
<p>It's not bullet-proof but for UNIX environments simple test like</p> <pre><code>if run("which python3").find("venv") == -1: # something when not executed from venv </code></pre> <p>works great for me. It's simpler then testing existing of some attribute and, anyway, you should name your venv directory <code>ve...
0
2016-10-18T13:40:57Z
[ "python", "virtualenv" ]
Pygame: Blitting a moving background creates too much blur
1,871,607
<p>What I am trying to do is create a viewport to view a small portion of a background. (And later put sprites in).</p> <p>However the problem I have noticed is there seems to be an issue of the background blurring when it starts moving. I was not sure if this is because blitting is slow or because of a problem in the...
1
2009-12-09T04:38:15Z
1,872,018
<p>By "blurry" do you mean that the background appears "doubled"? Do you get the same effect when moving a normal-sized (e.g., 64x64) sprite? </p> <p>If you are seeing double, then it's probably a refresh rate problem. Turning on vsync may help. </p> <p>What frame rate are you getting? </p> <p>If you slow down the a...
0
2009-12-09T06:39:04Z
[ "python", "pygame", "sprite", "blit" ]
Pygame: Blitting a moving background creates too much blur
1,871,607
<p>What I am trying to do is create a viewport to view a small portion of a background. (And later put sprites in).</p> <p>However the problem I have noticed is there seems to be an issue of the background blurring when it starts moving. I was not sure if this is because blitting is slow or because of a problem in the...
1
2009-12-09T04:38:15Z
1,874,053
<p>I couldn't know what caused the problem you faced, but I guess it is related to double buffering. </p> <p>Did you use at least two surfaces? </p> <pre><code># preparing two surfaces in __init__() screen = pygame.display.set_mode((800,600)) background = pygame.Surface(screen.get_size()) background.fill((250, 250, 2...
4
2009-12-09T13:53:59Z
[ "python", "pygame", "sprite", "blit" ]
Level Design in Pygame
1,871,672
<p>Hey--I'm trying to design my first game using the Pygame library for Python, and I was wondering what the best practices are for level design in general. I would love to hear what you guys think are good object oriented design patterns for managing levels. Also, I'm fairly new to Python--thanks!</p>
3
2009-12-09T05:01:37Z
1,871,698
<p>If this is your first Pygame application, don't spend time worrying about "object oriented design patterns for managing levels". What you need to do now is to figure out how to make Pygame do what you want it to do.</p> <ul> <li>Can you display everything you want to?</li> <li>Is your display flicker-free?</li> <li...
6
2009-12-09T05:09:54Z
[ "python", "design-patterns", "oop", "pygame" ]
Level Design in Pygame
1,871,672
<p>Hey--I'm trying to design my first game using the Pygame library for Python, and I was wondering what the best practices are for level design in general. I would love to hear what you guys think are good object oriented design patterns for managing levels. Also, I'm fairly new to Python--thanks!</p>
3
2009-12-09T05:01:37Z
1,871,700
<p>Generally speaking, a simple way to do it is using matrices (or multidimensional arrays - they work the same way here).</p> <p>Basically, each Map is an Array, with each item in the array being a square on the grid. For example a 3 by 3 grid would be as follows:</p> <p>(Psuedocode)</p> <p>var Map = [[1,2,3][1,2,...
1
2009-12-09T05:10:07Z
[ "python", "design-patterns", "oop", "pygame" ]
Level Design in Pygame
1,871,672
<p>Hey--I'm trying to design my first game using the Pygame library for Python, and I was wondering what the best practices are for level design in general. I would love to hear what you guys think are good object oriented design patterns for managing levels. Also, I'm fairly new to Python--thanks!</p>
3
2009-12-09T05:01:37Z
1,873,480
<p>With this type of game your maps are in terms of tiles (I'm assuming that by level you mean an individual level, not managing all of your levels). Each tile has</p> <ul> <li>an associated picture (what it looks like on the display)</li> <li>a type (ie, a wall, the ground, a trap, etc.)</li> </ul> <p>When I create ...
8
2009-12-09T12:03:04Z
[ "python", "design-patterns", "oop", "pygame" ]
In python is there a way to check if a function is a "generator function" before calling it?
1,871,685
<p>Lets say I have two functions:</p> <pre><code>def foo(): return 'foo' def bar(): yield 'bar' </code></pre> <p>The first one is a normal function, and the second is a generator function. Now I want to write something like this:</p> <pre><code>def run(func): if is_generator_function(func): gen = func() ...
37
2009-12-09T05:05:10Z
1,871,702
<pre><code>&gt;&gt;&gt; def foo(): ... return 'foo' ... &gt;&gt;&gt; def bar(): ... yield 'bar' ... &gt;&gt;&gt; import dis &gt;&gt;&gt; dis.dis(foo) 2 0 LOAD_CONST 1 ('foo') 3 RETURN_VALUE &gt;&gt;&gt; dis.dis(bar) 2 0 LOAD_CONST 1 ('bar')...
7
2009-12-09T05:10:44Z
[ "python", "function", "generator", "coroutine" ]