title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Traversing a Python object tree
1,141,039
<p>I'm trying to implement dynamic reloading objects in Python, that reflect code changes live.</p> <p>Modules reloading is working, but I have to recreate every instance of the modules' classes for changes to become effective.</p> <p>The problem is that objects data (objects <code>__dict__</code> content) is lost during the process.</p> <p>So I tried another approach:</p> <pre><code>def refresh(obj, memo=None): if memo is None: memo = {} d = id(obj) if d in memo: return memo[d] = None try: obj.__class__ = getattr(sys.modules[obj.__class__.__module__], obj.__class__.__name__) except TypeError: return for item in obj.__dict__.itervalues(): if isinstance(item, dict): for k, v in item.iteritems(): refresh(k, memo) refresh(v, memo) elif isinstance(item, (list, tuple)): for v in item: refresh(v, memo) else: refresh(item, memo) </code></pre> <p>And surprisingly it works ! After calling refresh() on my objects, the new code becomes effective, without need to recreate them.</p> <p>But I'm not sure if this is the correct way to traverse an object ? Is there a better way to traverse an object's components ?</p>
1
2009-07-17T00:59:26Z
1,141,337
<p>For reloading Python code, I came up with this implementation a long time ago.</p> <p><a href="http://www.codexon.com/posts/a-better-python-reload" rel="nofollow">http://www.codexon.com/posts/a-better-python-reload</a></p> <p>It's probably the fastest and cleanest way possible.</p>
0
2009-07-17T03:34:03Z
[ "python", "reload", "traversal" ]
Why was the 'thread' module renamed to '_thread' in Python 3.x?
1,141,047
<p>Python 3.x renamed the low-level module 'thread' to '_thread' -- I don't see why in the documentation. Does anyone know?</p>
8
2009-07-17T01:04:20Z
1,141,058
<p>I think the old <code>thread</code> module is deprecated in favour of the higher level <a href="http://docs.python.org/library/threading.html"><code>threading</code></a> module.</p>
7
2009-07-17T01:10:56Z
[ "python", "multithreading", "python-3.x" ]
Why was the 'thread' module renamed to '_thread' in Python 3.x?
1,141,047
<p>Python 3.x renamed the low-level module 'thread' to '_thread' -- I don't see why in the documentation. Does anyone know?</p>
8
2009-07-17T01:04:20Z
1,141,059
<p>It looks like the thread module became obsolete in 3.x in favor of the threading module. See <a href="http://www.python.org/dev/peps/pep-3108/#obsolete">PEP 3108</a>.</p>
8
2009-07-17T01:11:12Z
[ "python", "multithreading", "python-3.x" ]
Why was the 'thread' module renamed to '_thread' in Python 3.x?
1,141,047
<p>Python 3.x renamed the low-level module 'thread' to '_thread' -- I don't see why in the documentation. Does anyone know?</p>
8
2009-07-17T01:04:20Z
1,141,115
<p>It's been quite a long time since the low-level <code>thread</code> module was informally deprecated, with all users heartily encouraged to use the higher-level <code>threading</code> module instead; now with the ability to introduce backwards incompatibilities in Python 3, we've made that deprecation rather more than just "informal", that's all!-)</p>
10
2009-07-17T01:43:48Z
[ "python", "multithreading", "python-3.x" ]
Read Block Data in Python?
1,141,101
<p>I have a problem reading data file:</p> <pre><code>/// * ABC Names A-06,B-18, * Data 1.727e-01, 1.258e-01, 2.724e-01, 2.599e-01,-3.266e-01,-9.425e-02,-6.213e-02, 1.479e-01, 1.219e-01, 1.174e-01, 2.213e-01, 2.875e-01,-2.306e-01,-3.900e-03,-5.269e-02, 7.420e-02, 2.592e-01, 2.513e-01, 2.242e-01, 2.620e-01,-1.346e-01,-6.844e-02,-4.139e-02, 9.502e-02, 1.981e-01, 1.937e-01, 2.336e-01, 1.617e-01,-4.240e-02, 2.285e-02, 1.878e-02, 1.064e-01, 9.562e-02, 6.727e-02, 1.135e-01, 6.765e-02,-7.850e-02, 6.711e-02, 1.317e-02, 8.367e-02, * Starting position -.5000E+01 /// </code></pre> <p>Code run in Python? I tried using <code>readline()</code>, <code>readlines()</code> functions but no result.</p>
1
2009-07-17T01:35:15Z
1,141,108
<p>Suppose the file's named "abc.txt" and is in the current directory; then the following Python script:</p> <pre><code>f = open("abc.txt") all_lines = f.readlines() </code></pre> <p>will read all the lines into list of strings <code>all_lines</code>, each with its ending <code>\n</code> and all.</p> <p>What you want to do after that we can't guess unless you tell us, but the part you're asking about, the reading, should be satisfied.</p>
0
2009-07-17T01:39:55Z
[ "python", "file" ]
Read Block Data in Python?
1,141,101
<p>I have a problem reading data file:</p> <pre><code>/// * ABC Names A-06,B-18, * Data 1.727e-01, 1.258e-01, 2.724e-01, 2.599e-01,-3.266e-01,-9.425e-02,-6.213e-02, 1.479e-01, 1.219e-01, 1.174e-01, 2.213e-01, 2.875e-01,-2.306e-01,-3.900e-03,-5.269e-02, 7.420e-02, 2.592e-01, 2.513e-01, 2.242e-01, 2.620e-01,-1.346e-01,-6.844e-02,-4.139e-02, 9.502e-02, 1.981e-01, 1.937e-01, 2.336e-01, 1.617e-01,-4.240e-02, 2.285e-02, 1.878e-02, 1.064e-01, 9.562e-02, 6.727e-02, 1.135e-01, 6.765e-02,-7.850e-02, 6.711e-02, 1.317e-02, 8.367e-02, * Starting position -.5000E+01 /// </code></pre> <p>Code run in Python? I tried using <code>readline()</code>, <code>readlines()</code> functions but no result.</p>
1
2009-07-17T01:35:15Z
1,141,117
<p>Assuming you want to get the block from *Data to *Starting Position, </p> <pre><code>f=0 for line in open("file"): line=line.strip() if "Starting" in line: f=0 if "Data" in line: f=1 continue if f: print line </code></pre> <p>the idea is to set a flag. if *Data is hit, set flag. the print all lines if flag is set. If *Starting is hit, turn off the flag.</p>
0
2009-07-17T01:45:27Z
[ "python", "file" ]
Read Block Data in Python?
1,141,101
<p>I have a problem reading data file:</p> <pre><code>/// * ABC Names A-06,B-18, * Data 1.727e-01, 1.258e-01, 2.724e-01, 2.599e-01,-3.266e-01,-9.425e-02,-6.213e-02, 1.479e-01, 1.219e-01, 1.174e-01, 2.213e-01, 2.875e-01,-2.306e-01,-3.900e-03,-5.269e-02, 7.420e-02, 2.592e-01, 2.513e-01, 2.242e-01, 2.620e-01,-1.346e-01,-6.844e-02,-4.139e-02, 9.502e-02, 1.981e-01, 1.937e-01, 2.336e-01, 1.617e-01,-4.240e-02, 2.285e-02, 1.878e-02, 1.064e-01, 9.562e-02, 6.727e-02, 1.135e-01, 6.765e-02,-7.850e-02, 6.711e-02, 1.317e-02, 8.367e-02, * Starting position -.5000E+01 /// </code></pre> <p>Code run in Python? I tried using <code>readline()</code>, <code>readlines()</code> functions but no result.</p>
1
2009-07-17T01:35:15Z
1,141,148
<p>This ought to work for files with block names 'a', 'b', and 'c'. It will create a dictionary with keys as block titles like so:</p> <pre><code>{'a':['line1','line2'],'b':['line1'],'c':['line1','line2','line3']} </code></pre> <p>code:</p> <pre><code>block_names = ['b','a','c'] for line in open('file.txt'): block_dict = {} #dict to populate with lists of lines block = [] # dummy block in case there is data or lines before first block ck_nm = [blk_nm for blk_nm in block_names if line.startswith(blk_nm)] #search block names for a match if ck_nm: # did we find a match? block_dict[ck_nm[0]] = block = [] # set current block else: block.append(line) #..or line.split(',') ..however you want to parse the data </code></pre>
1
2009-07-17T01:57:31Z
[ "python", "file" ]
Read Block Data in Python?
1,141,101
<p>I have a problem reading data file:</p> <pre><code>/// * ABC Names A-06,B-18, * Data 1.727e-01, 1.258e-01, 2.724e-01, 2.599e-01,-3.266e-01,-9.425e-02,-6.213e-02, 1.479e-01, 1.219e-01, 1.174e-01, 2.213e-01, 2.875e-01,-2.306e-01,-3.900e-03,-5.269e-02, 7.420e-02, 2.592e-01, 2.513e-01, 2.242e-01, 2.620e-01,-1.346e-01,-6.844e-02,-4.139e-02, 9.502e-02, 1.981e-01, 1.937e-01, 2.336e-01, 1.617e-01,-4.240e-02, 2.285e-02, 1.878e-02, 1.064e-01, 9.562e-02, 6.727e-02, 1.135e-01, 6.765e-02,-7.850e-02, 6.711e-02, 1.317e-02, 8.367e-02, * Starting position -.5000E+01 /// </code></pre> <p>Code run in Python? I tried using <code>readline()</code>, <code>readlines()</code> functions but no result.</p>
1
2009-07-17T01:35:15Z
1,155,094
<p>Without any other information...</p> <pre><code>data = [ 1.727e-01, 1.258e-01, 2.724e-01, 2.599e-01,-3.266e-01,-9.425e-02,-6.213e-02, 1.479e-01, 1.219e-01, 1.174e-01, 2.213e-01, 2.875e-01,-2.306e-01,-3.900e-03,-5.269e-02, 7.420e-02, 2.592e-01, 2.513e-01, 2.242e-01, 2.620e-01,-1.346e-01,-6.844e-02,-4.139e-02, 9.502e-02, 1.981e-01, 1.937e-01, 2.336e-01, 1.617e-01,-4.240e-02, 2.285e-02, 1.878e-02, 1.064e-01, 9.562e-02, 6.727e-02, 1.135e-01, 6.765e-02,-7.850e-02, 6.711e-02, 1.317e-02, 8.367e-02, ] </code></pre>
0
2009-07-20T18:21:56Z
[ "python", "file" ]
Read Block Data in Python?
1,141,101
<p>I have a problem reading data file:</p> <pre><code>/// * ABC Names A-06,B-18, * Data 1.727e-01, 1.258e-01, 2.724e-01, 2.599e-01,-3.266e-01,-9.425e-02,-6.213e-02, 1.479e-01, 1.219e-01, 1.174e-01, 2.213e-01, 2.875e-01,-2.306e-01,-3.900e-03,-5.269e-02, 7.420e-02, 2.592e-01, 2.513e-01, 2.242e-01, 2.620e-01,-1.346e-01,-6.844e-02,-4.139e-02, 9.502e-02, 1.981e-01, 1.937e-01, 2.336e-01, 1.617e-01,-4.240e-02, 2.285e-02, 1.878e-02, 1.064e-01, 9.562e-02, 6.727e-02, 1.135e-01, 6.765e-02,-7.850e-02, 6.711e-02, 1.317e-02, 8.367e-02, * Starting position -.5000E+01 /// </code></pre> <p>Code run in Python? I tried using <code>readline()</code>, <code>readlines()</code> functions but no result.</p>
1
2009-07-17T01:35:15Z
1,156,722
<p>Here's a complete guess at some code that might load the type of file this is an example of, but which should be a little robust: </p> <pre><code>f = open("mdata.txt") data_dict = {} section = None data_for_section = "" for line in f: line = line.strip() #remove whitespace at start and end if section != None and (line[0] == "*" or line == "///"): # if we've just finished a section, put whatever we got into the data dict data_dict[section] = [bit for bit in data_for_section.split(",") if bit != ""] if line[0] == "*": # "*" denotes the start of a new section, probably, so remember the name section = line [2:] data_for_section = "" continue data_for_section += line f.close() #got the data, now for some output print "loaded file. Found headings: %s"%(", ".join(data_dict.keys())) for key in data_dict.keys(): if len(data_dict[key])&gt;5: print key, ": array of %i entries"%len(data_dict[key]) else: print key, ": ", data_dict[key] </code></pre> <p>which outputs for your file:</p> <pre>loaded file. Found headings: ABC Names, Data, Starting position ABC Names : ['A-06', 'B-18'] Data : array of 40 entries Starting position : ['-.5000E+01']</pre> <p>of course, you'd probably want to convert the list of data strings to floating point numbers in the case of data and starting position:</p> <pre><code>startingPosition = float(data_dict["Starting position"][0]) data_list_of_floats = map(float, data_dict["Data"]) </code></pre> <p>But as to the ABC Names and how they combine with the rest of the file, we'd need some more information for that.</p>
2
2009-07-21T00:31:31Z
[ "python", "file" ]
Read Block Data in Python?
1,141,101
<p>I have a problem reading data file:</p> <pre><code>/// * ABC Names A-06,B-18, * Data 1.727e-01, 1.258e-01, 2.724e-01, 2.599e-01,-3.266e-01,-9.425e-02,-6.213e-02, 1.479e-01, 1.219e-01, 1.174e-01, 2.213e-01, 2.875e-01,-2.306e-01,-3.900e-03,-5.269e-02, 7.420e-02, 2.592e-01, 2.513e-01, 2.242e-01, 2.620e-01,-1.346e-01,-6.844e-02,-4.139e-02, 9.502e-02, 1.981e-01, 1.937e-01, 2.336e-01, 1.617e-01,-4.240e-02, 2.285e-02, 1.878e-02, 1.064e-01, 9.562e-02, 6.727e-02, 1.135e-01, 6.765e-02,-7.850e-02, 6.711e-02, 1.317e-02, 8.367e-02, * Starting position -.5000E+01 /// </code></pre> <p>Code run in Python? I tried using <code>readline()</code>, <code>readlines()</code> functions but no result.</p>
1
2009-07-17T01:35:15Z
1,287,071
<p>Thank you for your reply. However, I attempted to start with Markus's code but failed when between this line and that line exist empty. Example: /// "filename.txt" have: * ABC Names A-06,B-18, * Data 1.727e-01, 1.258e-01, 2.724e-01, 2.599e-01,-3.266e-01,-9.425e-02,-6.213e-02, 1.479e-01, 1.219e-01, 1.174e-01, 2.213e-01, 2.875e-01,-2.306e-01,-3.900e-03,-5.269e-02, 7.420e-02, 2.592e-01, 2.513e-01, 2.242e-01, 2.620e-01,-1.346e-01,-6.844e-02,-4.139e-02, 9.502e-02, 1.981e-01, 1.937e-01, 2.336e-01, 1.617e-01,-4.240e-02, 2.285e-02, 1.878e-02, 1.064e-01, 9.562e-02, 6.727e-02, 1.135e-01, 6.765e-02,-7.850e-02, 6.711e-02, 1.317e-02, 8.367e-02, * Starting position -.5000E+01</p> <ul> <li><p>Total number of clicks (modified) 18</p></li> <li><p>Clicker times (modified) 448 748 /// Error when between "Starting position" and "Total number of clicks (modified)" have empty line. I need data: 1.727e-01, 1.258e-01, 2.724e-01, 2.599e-01,-3.266e-01,-9.425e-02,-6.213e-02, 1.479e-01, 1.219e-01, 1.174e-01, 2.213e-01, 2.875e-01,-2.306e-01,-3.900e-03,-5.269e-02, 7.420e-02, 2.592e-01, 2.513e-01, 2.242e-01, 2.620e-01,-1.346e-01,-6.844e-02,-4.139e-02, 9.502e-02, 1.981e-01, 1.937e-01, 2.336e-01, 1.617e-01,-4.240e-02, 2.285e-02, 1.878e-02, 1.064e-01, 9.562e-02, 6.727e-02, 1.135e-01, 6.765e-02,-7.850e-02, 6.711e-02, 1.317e-02, 8.367e-02, in block "* Data" and sometime need data<br /> 448 748 in block "* Clicker times (modified)"</p></li> </ul>
0
2009-08-17T09:47:40Z
[ "python", "file" ]
Python networking library for a simple card game
1,141,130
<p>I'm trying to implement a fairly simple <a href="http://www.sirlin.net/yomi" rel="nofollow">card game</a> in Python so that two players can play together other the Internet. I have no problem with doing the GUI, but I don't know the first thing about how to do the networking part. A couple libraries I've found so far:</p> <ul> <li><p><a href="http://pyro.sourceforge.net/manual/PyroManual.html" rel="nofollow">PyRO</a>: seems nice and seems to fit the problem nicely by having shared Card objects in various states. </p></li> <li><p><a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a> with <a href="http://code.google.com/p/pyglet-twisted/" rel="nofollow">pyglet-twisted</a>: this looks powerful but complicated; I've used Pyglet before though so maybe it wouldn't be too bad.</p></li> </ul> <p>Can anyone recommend the most appropriate one for my game (not necessarily on this list, I've probably missed lots of good ones)?</p>
3
2009-07-17T01:51:34Z
1,141,183
<p>Both of those libraries are very good and would work perfectly for your card game.</p> <p>Pyro might be easier to learn and use, but Twisted will scale better if you ever want to move into a very large number of players.</p> <p>Twisted can be daunting at first but there are some books to help you get over the hump.</p> <p>The are some other libraries to choose from but the two you found are mature and used widely within the Python community so you'll have a better chance of finding people to answer any questions.</p> <p>My personal recommendation would be to use Pyro if you're just wanting to play around with networking but go with Twisted if you have grand plans for lots of players on the internet.</p>
8
2009-07-17T02:11:10Z
[ "python", "networking" ]
Python networking library for a simple card game
1,141,130
<p>I'm trying to implement a fairly simple <a href="http://www.sirlin.net/yomi" rel="nofollow">card game</a> in Python so that two players can play together other the Internet. I have no problem with doing the GUI, but I don't know the first thing about how to do the networking part. A couple libraries I've found so far:</p> <ul> <li><p><a href="http://pyro.sourceforge.net/manual/PyroManual.html" rel="nofollow">PyRO</a>: seems nice and seems to fit the problem nicely by having shared Card objects in various states. </p></li> <li><p><a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a> with <a href="http://code.google.com/p/pyglet-twisted/" rel="nofollow">pyglet-twisted</a>: this looks powerful but complicated; I've used Pyglet before though so maybe it wouldn't be too bad.</p></li> </ul> <p>Can anyone recommend the most appropriate one for my game (not necessarily on this list, I've probably missed lots of good ones)?</p>
3
2009-07-17T01:51:34Z
1,141,429
<p>If you decide you don't want to use a 3rd party library, I'd recommend the <a href="http://docs.python.org/library/asynchat.html"><code>asynchat module</code></a> in the standard library. It's perfect for sending/receiving through a simple protocol.</p>
5
2009-07-17T04:26:15Z
[ "python", "networking" ]
Python networking library for a simple card game
1,141,130
<p>I'm trying to implement a fairly simple <a href="http://www.sirlin.net/yomi" rel="nofollow">card game</a> in Python so that two players can play together other the Internet. I have no problem with doing the GUI, but I don't know the first thing about how to do the networking part. A couple libraries I've found so far:</p> <ul> <li><p><a href="http://pyro.sourceforge.net/manual/PyroManual.html" rel="nofollow">PyRO</a>: seems nice and seems to fit the problem nicely by having shared Card objects in various states. </p></li> <li><p><a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a> with <a href="http://code.google.com/p/pyglet-twisted/" rel="nofollow">pyglet-twisted</a>: this looks powerful but complicated; I've used Pyglet before though so maybe it wouldn't be too bad.</p></li> </ul> <p>Can anyone recommend the most appropriate one for my game (not necessarily on this list, I've probably missed lots of good ones)?</p>
3
2009-07-17T01:51:34Z
1,142,309
<p>Twisted is the better of the two libraries but the time spent learning to use it but learning networking will take you similar amount of time (at least for me). </p> <p>If I were you I'd rather learn networking it will be much more useful to you in the future. The concepts are the same for most languages so its more portable as well. If you are going to take this approach have a look at <a href="http://www.amk.ca/python/howto/sockets/" rel="nofollow">http://www.amk.ca/python/howto/sockets/</a> it will take you through everything.</p>
3
2009-07-17T09:40:42Z
[ "python", "networking" ]
trac-past-commit-hook on remote repository
1,141,157
<p>Trying to set up the svn commit with trac using <a href="http://trac.edgewall.org/browser/branches/0.11-stable/contrib/trac-post-commit-hook" rel="nofollow">this</a> script.</p> <p>It is being called without issue, but the problem is this line here:</p> <pre><code>144 repos = self.env.get_repository() </code></pre> <p>Because I am calling this remotely self.env_get_repository() looks for the repository using the server drive and not the local drive mapping. That is, it is looking for E:/Projects/svn/InfoProj and not Y:/Projects/sv/InfoProj</p> <p>I noticed a <a href="http://trac.edgewall.org/changeset/7964" rel="nofollow">changeset</a> on the trac set for being able to call get_repository() and passing in the path as the variable, but it seems this hasn't made it into the latest stable release yet.</p> <p><a href="http://stackoverflow.com/questions/84178/how-do-i-implement-the-post-commit-hook-with-trac-svn-in-a-windows-environment">This version of the script</a> (the one submitted by code monkey) appears to do things differently, but is throwing an error that seems related:</p> <pre><code>154 if url is None: 155 url = self.env.config.get('project', 'url') 156 self.env.href = Href(url) 157 self.env.abs_href = Href(url) </code></pre> <p>Lines 156 / 157 throw error: Warning: TypeError: 'str' object is not callable </p> <p>The <a href="http://trac.edgewall.org/attachment/ticket/1602/trac-post-commit-hook.0.10.3.py" rel="nofollow">10.3 stable version</a> of the script throws a completely different error: Warning: NameError: global name 'core' is not defined </p> <p>I'm setting up trac for the first time on a Windows box with a remote repository. I'm using trac 0.11 stable with Python 2.6.</p> <p>I thought there would have been a lot more people out there trying to commit across servers who had come across this problem. I've looked around and couldn't find a solution. I'm supposing Linux has a more graceful way of handling this.</p> <p>Thanks in advance.</p>
0
2009-07-17T02:00:31Z
1,162,664
<p>This is totally do-able and just requires a couple of small hacks... woo hoo!</p> <p>The problem I was having is that get_repository reads the value of the svn repository from the trac.ini file. This was pointing at E:/ and not at Y:/. The simple fix involves a check to see if the repository is at *repository_dir* and if not, then check at a new variable *remote_repository_dir*. The second part of the fix involves removing the error message from cache.py that checks to see if the current repository address matches the one being passed in.</p> <p>As always, use this at your own risk and back everything up before hand!!!</p> <p>First open you trac.ini file and add a new variable 'remote_repository_dir' underneath the 'repository_dir' variable. Remote repository dir will point to the mapped drive on your local machine. It should now look something like this:</p> <pre><code>repository_dir = E:/Projects/svn/InfoProj remote_repository_dir = Y:/Projects/svn/InfoProj </code></pre> <p>Next we will modify the api.py file to check for the new variable if it can't find the repository at the *repository_dir* location. Around :71 you should have something like this:</p> <pre><code>repository_dir = Option('trac', 'repository_dir', '', """Path to local repository. This can also be a relative path (''since 0.11'').""") </code></pre> <p>Underneath this line add:</p> <pre><code>remote_repository_dir = Option('trac', 'remote_repository_dir', '', """Path to remote repository.""") </code></pre> <p>Next near :156 you will have this:</p> <pre><code> rtype, rdir = self.repository_type, self.repository_dir if not os.path.isabs(rdir): rdir = os.path.join(self.env.path, rdir) </code></pre> <p>Change that to this:</p> <pre><code> rtype, rdir = self.repository_type, self.repository_dir if not os.path.isdir(rdir): rdir = self.remote_repository_dir if not os.path.isabs(rdir): rdir = os.path.join(self.env.path, rdir) </code></pre> <p>Finally you will need to remove the alert in the cache.py file (note this is not the best way to do this, you should be able to include the remote variable as part of the check, but for now it works).</p> <p>In cache.py near :97 it should look like this:</p> <pre><code> if repository_dir: # directory part of the repo name can vary on case insensitive fs if os.path.normcase(repository_dir) != os.path.normcase(self.name): self.log.info("'repository_dir' has changed from %r to %r" % (repository_dir, self.name)) raise TracError(_("The 'repository_dir' has changed, a " "'trac-admin resync' operation is needed.")) elif repository_dir is None: # self.log.info('Storing initial "repository_dir": %s' % self.name) cursor.execute("INSERT INTO system (name,value) VALUES (%s,%s)", (CACHE_REPOSITORY_DIR, self.name,)) else: # 'repository_dir' cleared by a resync self.log.info('Resetting "repository_dir": %s' % self.name) cursor.execute("UPDATE system SET value=%s WHERE name=%s", (self.name, CACHE_REPOSITORY_DIR)) </code></pre> <p>We are going to remove the first part of the if statement so it now should look like this:</p> <pre><code> if repository_dir is None: # self.log.info('Storing initial "repository_dir": %s' % self.name) cursor.execute("INSERT INTO system (name,value) VALUES (%s,%s)", (CACHE_REPOSITORY_DIR, self.name,)) else: # 'repository_dir' cleared by a resync self.log.info('Resetting "repository_dir": %s' % self.name) cursor.execute("UPDATE system SET value=%s WHERE name=%s", (self.name, CACHE_REPOSITORY_DIR)) </code></pre> <p>Warning! Doing this will mean that it no longer gives you an error if your directory has changed and you need a resync.</p> <p>Hope this helps someone.</p>
0
2009-07-22T01:52:00Z
[ "python", "windows", "svn", "trac" ]
Name this python/ruby language construct (using array values to satisfy function parameters)
1,141,504
<p>What is this language construct called?</p> <p>In Python I can say:</p> <pre><code>def a(b,c): return b+c a(*[4,5]) </code></pre> <p>and get 9. Likewise in Ruby:</p> <pre><code>def a(b,c) b+c end a(*[4,5]) </code></pre> <p>What is this called, when one passes a single array to a function which otherwise requires multiple arguments?</p> <p>What is the name of the <code>*</code> operator?</p> <p>What other languages support this cool feature?</p>
18
2009-07-17T05:20:29Z
1,141,518
<p>I've been calling it "list expansion", but I don't think that's standard terminology (I don't think there's any...). Lisp in all versions (Scheme included), and Haskell and other functional languages, can do it easily enough, but I don't think it's easy to do in "mainstream" languages (maybe you can pull it off as a "reflection" stunt in some!-).</p>
2
2009-07-17T05:24:43Z
[ "python", "ruby", "syntax", "language-features" ]
Name this python/ruby language construct (using array values to satisfy function parameters)
1,141,504
<p>What is this language construct called?</p> <p>In Python I can say:</p> <pre><code>def a(b,c): return b+c a(*[4,5]) </code></pre> <p>and get 9. Likewise in Ruby:</p> <pre><code>def a(b,c) b+c end a(*[4,5]) </code></pre> <p>What is this called, when one passes a single array to a function which otherwise requires multiple arguments?</p> <p>What is the name of the <code>*</code> operator?</p> <p>What other languages support this cool feature?</p>
18
2009-07-17T05:20:29Z
1,141,520
<p>In ruby, it is often called "splat".</p> <p>Also in ruby, you can use it to mean 'all of the other elements in the list'.</p> <pre><code>a, *rest = [1,2,3,4,5,6] a # =&gt; 1 rest # =&gt; [2, 3, 4, 5, 6] </code></pre> <p>It can also appear on either side of the assignment operator:</p> <pre><code>a = d, *e </code></pre> <p>In this usage, it is a bit like scheme's cdr, although it needn't be all but the head of the list.</p>
10
2009-07-17T05:26:05Z
[ "python", "ruby", "syntax", "language-features" ]
Name this python/ruby language construct (using array values to satisfy function parameters)
1,141,504
<p>What is this language construct called?</p> <p>In Python I can say:</p> <pre><code>def a(b,c): return b+c a(*[4,5]) </code></pre> <p>and get 9. Likewise in Ruby:</p> <pre><code>def a(b,c) b+c end a(*[4,5]) </code></pre> <p>What is this called, when one passes a single array to a function which otherwise requires multiple arguments?</p> <p>What is the name of the <code>*</code> operator?</p> <p>What other languages support this cool feature?</p>
18
2009-07-17T05:20:29Z
1,141,556
<p>The Python docs call this <a href="http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists">Unpacking Argument Lists</a>. It's a pretty handy feature. In Python, you can also use a double asterisk (**) to unpack a dictionary (hash) into keyword arguments. They also work in reverse. I can define a function like this:</p> <pre><code>def sum(*args): result = 0 for a in args: result += a return result sum(1,2) sum(9,5,7,8) sum(1.7,2.3,8.9,3.4) </code></pre> <p>To pack all arguments into an arbitrarily sized list.</p>
25
2009-07-17T05:44:12Z
[ "python", "ruby", "syntax", "language-features" ]
Name this python/ruby language construct (using array values to satisfy function parameters)
1,141,504
<p>What is this language construct called?</p> <p>In Python I can say:</p> <pre><code>def a(b,c): return b+c a(*[4,5]) </code></pre> <p>and get 9. Likewise in Ruby:</p> <pre><code>def a(b,c) b+c end a(*[4,5]) </code></pre> <p>What is this called, when one passes a single array to a function which otherwise requires multiple arguments?</p> <p>What is the name of the <code>*</code> operator?</p> <p>What other languages support this cool feature?</p>
18
2009-07-17T05:20:29Z
1,141,568
<p>The typical terminology for this is called "applying a function to a list", or "apply" for short. </p> <p>See <a href="http://en.wikipedia.org/wiki/Apply">http://en.wikipedia.org/wiki/Apply</a></p> <p>It has been in LISP since pretty much its inception back in 1960 odd. Glad python rediscovered it :-}</p> <p>Apply is typically on a <em>list</em> or a representation of a list such as an array. However, one can apply functions to arguments that come from other palces, such as structs. Our PARLANSE language has fixed types (int, float, string, ...) and structures. Oddly enough, a function argument list looks a lot like a structure definintion, and in PARLANSE, it <em>is</em> a structure definition, and you can "apply" a PARLANSE function to a compatible structure. You can "make" structure instances, too, thus:</p> <pre> (define S (structure [t integer] [f float] [b (array boolean 1 3)] )structure )define s (= A (array boolean 1 3 ~f ~F ~f)) (= s (make S -3 19.2 (make (array boolean 1 3) ~f ~t ~f)) (define foo (function string S) ...) (foo +17 3e-2 A) ; standard function call (foo s) ; here's the "apply" </pre> <p>PARLANSE looks like lisp but isn't.</p>
5
2009-07-17T05:48:31Z
[ "python", "ruby", "syntax", "language-features" ]
Name this python/ruby language construct (using array values to satisfy function parameters)
1,141,504
<p>What is this language construct called?</p> <p>In Python I can say:</p> <pre><code>def a(b,c): return b+c a(*[4,5]) </code></pre> <p>and get 9. Likewise in Ruby:</p> <pre><code>def a(b,c) b+c end a(*[4,5]) </code></pre> <p>What is this called, when one passes a single array to a function which otherwise requires multiple arguments?</p> <p>What is the name of the <code>*</code> operator?</p> <p>What other languages support this cool feature?</p>
18
2009-07-17T05:20:29Z
1,141,642
<p>Ruby calls it <strong>splat</strong>, though David Black has also come up with the neat <strong>unar{,ra}y operator</strong> (i.e. <strong>unary unarray operator</strong>)</p>
3
2009-07-17T06:16:04Z
[ "python", "ruby", "syntax", "language-features" ]
Name this python/ruby language construct (using array values to satisfy function parameters)
1,141,504
<p>What is this language construct called?</p> <p>In Python I can say:</p> <pre><code>def a(b,c): return b+c a(*[4,5]) </code></pre> <p>and get 9. Likewise in Ruby:</p> <pre><code>def a(b,c) b+c end a(*[4,5]) </code></pre> <p>What is this called, when one passes a single array to a function which otherwise requires multiple arguments?</p> <p>What is the name of the <code>*</code> operator?</p> <p>What other languages support this cool feature?</p>
18
2009-07-17T05:20:29Z
1,143,763
<p>The majority of the questions have already been answered, but as to the question "What is the name of the * operator?": the technical term is "asterisk" (comes from the Latin word <em>asteriscum</em>, meaning "little star", which, in turn, comes from the Greek <em>ἀστερίσκος</em>). Often, though, it will be referred to as "star" or, as stated above, "splat".</p>
1
2009-07-17T14:52:18Z
[ "python", "ruby", "syntax", "language-features" ]
Name this python/ruby language construct (using array values to satisfy function parameters)
1,141,504
<p>What is this language construct called?</p> <p>In Python I can say:</p> <pre><code>def a(b,c): return b+c a(*[4,5]) </code></pre> <p>and get 9. Likewise in Ruby:</p> <pre><code>def a(b,c) b+c end a(*[4,5]) </code></pre> <p>What is this called, when one passes a single array to a function which otherwise requires multiple arguments?</p> <p>What is the name of the <code>*</code> operator?</p> <p>What other languages support this cool feature?</p>
18
2009-07-17T05:20:29Z
1,145,789
<p>Haskell has it too (for pairs), with the <code>uncurry</code> function:</p> <pre><code>ghci&gt; let f x y = 2*x + y f :: (Num a) =&gt; a -&gt; a -&gt; a ghci&gt; f 1 2 4 ghci&gt; f 10 3 23 ghci&gt; uncurry f (1,2) 4 ghci&gt; uncurry f (10,3) 23 </code></pre> <p>You can also make it into an operator, so it's more splat-like:</p> <pre><code>ghci&gt; f `uncurry` (1,2) 4 ghci&gt; let (***) = uncurry (***) :: (a -&gt; b -&gt; c) -&gt; (a, b) -&gt; c ghci&gt; f *** (10,3) 23 </code></pre> <p>And though it'd be easy to define similar functions for the 3-tuple, 4-tuple, etc cases, there isn't any general function for <code>n</code>-tuples (like splat works in other languages) because of Haskell's strict typing.</p>
2
2009-07-17T21:31:07Z
[ "python", "ruby", "syntax", "language-features" ]
Using and Installing Django Custom Field Models
1,141,524
<p>I found a custom field model (<a href="http://www.djangosnippets.org/snippets/377/" rel="nofollow">JSONField</a>) that I would like to integrate into my Django project. </p> <ul> <li><p>Where do I actually put the JSONField.py file? -- Would it reside in my Django project or would I put it in something like: /django/db/models/fields/</p></li> <li><p>Since I assume it can be done multiple ways, would it then impact how JSONField (or any custom field for that matter) would get imported into my models.py file as well?</p></li> </ul>
1
2009-07-17T05:27:07Z
1,141,528
<p>The best thing would be to keep Django and customizations apart. You could place the file anywhere on your pythonpath really </p>
0
2009-07-17T05:31:10Z
[ "python", "django", "django-models" ]
Using and Installing Django Custom Field Models
1,141,524
<p>I found a custom field model (<a href="http://www.djangosnippets.org/snippets/377/" rel="nofollow">JSONField</a>) that I would like to integrate into my Django project. </p> <ul> <li><p>Where do I actually put the JSONField.py file? -- Would it reside in my Django project or would I put it in something like: /django/db/models/fields/</p></li> <li><p>Since I assume it can be done multiple ways, would it then impact how JSONField (or any custom field for that matter) would get imported into my models.py file as well?</p></li> </ul>
1
2009-07-17T05:27:07Z
1,141,532
<p>For the first question, I would rather not put it into django directory, because in case of upgrades you may end up loosing all of your changes. It is a general point: modifying an external piece of code will lead to increased maintenance costs.<br /> Therefore, I would suggest you putting it into some place accessible from your pythonpath - it could be a module in your project, or directly inside the site-packages directory.</p> <p>As about the second question, just "installing" it will not impact your existing models.<br /> You have to explicitly use it, by either by adding it to all of your models that need it, either by defining a model that uses it, and from whom all of your models will inherit.</p>
1
2009-07-17T05:34:06Z
[ "python", "django", "django-models" ]
Using and Installing Django Custom Field Models
1,141,524
<p>I found a custom field model (<a href="http://www.djangosnippets.org/snippets/377/" rel="nofollow">JSONField</a>) that I would like to integrate into my Django project. </p> <ul> <li><p>Where do I actually put the JSONField.py file? -- Would it reside in my Django project or would I put it in something like: /django/db/models/fields/</p></li> <li><p>Since I assume it can be done multiple ways, would it then impact how JSONField (or any custom field for that matter) would get imported into my models.py file as well?</p></li> </ul>
1
2009-07-17T05:27:07Z
1,143,201
<p>It's worth remembering that Django is just Python, and so the same rules apply to Django customisations as they would for any other random Python library you might download. To use a bit of code, it has to be in a module somewhere on your Pythonpath, and then you can just to <code>from foo import x</code>. </p> <p>I sometimes have a <code>lib</code> directory within my Django project structure, and put into it all the various things I might need to import. In this case I might put the JSONField code into a module called <code>fields</code>, as I might have other customised fields. </p> <p>Since I know my project is already on the Pythonpath, I can just do <code>from lib.fields import JSONField</code>, then I can just do <code>myfield = JSONField(options)</code> in the model definition.</p>
2
2009-07-17T13:15:43Z
[ "python", "django", "django-models" ]
encryption with python
1,141,542
<p>If I want to use:</p> <pre><code>recip = M2Crypto.RSA.load_pub_key(open('recipient_public_key.pem','rb').read()) </code></pre> <p>Then how will it retrieve the key? What will recip will print?</p> <p>I need to get the public key of the recipient from the server(open key server) and for that first I need to store the key on server.</p>
1
2009-07-17T05:39:01Z
1,141,783
<p>check what public_key.pem returns .clear this how you want to recognize your recipient .</p>
0
2009-07-17T07:07:52Z
[ "python", "cryptography", "rsa" ]
How to hide a bulletpoint in blog
1,141,774
<p>how to hide a bullet points? example like this website</p> <p><a href="http://www.grainge.org/pages/various_rh_projects/alt_dropdowns/showhide_3/showhide3.htm" rel="nofollow">http://www.grainge.org/pages/various_rh_projects/alt_dropdowns/showhide_3/showhide3.htm</a></p> <p>you can see the example</p> <p>first Hotspot</p> <p>second hotspot</p> <p>if we click 'first' it appears but if not it's not appear. how to do that</p>
0
2009-07-17T07:04:16Z
1,141,784
<p>This is done in JavaScript, not python, I would wager. Basic strategy:</p> <ul> <li>Start by adding (in the HTML) class="hideme" to the div's or p's or li's you want to affect. </li> <li>Then using something like the below hideClass(class) function (jQuery would be worth looking at too), select all parts of the page with class="hideme" and set their style to display: none to hide or display: block to show</li> </ul> <p>.</p> <pre><code>function hideClass(name) { var matches = getElementsByClassName(name); for (var i = 0; i &lt; matches.length; i++) { var match = matches[i]; match.style.display = "none"; } } </code></pre> <p>This calls getElementsByClassName.js available here:</p> <p><a href="http://code.google.com/p/getelementsbyclassname/" rel="nofollow">http://code.google.com/p/getelementsbyclassname/</a></p> <p>A function showClass(name) could be made similarly, with match.style.display = "block";</p>
1
2009-07-17T07:08:15Z
[ "javascript", "jquery", "python", "html", "css" ]
How to hide a bulletpoint in blog
1,141,774
<p>how to hide a bullet points? example like this website</p> <p><a href="http://www.grainge.org/pages/various_rh_projects/alt_dropdowns/showhide_3/showhide3.htm" rel="nofollow">http://www.grainge.org/pages/various_rh_projects/alt_dropdowns/showhide_3/showhide3.htm</a></p> <p>you can see the example</p> <p>first Hotspot</p> <p>second hotspot</p> <p>if we click 'first' it appears but if not it's not appear. how to do that</p>
0
2009-07-17T07:04:16Z
1,141,829
<p>This is certainly done with javascript.</p> <p>Another possibility is to have empty elements </p> <p><code>&lt;div id="myelt"&gt;&lt;/div&gt;</code></p> <p>and to change the html content of this element </p> <p><code>document.getElementById('myelt').innerHTML = "My text";</code></p>
1
2009-07-17T07:24:57Z
[ "javascript", "jquery", "python", "html", "css" ]
How to hide a bulletpoint in blog
1,141,774
<p>how to hide a bullet points? example like this website</p> <p><a href="http://www.grainge.org/pages/various_rh_projects/alt_dropdowns/showhide_3/showhide3.htm" rel="nofollow">http://www.grainge.org/pages/various_rh_projects/alt_dropdowns/showhide_3/showhide3.htm</a></p> <p>you can see the example</p> <p>first Hotspot</p> <p>second hotspot</p> <p>if we click 'first' it appears but if not it's not appear. how to do that</p>
0
2009-07-17T07:04:16Z
1,141,845
<p>In jQuery you could do it like this (v. quick example):</p> <pre><code>$(function(){ $('ul ul') .hide() //Hide the sub-lists .siblings('a').click(function(){ $(this).siblings('ul').toggle(); //show or hide the hidden ul }); }); </code></pre> <p>This should also allow for sub-lists with hidden children and hotspots.</p>
0
2009-07-17T07:29:49Z
[ "javascript", "jquery", "python", "html", "css" ]
MySQL db problem in Python
1,141,790
<p>For me mysql db has been successfully instaled in my system.I verified through the following code that it is successfully installed without any errors.</p> <pre><code>C:\Python26&gt;python Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import MySQLdb &gt;&gt;&gt; </code></pre> <p>But when I imported the mysqldb in my script its giving <strong>No module name MySQLdb.</strong></p> <p>Kindly let me know the problem and the solution..</p> <p>I am using python 2.6 and mysql is 4.0.3 in windows XP.</p> <p>Thanks in advance...</p>
0
2009-07-17T07:10:37Z
1,141,795
<p>Since you show you are running linux, but you mention that mysql is running on windows, I suspect that you don't have MySQL, or the MySQL libraries or Python bindings, installed on the linux machine.</p>
0
2009-07-17T07:13:34Z
[ "python", "mysql" ]
MySQL db problem in Python
1,141,790
<p>For me mysql db has been successfully instaled in my system.I verified through the following code that it is successfully installed without any errors.</p> <pre><code>C:\Python26&gt;python Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import MySQLdb &gt;&gt;&gt; </code></pre> <p>But when I imported the mysqldb in my script its giving <strong>No module name MySQLdb.</strong></p> <p>Kindly let me know the problem and the solution..</p> <p>I am using python 2.6 and mysql is 4.0.3 in windows XP.</p> <p>Thanks in advance...</p>
0
2009-07-17T07:10:37Z
1,141,894
<p>1) Try using your package manager to download <strong><a href="http://www.novell.com/products/linuxpackages/server10/i386/python-mysql.html" rel="nofollow">python-mysql</a></strong> which includes MySQLdb.</p> <p>2) Ensure <code>/usr/lib/python2.4/site-packages/</code> is in your <a href="http://docs.python.org/using/cmdline.html#envvar-PYTHONPATH" rel="nofollow">PYTHONPATH</a>, e.g.:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; from pprint import pprint &gt;&gt;&gt; pprint(sys.path) ['', '/usr/lib/python2.4', '/usr/lib/python2.4/plat-linux2', '/usr/lib/python2.4/lib-tk', '/usr/lib/python2.4/site-packages'] </code></pre> <p>3) You seem to be using the correct capitalization in your example, but it bears mentioning that the module name is case-sensitive, i.e. MySQLdb (correct) != mysqldb (incorrect).</p> <p><strong>Edit</strong>: Looks like nilamo has found the problem. As mentioned in a comment: you might be running your script with Python 2.6, but MySQLdb is installed in 2.4's site-packages directory.</p>
2
2009-07-17T07:46:24Z
[ "python", "mysql" ]
defining functions in decorator
1,141,902
<p>Why does this not work? How can I make it work? That is, how can I make gu accessible inside my decorated function?</p> <pre><code>def decorate(f): def new_f(): def gu(): pass f() return new_f @decorate def fu(): gu() fu() </code></pre> <p>Do I need to add gu to a dictionary of defined functions somehow? Or can I add gu to the local namespace of f before calling it?</p>
1
2009-07-17T07:50:10Z
1,141,912
<p><b>gu</b> is local to the <b>new_f</b> function, which is local to the <b>decorate</b> function.</p>
1
2009-07-17T07:53:25Z
[ "python", "aop", "decorator", "argument-passing" ]
defining functions in decorator
1,141,902
<p>Why does this not work? How can I make it work? That is, how can I make gu accessible inside my decorated function?</p> <pre><code>def decorate(f): def new_f(): def gu(): pass f() return new_f @decorate def fu(): gu() fu() </code></pre> <p>Do I need to add gu to a dictionary of defined functions somehow? Or can I add gu to the local namespace of f before calling it?</p>
1
2009-07-17T07:50:10Z
1,141,918
<p>gu() is only defined within new_f(). Unless you return it or anchor it to new_f() or something else, it cannot be referenced from outside new_f()</p> <p>I don't know what you're up to, but this scheme seems very complex. Maybe you can find a less complicated solution.</p>
1
2009-07-17T07:54:30Z
[ "python", "aop", "decorator", "argument-passing" ]
defining functions in decorator
1,141,902
<p>Why does this not work? How can I make it work? That is, how can I make gu accessible inside my decorated function?</p> <pre><code>def decorate(f): def new_f(): def gu(): pass f() return new_f @decorate def fu(): gu() fu() </code></pre> <p>Do I need to add gu to a dictionary of defined functions somehow? Or can I add gu to the local namespace of f before calling it?</p>
1
2009-07-17T07:50:10Z
1,141,922
<p>If you need to pass <code>gu</code> to <code>fu</code> you need to do this explicitly by parameters:</p> <pre><code>def decorate(f): def new_f(): def gu(): pass f(gu) return new_f @decorate def fu(gu): gu() fu() </code></pre>
2
2009-07-17T07:56:28Z
[ "python", "aop", "decorator", "argument-passing" ]
defining functions in decorator
1,141,902
<p>Why does this not work? How can I make it work? That is, how can I make gu accessible inside my decorated function?</p> <pre><code>def decorate(f): def new_f(): def gu(): pass f() return new_f @decorate def fu(): gu() fu() </code></pre> <p>Do I need to add gu to a dictionary of defined functions somehow? Or can I add gu to the local namespace of f before calling it?</p>
1
2009-07-17T07:50:10Z
1,142,123
<p>In principle you can create a new function using the same code as the old one but substituting the global scope with an amended one:</p> <pre><code>import new def with_bar(func): def bar(x): return x + 1 f_globals = func.func_globals.copy() f_globals['bar'] = bar return new.function(func.func_code, f_globals, func.func_name, func.func_defaults, func.func_closure) @with_bar def foo(x): return bar(x) print foo(5) # prints 6 </code></pre> <p>In practice you really should find a better way to do this. Passing in functions as parameters is one option. There might be other approaches too, but it's hard to tell what would fit without a high-level problem description.</p>
0
2009-07-17T08:56:36Z
[ "python", "aop", "decorator", "argument-passing" ]
defining functions in decorator
1,141,902
<p>Why does this not work? How can I make it work? That is, how can I make gu accessible inside my decorated function?</p> <pre><code>def decorate(f): def new_f(): def gu(): pass f() return new_f @decorate def fu(): gu() fu() </code></pre> <p>Do I need to add gu to a dictionary of defined functions somehow? Or can I add gu to the local namespace of f before calling it?</p>
1
2009-07-17T07:50:10Z
1,144,072
<p>Why not make your decorator a class rather than a function? It's apparently possible, as I discovered when I looked through the help for the <code>property</code> builtin. (Previously, I had thought that you could merely apply decorators to classes, and not that the decorators themselves could be classes.)</p> <p>(Of course, <code>gu</code> would have to be a method of the class or of an inner class.)</p>
0
2009-07-17T15:38:50Z
[ "python", "aop", "decorator", "argument-passing" ]
How to modify the local namespace in python
1,142,068
<p>How can I modify the local namespace of a function in python? I know that locals() returns the local namespace of the function when called inside it, but I want to do something like this (I have a reason why I want to do this where g is not accessible to f, but it's quicker to give a trivial, stupid example to illustrate the problem):</p> <pre><code>def g(): pass def f(): g() f.add_to_locals({'g':g}) </code></pre>
3
2009-07-17T08:43:24Z
1,142,115
<p>Since the function isn't invoked, it has no "local" stack frame, yet. The most simple solution is to use a global context:</p> <pre><code>handler = None def f(): handler() def g(): pass handler = g </code></pre> <p>Or you could set g on the function object:</p> <pre><code>f.g = g </code></pre> <p>But I'm not sure how you can get the function object from within the function itself. If it was a method, you would use <code>self</code>.</p>
2
2009-07-17T08:54:45Z
[ "python", "namespaces", "local" ]
How to modify the local namespace in python
1,142,068
<p>How can I modify the local namespace of a function in python? I know that locals() returns the local namespace of the function when called inside it, but I want to do something like this (I have a reason why I want to do this where g is not accessible to f, but it's quicker to give a trivial, stupid example to illustrate the problem):</p> <pre><code>def g(): pass def f(): g() f.add_to_locals({'g':g}) </code></pre>
3
2009-07-17T08:43:24Z
1,142,120
<p>A function that's not executing doesn't have any locals; the local context is created when you run the function, and destroyed when it exits, so there's no "local namespace" to modify from outside the function.</p> <p>You can do something like this, though:</p> <pre><code>def f(): g = [1] def func(): print g[0] return func, g f, val = f() f() val[0] = 2 f() </code></pre> <p>This uses an array to simulate a reference.</p>
1
2009-07-17T08:56:19Z
[ "python", "namespaces", "local" ]
How to modify the local namespace in python
1,142,068
<p>How can I modify the local namespace of a function in python? I know that locals() returns the local namespace of the function when called inside it, but I want to do something like this (I have a reason why I want to do this where g is not accessible to f, but it's quicker to give a trivial, stupid example to illustrate the problem):</p> <pre><code>def g(): pass def f(): g() f.add_to_locals({'g':g}) </code></pre>
3
2009-07-17T08:43:24Z
1,142,244
<p>I think you could solve the problem tackling it from a completely different point.<br /> Functions are object, with their dictionaries; therefore, you can add g to f, and use it:</p> <pre><code>def g(): print "g" def f(): f.g() f.g = g </code></pre>
1
2009-07-17T09:24:05Z
[ "python", "namespaces", "local" ]
How to modify the local namespace in python
1,142,068
<p>How can I modify the local namespace of a function in python? I know that locals() returns the local namespace of the function when called inside it, but I want to do something like this (I have a reason why I want to do this where g is not accessible to f, but it's quicker to give a trivial, stupid example to illustrate the problem):</p> <pre><code>def g(): pass def f(): g() f.add_to_locals({'g':g}) </code></pre>
3
2009-07-17T08:43:24Z
1,142,259
<p>Why don't you just add an argument to <code>f()</code> and pass a reference to <code>g()</code>?</p> <pre><code>def g(): pass def f(func): func() f(g) </code></pre>
3
2009-07-17T09:29:45Z
[ "python", "namespaces", "local" ]
How to modify the local namespace in python
1,142,068
<p>How can I modify the local namespace of a function in python? I know that locals() returns the local namespace of the function when called inside it, but I want to do something like this (I have a reason why I want to do this where g is not accessible to f, but it's quicker to give a trivial, stupid example to illustrate the problem):</p> <pre><code>def g(): pass def f(): g() f.add_to_locals({'g':g}) </code></pre>
3
2009-07-17T08:43:24Z
1,142,397
<p>I assume you want to do this, because the function f is defined not by you, but by some other module. So you want to change how f() works. In particular, you want to change what is called when g is called.</p> <p>So I'll suggest this:</p> <pre><code>import thirdpartypackage def mynewg(): pass thirdpartypackage.g = mynewg </code></pre> <p>This will change the global g for the module thirdpartypackage. So when thirdpartypackage.f() now is called, it will call mynewg() instead of g().</p> <p>If this doesn't solve it, maybe g() is in fact imported from withing f(), or somthing. Then the solution is this:</p> <pre><code>import thirdpartypackage def mynewg(): pass deg mynewf(): mynewg() thirdpartypackage.f = mynewf </code></pre> <p>That is, you override f() completely with a modified version that does what you want it to.</p>
2
2009-07-17T10:03:47Z
[ "python", "namespaces", "local" ]
How to modify the local namespace in python
1,142,068
<p>How can I modify the local namespace of a function in python? I know that locals() returns the local namespace of the function when called inside it, but I want to do something like this (I have a reason why I want to do this where g is not accessible to f, but it's quicker to give a trivial, stupid example to illustrate the problem):</p> <pre><code>def g(): pass def f(): g() f.add_to_locals({'g':g}) </code></pre>
3
2009-07-17T08:43:24Z
1,144,561
<p>You've a couple of options. First, note that g in your example isn't actually a local to the function (ie. not assigned within it), it's a global (ie hasn't been assigned to a local variable). This means that it will be looked up in the module the function is defined in. This is fortunate, as there's no way of altering locals externally (short of patching the bytecode), as they get assigned when the function runs, not before.</p> <p>One option is simply to inject your function into the function's module's namespace. This will work, but will affect every function in that module that accesses the variable, rather than just the one function.</p> <p>To affect just the one function, you need to instead point that func_globals somewhere else. Unfortunately, this is a read-only property, but you can do what you want by recreating the function with the same body, but a different global namespace:</p> <pre><code>import new f = new.function(f.func_code, {'g': my_g_function}, f.func_name, f.func_defaults, f.func_closure) </code></pre> <p>f will now be indentical, except that it will look for globals in the provided dict. Note that this rebinds the whole global namespace - if there are variables there that f <em>does</em> look up, make sure you provide them too. This is also fairly hacky though, and may not work on versions of python other than cpython.</p>
8
2009-07-17T17:07:52Z
[ "python", "namespaces", "local" ]
How to modify the local namespace in python
1,142,068
<p>How can I modify the local namespace of a function in python? I know that locals() returns the local namespace of the function when called inside it, but I want to do something like this (I have a reason why I want to do this where g is not accessible to f, but it's quicker to give a trivial, stupid example to illustrate the problem):</p> <pre><code>def g(): pass def f(): g() f.add_to_locals({'g':g}) </code></pre>
3
2009-07-17T08:43:24Z
8,741,511
<p>This seems to work</p> <pre><code>def add_to_locals(l): l['newlocal'] = 1 add_to_locals(locals()) assert newlocal </code></pre>
0
2012-01-05T11:12:52Z
[ "python", "namespaces", "local" ]
Problem executing with Python+MySQL
1,142,098
<p>I am not getting the reason why my python script is not working though I hv put all the things correctly as my knowledge.The below test I did and it worked fine.But when I import the MySQLdb in my script it gives error as no module name MySQLdb.</p> <p>**C:\Python26>python Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information.</p> <blockquote> <blockquote> <blockquote> <p>import MySQLdb **</p> </blockquote> </blockquote> </blockquote> <p>Kindly let me know the reason for this error.</p> <p>And all the development is going on in windows XP, python 2.6, mysql 4.0.3</p> <p>Earlier 1 hour back I have posted the question but some mistake was there in the question itself..</p>
-1
2009-07-17T08:50:24Z
1,142,113
<p>seems like the path is not set properly.</p>
0
2009-07-17T08:54:14Z
[ "python", "mysql" ]
Python @property versus method performance - which one to use?
1,142,133
<p>I have written some code that uses attributes of an object:</p> <pre><code>class Foo: def __init__(self): self.bar = "baz" myFoo = Foo() print (myFoo.bar) </code></pre> <p>Now I want to do some fancy calculation to return <code>bar</code>. I could use <code>@property</code> to make methods act as the attribute <code>bar</code>, or I could refactor my code to use <code>myFoo.bar()</code>.</p> <p>Should I go back and add parens to all my <code>bar</code> accesses or use <code>@property</code>? Assume my code base is small now but due to entropy it will increase.</p>
11
2009-07-17T08:58:39Z
1,142,186
<p>If it's logically a property/attribute of the object, I'd say keep it as a property. If it's likely to become parametrised, by which I mean you may want to invoke <code>myFoo.bar(someArgs)</code> then bite the bullet now and make it a method.</p> <p>Under most circumstances, performance is unlikely to be an issue.</p>
18
2009-07-17T09:11:49Z
[ "python", "performance", "properties" ]
Python @property versus method performance - which one to use?
1,142,133
<p>I have written some code that uses attributes of an object:</p> <pre><code>class Foo: def __init__(self): self.bar = "baz" myFoo = Foo() print (myFoo.bar) </code></pre> <p>Now I want to do some fancy calculation to return <code>bar</code>. I could use <code>@property</code> to make methods act as the attribute <code>bar</code>, or I could refactor my code to use <code>myFoo.bar()</code>.</p> <p>Should I go back and add parens to all my <code>bar</code> accesses or use <code>@property</code>? Assume my code base is small now but due to entropy it will increase.</p>
11
2009-07-17T08:58:39Z
1,142,190
<p>In cases like these, I find it much better to choose the option that makes the most sense. You won't get any noticeable performance loss with small differences like these. It's much more important that your code is easy to use and maintain.</p> <p>As for choosing between using a method and a <code>@property</code>, it's a matter of taste, but since properties disguise themselves as simple attributes, nothing elaborate should be going on. A method indicates that it might be an expensive operation, and developers using your code will consider caching the value rather than fetching it again and again.</p> <p>So again, don't go on performance, always consider maintainability vs. performance. Computers get faster and faster as time goes by. The same does not stand for the readability of code.</p> <p>In short, if you want to get a simple calculated value, <code>@property</code> is an excellent choice; if you want an elaborate value calculated, a method indicates that better.</p>
6
2009-07-17T09:12:16Z
[ "python", "performance", "properties" ]
Python @property versus method performance - which one to use?
1,142,133
<p>I have written some code that uses attributes of an object:</p> <pre><code>class Foo: def __init__(self): self.bar = "baz" myFoo = Foo() print (myFoo.bar) </code></pre> <p>Now I want to do some fancy calculation to return <code>bar</code>. I could use <code>@property</code> to make methods act as the attribute <code>bar</code>, or I could refactor my code to use <code>myFoo.bar()</code>.</p> <p>Should I go back and add parens to all my <code>bar</code> accesses or use <code>@property</code>? Assume my code base is small now but due to entropy it will increase.</p>
11
2009-07-17T08:58:39Z
1,142,192
<p>That's exactly what @property is meant for.</p>
1
2009-07-17T09:12:40Z
[ "python", "performance", "properties" ]
Python @property versus method performance - which one to use?
1,142,133
<p>I have written some code that uses attributes of an object:</p> <pre><code>class Foo: def __init__(self): self.bar = "baz" myFoo = Foo() print (myFoo.bar) </code></pre> <p>Now I want to do some fancy calculation to return <code>bar</code>. I could use <code>@property</code> to make methods act as the attribute <code>bar</code>, or I could refactor my code to use <code>myFoo.bar()</code>.</p> <p>Should I go back and add parens to all my <code>bar</code> accesses or use <code>@property</code>? Assume my code base is small now but due to entropy it will increase.</p>
11
2009-07-17T08:58:39Z
1,142,205
<p>I would go for the refactoring, but only for a matter of style - it seems clearer to me that "fancy calculations" might be ongoing with a method call, while I would expect a property to be almost a no-op, but this is a matter of taste.</p> <p>Don't worry about the decorator's performance... if you think that it might be a problem, measure the performance in both cases and see how much it does add (my guess is that it will be totally negligible if compared to your fancy calculations).</p>
3
2009-07-17T09:15:34Z
[ "python", "performance", "properties" ]
Python @property versus method performance - which one to use?
1,142,133
<p>I have written some code that uses attributes of an object:</p> <pre><code>class Foo: def __init__(self): self.bar = "baz" myFoo = Foo() print (myFoo.bar) </code></pre> <p>Now I want to do some fancy calculation to return <code>bar</code>. I could use <code>@property</code> to make methods act as the attribute <code>bar</code>, or I could refactor my code to use <code>myFoo.bar()</code>.</p> <p>Should I go back and add parens to all my <code>bar</code> accesses or use <code>@property</code>? Assume my code base is small now but due to entropy it will increase.</p>
11
2009-07-17T08:58:39Z
1,143,856
<p>Wondering about performance is needless when it's so easy to measure it:</p> <pre><code>$ python -mtimeit -s'class X(object): &gt; @property &gt; def y(self): return 23 &gt; x=X()' 'x.y' 1000000 loops, best of 3: 0.685 usec per loop $ python -mtimeit -s'class X(object): def y(self): return 23 x=X()' 'x.y()' 1000000 loops, best of 3: 0.447 usec per loop $ </code></pre> <p>(on my slow laptop -- if you wonder why the 2nd case doesn't have secondary shell prompts, it's because I built it from the first with an up-arrow in bash, and that repeats the linebreak structure but not the prompts!-).</p> <p>So unless you're in a case where you know 200+ nanoseconds or so will matter (a tight inner loop you're trying to optimize to the utmost), you can afford to use the property approach; if you do some computations to get the value, the 200+ nanoseconds will of course become a smaller fraction of the total time taken.</p> <p>I do agree with other answers that if the computations become too heavy, or you may ever want parameters, etc, a method is preferable -- similarly, I'll add, if you ever need to stash the callable somewhere but only call it later, and other fancy functional programming tricks; but I wanted to make the performance point quantitatively, since <code>timeit</code> makes such measurements so easy!-)</p>
15
2009-07-17T15:06:38Z
[ "python", "performance", "properties" ]
Python @property versus method performance - which one to use?
1,142,133
<p>I have written some code that uses attributes of an object:</p> <pre><code>class Foo: def __init__(self): self.bar = "baz" myFoo = Foo() print (myFoo.bar) </code></pre> <p>Now I want to do some fancy calculation to return <code>bar</code>. I could use <code>@property</code> to make methods act as the attribute <code>bar</code>, or I could refactor my code to use <code>myFoo.bar()</code>.</p> <p>Should I go back and add parens to all my <code>bar</code> accesses or use <code>@property</code>? Assume my code base is small now but due to entropy it will increase.</p>
11
2009-07-17T08:58:39Z
1,144,085
<p>I agree with what most people here have said, I did much measurement when building hydrologic models in Python a couple years ago and found that the speed hit from using @property was <em>completely</em> overshadowed by calculation. </p> <p>As an example, creating method local variables (removing the "dot factor" in my calculations increased performance by almost an order of magnitude more than removing @property (these results are averaged over a mid-scale application). </p> <p>I'd look elsewhere for optimization, when it's necessary, and focus initially on getting good, maintainable code written. At this point, if @property is intuitive in your case, use it. If not, make a method. </p>
2
2009-07-17T15:40:53Z
[ "python", "performance", "properties" ]
Django: Why do some model fields clash with each other?
1,142,378
<p>I want to create an object that contains 2 links to Users. For example:</p> <pre><code>class GameClaim(models.Model): target = models.ForeignKey(User) claimer = models.ForeignKey(User) isAccepted = models.BooleanField() </code></pre> <p>but I am getting the following errors when running the server:</p> <ul> <li><blockquote> <p>Accessor for field 'target' clashes with related field 'User.gameclaim_set'. Add a related_name argument to the definition for 'target'.</p> </blockquote></li> <li><blockquote> <p>Accessor for field 'claimer' clashes with related field 'User.gameclaim_set'. Add a related_name argument to the definition for 'claimer'.</p> </blockquote></li> </ul> <p>Can you please explain why I am getting the errors and how to fix them?</p>
147
2009-07-17T09:59:08Z
1,142,467
<p>The <code>User</code> model is trying to create two fields with the same name, one for the <code>GameClaims</code> that have that <code>User</code> as the <code>target</code>, and another for the <code>GameClaims</code> that have that <code>User</code> as the <code>claimer</code>. Here's the <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#be-careful-with-related-name">docs on <code>related_name</code></a>, which is Django's way of letting you set the names of the attributes so the autogenerated ones don't conflict.</p>
6
2009-07-17T10:19:14Z
[ "python", "django", "django-models" ]
Django: Why do some model fields clash with each other?
1,142,378
<p>I want to create an object that contains 2 links to Users. For example:</p> <pre><code>class GameClaim(models.Model): target = models.ForeignKey(User) claimer = models.ForeignKey(User) isAccepted = models.BooleanField() </code></pre> <p>but I am getting the following errors when running the server:</p> <ul> <li><blockquote> <p>Accessor for field 'target' clashes with related field 'User.gameclaim_set'. Add a related_name argument to the definition for 'target'.</p> </blockquote></li> <li><blockquote> <p>Accessor for field 'claimer' clashes with related field 'User.gameclaim_set'. Add a related_name argument to the definition for 'claimer'.</p> </blockquote></li> </ul> <p>Can you please explain why I am getting the errors and how to fix them?</p>
147
2009-07-17T09:59:08Z
1,142,473
<p>You have two foreign keys to User. Django automatically creates a reverse relation from User back to GameClaim, which is usually <code>gameclaim_set</code>. However, because you have two FKs, you would have two <code>gameclaim_set</code> attributes, which is obviously impossible. So you need to tell Django what name to use for the reverse relation.</p> <p>Use the <code>related_name</code> attribute in the FK definition. e.g.</p> <pre><code>class GameClaim(models.Model): target = models.ForeignKey(User, related_name='gameclaim_targets') claimer = models.ForeignKey(User, related_name='gameclaim_users') isAccepted = models.BooleanField() </code></pre>
259
2009-07-17T10:20:48Z
[ "python", "django", "django-models" ]
Django: Why do some model fields clash with each other?
1,142,378
<p>I want to create an object that contains 2 links to Users. For example:</p> <pre><code>class GameClaim(models.Model): target = models.ForeignKey(User) claimer = models.ForeignKey(User) isAccepted = models.BooleanField() </code></pre> <p>but I am getting the following errors when running the server:</p> <ul> <li><blockquote> <p>Accessor for field 'target' clashes with related field 'User.gameclaim_set'. Add a related_name argument to the definition for 'target'.</p> </blockquote></li> <li><blockquote> <p>Accessor for field 'claimer' clashes with related field 'User.gameclaim_set'. Add a related_name argument to the definition for 'claimer'.</p> </blockquote></li> </ul> <p>Can you please explain why I am getting the errors and how to fix them?</p>
147
2009-07-17T09:59:08Z
3,517,643
<p>The OP isn't using a abstract base class... but if you are, you will find that hard coding the related_name in the FK (e.g. ..., related_name="myname") will result in a number of these conflict errors - one for each inherited class from the base class. The link provided below contains the workaround, which is simple, but definitely not obvious. </p> <p>From the django docs...</p> <blockquote> <p>If you are using the related_name attribute on a ForeignKey or ManyToManyField, you must always specify a unique reverse name for the field. This would normally cause a problem in abstract base classes, since the fields on this class are included into each of the child classes, with exactly the same values for the attributes (including related_name) each time.</p> </blockquote> <p>More info <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#be-careful-with-related-name" rel="nofollow">here</a>.</p>
4
2010-08-18T23:48:31Z
[ "python", "django", "django-models" ]
Django: Why do some model fields clash with each other?
1,142,378
<p>I want to create an object that contains 2 links to Users. For example:</p> <pre><code>class GameClaim(models.Model): target = models.ForeignKey(User) claimer = models.ForeignKey(User) isAccepted = models.BooleanField() </code></pre> <p>but I am getting the following errors when running the server:</p> <ul> <li><blockquote> <p>Accessor for field 'target' clashes with related field 'User.gameclaim_set'. Add a related_name argument to the definition for 'target'.</p> </blockquote></li> <li><blockquote> <p>Accessor for field 'claimer' clashes with related field 'User.gameclaim_set'. Add a related_name argument to the definition for 'claimer'.</p> </blockquote></li> </ul> <p>Can you please explain why I am getting the errors and how to fix them?</p>
147
2009-07-17T09:59:08Z
13,407,176
<p>I seem to come across this occasionally when I add a submodule as an application to a django project, for example given the following structure:</p> <pre><code>myapp/ myapp/module/ myapp/module/models.py </code></pre> <p>If I add the following to INSTALLED_APPS:</p> <pre><code>'myapp', 'myapp.module', </code></pre> <p>Django seems to process the myapp.mymodule models.py file twice and throws the above error. This can be resolved by not including the main module in the INSTALLED_APPS list:</p> <pre><code>'myapp.module', </code></pre> <p>Including the <code>myapp</code> instead of <code>myapp.module</code> causes all the database tables to be created with incorrect names, so this seems to be the correct way to do it.</p> <p>I came across this post while looking for a solution to this problem so figured I'd put this here :)</p>
0
2012-11-15T22:13:52Z
[ "python", "django", "django-models" ]
Django: Why do some model fields clash with each other?
1,142,378
<p>I want to create an object that contains 2 links to Users. For example:</p> <pre><code>class GameClaim(models.Model): target = models.ForeignKey(User) claimer = models.ForeignKey(User) isAccepted = models.BooleanField() </code></pre> <p>but I am getting the following errors when running the server:</p> <ul> <li><blockquote> <p>Accessor for field 'target' clashes with related field 'User.gameclaim_set'. Add a related_name argument to the definition for 'target'.</p> </blockquote></li> <li><blockquote> <p>Accessor for field 'claimer' clashes with related field 'User.gameclaim_set'. Add a related_name argument to the definition for 'claimer'.</p> </blockquote></li> </ul> <p>Can you please explain why I am getting the errors and how to fix them?</p>
147
2009-07-17T09:59:08Z
31,903,422
<p>Just adding to Jordan's answer (thanks for the tip Jordan) it can also happen if you import the level above the apps and then import the apps e.g.</p> <p><code>myproject/ apps/ foo_app/ bar_app/</code></p> <p>So if you are importing apps, foo_app and bar_app then you could get this issue. I had apps, foo_app and bar_app all listed in settings.INSTALLED_APPS</p> <p>And you want to avoid importing apps anyway, because then you have the same app installed in 2 different namespaces</p> <p><code>apps.foo_app</code> and <code>foo_app</code></p>
0
2015-08-09T10:53:13Z
[ "python", "django", "django-models" ]
Django: Why do some model fields clash with each other?
1,142,378
<p>I want to create an object that contains 2 links to Users. For example:</p> <pre><code>class GameClaim(models.Model): target = models.ForeignKey(User) claimer = models.ForeignKey(User) isAccepted = models.BooleanField() </code></pre> <p>but I am getting the following errors when running the server:</p> <ul> <li><blockquote> <p>Accessor for field 'target' clashes with related field 'User.gameclaim_set'. Add a related_name argument to the definition for 'target'.</p> </blockquote></li> <li><blockquote> <p>Accessor for field 'claimer' clashes with related field 'User.gameclaim_set'. Add a related_name argument to the definition for 'claimer'.</p> </blockquote></li> </ul> <p>Can you please explain why I am getting the errors and how to fix them?</p>
147
2009-07-17T09:59:08Z
34,833,294
<p>I had the same problem. Using run python manage.py makemigrations "appname" fixed it for me. I had accidentally deleted some migration files. No need to re-delete any files.</p>
-2
2016-01-16T23:25:13Z
[ "python", "django", "django-models" ]
Convert HTML to Django Fixture (JSON)
1,142,702
<p>We've got a couple of Django flatpages in our project, that are based on actual HTML files. These files undergo some changes once in a while and hence have to updated in the database. So I came up with the idea of simply copying the plain HTML text into a JSON fixture and do an <code>manage.py loaddata</code>.</p> <p>However, the problem is, that there are quite some characters inside the HTML that have to be escaped in order to pass as JSON. Is there some script, <a href="http://en.wikipedia.org/wiki/Sed" rel="nofollow">sed</a> command or maybe even an official Django solution for that problem?</p>
-1
2009-07-17T11:27:50Z
1,142,887
<p>You could <a href="http://docs.djangoproject.com/en/dev/howto/custom-management-commands/#howto-custom-management-commands" rel="nofollow">write your own manage.py command</a> to read in the HTML file and adding them to the flatpages:</p> <pre><code># Assuming variable html contains the new HTML file, #+ and var id the ID of the flatpage. from django.contrib.flatpages.models import FlatPage fp = FlatPage.objects.get (id=id) fp.content = html fp.save() </code></pre>
1
2009-07-17T12:09:17Z
[ "python", "django", "json" ]
AttributeError: 'unicode' object has no attribute '_meta'
1,142,717
<p>I am getting this error on "python manage.py migrate contacts".</p> <p>The error info does not pinpoint problem location. </p> <p>Here is the error description:</p> <p><a href="http://dpaste.com/68162/" rel="nofollow">http://dpaste.com/68162/</a></p> <p>Hers is a sample model definition:</p> <p><a href="http://dpaste.com/68173/" rel="nofollow">http://dpaste.com/68173/</a></p> <p>Can someone point me to right direction???</p> <p>I got this: <a href="http://blog.e-shell.org/66" rel="nofollow">http://blog.e-shell.org/66</a></p> <p>but can not figure out the problem.</p>
1
2009-07-17T11:30:17Z
1,142,929
<p>Figured out the problem. There was this line:</p> <pre><code>note = GenericRelation('Comment', object_id_field='object_pk') </code></pre> <p>in model <code>Company</code> and <code>Person</code>. But <code>Comment</code> class was undefined. I commented the line at both places. It works now.</p> <p>Thanks for your time.</p>
2
2009-07-17T12:16:35Z
[ "python", "django" ]
python + Spreadsheet
1,142,730
<p>Can anybody please tell me is there any possible way to connect to spreadsheet from python? I want to store some data from a form and submit it to google spreadsheet. Please help on this issue. What steps do I have to follow?</p> <p>Thanks in advance...</p>
4
2009-07-17T11:34:59Z
1,142,742
<p>There is a python api for google docs <a href="http://code.google.com/intl/fr/apis/gdata/articles/python_client_lib.html" rel="nofollow">http://code.google.com/intl/fr/apis/gdata/articles/python_client_lib.html</a>. I am not sure if it works with app engine</p>
1
2009-07-17T11:37:36Z
[ "python", "google-app-engine", "google-spreadsheet" ]
python + Spreadsheet
1,142,730
<p>Can anybody please tell me is there any possible way to connect to spreadsheet from python? I want to store some data from a form and submit it to google spreadsheet. Please help on this issue. What steps do I have to follow?</p> <p>Thanks in advance...</p>
4
2009-07-17T11:34:59Z
1,143,678
<p>Sure, you can validate with OAuth then use the gdata Python API -- see <a href="http://groups.google.com/group/gdata-python-client-library-contributors/browse%5Fthread/thread/19d93048d9914cd6" rel="nofollow">this thread</a> for more details and caveats, <a href="http://code.google.com/p/gdata-python-client/source/browse/#svn/trunk/samples/oauth/oauth%5Fon%5Fappengine" rel="nofollow">this code</a> for a good simple example of OAuth use in Python on App Engine.</p>
1
2009-07-17T14:38:04Z
[ "python", "google-app-engine", "google-spreadsheet" ]
python + Spreadsheet
1,142,730
<p>Can anybody please tell me is there any possible way to connect to spreadsheet from python? I want to store some data from a form and submit it to google spreadsheet. Please help on this issue. What steps do I have to follow?</p> <p>Thanks in advance...</p>
4
2009-07-17T11:34:59Z
5,413,289
<p>I have recently written a module to do this. check it out <a href="https://sourceforge.net/projects/pyworkbooks/" rel="nofollow">https://sourceforge.net/projects/pyworkbooks/</a></p>
0
2011-03-24T00:22:24Z
[ "python", "google-app-engine", "google-spreadsheet" ]
python + Spreadsheet
1,142,730
<p>Can anybody please tell me is there any possible way to connect to spreadsheet from python? I want to store some data from a form and submit it to google spreadsheet. Please help on this issue. What steps do I have to follow?</p> <p>Thanks in advance...</p>
4
2009-07-17T11:34:59Z
8,532,699
<p>The easiest way to connect to Google Spreadsheet is by using this <a href="http://burnash.github.com/gspread">spreadsheet library</a>. These are the steps you need to follow:</p> <pre><code>import gspread # Login with your Google account gc = gspread.login('account@gmail.com','password') # Spreadsheets can be opened by their title in Google Docs spreadsheet = gc.open("_YOUR_TARGET_SPREADSHEET_") # Select worksheet by index worksheet = spreadsheet.get_worksheet(0) # Update cell with your form value worksheet.update_cell(1, 2, form_value_1) </code></pre>
9
2011-12-16T10:14:08Z
[ "python", "google-app-engine", "google-spreadsheet" ]
python + Spreadsheet
1,142,730
<p>Can anybody please tell me is there any possible way to connect to spreadsheet from python? I want to store some data from a form and submit it to google spreadsheet. Please help on this issue. What steps do I have to follow?</p> <p>Thanks in advance...</p>
4
2009-07-17T11:34:59Z
10,110,465
<p>Here is a very simple wrapper for the Google Spreasheets API i've recently written:</p> <p><a href="http://github.com/yoavaviram/python-google-spreadsheet" rel="nofollow">http://github.com/yoavaviram/python-google-spreadsheet</a></p> <p>Its compatible with App Engine.</p>
1
2012-04-11T16:54:18Z
[ "python", "google-app-engine", "google-spreadsheet" ]
Merge some list items in a Python List
1,142,851
<p>Say I have a list like this:</p> <pre><code>[a, b, c, d, e, f, g] </code></pre> <p>How do modify that list so that it looks like this?</p> <pre><code>[a, b, c, def, g] </code></pre> <p>I would much prefer that it modified the existing list directly, not created a new list. </p>
11
2009-07-17T12:03:05Z
1,142,876
<p>That example is pretty vague, but maybe something like this?</p> <pre><code>items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] items[3:6] = [''.join(items[3:6])] </code></pre> <p>It basically does a splice (or <a href="http://docs.python.org/tutorial/introduction.html#lists">assignment to a slice</a>) operation. It removes items 3 to 6 and inserts a new list in their place (in this case a list with one item, which is the concatenation of the three items that were removed.)</p> <p>For any type of list, you could do this (using the <code>+</code> operator on all items no matter what their type is):</p> <pre><code>items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] items[3:6] = [reduce(lambda x, y: x + y, items[3:6])] </code></pre> <p>This makes use of the <a href="http://docs.python.org/library/functions.html#reduce"><code>reduce</code></a> function with a <a href="http://docs.python.org/reference/expressions.html#lambda"><code>lambda</code></a> function that basically adds the items together using the <code>+</code> operator.</p>
20
2009-07-17T12:07:51Z
[ "python", "list", "concatenation" ]
Merge some list items in a Python List
1,142,851
<p>Say I have a list like this:</p> <pre><code>[a, b, c, d, e, f, g] </code></pre> <p>How do modify that list so that it looks like this?</p> <pre><code>[a, b, c, def, g] </code></pre> <p>I would much prefer that it modified the existing list directly, not created a new list. </p>
11
2009-07-17T12:03:05Z
1,142,879
<p>On what basis should the merging take place? Your question is rather vague. Also, I assume a, b, ..., f are supposed to be strings, that is, 'a', 'b', ..., 'f'.</p> <pre><code>&gt;&gt;&gt; x = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] &gt;&gt;&gt; x[3:6] = [''.join(x[3:6])] &gt;&gt;&gt; x ['a', 'b', 'c', 'def', 'g'] </code></pre> <p>Check out the documentation on <a href="http://docs.python.org/3.0/library/stdtypes.html#sequence-types-str-bytes-bytearray-list-tuple-range">sequence types</a>, specifically on <a href="http://docs.python.org/3.0/library/stdtypes.html#mutable-sequence-types">mutable sequence types</a>. And perhaps also on <a href="http://docs.python.org/3.0/library/stdtypes.html#string-methods">string methods</a>.</p>
26
2009-07-17T12:08:15Z
[ "python", "list", "concatenation" ]
Merge some list items in a Python List
1,142,851
<p>Say I have a list like this:</p> <pre><code>[a, b, c, d, e, f, g] </code></pre> <p>How do modify that list so that it looks like this?</p> <pre><code>[a, b, c, def, g] </code></pre> <p>I would much prefer that it modified the existing list directly, not created a new list. </p>
11
2009-07-17T12:03:05Z
1,142,906
<p>my telepathic abilities are not particularly great, but here is what I think you want:</p> <pre><code>def merge(list_of_strings, indices): list_of_strings[indices[0]] = ''.join(list_of_strings[i] for i in indices) list_of_strings = [s for i, s in enumerate(list_of_strings) if i not in indices[1:]] return list_of_strings </code></pre> <p>I should note, since it might be not obvious, that it's not the same as what is proposed in other answers.</p>
0
2009-07-17T12:12:36Z
[ "python", "list", "concatenation" ]
Merge some list items in a Python List
1,142,851
<p>Say I have a list like this:</p> <pre><code>[a, b, c, d, e, f, g] </code></pre> <p>How do modify that list so that it looks like this?</p> <pre><code>[a, b, c, def, g] </code></pre> <p>I would much prefer that it modified the existing list directly, not created a new list. </p>
11
2009-07-17T12:03:05Z
1,143,043
<p>just a variation</p> <pre><code>alist=["a", "b", "c", "d", "e", 0, "g"] alist[3:6] = [''.join(map(str,alist[3:6]))] print alist </code></pre>
2
2009-07-17T12:43:12Z
[ "python", "list", "concatenation" ]
PyQt: Overriding QGraphicsView.drawItems
1,142,970
<p>I need to customize the drawing process of a QGraphicsView, and so I override the drawItems method like this:</p> <pre><code>self.graphicsview.drawItems=self.drawer.drawItems </code></pre> <p>where <code>self.graphicsview</code> is a QGraphicsView, and <code>self.drawer</code> is a custom class with a method <code>drawItems</code>.<br /> In this method I check a few flags to decide how to draw each item, and then call <code>item.paint</code>, like this:</p> <pre><code>def drawItems(self, painter, items, options): for item in items: print "Processing", item # ... Do checking ... item.paint(painter, options, self.target) </code></pre> <p><code>self.target</code> is the QGraphicsView's QGraphicsScene.<br /> However, once it reaches <code>item.paint</code>, it breaks out of the loop - without any errors. If I put conditionals around the painting, and for each possible type of QGraphicsItem paste the code that is supposed to be executed (by looking at the Qt git-sources), everything works.<br /> Not a very nice solution though... And I don't understand how it could even break out of the loop?</p>
3
2009-07-17T12:25:04Z
1,143,218
<p>The reason why the loop suddenly exits is that an Exception is thrown. Python doesn't handle it (there is no <code>try:</code> block), so it's passed to the called (Qt's C++ code) which has no idea about Python exceptions, so it's lost.</p> <p>Add a try/except around the loop and you should see the reason why this happens.</p> <p>Note: Since Python 2.4, you should not override methods this way anymore.</p> <p>Instead, you must derive a new class from QGraphicsView and add your <code>drawItems()</code> method to this new class. This will replace the original method properly.</p> <p>Don't forget to call <code>super()</code> in the <code>__init__</code> method! Otherwise, your object won't work properly.</p>
0
2009-07-17T13:20:47Z
[ "python", "pyqt" ]
PyQt: Overriding QGraphicsView.drawItems
1,142,970
<p>I need to customize the drawing process of a QGraphicsView, and so I override the drawItems method like this:</p> <pre><code>self.graphicsview.drawItems=self.drawer.drawItems </code></pre> <p>where <code>self.graphicsview</code> is a QGraphicsView, and <code>self.drawer</code> is a custom class with a method <code>drawItems</code>.<br /> In this method I check a few flags to decide how to draw each item, and then call <code>item.paint</code>, like this:</p> <pre><code>def drawItems(self, painter, items, options): for item in items: print "Processing", item # ... Do checking ... item.paint(painter, options, self.target) </code></pre> <p><code>self.target</code> is the QGraphicsView's QGraphicsScene.<br /> However, once it reaches <code>item.paint</code>, it breaks out of the loop - without any errors. If I put conditionals around the painting, and for each possible type of QGraphicsItem paste the code that is supposed to be executed (by looking at the Qt git-sources), everything works.<br /> Not a very nice solution though... And I don't understand how it could even break out of the loop?</p>
3
2009-07-17T12:25:04Z
1,143,459
<p>There is an exception that occurs when the items are painted, but it is not reported right away. On my system (PyQt 4.5.1, Python 2.6), no exception is reported when I monkey-patch the following method:</p> <pre><code>def drawItems(painter, items, options): print len(items) for idx, i in enumerate(items): print idx, i if idx &gt; 5: raise ValueError() </code></pre> <p>Output:</p> <pre><code>45 0 &lt;PyQt4.QtGui.QGraphicsPathItem object at 0x3585270&gt; 1 &lt;PyQt4.QtGui.QGraphicsSimpleTextItem object at 0x356ca68&gt; 2 &lt;PyQt4.QtGui.QGraphicsSimpleTextItem object at 0x356ce20&gt; 3 &lt;PyQt4.QtGui.QGraphicsSimpleTextItem object at 0x356cc88&gt; 4 &lt;PyQt4.QtGui.QGraphicsSimpleTextItem object at 0x356cc00&gt; 5 &lt;PyQt4.QtGui.QGraphicsSimpleTextItem object at 0x356caf0&gt; 6 &lt;PyQt4.QtGui.QGraphicsSimpleTextItem object at 0x356cb78&gt; </code></pre> <p>However, once I close the application, the following method is printed:</p> <pre><code>Exception ValueError: ValueError() in &lt;module 'threading' from '/usr/lib/python2.6/threading.pyc'&gt; ignored </code></pre> <p>I tried printing <code>threading.currentThread()</code>, but it returns the same thread whether it's called in- or outside the monkey-patched <code>drawItems</code> method.</p> <p>In your code, this is likely due to the fact that you pass <code>options</code> (which is a list of style options objects) to the individual items rather than the respective option object. Using this code should give you the correct results:</p> <pre><code>def drawItems(self, painter, items, options): for item, option in zip(items, options): print "Processing", item # ... Do checking ... item.paint(painter, option, self.target) </code></pre> <p>Also, you say the <code>self.target</code> is the scene object. The <a href="http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qgraphicsitem.html#paint" rel="nofollow">documentation for <code>paint()</code></a> says:</p> <blockquote> <p>This function, which is usually called by QGraphicsView, paints the contents of an item in local coordinates. ... The widget argument is optional. If provided, it points to the widget that is being painted on; otherwise, it is 0. For cached painting, widget is always 0.</p> </blockquote> <p>and the type is <code>QWidget*</code>. <code>QGraphicsScene</code> inherits from <code>QObject</code> and is not a widget, so it is likely that this is wrong, too.</p> <p>Still, the fact that the exception is not reported at all, or not right away suggests some foul play, you should contact the maintainer.</p>
3
2009-07-17T13:58:52Z
[ "python", "pyqt" ]
Create NTFS junction point in Python
1,143,260
<p>Is there a way to create an NTFS junction point in Python? I know I can call the <code>junction</code> utility, but it would be better not to rely on external tools.</p>
8
2009-07-17T13:27:31Z
1,143,276
<p>You don't want to rely on external tools but you don't mind relying on the specific environment? I think you could safely assume that, if it's NTFS you're running on, the junction utility will probably be there.</p> <p>But, if you mean you'd rather not call out to an external program, I've found the <a href="http://docs.python.org/library/ctypes.html" rel="nofollow">ctypes</a> stuff to be invaluable. It allows you to call Windows DLLs directly from Python. And I'm pretty sure it's in the standard Python releases nowadays.</p> <p>You'd just have to figure out which Windows DLL the <code>CreateJunction()</code> (or whatever Windows calls it) API call is in and set up the parameters and call. Best of luck with that, Microsoft don't seem to support it very well. You <em>could</em> disassemble the SysInternals <code>junction</code> program or <code>linkd</code> or one of the other tools to find out how they do it.</p> <p>Me, I'm pretty lazy, I'd just call <code>junction</code> as an external process :-)</p>
0
2009-07-17T13:30:26Z
[ "python", "windows", "ntfs", "junction" ]
Create NTFS junction point in Python
1,143,260
<p>Is there a way to create an NTFS junction point in Python? I know I can call the <code>junction</code> utility, but it would be better not to rely on external tools.</p>
8
2009-07-17T13:27:31Z
1,143,329
<p>you can use python win32 API modules e.g.</p> <pre><code>import win32file win32file.CreateSymbolicLink(srcDir, targetDir, 1) </code></pre> <p>see <a href="http://docs.activestate.com/activepython/2.5/pywin32/win32file__CreateSymbolicLink_meth.html" rel="nofollow">http://docs.activestate.com/activepython/2.5/pywin32/win32file__CreateSymbolicLink_meth.html</a> for more details</p> <p>if you do not want to rely on that too, you can always use ctypes and directly call CreateSymbolicLinl win32 API, which is anyway a simple call</p> <p>here is example call using ctypes</p> <pre><code>import ctypes kdll = ctypes.windll.LoadLibrary("kernel32.dll") kdll.CreateSymbolicLinkA("d:\testdir", "d:\testdir_link", 1) </code></pre> <p><a href="http://msdn.microsoft.com/en-us/library/aa363866%28VS.85%29.aspx" rel="nofollow">MSDN</a> says Minimum supported client Windows Vista</p>
8
2009-07-17T13:38:16Z
[ "python", "windows", "ntfs", "junction" ]
Create NTFS junction point in Python
1,143,260
<p>Is there a way to create an NTFS junction point in Python? I know I can call the <code>junction</code> utility, but it would be better not to rely on external tools.</p>
8
2009-07-17T13:27:31Z
10,221,068
<p>I answered this in a <a href="http://stackoverflow.com/questions/1447575/symlinks-on-windows/7924557#7924557">similar question</a>, so I'll copy my answer to that below. Since writing that answer, I ended up writing a python-only (if you can call a module that uses ctypes python-only) module to creating, reading, and checking junctions which can be found in <a href="https://github.com/Juntalis/ntfslink-python/tree/master/ntfslink">this folder</a>. Hope that helps.</p> <p>Also, unlike the answer that utilizes uses the <strong>CreateSymbolicLinkA</strong> API, the linked implementation should work on any Windows version that supports junctions. CreateSymbolicLinkA is only supported in Vista+.</p> <p><strong>Answer:</strong></p> <p><a href="https://github.com/juntalis/ntfslink-python">python ntfslink extension</a></p> <p>Or if you want to use pywin32, you can use the previously stated method, and to read, use:</p> <pre><code>from win32file import * from winioctlcon import FSCTL_GET_REPARSE_POINT __all__ = ['islink', 'readlink'] # Win32file doesn't seem to have this attribute. FILE_ATTRIBUTE_REPARSE_POINT = 1024 # To make things easier. REPARSE_FOLDER = (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT) # For the parse_reparse_buffer function SYMBOLIC_LINK = 'symbolic' MOUNTPOINT = 'mountpoint' GENERIC = 'generic' def islink(fpath): """ Windows islink implementation. """ if GetFileAttributes(fpath) &amp; REPARSE_FOLDER: return True return False def parse_reparse_buffer(original, reparse_type=SYMBOLIC_LINK): """ Implementing the below in Python: typedef struct _REPARSE_DATA_BUFFER { ULONG ReparseTag; USHORT ReparseDataLength; USHORT Reserved; union { struct { USHORT SubstituteNameOffset; USHORT SubstituteNameLength; USHORT PrintNameOffset; USHORT PrintNameLength; ULONG Flags; WCHAR PathBuffer[1]; } SymbolicLinkReparseBuffer; struct { USHORT SubstituteNameOffset; USHORT SubstituteNameLength; USHORT PrintNameOffset; USHORT PrintNameLength; WCHAR PathBuffer[1]; } MountPointReparseBuffer; struct { UCHAR DataBuffer[1]; } GenericReparseBuffer; } DUMMYUNIONNAME; } REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER; """ # Size of our data types SZULONG = 4 # sizeof(ULONG) SZUSHORT = 2 # sizeof(USHORT) # Our structure. # Probably a better way to iterate a dictionary in a particular order, # but I was in a hurry, unfortunately, so I used pkeys. buffer = { 'tag' : SZULONG, 'data_length' : SZUSHORT, 'reserved' : SZUSHORT, SYMBOLIC_LINK : { 'substitute_name_offset' : SZUSHORT, 'substitute_name_length' : SZUSHORT, 'print_name_offset' : SZUSHORT, 'print_name_length' : SZUSHORT, 'flags' : SZULONG, 'buffer' : u'', 'pkeys' : [ 'substitute_name_offset', 'substitute_name_length', 'print_name_offset', 'print_name_length', 'flags', ] }, MOUNTPOINT : { 'substitute_name_offset' : SZUSHORT, 'substitute_name_length' : SZUSHORT, 'print_name_offset' : SZUSHORT, 'print_name_length' : SZUSHORT, 'buffer' : u'', 'pkeys' : [ 'substitute_name_offset', 'substitute_name_length', 'print_name_offset', 'print_name_length', ] }, GENERIC : { 'pkeys' : [], 'buffer': '' } } # Header stuff buffer['tag'] = original[:SZULONG] buffer['data_length'] = original[SZULONG:SZUSHORT] buffer['reserved'] = original[SZULONG+SZUSHORT:SZUSHORT] original = original[8:] # Parsing k = reparse_type for c in buffer[k]['pkeys']: if type(buffer[k][c]) == int: sz = buffer[k][c] bytes = original[:sz] buffer[k][c] = 0 for b in bytes: n = ord(b) if n: buffer[k][c] += n original = original[sz:] # Using the offset and length's grabbed, we'll set the buffer. buffer[k]['buffer'] = original return buffer def readlink(fpath): """ Windows readlink implementation. """ # This wouldn't return true if the file didn't exist, as far as I know. if not islink(fpath): return None # Open the file correctly depending on the string type. handle = CreateFileW(fpath, GENERIC_READ, 0, None, OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, 0) \ if type(fpath) == unicode else \ CreateFile(fpath, GENERIC_READ, 0, None, OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, 0) # MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16384 = (16*1024) buffer = DeviceIoControl(handle, FSCTL_GET_REPARSE_POINT, None, 16*1024) # Above will return an ugly string (byte array), so we'll need to parse it. # But first, we'll close the handle to our file so we're not locking it anymore. CloseHandle(handle) # Minimum possible length (assuming that the length of the target is bigger than 0) if len(buffer) &lt; 9: return None # Parse and return our result. result = parse_reparse_buffer(buffer) offset = result[SYMBOLIC_LINK]['substitute_name_offset'] ending = offset + result[SYMBOLIC_LINK]['substitute_name_length'] rpath = result[SYMBOLIC_LINK]['buffer'][offset:ending].replace('\x00','') if len(rpath) &gt; 4 and rpath[0:4] == '\\??\\': rpath = rpath[4:] return rpath def realpath(fpath): from os import path while islink(fpath): rpath = readlink(fpath) if not path.isabs(rpath): rpath = path.abspath(path.join(path.dirname(fpath), rpath)) fpath = rpath return fpath def example(): from os import system, unlink system('cmd.exe /c echo Hello World &gt; test.txt') system('mklink test-link.txt test.txt') print 'IsLink: %s' % islink('test-link.txt') print 'ReadLink: %s' % readlink('test-link.txt') print 'RealPath: %s' % realpath('test-link.txt') unlink('test-link.txt') unlink('test.txt') if __name__=='__main__': example() </code></pre> <p>Adjust the attributes in the CreateFile to your needs, but for a normal situation, it should work. Feel free to improve on it.</p> <p>It should also work for folder junctions if you use MOUNTPOINT instead of SYMBOLIC_LINK.</p> <p>You may way to check that</p> <pre><code>sys.getwindowsversion()[0] &gt;= 6 </code></pre> <p>if you put this into something you're releasing, since this form of symbolic link is only supported on Vista+.</p>
5
2012-04-19T02:59:18Z
[ "python", "windows", "ntfs", "junction" ]
Create NTFS junction point in Python
1,143,260
<p>Is there a way to create an NTFS junction point in Python? I know I can call the <code>junction</code> utility, but it would be better not to rely on external tools.</p>
8
2009-07-17T13:27:31Z
35,137,978
<p>Since Python 3.5 there's a function <code>CreateJunction</code> in <code>_winapi</code> module.</p> <pre><code>import _winapi _winapi.CreateJunction(source, target) </code></pre>
1
2016-02-01T18:46:26Z
[ "python", "windows", "ntfs", "junction" ]
Removing duplicates from list of lists in Python
1,143,379
<p>Can anyone suggest a good solution to remove duplicates from nested lists if wanting to evaluate duplicates based on first element of each nested list?</p> <p>The main list looks like this:</p> <pre><code>L = [['14', '65', 76], ['2', '5', 6], ['7', '12', 33], ['14', '22', 46]] </code></pre> <p>If there is another list with the same element at first position <code>[k][0]</code> that had already occurred, then I'd like to remove that list and get this result:</p> <pre><code>L = [['14', '65', 76], ['2', '5', 6], ['7', '12', 33]] </code></pre> <p>Can you suggest an algorithm to achieve this goal?</p>
7
2009-07-17T13:45:48Z
1,143,408
<p>i am not sure what you meant by "another list", so i assume you are saying those lists inside L</p> <pre><code>a=[] L = [['14', '65', 76], ['2', '5', 6], ['7', '12', 33], ['14', '22', 46],['7','a','b']] for item in L: if not item[0] in a: a.append(item[0]) print item </code></pre>
0
2009-07-17T13:50:49Z
[ "python", "list" ]
Removing duplicates from list of lists in Python
1,143,379
<p>Can anyone suggest a good solution to remove duplicates from nested lists if wanting to evaluate duplicates based on first element of each nested list?</p> <p>The main list looks like this:</p> <pre><code>L = [['14', '65', 76], ['2', '5', 6], ['7', '12', 33], ['14', '22', 46]] </code></pre> <p>If there is another list with the same element at first position <code>[k][0]</code> that had already occurred, then I'd like to remove that list and get this result:</p> <pre><code>L = [['14', '65', 76], ['2', '5', 6], ['7', '12', 33]] </code></pre> <p>Can you suggest an algorithm to achieve this goal?</p>
7
2009-07-17T13:45:48Z
1,143,419
<p>use a dict instead like so:</p> <pre><code>L = {'14': ['65', 76], '2': ['5', 6], '7': ['12', 33]} L['14'] = ['22', 46] </code></pre> <p>if you are receiving the first list from some external source, convert it like so:</p> <pre><code>L = [['14', '65', 76], ['2', '5', 6], ['7', '12', 33], ['14', '22', 46]] L_dict = dict((x[0], x[1:]) for x in L) </code></pre>
3
2009-07-17T13:52:29Z
[ "python", "list" ]
Removing duplicates from list of lists in Python
1,143,379
<p>Can anyone suggest a good solution to remove duplicates from nested lists if wanting to evaluate duplicates based on first element of each nested list?</p> <p>The main list looks like this:</p> <pre><code>L = [['14', '65', 76], ['2', '5', 6], ['7', '12', 33], ['14', '22', 46]] </code></pre> <p>If there is another list with the same element at first position <code>[k][0]</code> that had already occurred, then I'd like to remove that list and get this result:</p> <pre><code>L = [['14', '65', 76], ['2', '5', 6], ['7', '12', 33]] </code></pre> <p>Can you suggest an algorithm to achieve this goal?</p>
7
2009-07-17T13:45:48Z
1,143,432
<p>Do you care about preserving order / which duplicate is removed? If not, then:</p> <pre><code>dict((x[0], x) for x in L).values() </code></pre> <p>will do it. If you want to preserve order, and want to keep the first one you find then:</p> <pre><code>def unique_items(L): found = set() for item in L: if item[0] not in found: yield item found.add(item[0]) print list(unique_items(L)) </code></pre>
24
2009-07-17T13:54:27Z
[ "python", "list" ]
Removing duplicates from list of lists in Python
1,143,379
<p>Can anyone suggest a good solution to remove duplicates from nested lists if wanting to evaluate duplicates based on first element of each nested list?</p> <p>The main list looks like this:</p> <pre><code>L = [['14', '65', 76], ['2', '5', 6], ['7', '12', 33], ['14', '22', 46]] </code></pre> <p>If there is another list with the same element at first position <code>[k][0]</code> that had already occurred, then I'd like to remove that list and get this result:</p> <pre><code>L = [['14', '65', 76], ['2', '5', 6], ['7', '12', 33]] </code></pre> <p>Can you suggest an algorithm to achieve this goal?</p>
7
2009-07-17T13:45:48Z
1,143,486
<p>If the order does not matter, code below</p> <pre><code>print [ [k] + v for (k, v) in dict( [ [a[0], a[1:]] for a in reversed(L) ] ).items() ] </code></pre> <p>gives</p> <blockquote> <p>[['2', '5', '6'], ['14', '65', '76'], ['7', '12', '33']]</p> </blockquote>
0
2009-07-17T14:03:11Z
[ "python", "list" ]
Removing duplicates from list of lists in Python
1,143,379
<p>Can anyone suggest a good solution to remove duplicates from nested lists if wanting to evaluate duplicates based on first element of each nested list?</p> <p>The main list looks like this:</p> <pre><code>L = [['14', '65', 76], ['2', '5', 6], ['7', '12', 33], ['14', '22', 46]] </code></pre> <p>If there is another list with the same element at first position <code>[k][0]</code> that had already occurred, then I'd like to remove that list and get this result:</p> <pre><code>L = [['14', '65', 76], ['2', '5', 6], ['7', '12', 33]] </code></pre> <p>Can you suggest an algorithm to achieve this goal?</p>
7
2009-07-17T13:45:48Z
36,055,698
<p>Use Pandas : </p> <pre><code>import pandas as pd L = [['14', '65', 76], ['2', '5', 6], ['7', '12', 33], ['14', '22', 46],['7','a','b']] df = pd.DataFrame(L) df = df.drop_duplicates() L_no_duplicates = df.values.tolist() </code></pre> <p>If you want to drop duplicates in specific columns only use instead:</p> <pre><code>df = df.drop_duplicates([1,2]) </code></pre>
0
2016-03-17T08:57:10Z
[ "python", "list" ]
Python sorting list of dictionaries by multiple keys
1,143,671
<p>I have a list of dicts:</p> <pre><code>b = [{u'TOT_PTS_Misc': u'Utley, Alex', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Russo, Brandon', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Chappell, Justin', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Foster, Toney', u'Total_Points': 80.0}, {u'TOT_PTS_Misc': u'Lawson, Roman', u'Total_Points': 80.0}, {u'TOT_PTS_Misc': u'Lempke, Sam', u'Total_Points': 80.0}, {u'TOT_PTS_Misc': u'Gnezda, Alex', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Kirks, Damien', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Worden, Tom', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Korecz, Mike', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Swartz, Brian', u'Total_Points': 66.0}, {u'TOT_PTS_Misc': u'Burgess, Randy', u'Total_Points': 66.0}, {u'TOT_PTS_Misc': u'Smugala, Ryan', u'Total_Points': 66.0}, {u'TOT_PTS_Misc': u'Harmon, Gary', u'Total_Points': 66.0}, {u'TOT_PTS_Misc': u'Blasinsky, Scott', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Carter III, Laymon', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Coleman, Johnathan', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Venditti, Nick', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Blackwell, Devon', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Kovach, Alex', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Bolden, Antonio', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Smith, Ryan', u'Total_Points': 60.0}] </code></pre> <p>and I need to use a multi key sort reversed by Total_Points, then not reversed by <code>TOT_PTS_Misc</code>.</p> <p>This can be done at the command prompt like so:</p> <pre><code>a = sorted(b, key=lambda d: (-d['Total_Points'], d['TOT_PTS_Misc'])) </code></pre> <p>But I have to run this through a function, where I pass in the list and the sort keys. For example, <code>def multikeysort(dict_list, sortkeys):</code>.</p> <p>How can the lambda line be used which will sort the list, for an arbitrary number of keys that are passed in to the multikeysort function, and take into consideration that the sortkeys may have any number of keys and those that need reversed sorts will be identified with a '-' before it?</p>
55
2009-07-17T14:36:48Z
1,143,719
<pre><code>def sortkeypicker(keynames): negate = set() for i, k in enumerate(keynames): if k[:1] == '-': keynames[i] = k[1:] negate.add(k[1:]) def getit(adict): composite = [adict[k] for k in keynames] for i, (k, v) in enumerate(zip(keynames, composite)): if k in negate: composite[i] = -v return composite return getit a = sorted(b, key=sortkeypicker(['-Total_Points', 'TOT_PTS_Misc'])) </code></pre>
18
2009-07-17T14:44:47Z
[ "python" ]
Python sorting list of dictionaries by multiple keys
1,143,671
<p>I have a list of dicts:</p> <pre><code>b = [{u'TOT_PTS_Misc': u'Utley, Alex', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Russo, Brandon', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Chappell, Justin', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Foster, Toney', u'Total_Points': 80.0}, {u'TOT_PTS_Misc': u'Lawson, Roman', u'Total_Points': 80.0}, {u'TOT_PTS_Misc': u'Lempke, Sam', u'Total_Points': 80.0}, {u'TOT_PTS_Misc': u'Gnezda, Alex', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Kirks, Damien', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Worden, Tom', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Korecz, Mike', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Swartz, Brian', u'Total_Points': 66.0}, {u'TOT_PTS_Misc': u'Burgess, Randy', u'Total_Points': 66.0}, {u'TOT_PTS_Misc': u'Smugala, Ryan', u'Total_Points': 66.0}, {u'TOT_PTS_Misc': u'Harmon, Gary', u'Total_Points': 66.0}, {u'TOT_PTS_Misc': u'Blasinsky, Scott', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Carter III, Laymon', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Coleman, Johnathan', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Venditti, Nick', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Blackwell, Devon', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Kovach, Alex', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Bolden, Antonio', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Smith, Ryan', u'Total_Points': 60.0}] </code></pre> <p>and I need to use a multi key sort reversed by Total_Points, then not reversed by <code>TOT_PTS_Misc</code>.</p> <p>This can be done at the command prompt like so:</p> <pre><code>a = sorted(b, key=lambda d: (-d['Total_Points'], d['TOT_PTS_Misc'])) </code></pre> <p>But I have to run this through a function, where I pass in the list and the sort keys. For example, <code>def multikeysort(dict_list, sortkeys):</code>.</p> <p>How can the lambda line be used which will sort the list, for an arbitrary number of keys that are passed in to the multikeysort function, and take into consideration that the sortkeys may have any number of keys and those that need reversed sorts will be identified with a '-' before it?</p>
55
2009-07-17T14:36:48Z
1,143,829
<pre><code>from operator import itemgetter from functools import partial def _neg_itemgetter(key, d): return -d[key] def key_getter(key_expr): keys = key_expr.split(",") getters = [] for k in keys: k = k.strip() if k.startswith("-"): getters.append(partial(_neg_itemgetter, k[1:])) else: getters.append(itemgetter(k)) def keyfunc(dct): return [kg(dct) for kg in getters] return keyfunc def multikeysort(dict_list, sortkeys): return sorted(dict_list, key = key_getter(sortkeys) </code></pre> <p>Demonstration:</p> <pre><code>&gt;&gt;&gt; multikeysort([{u'TOT_PTS_Misc': u'Utley, Alex', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Russo, Brandon', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Chappell, Justin', u'Total_Points': 96.0}], "-Total_Points,TOT_PTS_Misc") [{u'Total_Points': 96.0, u'TOT_PTS_Misc': u'Chappell, Justin'}, {u'Total_Points': 96.0, u'TOT_PTS_Misc': u'Russo, Brandon'}, {u'Total_Points': 60.0, u'TOT_PTS_Misc': u'Utley, Alex'}] </code></pre> <p>The parsing is a bit fragile, but at least it allows for variable number of spaces between the keys.</p>
0
2009-07-17T15:01:59Z
[ "python" ]
Python sorting list of dictionaries by multiple keys
1,143,671
<p>I have a list of dicts:</p> <pre><code>b = [{u'TOT_PTS_Misc': u'Utley, Alex', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Russo, Brandon', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Chappell, Justin', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Foster, Toney', u'Total_Points': 80.0}, {u'TOT_PTS_Misc': u'Lawson, Roman', u'Total_Points': 80.0}, {u'TOT_PTS_Misc': u'Lempke, Sam', u'Total_Points': 80.0}, {u'TOT_PTS_Misc': u'Gnezda, Alex', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Kirks, Damien', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Worden, Tom', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Korecz, Mike', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Swartz, Brian', u'Total_Points': 66.0}, {u'TOT_PTS_Misc': u'Burgess, Randy', u'Total_Points': 66.0}, {u'TOT_PTS_Misc': u'Smugala, Ryan', u'Total_Points': 66.0}, {u'TOT_PTS_Misc': u'Harmon, Gary', u'Total_Points': 66.0}, {u'TOT_PTS_Misc': u'Blasinsky, Scott', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Carter III, Laymon', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Coleman, Johnathan', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Venditti, Nick', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Blackwell, Devon', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Kovach, Alex', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Bolden, Antonio', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Smith, Ryan', u'Total_Points': 60.0}] </code></pre> <p>and I need to use a multi key sort reversed by Total_Points, then not reversed by <code>TOT_PTS_Misc</code>.</p> <p>This can be done at the command prompt like so:</p> <pre><code>a = sorted(b, key=lambda d: (-d['Total_Points'], d['TOT_PTS_Misc'])) </code></pre> <p>But I have to run this through a function, where I pass in the list and the sort keys. For example, <code>def multikeysort(dict_list, sortkeys):</code>.</p> <p>How can the lambda line be used which will sort the list, for an arbitrary number of keys that are passed in to the multikeysort function, and take into consideration that the sortkeys may have any number of keys and those that need reversed sorts will be identified with a '-' before it?</p>
55
2009-07-17T14:36:48Z
1,144,405
<p>This answer works for any kind of column in the dictionary -- the negated column need not be a number.</p> <pre><code>def multikeysort(items, columns): from operator import itemgetter comparers = [((itemgetter(col[1:].strip()), -1) if col.startswith('-') else (itemgetter(col.strip()), 1)) for col in columns] def comparer(left, right): for fn, mult in comparers: result = cmp(fn(left), fn(right)) if result: return mult * result else: return 0 return sorted(items, cmp=comparer) </code></pre> <p>You can call it like this:</p> <pre><code>b = [{u'TOT_PTS_Misc': u'Utley, Alex', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Russo, Brandon', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Chappell, Justin', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Foster, Toney', u'Total_Points': 80.0}, {u'TOT_PTS_Misc': u'Lawson, Roman', u'Total_Points': 80.0}, {u'TOT_PTS_Misc': u'Lempke, Sam', u'Total_Points': 80.0}, {u'TOT_PTS_Misc': u'Gnezda, Alex', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Kirks, Damien', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Worden, Tom', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Korecz, Mike', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Swartz, Brian', u'Total_Points': 66.0}, {u'TOT_PTS_Misc': u'Burgess, Randy', u'Total_Points': 66.0}, {u'TOT_PTS_Misc': u'Smugala, Ryan', u'Total_Points': 66.0}, {u'TOT_PTS_Misc': u'Harmon, Gary', u'Total_Points': 66.0}, {u'TOT_PTS_Misc': u'Blasinsky, Scott', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Carter III, Laymon', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Coleman, Johnathan', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Venditti, Nick', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Blackwell, Devon', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Kovach, Alex', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Bolden, Antonio', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Smith, Ryan', u'Total_Points': 60.0}] a = multikeysort(b, ['-Total_Points', 'TOT_PTS_Misc']) for item in a: print item </code></pre> <p>Try it with either column negated. You will see the sort order reverse.</p> <p>Next: change it so it does not use extra class....</p> <hr> <p>2016-01-17</p> <p>Taking my inspiration from this answer <a href="http://stackoverflow.com/questions/2361426/what-is-the-best-way-to-get-the-first-item-from-an-iterable-matching-a-condition">What is the best way to get the first item from an iterable matching a condition?</a>, I shortened the code:</p> <pre><code>from operator import itemgetter as i def multikeysort(items, columns): comparers = [ ((i(col[1:].strip()), -1) if col.startswith('-') else (i(col.strip()), 1)) for col in columns ] def comparer(left, right): comparer_iter = ( cmp(fn(left), fn(right)) * mult for fn, mult in comparers ) return next((result for result in comparer_iter if result), 0) return sorted(items, cmp=comparer) </code></pre> <p>In case you like your code terse.</p> <hr> <p>Later 2016-01-17</p> <p>This works with python3 (which eliminated the <code>cmp</code> argument to <code>sort</code>):</p> <pre><code>from operator import itemgetter as i from functools import cmp_to_key def multikeysort(items, columns): comparers = [ ((i(col[1:].strip()), -1) if col.startswith('-') else (i(col.strip()), 1)) for col in columns ] def comparer(left, right): comparer_iter = ( cmp(fn(left), fn(right)) * mult for fn, mult in comparers ) return next((result for result in comparer_iter if result), 0) return sorted(items, key=cmp_to_key(comparer)) </code></pre> <p>Inspired by this answer <a href="http://stackoverflow.com/questions/2531952/how-should-i-do-custom-sort-in-python-3">How should I do custom sort in Python 3?</a></p>
51
2009-07-17T16:35:39Z
[ "python" ]
Python sorting list of dictionaries by multiple keys
1,143,671
<p>I have a list of dicts:</p> <pre><code>b = [{u'TOT_PTS_Misc': u'Utley, Alex', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Russo, Brandon', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Chappell, Justin', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Foster, Toney', u'Total_Points': 80.0}, {u'TOT_PTS_Misc': u'Lawson, Roman', u'Total_Points': 80.0}, {u'TOT_PTS_Misc': u'Lempke, Sam', u'Total_Points': 80.0}, {u'TOT_PTS_Misc': u'Gnezda, Alex', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Kirks, Damien', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Worden, Tom', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Korecz, Mike', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Swartz, Brian', u'Total_Points': 66.0}, {u'TOT_PTS_Misc': u'Burgess, Randy', u'Total_Points': 66.0}, {u'TOT_PTS_Misc': u'Smugala, Ryan', u'Total_Points': 66.0}, {u'TOT_PTS_Misc': u'Harmon, Gary', u'Total_Points': 66.0}, {u'TOT_PTS_Misc': u'Blasinsky, Scott', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Carter III, Laymon', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Coleman, Johnathan', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Venditti, Nick', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Blackwell, Devon', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Kovach, Alex', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Bolden, Antonio', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Smith, Ryan', u'Total_Points': 60.0}] </code></pre> <p>and I need to use a multi key sort reversed by Total_Points, then not reversed by <code>TOT_PTS_Misc</code>.</p> <p>This can be done at the command prompt like so:</p> <pre><code>a = sorted(b, key=lambda d: (-d['Total_Points'], d['TOT_PTS_Misc'])) </code></pre> <p>But I have to run this through a function, where I pass in the list and the sort keys. For example, <code>def multikeysort(dict_list, sortkeys):</code>.</p> <p>How can the lambda line be used which will sort the list, for an arbitrary number of keys that are passed in to the multikeysort function, and take into consideration that the sortkeys may have any number of keys and those that need reversed sorts will be identified with a '-' before it?</p>
55
2009-07-17T14:36:48Z
1,144,983
<p>Since you're already comfortable with lambda, here's a less verbose solution.</p> <pre><code>&gt;&gt;&gt; def itemgetter(*names): return lambda mapping: tuple(-mapping[name[1:]] if name.startswith('-') else mapping[name] for name in names) &gt;&gt;&gt; itemgetter('a', '-b')({'a': 1, 'b': 2}) (1, -2) </code></pre>
0
2009-07-17T18:37:32Z
[ "python" ]
Python sorting list of dictionaries by multiple keys
1,143,671
<p>I have a list of dicts:</p> <pre><code>b = [{u'TOT_PTS_Misc': u'Utley, Alex', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Russo, Brandon', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Chappell, Justin', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Foster, Toney', u'Total_Points': 80.0}, {u'TOT_PTS_Misc': u'Lawson, Roman', u'Total_Points': 80.0}, {u'TOT_PTS_Misc': u'Lempke, Sam', u'Total_Points': 80.0}, {u'TOT_PTS_Misc': u'Gnezda, Alex', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Kirks, Damien', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Worden, Tom', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Korecz, Mike', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Swartz, Brian', u'Total_Points': 66.0}, {u'TOT_PTS_Misc': u'Burgess, Randy', u'Total_Points': 66.0}, {u'TOT_PTS_Misc': u'Smugala, Ryan', u'Total_Points': 66.0}, {u'TOT_PTS_Misc': u'Harmon, Gary', u'Total_Points': 66.0}, {u'TOT_PTS_Misc': u'Blasinsky, Scott', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Carter III, Laymon', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Coleman, Johnathan', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Venditti, Nick', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Blackwell, Devon', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Kovach, Alex', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Bolden, Antonio', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Smith, Ryan', u'Total_Points': 60.0}] </code></pre> <p>and I need to use a multi key sort reversed by Total_Points, then not reversed by <code>TOT_PTS_Misc</code>.</p> <p>This can be done at the command prompt like so:</p> <pre><code>a = sorted(b, key=lambda d: (-d['Total_Points'], d['TOT_PTS_Misc'])) </code></pre> <p>But I have to run this through a function, where I pass in the list and the sort keys. For example, <code>def multikeysort(dict_list, sortkeys):</code>.</p> <p>How can the lambda line be used which will sort the list, for an arbitrary number of keys that are passed in to the multikeysort function, and take into consideration that the sortkeys may have any number of keys and those that need reversed sorts will be identified with a '-' before it?</p>
55
2009-07-17T14:36:48Z
3,301,620
<p>I use the following for sorting a 2d array on a number of columns</p> <pre><code>def k(a,b): def _k(item): return (item[a],item[b]) return _k </code></pre> <p>This could be extended to work on an arbitrary number of items. I tend to think finding a better access pattern to your sortable keys is better than writing a fancy comparator.</p> <pre><code>&gt;&gt;&gt; data = [[0,1,2,3,4],[0,2,3,4,5],[1,0,2,3,4]] &gt;&gt;&gt; sorted(data, key=k(0,1)) [[0, 1, 2, 3, 4], [0, 2, 3, 4, 5], [1, 0, 2, 3, 4]] &gt;&gt;&gt; sorted(data, key=k(1,0)) [[1, 0, 2, 3, 4], [0, 1, 2, 3, 4], [0, 2, 3, 4, 5]] &gt;&gt;&gt; sorted(a, key=k(2,0)) [[0, 1, 2, 3, 4], [1, 0, 2, 3, 4], [0, 2, 3, 4, 5]] </code></pre>
5
2010-07-21T16:34:33Z
[ "python" ]
Python sorting list of dictionaries by multiple keys
1,143,671
<p>I have a list of dicts:</p> <pre><code>b = [{u'TOT_PTS_Misc': u'Utley, Alex', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Russo, Brandon', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Chappell, Justin', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Foster, Toney', u'Total_Points': 80.0}, {u'TOT_PTS_Misc': u'Lawson, Roman', u'Total_Points': 80.0}, {u'TOT_PTS_Misc': u'Lempke, Sam', u'Total_Points': 80.0}, {u'TOT_PTS_Misc': u'Gnezda, Alex', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Kirks, Damien', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Worden, Tom', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Korecz, Mike', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Swartz, Brian', u'Total_Points': 66.0}, {u'TOT_PTS_Misc': u'Burgess, Randy', u'Total_Points': 66.0}, {u'TOT_PTS_Misc': u'Smugala, Ryan', u'Total_Points': 66.0}, {u'TOT_PTS_Misc': u'Harmon, Gary', u'Total_Points': 66.0}, {u'TOT_PTS_Misc': u'Blasinsky, Scott', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Carter III, Laymon', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Coleman, Johnathan', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Venditti, Nick', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Blackwell, Devon', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Kovach, Alex', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Bolden, Antonio', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Smith, Ryan', u'Total_Points': 60.0}] </code></pre> <p>and I need to use a multi key sort reversed by Total_Points, then not reversed by <code>TOT_PTS_Misc</code>.</p> <p>This can be done at the command prompt like so:</p> <pre><code>a = sorted(b, key=lambda d: (-d['Total_Points'], d['TOT_PTS_Misc'])) </code></pre> <p>But I have to run this through a function, where I pass in the list and the sort keys. For example, <code>def multikeysort(dict_list, sortkeys):</code>.</p> <p>How can the lambda line be used which will sort the list, for an arbitrary number of keys that are passed in to the multikeysort function, and take into consideration that the sortkeys may have any number of keys and those that need reversed sorts will be identified with a '-' before it?</p>
55
2009-07-17T14:36:48Z
12,925,750
<p><a href="http://stygianvision.net/updates/python-sort-list-object-dictionary-multiple-key/">http://stygianvision.net/updates/python-sort-list-object-dictionary-multiple-key/</a> has a nice rundown on various techniques for doing this. If your requirements are simpler than "full bidirectional multikey", take a look. It's clear the accepted answer and the blog post I just referenced influenced each other in some way, though I don't know which order.</p> <p>In case the link dies here's a very quick synopsis of examples not covered above:</p> <pre><code>mylist = sorted(mylist, key=itemgetter('name', 'age')) mylist = sorted(mylist, key=lambda k: (k['name'].lower(), k['age'])) mylist = sorted(mylist, key=lambda k: (k['name'].lower(), -k['age'])) </code></pre>
13
2012-10-17T01:15:02Z
[ "python" ]
Python sorting list of dictionaries by multiple keys
1,143,671
<p>I have a list of dicts:</p> <pre><code>b = [{u'TOT_PTS_Misc': u'Utley, Alex', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Russo, Brandon', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Chappell, Justin', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Foster, Toney', u'Total_Points': 80.0}, {u'TOT_PTS_Misc': u'Lawson, Roman', u'Total_Points': 80.0}, {u'TOT_PTS_Misc': u'Lempke, Sam', u'Total_Points': 80.0}, {u'TOT_PTS_Misc': u'Gnezda, Alex', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Kirks, Damien', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Worden, Tom', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Korecz, Mike', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Swartz, Brian', u'Total_Points': 66.0}, {u'TOT_PTS_Misc': u'Burgess, Randy', u'Total_Points': 66.0}, {u'TOT_PTS_Misc': u'Smugala, Ryan', u'Total_Points': 66.0}, {u'TOT_PTS_Misc': u'Harmon, Gary', u'Total_Points': 66.0}, {u'TOT_PTS_Misc': u'Blasinsky, Scott', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Carter III, Laymon', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Coleman, Johnathan', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Venditti, Nick', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Blackwell, Devon', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Kovach, Alex', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Bolden, Antonio', u'Total_Points': 60.0}, {u'TOT_PTS_Misc': u'Smith, Ryan', u'Total_Points': 60.0}] </code></pre> <p>and I need to use a multi key sort reversed by Total_Points, then not reversed by <code>TOT_PTS_Misc</code>.</p> <p>This can be done at the command prompt like so:</p> <pre><code>a = sorted(b, key=lambda d: (-d['Total_Points'], d['TOT_PTS_Misc'])) </code></pre> <p>But I have to run this through a function, where I pass in the list and the sort keys. For example, <code>def multikeysort(dict_list, sortkeys):</code>.</p> <p>How can the lambda line be used which will sort the list, for an arbitrary number of keys that are passed in to the multikeysort function, and take into consideration that the sortkeys may have any number of keys and those that need reversed sorts will be identified with a '-' before it?</p>
55
2009-07-17T14:36:48Z
29,849,371
<p>I know this is a rather old question, but none of the answers mention that Python guarantees a stable sort order for its sorting routines such as <code>list.sort()</code> and <code>sorted()</code>, which means items that compare equal retain their original order.</p> <p>This means that the equivalent of <code>ORDER BY name ASC, age DESC</code> (using SQL notation) for a list of dictionaries can be done like this:</p> <pre><code>items.sort(key=operator.itemgetter('age'), reverse=True) items.sort(key=operator.itemgetter('name')) </code></pre> <p>The reversing/inverting works for all orderable types, not just numbers which you can negate by putting a minus sign in front.</p> <p>And because of the Timsort algorithm used in (at least) CPython, this is actually rather fast in practice.</p>
8
2015-04-24T13:54:15Z
[ "python" ]
How to add a button (Add-in) to Outlook using Python
1,143,798
<p>I'm looking the way to build an AddIn for Outlook with Python that add a button to the toolbar that has a behavior (doesn't matter). I've searched around and didn't found anything. The only things I've found are backend, no GUI.</p> <p>thanks!</p>
0
2009-07-17T14:56:53Z
1,144,428
<p>You could study the source for the SpamBayes outlook addin:</p> <ul> <li><a href="http://spambayes.svn.sourceforge.net/viewvc/spambayes/trunk/spambayes/Outlook2000/addin.py?revision=3243&amp;view=markup" rel="nofollow">http://spambayes.svn.sourceforge.net/viewvc/spambayes/trunk/spambayes/Outlook2000/addin.py?revision=3243&amp;view=markup</a></li> </ul> <p>which used "Spam" and "Not Spam" buttons. (Search for _AddControl function.)</p> <p>General info on the addin here:</p> <ul> <li><a href="http://spambayes.sourceforge.net/windows.html" rel="nofollow">http://spambayes.sourceforge.net/windows.html</a></li> </ul>
1
2009-07-17T16:39:46Z
[ "python", "winapi", "outlook" ]
How do you add a model method to an existing class within an interactive session (in iPython)?
1,143,833
<p>I have a basic model:</p> <pre><code>class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) state = USStateField() </code></pre> <p>I start up an iPython session with:</p> <pre><code>$ python manage.py shell &gt;&gt;&gt; from app.models import Person </code></pre> <p>How do I add this model method within the iPython session?</p> <pre><code>&gt;&gt;&gt; def is_midwestern(self): ... "Returns True if this person is from the Midwest." ... return self.state in ('IL', 'WI', 'MI', 'IN', 'OH', 'IA', 'MO') &gt;&gt;&gt; person = Person.objects.filter(last_name='Franklin') &gt;&gt;&gt; person.is_midwestern True </code></pre> <p>I want to be able to test these model methods without having to add the method to the models.py file and then restarting the iPython shell session.</p> <p>I seem to be doing something wrong because when I add a new model method in an interactive session, it doesn't seem to be linked to the class like it does when the model method is defined in a file. </p> <p>So if I created the model method as above and attempted to use it. e.g. ' >>> person = Person.objects.filter(last_name='Franklin')<br /> <code>&gt;&gt;&gt; person.is_midwestern<br /> 'Person' object has no attribute </code>'is_midwestern'`</p>
0
2009-07-17T15:02:23Z
1,143,896
<p>why can't you just do this Person.is_midwestern = is_miswestern e.g.</p> <pre><code>&gt;&gt;&gt; class Person: ... def __init__(self): self.mid = True ... &gt;&gt;&gt; def is_midwestern(self): return self.mid ... &gt;&gt;&gt; Person.is_midwestern = is_midwestern &gt;&gt;&gt; p = Person() &gt;&gt;&gt; p.is_midwestern() True &gt;&gt;&gt; </code></pre>
3
2009-07-17T15:12:01Z
[ "python", "django", "ipython" ]
How do I convert (or scale) axis values and redefine the tick frequency in matplotlib?
1,143,848
<p>I am displaying a jpg image (I rotate this by 90 degrees, if this is relevant) and of course the axes display the pixel coordinates. I would like to convert the axis so that instead of displaying the pixel number, it will display my unit of choice - be it radians, degrees, or in my case an astronomical coordinate. I know the conversion from pixel to (eg) degree. Here is a snippet of what my code looks like currently:</p> <pre><code>import matplotlib.pyplot as plt import Image import matplotlib thumb = Image.open(self.image) thumb = thumb.rotate(90) dpi = plt.rcParams['figure.dpi'] figsize = thumb.size[0]/dpi, thumb.size[1]/dpi fig = plt.figure(figsize=figsize) plt.imshow(thumb, origin='lower',aspect='equal') plt.show() </code></pre> <p>...so following on from this, can I take each value that matplotlib would print on the axis, and change/replace it with a string to output instead? I would want to do this for a specific coordinate format - eg, rather than an angle of 10.44 (degrees), I would like it to read 10 26' 24'' (ie, degrees, arcmins, arcsecs)</p> <p>Finally on this theme, I'd want control over the tick frequency, on the plot. Matplotlib might print the axis value every 50 pixels, but I'd really want it every (for example) degree.</p> <p>It sounds like I would like to define some kind of array with the pixel values and their converted values (degrees etc) that I want to be displayed, having control over the sampling frequency over the range xmin/xmax range.</p> <p>Are there any matplotlib experts on Stack Overflow? If so, thanks very much in advance for your help! To make this a more learning experience, I'd really appreciate being prodded in the direction of tutorials etc on this kind of matplotlib problem. I've found myself getting very confused with axes, axis, figures, artists etc!</p> <p>Cheers,</p> <p>Dave</p>
20
2009-07-17T15:05:17Z
1,144,137
<p>It looks like you're dealing with the <code>matplotlib.pyplot</code> interface, which means that you'll be able to bypass most of the dealing with artists, axes, and the like. You can control the values and labels of the tick marks by using the <a href="http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.xticks"><code>matplotlib.pyplot.xticks</code></a> command, as follows:</p> <pre><code>tick_locs = [list of locations where you want your tick marks placed] tick_lbls = [list of corresponding labels for each of the tick marks] plt.xticks(tick_locs, tick_lbls) </code></pre> <p>For your particular example, you'll have to compute what the tick marks are relative to the units (i.e. pixels) of your original plot (since you're using <code>imshow</code>) - you said you know how to do this, though.</p> <p>I haven't dealt with images much, but you may be able to use a different plotting method (e.g. <code>pcolor</code>) that allows you to supply <code>x</code> and <code>y</code> information. That may give you a few more options for specifying the units of your image.</p> <p>For tutorials, you would do well to look through the <a href="http://matplotlib.sourceforge.net/gallery.html">matplotlib gallery</a> - find something you like, and read the code that produced it. One of the guys in our office recently bought a book on <a href="http://www.apress.com/book/view/9781430218432">Python visualization</a> - that may be worthwhile looking at.</p> <p>The way that I generally think of all the various pieces is as follows:</p> <ul> <li>A <code>Figure</code> is a container for all the <code>Axes</code></li> <li>An <code>Axes</code> is the space where what you draw (i.e. your plot) actually shows up</li> <li>An <code>Axis</code> is the actual <code>x</code> and <code>y</code> axes</li> <li>Artists? That's too deep in the interface for me: I've never had to worry about those yet, even though I rarely use the <code>pyplot</code> module in production plots.</li> </ul>
30
2009-07-17T15:49:08Z
[ "python", "matplotlib" ]
Looking for values in nested tuple
1,144,178
<p>Say I have:</p> <pre><code>t = ( ('dog', 'Dog'), ('cat', 'Cat'), ('fish', 'Fish'), ) </code></pre> <p>And I need to check if a value is in the first bit of the nested tuple (ie. the lowercase bits). How can I do this? The capitalised values do not matter really, I want to search for a string in only the lowercase values.</p> <pre><code>if 'fish' in t: print "Fish in t." </code></pre> <p>Doesn't work.</p> <p>Is there a good way of doing this without doing a for loop with if statements?</p>
0
2009-07-17T15:57:17Z
1,144,206
<p>The elements of a tuple can be extracted by specifying an index: <code>('a', 'b')[0] == 'a'</code>. You can use a <a href="http://docs.python.org/3.0/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a> to iterate over all elements of some <em>iterable</em>. A tuple is also iterable. Lastly, <a href="http://docs.python.org/3.0/library/functions.html#any" rel="nofollow"><code>any()</code></a> tells whether any element in a given iterable evaluates to <code>True</code>. Putting all this together:</p> <pre><code>&gt;&gt;&gt; t = ( ... ('dog', 'Dog'), ... ('cat', 'Cat'), ... ('fish', 'Fish'), ... ) &gt;&gt;&gt; def contains(w, t): ... return any(w == e[0] for e in t) ... &gt;&gt;&gt; contains('fish', t) True &gt;&gt;&gt; contains('dish', t) False </code></pre>
5
2009-07-17T16:00:08Z
[ "python" ]
Looking for values in nested tuple
1,144,178
<p>Say I have:</p> <pre><code>t = ( ('dog', 'Dog'), ('cat', 'Cat'), ('fish', 'Fish'), ) </code></pre> <p>And I need to check if a value is in the first bit of the nested tuple (ie. the lowercase bits). How can I do this? The capitalised values do not matter really, I want to search for a string in only the lowercase values.</p> <pre><code>if 'fish' in t: print "Fish in t." </code></pre> <p>Doesn't work.</p> <p>Is there a good way of doing this without doing a for loop with if statements?</p>
0
2009-07-17T15:57:17Z
1,144,208
<p>Try:</p> <pre><code>any('fish' == tup[0] for tup in t) </code></pre> <p>EDIT: Stephan is right; fixed 'fish' == tup[0]. Also see his more complete answer.</p>
4
2009-07-17T16:00:51Z
[ "python" ]
Looking for values in nested tuple
1,144,178
<p>Say I have:</p> <pre><code>t = ( ('dog', 'Dog'), ('cat', 'Cat'), ('fish', 'Fish'), ) </code></pre> <p>And I need to check if a value is in the first bit of the nested tuple (ie. the lowercase bits). How can I do this? The capitalised values do not matter really, I want to search for a string in only the lowercase values.</p> <pre><code>if 'fish' in t: print "Fish in t." </code></pre> <p>Doesn't work.</p> <p>Is there a good way of doing this without doing a for loop with if statements?</p>
0
2009-07-17T15:57:17Z
1,144,221
<p>You could do something like this:</p> <pre><code>if 'fish' in (item[0] for item in t): print "Fish in t." </code></pre> <p>or this:</p> <pre><code>if any(item[0] == 'fish' for item in t): print "Fish in t." </code></pre> <p>If you don't care about the order but want to keep the association between <code>'dog'</code> and <code>'Dog'</code>, you may want to use a dictionary instead:</p> <pre><code>t = { 'dog': 'Dog', 'cat': 'Cat', 'fish': 'Fish', } if 'fish' in t: print "Fish in t." </code></pre>
2
2009-07-17T16:03:22Z
[ "python" ]
Looking for values in nested tuple
1,144,178
<p>Say I have:</p> <pre><code>t = ( ('dog', 'Dog'), ('cat', 'Cat'), ('fish', 'Fish'), ) </code></pre> <p>And I need to check if a value is in the first bit of the nested tuple (ie. the lowercase bits). How can I do this? The capitalised values do not matter really, I want to search for a string in only the lowercase values.</p> <pre><code>if 'fish' in t: print "Fish in t." </code></pre> <p>Doesn't work.</p> <p>Is there a good way of doing this without doing a for loop with if statements?</p>
0
2009-07-17T15:57:17Z
1,145,330
<p>When you have an iterable of key-value pairs such as:</p> <pre><code>t = ( ('dog', 'Dog'), ('cat', 'Cat'), ('fish', 'Fish'), ) </code></pre> <p>You can "cast" it to a dictionary using the <a href="http://docs.python.org/tutorial/datastructures.html#dictionaries" rel="nofollow">dict()</a> constructor, then use the <code>in</code> keyword.</p> <pre><code>if 'fish' in dict(t): print 'fish is in t' </code></pre> <p>This is very similar to the <a href="http://stackoverflow.com/questions/1144178/looking-for-values-in-nested-tuple/1144221#1144221">above answer</a>.</p>
1
2009-07-17T19:51:21Z
[ "python" ]
Hacking JavaScript Array Into JSON With Python
1,144,400
<p>I am fetching a .js file from a remote site that contains data I want to process as JSON using the simplejson library on my Google App Engine site. The .js file looks like this:</p> <pre><code>var txns = [ { apples: '100', oranges: '20', type: 'SELL'}, { apples: '200', oranges: '10', type: 'BUY'}] </code></pre> <p>I have no control over the format of this file. What I did at first just to hack through it was to chop the <code>"var txns = "</code> bit off of the string and then do a series of <code>.replace(old, new, [count])</code> on the string until it looked like standard JSON:</p> <pre><code>cleanJSON = malformedJSON.replace("'", '"').replace('apples:', '"apples":').replace('oranges:', '"oranges":').replace('type:', '"type":').replace('{', '{"transaction":{').replace('}', '}}') </code></pre> <p>So that it now looks like:</p> <pre><code>[{ "transaction" : { "apples": "100", "oranges": "20", "type": "SELL"} }, { "transaction" : { "apples": "200", "oranges": "10", "type": "BUY"} }] </code></pre> <p>How would you tackle this formatting issue? Is there a known way (library, script) to format a JavaScript array into JSON notation?</p>
4
2009-07-17T16:34:59Z
1,144,451
<p><a href="http://www.devpro.it/JSON/files/JSON-js.html" rel="nofollow">http://www.devpro.it/JSON/files/JSON-js.html</a></p>
-1
2009-07-17T16:44:10Z
[ "javascript", "python", "json" ]
Hacking JavaScript Array Into JSON With Python
1,144,400
<p>I am fetching a .js file from a remote site that contains data I want to process as JSON using the simplejson library on my Google App Engine site. The .js file looks like this:</p> <pre><code>var txns = [ { apples: '100', oranges: '20', type: 'SELL'}, { apples: '200', oranges: '10', type: 'BUY'}] </code></pre> <p>I have no control over the format of this file. What I did at first just to hack through it was to chop the <code>"var txns = "</code> bit off of the string and then do a series of <code>.replace(old, new, [count])</code> on the string until it looked like standard JSON:</p> <pre><code>cleanJSON = malformedJSON.replace("'", '"').replace('apples:', '"apples":').replace('oranges:', '"oranges":').replace('type:', '"type":').replace('{', '{"transaction":{').replace('}', '}}') </code></pre> <p>So that it now looks like:</p> <pre><code>[{ "transaction" : { "apples": "100", "oranges": "20", "type": "SELL"} }, { "transaction" : { "apples": "200", "oranges": "10", "type": "BUY"} }] </code></pre> <p>How would you tackle this formatting issue? Is there a known way (library, script) to format a JavaScript array into JSON notation?</p>
4
2009-07-17T16:34:59Z
1,144,458
<p>If you <strong>know</strong> that's what it's always going to look like, you could do a regex to find unquoted space-delimited text that ends with a colon and surround it with quotes.</p> <p>I'm always worried about unexpected input with a regex like that, though. How do you know the remote source won't change what you get?</p>
0
2009-07-17T16:44:54Z
[ "javascript", "python", "json" ]
Hacking JavaScript Array Into JSON With Python
1,144,400
<p>I am fetching a .js file from a remote site that contains data I want to process as JSON using the simplejson library on my Google App Engine site. The .js file looks like this:</p> <pre><code>var txns = [ { apples: '100', oranges: '20', type: 'SELL'}, { apples: '200', oranges: '10', type: 'BUY'}] </code></pre> <p>I have no control over the format of this file. What I did at first just to hack through it was to chop the <code>"var txns = "</code> bit off of the string and then do a series of <code>.replace(old, new, [count])</code> on the string until it looked like standard JSON:</p> <pre><code>cleanJSON = malformedJSON.replace("'", '"').replace('apples:', '"apples":').replace('oranges:', '"oranges":').replace('type:', '"type":').replace('{', '{"transaction":{').replace('}', '}}') </code></pre> <p>So that it now looks like:</p> <pre><code>[{ "transaction" : { "apples": "100", "oranges": "20", "type": "SELL"} }, { "transaction" : { "apples": "200", "oranges": "10", "type": "BUY"} }] </code></pre> <p>How would you tackle this formatting issue? Is there a known way (library, script) to format a JavaScript array into JSON notation?</p>
4
2009-07-17T16:34:59Z
1,144,532
<p>I would use the yaml parser as its better at most things like this. It comes with GAE as well as it is used for the config files. Json is a subset of yaml.</p> <p>All you have to do is get rid of "var txns =" then yaml should do the rest. </p> <pre><code>import yaml string = """[{ apples: '100', oranges: '20', type: 'SELL'}, { apples: '200', oranges: '10', type: 'BUY'}]""" list = yaml.load(string) print list </code></pre> <p>This gives you.</p> <pre><code>[{'type': 'SELL', 'apples': '100', 'oranges': '20'}, {'type': 'BUY', 'apples': '200', 'oranges': '10'}] </code></pre> <p>Once loaded you can always dump it back as a json.</p>
4
2009-07-17T17:03:13Z
[ "javascript", "python", "json" ]
Hacking JavaScript Array Into JSON With Python
1,144,400
<p>I am fetching a .js file from a remote site that contains data I want to process as JSON using the simplejson library on my Google App Engine site. The .js file looks like this:</p> <pre><code>var txns = [ { apples: '100', oranges: '20', type: 'SELL'}, { apples: '200', oranges: '10', type: 'BUY'}] </code></pre> <p>I have no control over the format of this file. What I did at first just to hack through it was to chop the <code>"var txns = "</code> bit off of the string and then do a series of <code>.replace(old, new, [count])</code> on the string until it looked like standard JSON:</p> <pre><code>cleanJSON = malformedJSON.replace("'", '"').replace('apples:', '"apples":').replace('oranges:', '"oranges":').replace('type:', '"type":').replace('{', '{"transaction":{').replace('}', '}}') </code></pre> <p>So that it now looks like:</p> <pre><code>[{ "transaction" : { "apples": "100", "oranges": "20", "type": "SELL"} }, { "transaction" : { "apples": "200", "oranges": "10", "type": "BUY"} }] </code></pre> <p>How would you tackle this formatting issue? Is there a known way (library, script) to format a JavaScript array into JSON notation?</p>
4
2009-07-17T16:34:59Z
1,144,597
<p>It's not too difficult to write your own little parsor for that using <a href="http://pyparsing.wikispaces.com/">PyParsing</a>.</p> <pre><code>import json from pyparsing import * data = """var txns = [ { apples: '100', oranges: '20', type: 'SELL'}, { apples: '200', oranges: '10', type: 'BUY'}]""" def js_grammar(): key = Word(alphas).setResultsName("key") value = QuotedString("'").setResultsName("value") pair = Group(key + Literal(":").suppress() + value) object_ = nestedExpr("{", "}", delimitedList(pair, ",")) array = nestedExpr("[", "]", delimitedList(object_, ",")) return array + StringEnd() JS_GRAMMAR = js_grammar() def parse(js): return JS_GRAMMAR.parseString(js[len("var txns = "):])[0] def to_dict(object_): return dict((p.key, p.value) for p in object_) result = [ {"transaction": to_dict(object_)} for object_ in parse(data)] print json.dumps(result) </code></pre> <p>This is going to print</p> <pre><code>[{"transaction": {"type": "SELL", "apples": "100", "oranges": "20"}}, {"transaction": {"type": "BUY", "apples": "200", "oranges": "10"}}] </code></pre> <p>You can also add the assignment to the grammar itself. Given there are already off-the-shelf parsers for it, you should better use those. </p>
5
2009-07-17T17:12:33Z
[ "javascript", "python", "json" ]
Hacking JavaScript Array Into JSON With Python
1,144,400
<p>I am fetching a .js file from a remote site that contains data I want to process as JSON using the simplejson library on my Google App Engine site. The .js file looks like this:</p> <pre><code>var txns = [ { apples: '100', oranges: '20', type: 'SELL'}, { apples: '200', oranges: '10', type: 'BUY'}] </code></pre> <p>I have no control over the format of this file. What I did at first just to hack through it was to chop the <code>"var txns = "</code> bit off of the string and then do a series of <code>.replace(old, new, [count])</code> on the string until it looked like standard JSON:</p> <pre><code>cleanJSON = malformedJSON.replace("'", '"').replace('apples:', '"apples":').replace('oranges:', '"oranges":').replace('type:', '"type":').replace('{', '{"transaction":{').replace('}', '}}') </code></pre> <p>So that it now looks like:</p> <pre><code>[{ "transaction" : { "apples": "100", "oranges": "20", "type": "SELL"} }, { "transaction" : { "apples": "200", "oranges": "10", "type": "BUY"} }] </code></pre> <p>How would you tackle this formatting issue? Is there a known way (library, script) to format a JavaScript array into JSON notation?</p>
4
2009-07-17T16:34:59Z
1,144,621
<p>You could create an intermediate page containing a Javascript script that just loads the remote one and dumps it to JSON. Then Python can make requests to your intermediate page and get out nice JSON.</p>
0
2009-07-17T17:18:43Z
[ "javascript", "python", "json" ]
Using Eval in Python to create class variables
1,144,702
<p>I wrote a class that lets me pass in a list of variable types, variable names, prompts, and default values. The class creates a wxPython panel, which is displayed in a frame that lets the user set the input values before pressing the calculate button and getting the results back as a plot. I add all of the variables to the class using exec statements. This keeps all of the variables together in one class, and I can refer to them by name.</p> <pre><code>light = Variables( frame , [ ['f','wavelength','Wavelength (nm)',632.8] ,\ ['f','n','Index of Refraction',1.0],]) </code></pre> <p>Inside the class I create and set the variables with statments like:</p> <pre><code>for variable in self.variable_list: var_type,var_text_ctrl,var_name = variable if var_type == 'f' : exec( 'self.' + var_name + ' = ' + var_text_ctrl.GetValue() ) </code></pre> <p>When I need to use the variables, I can just refer to them by name:</p> <pre><code> wl = light.wavelength n = light.n </code></pre> <p>Then I read on SO that there is rarely a need to use exec in Python. Is there a problem with this approach? Is there a better way to create a class that holds variables that should be grouped together, that you want to be able to edit, and also has the code and wxPython calls for displaying, editing, (and also saving all the variables to a file or reading them back again)?</p> <p>Curt</p>
1
2009-07-17T17:36:01Z
1,144,726
<p>You can use the <code>setattr</code> function, which takes three arguments: the object, the name of the attribute, and it's value. For example,</p> <pre><code>setattr(self, 'wavelength', wavelength_val) </code></pre> <p>is equivalent to:</p> <pre><code>self.wavelength = wavelength_val </code></pre> <p>So you could do something like this:</p> <pre><code>for variable in self.variable_list: var_type,var_text_ctrl,var_name = variable if var_type == 'f' : setattr(self, var_name, var_text_ctrl.GetValue()) </code></pre>
18
2009-07-17T17:40:40Z
[ "python", "wxpython", "scientific-computing" ]
Using Eval in Python to create class variables
1,144,702
<p>I wrote a class that lets me pass in a list of variable types, variable names, prompts, and default values. The class creates a wxPython panel, which is displayed in a frame that lets the user set the input values before pressing the calculate button and getting the results back as a plot. I add all of the variables to the class using exec statements. This keeps all of the variables together in one class, and I can refer to them by name.</p> <pre><code>light = Variables( frame , [ ['f','wavelength','Wavelength (nm)',632.8] ,\ ['f','n','Index of Refraction',1.0],]) </code></pre> <p>Inside the class I create and set the variables with statments like:</p> <pre><code>for variable in self.variable_list: var_type,var_text_ctrl,var_name = variable if var_type == 'f' : exec( 'self.' + var_name + ' = ' + var_text_ctrl.GetValue() ) </code></pre> <p>When I need to use the variables, I can just refer to them by name:</p> <pre><code> wl = light.wavelength n = light.n </code></pre> <p>Then I read on SO that there is rarely a need to use exec in Python. Is there a problem with this approach? Is there a better way to create a class that holds variables that should be grouped together, that you want to be able to edit, and also has the code and wxPython calls for displaying, editing, (and also saving all the variables to a file or reading them back again)?</p> <p>Curt</p>
1
2009-07-17T17:36:01Z
1,155,728
<p>I agree with mipadi's answer, but wanted to add one more answer, since the Original Post asked if there's a problem using exec. I'd like to address that.</p> <p>Think like a criminal.</p> <p>If your malicious adversary knew you had code that read:</p> <pre> exec( 'self.' + var_name + ' = ' + var_text_ctrl.GetValue() ) </pre> <p>then he or she may try to inject values for var_name and var_text_ctrl that hacks your code. </p> <p>Imagine if a malicious user could get var_name to be this value:</p> <pre> var_name = """ a = 1 # some bogus assignment to complete "self." statement import os # malicious code starts here os.rmdir('/bin') # do some evil # end it with another var_name # ("a" alone, on the next line) a """ </pre> <p>All of the sudden, the malicious adversary was able to get YOU to exec[ute] code to delete your /bin directory (or whatever evil they want). Now your exec statement roughly reads the equivalent of:</p> <pre> exec ("self.a=1 \n import os \n os.rmdir('/bin') \n\n " "a" + ' = ' + var_text_ctrl.GetValue() ) </pre> <p>Not good!!!</p> <p>As you can imagine, it's possible to construct all sorts of malicious code injections when exec is used. This puts the burden onto the developer to think of any way that the code can be hacked - and adds unnecessary risk, when a risk-free alternative is available.</p>
1
2009-07-20T20:17:39Z
[ "python", "wxpython", "scientific-computing" ]
Using Eval in Python to create class variables
1,144,702
<p>I wrote a class that lets me pass in a list of variable types, variable names, prompts, and default values. The class creates a wxPython panel, which is displayed in a frame that lets the user set the input values before pressing the calculate button and getting the results back as a plot. I add all of the variables to the class using exec statements. This keeps all of the variables together in one class, and I can refer to them by name.</p> <pre><code>light = Variables( frame , [ ['f','wavelength','Wavelength (nm)',632.8] ,\ ['f','n','Index of Refraction',1.0],]) </code></pre> <p>Inside the class I create and set the variables with statments like:</p> <pre><code>for variable in self.variable_list: var_type,var_text_ctrl,var_name = variable if var_type == 'f' : exec( 'self.' + var_name + ' = ' + var_text_ctrl.GetValue() ) </code></pre> <p>When I need to use the variables, I can just refer to them by name:</p> <pre><code> wl = light.wavelength n = light.n </code></pre> <p>Then I read on SO that there is rarely a need to use exec in Python. Is there a problem with this approach? Is there a better way to create a class that holds variables that should be grouped together, that you want to be able to edit, and also has the code and wxPython calls for displaying, editing, (and also saving all the variables to a file or reading them back again)?</p> <p>Curt</p>
1
2009-07-17T17:36:01Z
1,191,425
<p>For the security conscious, there might be an acceptable alternative. There used to be a module call rexec that allowed "restricted" execution of arbitrary python code. This module was removed from recent python versions. <a href="http://pypi.python.org/pypi/RestrictedPython" rel="nofollow">http://pypi.python.org/pypi/RestrictedPython</a> is another implementation by the Zope people that creates a "restricted" environment for arbitrary python code.</p>
0
2009-07-28T01:01:47Z
[ "python", "wxpython", "scientific-computing" ]
Using Eval in Python to create class variables
1,144,702
<p>I wrote a class that lets me pass in a list of variable types, variable names, prompts, and default values. The class creates a wxPython panel, which is displayed in a frame that lets the user set the input values before pressing the calculate button and getting the results back as a plot. I add all of the variables to the class using exec statements. This keeps all of the variables together in one class, and I can refer to them by name.</p> <pre><code>light = Variables( frame , [ ['f','wavelength','Wavelength (nm)',632.8] ,\ ['f','n','Index of Refraction',1.0],]) </code></pre> <p>Inside the class I create and set the variables with statments like:</p> <pre><code>for variable in self.variable_list: var_type,var_text_ctrl,var_name = variable if var_type == 'f' : exec( 'self.' + var_name + ' = ' + var_text_ctrl.GetValue() ) </code></pre> <p>When I need to use the variables, I can just refer to them by name:</p> <pre><code> wl = light.wavelength n = light.n </code></pre> <p>Then I read on SO that there is rarely a need to use exec in Python. Is there a problem with this approach? Is there a better way to create a class that holds variables that should be grouped together, that you want to be able to edit, and also has the code and wxPython calls for displaying, editing, (and also saving all the variables to a file or reading them back again)?</p> <p>Curt</p>
1
2009-07-17T17:36:01Z
1,196,513
<p>The module was removed because it had security issues. Very difficult to provide an environment where any code can be executed in a restricted environment, with all the introspection that Python has.</p> <p>A better bet is to avoid eval and exec.</p> <p>A really off-the-wall idea is to use Google App Engine, and let them worry about malicious code.</p>
0
2009-07-28T20:21:24Z
[ "python", "wxpython", "scientific-computing" ]