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
Python Script to find instances of a set of strings in a set of files
1,483,830
<p>I have a file which I use to centralize all strings used in my application. Lets call it Strings.txt;</p> <pre><code>TITLE="Title" T_AND_C="Accept my terms and conditions please" START_BUTTON="Start" BACK_BUTTON="Back" ... </code></pre> <p>This helps me with I18n, the issue is that my application is now a lot larger and has evolved. As such a lot of these strings are probably not used anymore. I want to eliminate the ones that have gone and tidy up the file. </p> <p>I want to write a python script, using regular expressions I can get all of the string aliases but how can I search all files in a Java package hierarchy for an instance of a string? If there is a reason I use use perl or bash then let me know as I can but I'd prefer to stick to one scripting language.</p> <p>Please ask for clarification if this doesn't make sense, hopefully this is straightforward, I just haven't used python much.</p> <p>Thanks in advance,</p> <p>Gav</p>
1
2009-09-27T16:02:19Z
1,483,855
<p>to parse your <code>strings.txt</code> you don't need regular expressions:</p> <pre><code>all_strings = [i.partition('=')[0] for i in open('strings.txt')] </code></pre> <p>to parse your source you could use the dumbest regex:</p> <pre><code>re.search('\bTITLE\b', source) # for each string in all_strings </code></pre> <p>to walk the source directory you could use <code>os.walk</code>.</p> <p>Successful <code>re.search</code> would mean that you need to remove that string from the <code>all_strings</code>: you'll be left with strings that needs to be removed from <code>strings.txt</code>.</p>
0
2009-09-27T16:18:09Z
[ "python", "find", "internationalization" ]
Python Script to find instances of a set of strings in a set of files
1,483,830
<p>I have a file which I use to centralize all strings used in my application. Lets call it Strings.txt;</p> <pre><code>TITLE="Title" T_AND_C="Accept my terms and conditions please" START_BUTTON="Start" BACK_BUTTON="Back" ... </code></pre> <p>This helps me with I18n, the issue is that my application is now a lot larger and has evolved. As such a lot of these strings are probably not used anymore. I want to eliminate the ones that have gone and tidy up the file. </p> <p>I want to write a python script, using regular expressions I can get all of the string aliases but how can I search all files in a Java package hierarchy for an instance of a string? If there is a reason I use use perl or bash then let me know as I can but I'd prefer to stick to one scripting language.</p> <p>Please ask for clarification if this doesn't make sense, hopefully this is straightforward, I just haven't used python much.</p> <p>Thanks in advance,</p> <p>Gav</p>
1
2009-09-27T16:02:19Z
1,483,979
<p>You should consider using <a href="http://www.yaml.org/" rel="nofollow">YAML</a>: easy to use, human readable.</p>
0
2009-09-27T17:13:07Z
[ "python", "find", "internationalization" ]
Python Script to find instances of a set of strings in a set of files
1,483,830
<p>I have a file which I use to centralize all strings used in my application. Lets call it Strings.txt;</p> <pre><code>TITLE="Title" T_AND_C="Accept my terms and conditions please" START_BUTTON="Start" BACK_BUTTON="Back" ... </code></pre> <p>This helps me with I18n, the issue is that my application is now a lot larger and has evolved. As such a lot of these strings are probably not used anymore. I want to eliminate the ones that have gone and tidy up the file. </p> <p>I want to write a python script, using regular expressions I can get all of the string aliases but how can I search all files in a Java package hierarchy for an instance of a string? If there is a reason I use use perl or bash then let me know as I can but I'd prefer to stick to one scripting language.</p> <p>Please ask for clarification if this doesn't make sense, hopefully this is straightforward, I just haven't used python much.</p> <p>Thanks in advance,</p> <p>Gav</p>
1
2009-09-27T16:02:19Z
1,483,983
<p>You are re-inventing <a href="http://docs.python.org/library/gettext.html" rel="nofollow">gettext</a>, the standard for translating programs in the Free Software sphere (even outside python).</p> <p>Gettext works with, in principle, large files with strings like these :-). Helper programs exist to merge in new marked strings from the source into all translated versions, marking unused strings etc etc. Perhaps you should take a look at it.</p>
0
2009-09-27T17:16:55Z
[ "python", "find", "internationalization" ]
Djapian - filtering results
1,483,874
<p>I use Djapian to search for object by keywords, but I want to be able to filter results. It would be nice to use Django's QuerySet API for this, for example:</p> <pre><code>if query.strip(): results = Model.indexer.search(query).prefetch() else: results = Model.objects.all() results = results.filter(somefield__lt=somevalue) return results </code></pre> <p>But Djapian returns a <code>ResultSet</code> of <code>Hit</code> objects, not <code>Model</code> objects. I can of course filter the objects "by hand", in Python, but it's not realistic in case of filtering all objects (when query is empty) - I would have to retrieve the whole table from database.</p> <p>Am I out of luck with using Djapian for this?</p>
1
2009-09-27T16:27:35Z
1,484,011
<p>I dont know Djapian, but i am familiar with xapian. In Xapian you can filter the results with a <a href="http://xapian.org/docs/apidoc/html/classXapian%5F1%5F1MatchDecider.html" rel="nofollow">MatchDecider</a>.</p> <p>The decision function of the match decider gets called on every document which matches the search criteria so it's not a good idea to do a database query for every document here, but you can of course access the values of the document.</p> <p>For example at <a href="http://ubuntuusers.de" rel="nofollow">ubuntuusers.de</a> we have a xapian database which contains blog posts, forum posts, planet entries, wiki entries and so on and each document in the xapian database has some additional access information stored as value. After the query, an AuthMatchDecider filters the potential documents and returns the filtered MSet which are then displayed to the user.</p> <p>If the decision procedure is as simple as somefield &lt; somevalue, you could also simply add the value of somefield to the values of the document (using the <code>sortable_serialize</code> function provided by xapian) and add (using <code>OP_FILTER</code>) an <code>OP_VALUE_RANGE</code> query to the original query.</p>
0
2009-09-27T17:26:02Z
[ "python", "django", "search", "full-text-search", "xapian" ]
Djapian - filtering results
1,483,874
<p>I use Djapian to search for object by keywords, but I want to be able to filter results. It would be nice to use Django's QuerySet API for this, for example:</p> <pre><code>if query.strip(): results = Model.indexer.search(query).prefetch() else: results = Model.objects.all() results = results.filter(somefield__lt=somevalue) return results </code></pre> <p>But Djapian returns a <code>ResultSet</code> of <code>Hit</code> objects, not <code>Model</code> objects. I can of course filter the objects "by hand", in Python, but it's not realistic in case of filtering all objects (when query is empty) - I would have to retrieve the whole table from database.</p> <p>Am I out of luck with using Djapian for this?</p>
1
2009-09-27T16:27:35Z
1,485,009
<p>I went through its source and found that Djapian has a filter method that can be applied to its results. I have just tried the below code and it seems to be working. </p> <p>My indexer is as follows:</p> <pre><code>class MarketIndexer( djapian.Indexer ): fields = [ 'name', 'description', 'tags_string', 'state'] tags = [('state', 'state'),] </code></pre> <p>Here is how I filter results (never mind the first line that does stuff for wildcard usage):</p> <pre><code>objects = model.indexer.search(q_wc).flags(djapian.resultset.xapian.QueryParser.FLAG_WILDCARD).prefetch() objects = objects.filter(state=1) </code></pre> <p>When executed, it now brings <code>Market</code>s that have their state equal to "1".</p>
4
2009-09-28T01:21:39Z
[ "python", "django", "search", "full-text-search", "xapian" ]
python PIL - background displayed opaque instead of transparent
1,484,101
<p>I want to generate 32x32 sized thumbnails from uploaded images (actually avatars). </p> <p>To prevent a thumbnail from being smaller than that size, I want to create a transparent 32x32 background and paste the thumbnail on it. </p> <p>The code below tries to do so. However, the avatar is displayed on a black and opaque background; I lose transparency information somewhere through the process. Where am I doing wrong?</p> <pre><code>def handle_image(img): size = SMALL_AVATAR_IMAGE_SIZE img.thumbnail(size, Image.ANTIALIAS) img = img.convert('RGBA') background = Image.new('RGBA', size, (255, 255, 255, 0)) background.paste(img, (0, (size[1] - img.size[1]) / 2), img) img = background processed_image_small = ContentFile(img.tostring('jpeg', img.mode)) targetpath = str(self.user.id) + '_S' + '.jpg' self.img_small.save(targetpath, processed_image_small,save=False) </code></pre>
3
2009-09-27T18:12:52Z
1,484,110
<p>You're generating a JPG image. JPEGs don't support background transparency. You need to generate a PNG image to support transparencies.</p>
5
2009-09-27T18:18:15Z
[ "python", "django", "image" ]
python PIL - background displayed opaque instead of transparent
1,484,101
<p>I want to generate 32x32 sized thumbnails from uploaded images (actually avatars). </p> <p>To prevent a thumbnail from being smaller than that size, I want to create a transparent 32x32 background and paste the thumbnail on it. </p> <p>The code below tries to do so. However, the avatar is displayed on a black and opaque background; I lose transparency information somewhere through the process. Where am I doing wrong?</p> <pre><code>def handle_image(img): size = SMALL_AVATAR_IMAGE_SIZE img.thumbnail(size, Image.ANTIALIAS) img = img.convert('RGBA') background = Image.new('RGBA', size, (255, 255, 255, 0)) background.paste(img, (0, (size[1] - img.size[1]) / 2), img) img = background processed_image_small = ContentFile(img.tostring('jpeg', img.mode)) targetpath = str(self.user.id) + '_S' + '.jpg' self.img_small.save(targetpath, processed_image_small,save=False) </code></pre>
3
2009-09-27T18:12:52Z
1,484,113
<p>That is because JPEG cannot save transparency informations which are contained in a RGBA image. You may want to save the avatar to a format like PNG which is able to keep these informations.</p>
5
2009-09-27T18:19:45Z
[ "python", "django", "image" ]
Replace/delete field using sqlalchemy
1,484,235
<p>Using postgres in python,</p> <ol> <li><p>How do I replace all fields from the same column that match a specified value? For example, let's say I want to replace any fields that match "green" with "red" in the "Color" column.</p></li> <li><p>How to delete all fields from the same column that match a specified value? For example, I'm trying to deleted all fields that match "green" in the Color column.</p></li> </ol>
7
2009-09-27T19:17:05Z
1,484,267
<p>Ad1. You need something like this:</p> <pre><code>session.query(Foo).filter_by(color = 'green').update({ 'color': 'red' }) session.commit() </code></pre> <p>Ad2. Similarly:</p> <pre><code>session.query(Foo).filter_by(color = 'green').delete() session.commit() </code></pre> <p>You can find the querying documentation <a href="http://www.sqlalchemy.org/docs/05/reference/orm/query.html">here</a> and <a href="http://www.sqlalchemy.org/docs/05/ormtutorial.html#querying">here</a>.</p>
9
2009-09-27T19:39:37Z
[ "python", "postgresql", "replace", "sqlalchemy" ]
How do I use PyMock and Nose with Django models?
1,484,293
<p>I'm trying to do TDD with PyMock, but I keep getting error when I use Nose and execute core.py from command line:</p> <p>"ERROR: Failure: ImportError (Settings cannot be imported, because environment variable DJA NGO_SETTINGS_MODULE is undefined.)"</p> <p>If I remove "from cms.models import Entry" from the unit test module I created, everything works fine, but I need to mock functionality in django module cms.models.Entry that I created.</p> <p>What am I doing wrong? Can this be done?</p>
2
2009-09-27T19:48:42Z
1,484,428
<p>You <strong>do</strong> need <code>DJANGO_SETTINGS_MODULE</code> defined in order to run <code>core.py</code> -- why don't you just <code>export DJANGO_SETTINGS_MODULE=whatever</code> in your bash session before starting nose?</p>
4
2009-09-27T20:41:18Z
[ "python", "django", "unit-testing", "nose" ]
Python process pool and scope
1,484,310
<p>I am trying to run autogenerated code (which might potentially not terminate) in a loop, for genetic programming. I'm trying to use multiprocessing pool for this, since I don't want the big performance overhead of creating a new process each time, and I can terminate the pool process if it runs too long (which i cant do with threads).</p> <p>Essentially, my program is</p> <pre><code>if __name__ == '__main__': pool = Pool(processes=1) while ...: source = generate() #autogenerate code exec(source) print meth() # just a test, prints a result, since meth was defined in source result = pool.apply_async(meth) try: print result.get(timeout=3) except: pool.terminate() </code></pre> <p>This is the code that should work, but doesn't, instead i get </p> <pre><code>AttributeError: 'module' object has no attribute 'meth' </code></pre> <p>It seems that Pool only sees the meth method, if it is defined in the very top level. Any suggestions how to get it to run dynamically created method?</p> <p>Edit: the problem is exactly the same with Process, i.e.</p> <pre><code>source = generated() exec(source) if __name__ == '__main__': p = Process(target = meth) p.start() </code></pre> <p>works, while</p> <pre><code>if __name__ == '__main__': source = generated() exec(source) p = Process(target = meth) p.start() </code></pre> <p>doesn't, and fails with an AttributeError</p>
0
2009-09-27T19:55:03Z
1,484,409
<p>Did you read <a href="http://docs.python.org/library/multiprocessing.html#multiprocessing-programming" rel="nofollow">the programming guidelines</a>? There is lots of stuff in there about global variables. There are even more limitations under Windows. You don't say which platform you are running on, but this could be the problem if you are running under Windows. From the above link</p> <blockquote> <p>Global variables</p> <p>Bear in mind that if code run in a child process tries to access a global variable, then the value it sees (if any) may not be the same as the value in the parent process at the time that Process.start() was called.</p> <p>However, global variables which are just module level constants cause no problems.</p> </blockquote>
3
2009-09-27T20:33:21Z
[ "python", "pool" ]
Python process pool and scope
1,484,310
<p>I am trying to run autogenerated code (which might potentially not terminate) in a loop, for genetic programming. I'm trying to use multiprocessing pool for this, since I don't want the big performance overhead of creating a new process each time, and I can terminate the pool process if it runs too long (which i cant do with threads).</p> <p>Essentially, my program is</p> <pre><code>if __name__ == '__main__': pool = Pool(processes=1) while ...: source = generate() #autogenerate code exec(source) print meth() # just a test, prints a result, since meth was defined in source result = pool.apply_async(meth) try: print result.get(timeout=3) except: pool.terminate() </code></pre> <p>This is the code that should work, but doesn't, instead i get </p> <pre><code>AttributeError: 'module' object has no attribute 'meth' </code></pre> <p>It seems that Pool only sees the meth method, if it is defined in the very top level. Any suggestions how to get it to run dynamically created method?</p> <p>Edit: the problem is exactly the same with Process, i.e.</p> <pre><code>source = generated() exec(source) if __name__ == '__main__': p = Process(target = meth) p.start() </code></pre> <p>works, while</p> <pre><code>if __name__ == '__main__': source = generated() exec(source) p = Process(target = meth) p.start() </code></pre> <p>doesn't, and fails with an AttributeError</p>
0
2009-09-27T19:55:03Z
1,484,423
<p><code>Process</code> (via pool or otherwise) won't have a <code>__name__</code> of <code>'__main__'</code>, so it will not execute anything that depends on that condition -- including the <code>exec</code> statements that you depend on in order to find your <code>meth</code>, of course.</p> <p>Why are you so keen on having that <code>exec</code> guarded by a condition that, by design, IS going to be false in your sub-process, yet have that sub-process <strong>depend</strong> (contradictorily!) on the execution of that <code>exec</code>...?! It's really boggling my mind...</p>
2
2009-09-27T20:39:21Z
[ "python", "pool" ]
Python process pool and scope
1,484,310
<p>I am trying to run autogenerated code (which might potentially not terminate) in a loop, for genetic programming. I'm trying to use multiprocessing pool for this, since I don't want the big performance overhead of creating a new process each time, and I can terminate the pool process if it runs too long (which i cant do with threads).</p> <p>Essentially, my program is</p> <pre><code>if __name__ == '__main__': pool = Pool(processes=1) while ...: source = generate() #autogenerate code exec(source) print meth() # just a test, prints a result, since meth was defined in source result = pool.apply_async(meth) try: print result.get(timeout=3) except: pool.terminate() </code></pre> <p>This is the code that should work, but doesn't, instead i get </p> <pre><code>AttributeError: 'module' object has no attribute 'meth' </code></pre> <p>It seems that Pool only sees the meth method, if it is defined in the very top level. Any suggestions how to get it to run dynamically created method?</p> <p>Edit: the problem is exactly the same with Process, i.e.</p> <pre><code>source = generated() exec(source) if __name__ == '__main__': p = Process(target = meth) p.start() </code></pre> <p>works, while</p> <pre><code>if __name__ == '__main__': source = generated() exec(source) p = Process(target = meth) p.start() </code></pre> <p>doesn't, and fails with an AttributeError</p>
0
2009-09-27T19:55:03Z
1,484,579
<p>As I commented above, all your examples are working as you expect on my Linux box (Debian Lenny, Python2.5, processing 0.52, see test code below).</p> <p>There seems to be many restrictions on windows on objects you can transmit from one process to another. Reading the doc pointed out by Nick it seems that on window the os missing fork it will run a brand new python interpreter import modules and pickle/unpickle objects that should be passed around. If they can't be pickled I expect that you'll get the kind of problem that occured to you.</p> <p>Hence a complete (not) working example may be usefull for diagnosis. The answer may be in the things you've hidden as irrelevant.</p> <pre><code>from processing import Pool import os def generated(): return ( """ def meth(): import time starttime = time.time() pid = os.getpid() while 1: if time.time() - starttime &gt; 1: print "process %s" % pid starttime = starttime + 1 """) if __name__ == '__main__': pid = os.getpid() print "main pid=%s" % pid for n in range(5): source = generated() #autogenerate code exec(source) pool = Pool(processes=1) result = pool.apply_async(meth) try: print result.get(timeout=3) except: pool.terminate() </code></pre> <p>Another suggestion would be to use threads. <strong>yes you can</strong> even if you don't know if your generated code will stop or not or if your generated code have differently nested loops. Loops are no restriction at all, that's precisely a point for using generators (extracting control flow). I do not see why it couldn't apply to what you are doing. [Agreed it is probably more change that independent processes] See example below.</p> <pre><code>import time class P(object): def __init__(self, name): self.name = name self.starttime = time.time() self.lastexecutiontime = self.starttime self.gen = self.run() def toolong(self): if time.time() - self.starttime &gt; 10: print "process %s too long" % self.name return True return False class P1(P): def run(self): for x in xrange(1000): for y in xrange(1000): for z in xrange(1000): if time.time() - self.lastexecutiontime &gt; 1: print "process %s" % self.name self.lastexecutiontime = self.lastexecutiontime + 1 yield self.result = self.name.uppercase() class P2(P): def run(self): for x in range(10000000): if time.time() - self.lastexecutiontime &gt; 1: print "process %s" % self.name self.lastexecutiontime = self.lastexecutiontime + 1 yield self.result = self.name.capitalize() pool = [P1('one'), P1('two'), P2('three')] while len(pool) &gt; 0: current = pool.pop() try: current.gen.next() except StopIteration: print "Thread %s ended. Result '%s'" % (current.name, current.result) else: if current.toolong(): print "Forced end for thread %s" % current.name else: pool.insert(0, current) </code></pre>
0
2009-09-27T21:51:38Z
[ "python", "pool" ]
Wildcard for PyGTK States
1,484,339
<p>How do I combine:</p> <pre><code>button.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("Green")) button.modify_bg(gtk.STATE_ACTIVE, gtk.gdk.color_parse("Green")) button.modify_bg(gtk.STATE_SELECTED, gtk.gdk.color_parse("Green")) </code></pre> <p>etc.</p> <p>Into a one-liner wildcard covering all of the possible states (<a href="http://tinyurl.com/y99jzfp" rel="nofollow">See Doc</a>)</p>
0
2009-09-27T20:04:24Z
1,484,536
<p>I do not think you can do that. You can still do it with fewer lines though:</p> <pre><code>states = [gtk.STATE_NORMAL, gtk.STATE_ACTIVE, gtk.STATE_PRELIGHT, gtk.STATE_SELECTED, gtk.STATE_INSENSITIVE] for state in states: button.modify_bg(state, gtk.gdk.color_parse("Green")) </code></pre>
1
2009-09-27T21:33:14Z
[ "python", "pygtk", "state" ]
Wildcard for PyGTK States
1,484,339
<p>How do I combine:</p> <pre><code>button.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("Green")) button.modify_bg(gtk.STATE_ACTIVE, gtk.gdk.color_parse("Green")) button.modify_bg(gtk.STATE_SELECTED, gtk.gdk.color_parse("Green")) </code></pre> <p>etc.</p> <p>Into a one-liner wildcard covering all of the possible states (<a href="http://tinyurl.com/y99jzfp" rel="nofollow">See Doc</a>)</p>
0
2009-09-27T20:04:24Z
1,485,699
<p>EDIT:</p> <p>Maybe this comes in handy: <a href="http://faq.pygtk.org/index.py?req=show&amp;file=faq04.006.htp" rel="nofollow">http://faq.pygtk.org/index.py?req=show&amp;file=faq04.006.htp</a></p>
0
2009-09-28T06:36:01Z
[ "python", "pygtk", "state" ]
how % applies to this method in Python?
1,484,375
<p>From my studying of python, I've found two uses for %. It can be used as what's called a modulo, meaning it will divide the value to the left of it and the value to the right of it and spit back the remainder.</p> <p>The other use is a string formatter. So I can do something like <code>'Hi there %s' % name</code>, where name is a list of names.</p> <p>Also, if you see <code>%%</code> in a string formatting, that means a literal <code>%</code> will be entered.</p> <p>Here is my question, I found this:</p> <pre><code>class FormatFormatStr(FormatObj): def __init__(self, fmt): self.fmt = fmt def tostr(self, x): if x is None: return 'None' return self.fmt%self.toval(x) </code></pre> <p>What does <code>return self.fmt%self.toval(x)</code> mean? It can't be a modulo because <code>tova</code>l will give me a string. It's not really a string formatter because there isn't another percent sign.</p> <p>also, related to this:</p> <pre><code>def csvformat_factory(format): format = copy.deepcopy(format) if isinstance(format, FormatFloat): format.scale = 1. # override scaling for storage format.fmt = '%r' return format </code></pre> <p>What does the percent mean in <code>format.fmt = '%r'</code> does this mean to insert a string a la <code>repr()</code>? Or does it mean insert what the variable <code>r</code> represents? <code>r</code> in this overall program also refers to a recarray.</p> <p>Thanks everyone. Hope this makes sense =)</p>
2
2009-09-27T20:17:37Z
1,484,388
<p>The string % operator is simpler than you are imagining. It takes a string on the left side, and a variety of things on the right side. The left side doesn't have to be a literal string, it can be a variable, or the result of another computation. Any expression that results in a string is valid for the left side of the %.</p> <p>In your first example, <code>self.fmt</code> is a string. In order to be useful in this context, it should have a percent sign in it.</p> <p>In your second example, <code>format.fmt</code> is being set to a string that would be useful as the left side of the %. In this case, "%r" means, insert the repr() of the value into the string, as you have said.</p>
4
2009-09-27T20:24:06Z
[ "python", "class", "string-formatting" ]
how % applies to this method in Python?
1,484,375
<p>From my studying of python, I've found two uses for %. It can be used as what's called a modulo, meaning it will divide the value to the left of it and the value to the right of it and spit back the remainder.</p> <p>The other use is a string formatter. So I can do something like <code>'Hi there %s' % name</code>, where name is a list of names.</p> <p>Also, if you see <code>%%</code> in a string formatting, that means a literal <code>%</code> will be entered.</p> <p>Here is my question, I found this:</p> <pre><code>class FormatFormatStr(FormatObj): def __init__(self, fmt): self.fmt = fmt def tostr(self, x): if x is None: return 'None' return self.fmt%self.toval(x) </code></pre> <p>What does <code>return self.fmt%self.toval(x)</code> mean? It can't be a modulo because <code>tova</code>l will give me a string. It's not really a string formatter because there isn't another percent sign.</p> <p>also, related to this:</p> <pre><code>def csvformat_factory(format): format = copy.deepcopy(format) if isinstance(format, FormatFloat): format.scale = 1. # override scaling for storage format.fmt = '%r' return format </code></pre> <p>What does the percent mean in <code>format.fmt = '%r'</code> does this mean to insert a string a la <code>repr()</code>? Or does it mean insert what the variable <code>r</code> represents? <code>r</code> in this overall program also refers to a recarray.</p> <p>Thanks everyone. Hope this makes sense =)</p>
2
2009-09-27T20:17:37Z
1,484,389
<pre><code>def tostr(self, x): if x is None: return 'None' return self.fmt%self.toval(x) </code></pre> <p>The <code>%</code> in this is a string formatter, definitely. Pass the <code>tostr</code> method a formatter, eg <code>"%s"</code> or <code>"%r"</code> to see what happens</p> <p>I think the <code>'%r'</code> in <code>csvformat_factory</code> is also a string formatter. <code>'%r'</code> means take the <code>repr()</code> which is a reasonable way to display something to a user. I imagine that <code>format.fmt</code> is used elsewhere <code>format.fmt % somevalue</code>.</p>
0
2009-09-27T20:24:28Z
[ "python", "class", "string-formatting" ]
how % applies to this method in Python?
1,484,375
<p>From my studying of python, I've found two uses for %. It can be used as what's called a modulo, meaning it will divide the value to the left of it and the value to the right of it and spit back the remainder.</p> <p>The other use is a string formatter. So I can do something like <code>'Hi there %s' % name</code>, where name is a list of names.</p> <p>Also, if you see <code>%%</code> in a string formatting, that means a literal <code>%</code> will be entered.</p> <p>Here is my question, I found this:</p> <pre><code>class FormatFormatStr(FormatObj): def __init__(self, fmt): self.fmt = fmt def tostr(self, x): if x is None: return 'None' return self.fmt%self.toval(x) </code></pre> <p>What does <code>return self.fmt%self.toval(x)</code> mean? It can't be a modulo because <code>tova</code>l will give me a string. It's not really a string formatter because there isn't another percent sign.</p> <p>also, related to this:</p> <pre><code>def csvformat_factory(format): format = copy.deepcopy(format) if isinstance(format, FormatFloat): format.scale = 1. # override scaling for storage format.fmt = '%r' return format </code></pre> <p>What does the percent mean in <code>format.fmt = '%r'</code> does this mean to insert a string a la <code>repr()</code>? Or does it mean insert what the variable <code>r</code> represents? <code>r</code> in this overall program also refers to a recarray.</p> <p>Thanks everyone. Hope this makes sense =)</p>
2
2009-09-27T20:17:37Z
1,484,390
<p>The code: return self.fmt % self.toval(x)</p> <p>Is the "string formatting" use of the % operator, just like you suspected.</p> <p>The class is handed format, which is a string containing the formatting, and when tostr(x) is called, it will return the string % x.</p> <p>This is just like using % directly, only with saving the format string for later. In other words, instead of doing:</p> <pre><code>"I want to print the number: %n" % 20 </code></pre> <p>What's happening is:</p> <pre><code>format_str = "I want to print the number: %n" x = 20 print format_str % x </code></pre> <p>Which is exactly the same thing.</p>
0
2009-09-27T20:25:16Z
[ "python", "class", "string-formatting" ]
how % applies to this method in Python?
1,484,375
<p>From my studying of python, I've found two uses for %. It can be used as what's called a modulo, meaning it will divide the value to the left of it and the value to the right of it and spit back the remainder.</p> <p>The other use is a string formatter. So I can do something like <code>'Hi there %s' % name</code>, where name is a list of names.</p> <p>Also, if you see <code>%%</code> in a string formatting, that means a literal <code>%</code> will be entered.</p> <p>Here is my question, I found this:</p> <pre><code>class FormatFormatStr(FormatObj): def __init__(self, fmt): self.fmt = fmt def tostr(self, x): if x is None: return 'None' return self.fmt%self.toval(x) </code></pre> <p>What does <code>return self.fmt%self.toval(x)</code> mean? It can't be a modulo because <code>tova</code>l will give me a string. It's not really a string formatter because there isn't another percent sign.</p> <p>also, related to this:</p> <pre><code>def csvformat_factory(format): format = copy.deepcopy(format) if isinstance(format, FormatFloat): format.scale = 1. # override scaling for storage format.fmt = '%r' return format </code></pre> <p>What does the percent mean in <code>format.fmt = '%r'</code> does this mean to insert a string a la <code>repr()</code>? Or does it mean insert what the variable <code>r</code> represents? <code>r</code> in this overall program also refers to a recarray.</p> <p>Thanks everyone. Hope this makes sense =)</p>
2
2009-09-27T20:17:37Z
1,484,391
<p>In</p> <pre><code>return self.fmt%self.toval(x) </code></pre> <p><code>self.fmt</code> is a string, and that string presumably has a percent-sign placeholder in it.</p> <p><code>%r</code> in a format string is like <code>%s</code> but it prints the <code>repr()</code> of the string, so it'll have quotes and backslashes and all that.</p> <p><code>%</code> is just an operator which is just a method, and like any other method you can either pass in a literal value or a variable containing a value. In your examples they use a variable containing the format string.</p>
3
2009-09-27T20:25:16Z
[ "python", "class", "string-formatting" ]
how % applies to this method in Python?
1,484,375
<p>From my studying of python, I've found two uses for %. It can be used as what's called a modulo, meaning it will divide the value to the left of it and the value to the right of it and spit back the remainder.</p> <p>The other use is a string formatter. So I can do something like <code>'Hi there %s' % name</code>, where name is a list of names.</p> <p>Also, if you see <code>%%</code> in a string formatting, that means a literal <code>%</code> will be entered.</p> <p>Here is my question, I found this:</p> <pre><code>class FormatFormatStr(FormatObj): def __init__(self, fmt): self.fmt = fmt def tostr(self, x): if x is None: return 'None' return self.fmt%self.toval(x) </code></pre> <p>What does <code>return self.fmt%self.toval(x)</code> mean? It can't be a modulo because <code>tova</code>l will give me a string. It's not really a string formatter because there isn't another percent sign.</p> <p>also, related to this:</p> <pre><code>def csvformat_factory(format): format = copy.deepcopy(format) if isinstance(format, FormatFloat): format.scale = 1. # override scaling for storage format.fmt = '%r' return format </code></pre> <p>What does the percent mean in <code>format.fmt = '%r'</code> does this mean to insert a string a la <code>repr()</code>? Or does it mean insert what the variable <code>r</code> represents? <code>r</code> in this overall program also refers to a recarray.</p> <p>Thanks everyone. Hope this makes sense =)</p>
2
2009-09-27T20:17:37Z
1,484,396
<p>% has more than one use in string formatting. One use is in %s, %d, etc.</p> <p>Another use is to separate 'string in which we use %d and %s' from int-value and string-value.</p> <p>For example </p> <pre><code>'string in which we use %d and %s' % (17, 'blue') </code></pre> <p>would result in </p> <pre><code>'string in which we use 17 and blue' </code></pre> <p>we could store 'string in which we use %d and %s' in a variable,</p> <pre><code>a = 'string in which we use %d and %s' </code></pre> <p>then</p> <pre><code>a % (17, 'blue') </code></pre> <p>results in </p> <pre><code>'string in which we use 17 and blue' </code></pre> <p>In your example self.fmt%self.toval(x)</p> <p>self.fmt is similar to a above and self.toval(x) is (17, 'blue')</p>
0
2009-09-27T20:27:03Z
[ "python", "class", "string-formatting" ]
Ñ not displayed in google app engine website
1,484,427
<p>I'm using google app engine to build a website and I'm having problems with special characters. I think I've reduced the problem to this two code samples:</p> <pre><code>request = urlfetch.fetch( url=self.WWW_INFO, payload=urllib.urlencode(inputs), method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'}) print request.content </code></pre> <p>The previous code displays the content just fine, showing the special characters. But, the correct way to use the framework to display something is using:</p> <pre><code>request = urlfetch.fetch( url=self.WWW_INFO, payload=urllib.urlencode(inputs), method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'}) self.response.out.write(request.content) </code></pre> <p>Which doesn't display the special characters, and instead just prints �. What should I do so it displays correctly?</p> <p>I know I'm missing something, but I can't seem to grasp what it is. The website sets the <code>&lt;meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"&gt;</code>, and I've tried with <code>charset=UTF-8</code> with no success.</p> <p>I'll appreciate any advice that can point me in the right direction.</p>
0
2009-09-27T20:41:09Z
1,484,439
<p>You need to get the <code>charset</code> from the <code>content-type</code> header in the fetch's result, use it to decode the bytes into Unicode, then, on the response, set the header with your favorite encoding (I do suggest utf-8 -- no good reason to do otherwise) and emit the encoding of the Unicode text via that codec. The pass through unicode is not strictly needed (when you're doing nothing at all with the contents, just bouncing it right back to the response, you might use identical content-type and charset to what you received) but it's recommended on general grounds (use encoded byte strings only on input/output, always keep all text "within" your app as unicode).</p> <p>IOW, your problem seems to be mostly that you're not setting headers correctly on the response.</p>
1
2009-09-27T20:47:15Z
[ "python", "google-app-engine", "unicode", "utf-8" ]
HTML tag replacement using regex and python
1,484,575
<p>I have a Python script that will look at an HTML file that has the following format:</p> <pre><code>&lt;DOC&gt; &lt;HTML&gt; ... &lt;/HTML&gt; &lt;/DOC&gt; &lt;DOC&gt; &lt;HTML&gt; ... &lt;/HTML&gt; &lt;/DOC&gt; </code></pre> <p>How do I remove all HTML tags (replace the tags with '') with the exception of the opening and closing DOC tags using regex in Python? Also, if I want to retain the alt-text of an tag, what should the regex expression look like?</p>
1
2009-09-27T21:49:34Z
1,484,584
<p>search and replace with this regex: search for: &lt;.*?> replace with: " </p>
1
2009-09-27T21:53:42Z
[ "python", "html", "regex", "tags" ]
HTML tag replacement using regex and python
1,484,575
<p>I have a Python script that will look at an HTML file that has the following format:</p> <pre><code>&lt;DOC&gt; &lt;HTML&gt; ... &lt;/HTML&gt; &lt;/DOC&gt; &lt;DOC&gt; &lt;HTML&gt; ... &lt;/HTML&gt; &lt;/DOC&gt; </code></pre> <p>How do I remove all HTML tags (replace the tags with '') with the exception of the opening and closing DOC tags using regex in Python? Also, if I want to retain the alt-text of an tag, what should the regex expression look like?</p>
1
2009-09-27T21:49:34Z
1,485,191
<p>Check out <a href="http://codespeak.net/lxml/" rel="nofollow">lxml</a>, a really nice python library for dealing with xml. You can use drop_tag to accomplish what you are looking for.</p> <pre> from lxml import html h = html.fragment_fromstring('&lt;doc&gt;Hello &lt;b&gt;World!&lt;/b&gt;&lt;/doc&gt;') h.find('*').drop_tag() print(html.tostring(h, encoding=unicode)) &lt;doc&gt;Hello World!&lt;/doc&gt; </pre>
2
2009-09-28T02:54:23Z
[ "python", "html", "regex", "tags" ]
HTML tag replacement using regex and python
1,484,575
<p>I have a Python script that will look at an HTML file that has the following format:</p> <pre><code>&lt;DOC&gt; &lt;HTML&gt; ... &lt;/HTML&gt; &lt;/DOC&gt; &lt;DOC&gt; &lt;HTML&gt; ... &lt;/HTML&gt; &lt;/DOC&gt; </code></pre> <p>How do I remove all HTML tags (replace the tags with '') with the exception of the opening and closing DOC tags using regex in Python? Also, if I want to retain the alt-text of an tag, what should the regex expression look like?</p>
1
2009-09-27T21:49:34Z
1,485,230
<p>For what you are trying to accomplish I would use BeautifulSoup rather than regex.</p> <p><a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">http://www.crummy.com/software/BeautifulSoup/</a></p>
3
2009-09-28T03:11:57Z
[ "python", "html", "regex", "tags" ]
How to build a mini-network of small programs feeding each other data?
1,484,658
<p>I'm trying to simulate a real-time network where nodes are consumers and producers of different rates. How would I quickly implement a sample of this with Python? I was imagining that I'd write a simple program for each node, but I'm not sure how to connect them to each other.</p>
6
2009-09-27T22:32:20Z
1,484,676
<p>Look into <a href="http://networkx.lanl.gov/" rel="nofollow">NetworkX</a> <strong>a Python library for creating and manipulating networks</strong>. Edit: Attention, nearby/related to NetworkX, and also hosted at Los Alamos NL, is PyGraphviz, a utility to display graphs. Thank you to las3jrock to point out that I had the wrong link initialy.</p> <p>You can either use NetworkX as-is, or get inspiration from this library (I wouldn't bother this library really has "all things graph" that seem to be needed for network simulation.) In any case, this type of graph creation and manipulation would allow you to represent (and grow / shrink / evolve) the network. </p> <p>With a single centralized object/service based on a graph library as mentioned, you'd be left with creating one (or several) class to represent the behavior of the network nodes. </p> <p>Then, depending on your needs, and if the network is relatively small, the network nodes could effectively be "let loose", and run inside of <strong>threads</strong>. Alternatively (and this is often easy to manage for simulations), there could be <strong>a centralized method which iterates through the nodes and invoke their "do_it" methods</strong> when appropriate. If the "refresh rate" of such a centralized controller is high enough, real-time clocks at the level of nodes can be used to determine when particular behaviors of the node should be triggered. This simiulation can be event driven, or simply polled (again if refresh period is low enough relative to the clocks' basic unit of time.)</p> <p>The centralized "map" of the network would offer the various <strong>network-related primitives</strong> required by the network nodes to perform their "job" (whatever this may be). In other word, the nodes could inquire from the "map" the list of their direct neighbors, the directory of the complete network, the routes (and their cost) towards any given node etc, .</p> <p>Alternatively, the <strong>structure of the network could be distributed over the nodes of the network itself</strong>, à la Internet. This decentralized approach has several advantages, but it implies adding logic and data to the nodes so they implement the equivalent of DNS and Routing. This approach also has the <strong>drawback</strong> of requiring that a fair amount of traffic between nodes be related to the discovery and maintenance of the topology of the network rather than to whatever semantics of communication/exchange the network is meant to emulate. In a nutshell, I wouldn't suggest using this decentralized approach, unless the simulation at hand was aimed at studying the very protocols of such distributed network management systems.</p> <p><strong>Edit:</strong></p> <p>The DES approach suggested in several replies certainly addresses the <strong><em>simulation</em></strong> part of the question. If the <strong><em>network</em></strong> part of question is important, implementing a virtual network based on a strong graph library will be an important part of the solution. Such an approach would expose more readily the dynamics of the system associated with the network topology.</p>
1
2009-09-27T22:44:18Z
[ "python", "simulation" ]
How to build a mini-network of small programs feeding each other data?
1,484,658
<p>I'm trying to simulate a real-time network where nodes are consumers and producers of different rates. How would I quickly implement a sample of this with Python? I was imagining that I'd write a simple program for each node, but I'm not sure how to connect them to each other.</p>
6
2009-09-27T22:32:20Z
1,484,680
<p>Here's how to make a basic client/server program: <a href="http://wdvl.internet.com/Authoring/python/client/watts06152009.html" rel="nofollow">http://wdvl.internet.com/Authoring/python/client/watts06152009.html</a></p> <p>For the data to send from one to another, I'd recommend <a href="http://json.org/" rel="nofollow">JSON</a>, the most simple format ever. Check simplejson if you want to implement it on python: <a href="http://pypi.python.org/pypi/simplejson/" rel="nofollow">http://pypi.python.org/pypi/simplejson/</a></p>
0
2009-09-27T22:45:28Z
[ "python", "simulation" ]
How to build a mini-network of small programs feeding each other data?
1,484,658
<p>I'm trying to simulate a real-time network where nodes are consumers and producers of different rates. How would I quickly implement a sample of this with Python? I was imagining that I'd write a simple program for each node, but I'm not sure how to connect them to each other.</p>
6
2009-09-27T22:32:20Z
1,484,681
<p>Inter-process communication is a generally hard thing to get right. You may want to consider if another approach would meet your needs, like a discrete events simulator.</p> <p>In a DES, you don't actually do the work of each node, just simulate how long each node would take to get the work done. You can use a priority queue to keep track of the incoming and outgoing work, and instrument the system to keep track of the queue size globally, and for each node.</p> <p>Perhaps if you provide more detail on what you're trying to accomplish, we can give more specific recommendations.</p> <p><strong>Edit:</strong> Python has a built-in priority queue in the <code>heapq</code> module, see <a href="http://docs.python.org/library/heapq.html" rel="nofollow">http://docs.python.org/library/heapq.html</a>.</p>
2
2009-09-27T22:45:31Z
[ "python", "simulation" ]
How to build a mini-network of small programs feeding each other data?
1,484,658
<p>I'm trying to simulate a real-time network where nodes are consumers and producers of different rates. How would I quickly implement a sample of this with Python? I was imagining that I'd write a simple program for each node, but I'm not sure how to connect them to each other.</p>
6
2009-09-27T22:32:20Z
1,484,705
<h3>Stick with traditional simulation structures, at least at first</h3> <p>Is it your goal to write an asynchronous system as an exercise? If so, then I guess you have to implement at least a multi-threaded if not multi-process or network system.</p> <p>But if it's really a simulation, and what you want are the analysis results, implementing an actual distributed model would be a horribly complex approach that is likely to yield far less data than an abstract simulation would, that is, the simulation <em>itself</em> doesn't have to <em>be</em> a network of asynchronous actors communicating. That would just be a good way to make the problem so hard it won't get solved.</p> <p>I say, stick with the traditional simulation architecture.</p> <h3>The Classic Discrete Event Simulation</h3> <p>The way this works is that as a central data structure you have a sorted collection of pending events. The events are naturally sorted by increasing time.</p> <p>The program has a main loop, where it takes the next (i.e., the lowest-valued) event out of the collection, advances the simulation clock to the time of this event, and then calls any task-specific processing associated with the event.</p> <p>But, you ask, what if something was supposed to happen in the time delta that the simulator just jumped across? Well, by definition, there was nothing. If an individual element of the simulation needed something to happen in that interval, it was responsible for allocating an event and inserting it into the (sorted) collection.</p> <p>While there are many packages and programs out there that are geared to simulation, the guts of a simulation are not that hard, and it's perfectly reasonable to write it up from scratch in your favorite language.</p> <p>Have fun!</p>
5
2009-09-27T22:59:00Z
[ "python", "simulation" ]
How to build a mini-network of small programs feeding each other data?
1,484,658
<p>I'm trying to simulate a real-time network where nodes are consumers and producers of different rates. How would I quickly implement a sample of this with Python? I was imagining that I'd write a simple program for each node, but I'm not sure how to connect them to each other.</p>
6
2009-09-27T22:32:20Z
1,484,763
<p>Two things come to mind:</p> <p>1- You could write one or more daemons with Twisted Python. (Be warned, twisted can get a little overwhelming , since its an event-driven async system ). Each daemon can bind to a port and make itself available to other daemons. Alternately, you could just run everything within one daemon, and just have each "process" that you script fire at a different interval.. and talk to one another through bound ports as well.</p> <p>2- You could use a single event driven core -- there are a few --, and just fork a bunch of processes or threads for each task.</p>
0
2009-09-27T23:27:40Z
[ "python", "simulation" ]
How to build a mini-network of small programs feeding each other data?
1,484,658
<p>I'm trying to simulate a real-time network where nodes are consumers and producers of different rates. How would I quickly implement a sample of this with Python? I was imagining that I'd write a simple program for each node, but I'm not sure how to connect them to each other.</p>
6
2009-09-27T22:32:20Z
1,484,764
<p>I like @DigitalRoss's and dcrosta's suggestions of a discrete-even simulation, and I'd like to point out that the <a href="http://docs.python.org/library/sched.html" rel="nofollow">sched</a> module in the Python standard library is just what you need at the core of such a system (no need to rebuild the core on top of heapq, or otherwise). You just need to initialize a <code>sched.scheduler</code> instance, instead of the usual <code>time.time</code> and <code>time.sleep</code>, by passing it two callables that <em>simulate</em> the passage of time.</p> <p>For example:</p> <pre><code>class FakeTime(object): def __init__(self, start=0.0): self.now = start def time(self): return self.now def sleep(self, delay): self.now += delay mytimer = FakeTime() </code></pre> <p>and use <code>s = sched.scheduler(mytimer.time, mytimer.sleep)</code> to instantiate the scheduler.</p>
2
2009-09-27T23:28:34Z
[ "python", "simulation" ]
How to build a mini-network of small programs feeding each other data?
1,484,658
<p>I'm trying to simulate a real-time network where nodes are consumers and producers of different rates. How would I quickly implement a sample of this with Python? I was imagining that I'd write a simple program for each node, but I'm not sure how to connect them to each other.</p>
6
2009-09-27T22:32:20Z
1,486,960
<p>Just use Stackless Python, create tasklets, connect them with channels, and everything will work. It is extremely simple.</p>
0
2009-09-28T13:12:07Z
[ "python", "simulation" ]
How to build a mini-network of small programs feeding each other data?
1,484,658
<p>I'm trying to simulate a real-time network where nodes are consumers and producers of different rates. How would I quickly implement a sample of this with Python? I was imagining that I'd write a simple program for each node, but I'm not sure how to connect them to each other.</p>
6
2009-09-27T22:32:20Z
1,487,634
<p>This is something Stackless does very well.</p> <p>Also, you could use generators / co-routines.</p> <p>Interesting links:</p> <p><a href="http://www.python.org/dev/peps/pep-0342/" rel="nofollow">http://www.python.org/dev/peps/pep-0342/</a></p> <p>New users can only post 1 hyper link... so here is the other one</p> <pre><code>'/'.join(['http:/', 'us.pycon.org', '2009', 'tutorials', 'schedule', '1PM6/']) </code></pre>
0
2009-09-28T15:17:48Z
[ "python", "simulation" ]
How do I Access File Properties on Windows Vista with Python?
1,484,746
<p>The question is as simple as in the title, how do I access windows file properties like date-modifed, and more specifically tags, with Python? For a program I'm doing, I need to get lists of all the tags on various files in a particular folder, and I'm not sure on how to do this. I have the win32 module, but I don't see what I need.</p> <p>Thanks guys, for the quick responses, however, the main stat I need from the files is the tags attribute now included in windows vista, and unfortunately, that isn't included in the os.stat and stat modules. Thank you though, as I did need this data, too, but it was more of an after-thought on my part.</p>
2
2009-09-27T23:17:31Z
1,484,750
<p>You can use <a href="http://docs.python.org/library/os.html#os.stat">os.stat</a> with <a href="http://docs.python.org/library/stat.html">stat</a></p> <pre><code>import os import stat import time def get_info(file_name): time_format = "%m/%d/%Y %I:%M:%S %p" file_stats = os.stat(file_name) modification_time = time.strftime(time_format,time.localtime(file_stats[stat.ST_MTIME])) access_time = time.strftime(time_format,time.localtime(file_stats[stat.ST_ATIME])) return modification_time, access_time </code></pre> <p>You can get lots of other stats, check the stat module for the full list. To extract info for all files in a folder, use <a href="http://docs.python.org/library/os.html#os.walk">os.walk</a></p> <pre><code>import os for root, dirs, files in os.walk(/path/to/your/folder): for name in files: print get_info(os.path.join(root, name)) </code></pre>
6
2009-09-27T23:20:16Z
[ "python", "winapi", "windows-vista", "properties" ]
How do I Access File Properties on Windows Vista with Python?
1,484,746
<p>The question is as simple as in the title, how do I access windows file properties like date-modifed, and more specifically tags, with Python? For a program I'm doing, I need to get lists of all the tags on various files in a particular folder, and I'm not sure on how to do this. I have the win32 module, but I don't see what I need.</p> <p>Thanks guys, for the quick responses, however, the main stat I need from the files is the tags attribute now included in windows vista, and unfortunately, that isn't included in the os.stat and stat modules. Thank you though, as I did need this data, too, but it was more of an after-thought on my part.</p>
2
2009-09-27T23:17:31Z
1,484,768
<p>Example: </p> <pre><code>import time, datetime fstat = os.stat(FILENAME) st_mtime = fstat.st_mtime # Date modified a,b,c,d,e,f,g,h,i = time.localtime(st_mtime) print datetime.datetime(a,b,c,d,e,f,g) </code></pre>
1
2009-09-27T23:30:28Z
[ "python", "winapi", "windows-vista", "properties" ]
How do I Access File Properties on Windows Vista with Python?
1,484,746
<p>The question is as simple as in the title, how do I access windows file properties like date-modifed, and more specifically tags, with Python? For a program I'm doing, I need to get lists of all the tags on various files in a particular folder, and I'm not sure on how to do this. I have the win32 module, but I don't see what I need.</p> <p>Thanks guys, for the quick responses, however, the main stat I need from the files is the tags attribute now included in windows vista, and unfortunately, that isn't included in the os.stat and stat modules. Thank you though, as I did need this data, too, but it was more of an after-thought on my part.</p>
2
2009-09-27T23:17:31Z
1,512,536
<p>Apparently, you need to use the <a href="http://msdn.microsoft.com/en-us/library/bb331575%28VS.85%29.aspx" rel="nofollow">Windows Search API</a> looking for <a href="http://msdn.microsoft.com/en-us/library/bb787519%28VS.85%29.aspx" rel="nofollow">System.Keywords</a> -- you can access the API directly via <a href="http://docs.python.org/library/ctypes.html" rel="nofollow"><code>ctypes</code></a>, or indirectly (needing <a href="http://python.net/crew/skippy/win32/Downloads.html" rel="nofollow">win32 extensions</a>) through the API's <a href="http://msdn.microsoft.com/en-us/library/bb286799%28VS.85%29.aspx" rel="nofollow">COM Interop</a> assembly. Sorry, I have no vista installation on which to check, but I hope these links are useful!</p>
3
2009-10-03T01:37:05Z
[ "python", "winapi", "windows-vista", "properties" ]
How do I Access File Properties on Windows Vista with Python?
1,484,746
<p>The question is as simple as in the title, how do I access windows file properties like date-modifed, and more specifically tags, with Python? For a program I'm doing, I need to get lists of all the tags on various files in a particular folder, and I'm not sure on how to do this. I have the win32 module, but I don't see what I need.</p> <p>Thanks guys, for the quick responses, however, the main stat I need from the files is the tags attribute now included in windows vista, and unfortunately, that isn't included in the os.stat and stat modules. Thank you though, as I did need this data, too, but it was more of an after-thought on my part.</p>
2
2009-09-27T23:17:31Z
5,846,160
<p>(You might notice a longer version of the following response given on <a href="http://stackoverflow.com/questions/1512435/how-do-you-retrieve-the-tags-of-a-file-in-a-list-with-python-windows-vista/5846091">another</a> of your threads.)</p> <ol> <li>Download and install the <a href="http://sourceforge.net/projects/pywin32/files/" rel="nofollow">pywin32 extension</a>.</li> <li>Grab <a href="http://timgolden.me.uk/python/win32_how_do_i/get-document-summary-info.html" rel="nofollow">the code</a> Tim Golden wrote for this very task.</li> <li>Save Tim's code as a module on your own computer.</li> <li>Call the <code>property_sets</code> method of your new module (supplying the necessary filepath). The method returns a generator, which is iterable. See the following example code and output.</li> </ol>
0
2011-05-01T03:08:26Z
[ "python", "winapi", "windows-vista", "properties" ]
how are these two variables unpacked?
1,484,748
<p>Through tutorials I had learned that you can define two variables in the same statement, e.g.:</p> <pre><code>In [15]: a, b = 'hello', 'hi!' In [16]: a Out[16]: 'hello' In [17]: b Out[17]: 'hi!' </code></pre> <p>well how does that apply to here?</p> <pre><code>fh, opened = cbook.to_filehandle(fname, 'w', return_opened = True) </code></pre> <p>I prodded further:</p> <pre><code>In [18]: fh Out[18]: &lt;open file 'attempt.csv', mode 'w' at 0xaac89d0&gt; In [19]: opened Out[19]: True </code></pre> <p>my issue comes really with 'opened'. Well normally if two variables are being defined, there would be a comma and then whatever is there would define 'opened.' This is not the case. Even with that issue looming, 'opened' is equal to True which I assume is because 'return_opened = True.' Well that's weird because I don't remember in any tutorial that you could just add a 'return_' before a variable to affect that variable. </p> <p>I play with it some more and I change the True to False and I get this:</p> <pre><code>In [10]: fh, opened = cbook.to_filehandle(fname, 'w', return_opened = False) --------------------------------------------------------------------------- IOError Traceback (most recent call last) /home/blahblahblah/Documents/Programming/EXERCISES/piece.py in &lt;module&gt;() ----&gt; 1 2 3 4 5 IOError: [Errno 9] Bad file descriptor </code></pre> <p>so I guess it only accepts False. </p> <p>I guess I'd like if someone could explain what is going on here.</p> <p>Gracias amigos!</p> <p>here's the entire code:</p> <pre><code>if missingd is None: missingd = dict() def with_mask(func): def newfunc(val, mask, mval): if mask: return mval else: return func(val) return newfunc formatd = get_formatd(r, formatd) funcs = [] for i, name in enumerate(r.dtype.names): funcs.append(with_mask(csvformat_factory(formatd[name]).tostr)) fh, opened = cbook.to_filehandle(fname, 'w', return_opened=True) writer = csv.writer(fh, delimiter=delimiter) header = r.dtype.names writer.writerow(header) # Our list of specials for missing values mvals = [] for name in header: mvals.append(missingd.get(name, missing)) ismasked = False if len(r): row = r[0] ismasked = hasattr(row, '_fieldmask') for row in r: if ismasked: row, rowmask = row.item(), row._fieldmask.item() else: rowmask = [False] * len(row) writer.writerow([func(val, mask, mval) for func, val, mask, mval in zip(funcs, row, rowmask, mvals)]) if opened: fh.close() </code></pre>
1
2009-09-27T23:19:54Z
1,484,758
<p>My guess is that the function internally looks something like this:</p> <pre><code>def to_filehandle(filename, mode, return_opened=False): # do something to open the file and set opened # to True if it worked, False otherwise if return_opened: return the_filehandle, opened else: return the_filehandle </code></pre> <p>There is nothing special or magical about the <code>return_opened</code> keyword argument; it is simply changing the behavior of this particular function.</p>
2
2009-09-27T23:25:44Z
[ "python", "variables" ]
how are these two variables unpacked?
1,484,748
<p>Through tutorials I had learned that you can define two variables in the same statement, e.g.:</p> <pre><code>In [15]: a, b = 'hello', 'hi!' In [16]: a Out[16]: 'hello' In [17]: b Out[17]: 'hi!' </code></pre> <p>well how does that apply to here?</p> <pre><code>fh, opened = cbook.to_filehandle(fname, 'w', return_opened = True) </code></pre> <p>I prodded further:</p> <pre><code>In [18]: fh Out[18]: &lt;open file 'attempt.csv', mode 'w' at 0xaac89d0&gt; In [19]: opened Out[19]: True </code></pre> <p>my issue comes really with 'opened'. Well normally if two variables are being defined, there would be a comma and then whatever is there would define 'opened.' This is not the case. Even with that issue looming, 'opened' is equal to True which I assume is because 'return_opened = True.' Well that's weird because I don't remember in any tutorial that you could just add a 'return_' before a variable to affect that variable. </p> <p>I play with it some more and I change the True to False and I get this:</p> <pre><code>In [10]: fh, opened = cbook.to_filehandle(fname, 'w', return_opened = False) --------------------------------------------------------------------------- IOError Traceback (most recent call last) /home/blahblahblah/Documents/Programming/EXERCISES/piece.py in &lt;module&gt;() ----&gt; 1 2 3 4 5 IOError: [Errno 9] Bad file descriptor </code></pre> <p>so I guess it only accepts False. </p> <p>I guess I'd like if someone could explain what is going on here.</p> <p>Gracias amigos!</p> <p>here's the entire code:</p> <pre><code>if missingd is None: missingd = dict() def with_mask(func): def newfunc(val, mask, mval): if mask: return mval else: return func(val) return newfunc formatd = get_formatd(r, formatd) funcs = [] for i, name in enumerate(r.dtype.names): funcs.append(with_mask(csvformat_factory(formatd[name]).tostr)) fh, opened = cbook.to_filehandle(fname, 'w', return_opened=True) writer = csv.writer(fh, delimiter=delimiter) header = r.dtype.names writer.writerow(header) # Our list of specials for missing values mvals = [] for name in header: mvals.append(missingd.get(name, missing)) ismasked = False if len(r): row = r[0] ismasked = hasattr(row, '_fieldmask') for row in r: if ismasked: row, rowmask = row.item(), row._fieldmask.item() else: rowmask = [False] * len(row) writer.writerow([func(val, mask, mval) for func, val, mask, mval in zip(funcs, row, rowmask, mvals)]) if opened: fh.close() </code></pre>
1
2009-09-27T23:19:54Z
1,484,772
<p>In Python, a function have more than one return value. In this case, the function '<code>cbook.to_filehandle</code>' return the two value.</p> <p>About the error, I think we cannot tell much about it until we know what '<code>cbook.to_filehandle</code>' supposes to do or see it code.</p>
0
2009-09-27T23:31:17Z
[ "python", "variables" ]
how are these two variables unpacked?
1,484,748
<p>Through tutorials I had learned that you can define two variables in the same statement, e.g.:</p> <pre><code>In [15]: a, b = 'hello', 'hi!' In [16]: a Out[16]: 'hello' In [17]: b Out[17]: 'hi!' </code></pre> <p>well how does that apply to here?</p> <pre><code>fh, opened = cbook.to_filehandle(fname, 'w', return_opened = True) </code></pre> <p>I prodded further:</p> <pre><code>In [18]: fh Out[18]: &lt;open file 'attempt.csv', mode 'w' at 0xaac89d0&gt; In [19]: opened Out[19]: True </code></pre> <p>my issue comes really with 'opened'. Well normally if two variables are being defined, there would be a comma and then whatever is there would define 'opened.' This is not the case. Even with that issue looming, 'opened' is equal to True which I assume is because 'return_opened = True.' Well that's weird because I don't remember in any tutorial that you could just add a 'return_' before a variable to affect that variable. </p> <p>I play with it some more and I change the True to False and I get this:</p> <pre><code>In [10]: fh, opened = cbook.to_filehandle(fname, 'w', return_opened = False) --------------------------------------------------------------------------- IOError Traceback (most recent call last) /home/blahblahblah/Documents/Programming/EXERCISES/piece.py in &lt;module&gt;() ----&gt; 1 2 3 4 5 IOError: [Errno 9] Bad file descriptor </code></pre> <p>so I guess it only accepts False. </p> <p>I guess I'd like if someone could explain what is going on here.</p> <p>Gracias amigos!</p> <p>here's the entire code:</p> <pre><code>if missingd is None: missingd = dict() def with_mask(func): def newfunc(val, mask, mval): if mask: return mval else: return func(val) return newfunc formatd = get_formatd(r, formatd) funcs = [] for i, name in enumerate(r.dtype.names): funcs.append(with_mask(csvformat_factory(formatd[name]).tostr)) fh, opened = cbook.to_filehandle(fname, 'w', return_opened=True) writer = csv.writer(fh, delimiter=delimiter) header = r.dtype.names writer.writerow(header) # Our list of specials for missing values mvals = [] for name in header: mvals.append(missingd.get(name, missing)) ismasked = False if len(r): row = r[0] ismasked = hasattr(row, '_fieldmask') for row in r: if ismasked: row, rowmask = row.item(), row._fieldmask.item() else: rowmask = [False] * len(row) writer.writerow([func(val, mask, mval) for func, val, mask, mval in zip(funcs, row, rowmask, mvals)]) if opened: fh.close() </code></pre>
1
2009-09-27T23:19:54Z
1,484,774
<p>With tuple assignment, the right side doesn't need to be an explicit tuple:</p> <pre><code>x = 1, 0 a, b = x </code></pre> <p>does the same thing as:</p> <pre><code>a, b = 1, 0 </code></pre> <p>If a function returns a tuple, you can unpack it with tuple assignment:</p> <pre><code>def my_fn(): return 1, 0 a, b = my_fn() </code></pre>
2
2009-09-27T23:31:29Z
[ "python", "variables" ]
how are these two variables unpacked?
1,484,748
<p>Through tutorials I had learned that you can define two variables in the same statement, e.g.:</p> <pre><code>In [15]: a, b = 'hello', 'hi!' In [16]: a Out[16]: 'hello' In [17]: b Out[17]: 'hi!' </code></pre> <p>well how does that apply to here?</p> <pre><code>fh, opened = cbook.to_filehandle(fname, 'w', return_opened = True) </code></pre> <p>I prodded further:</p> <pre><code>In [18]: fh Out[18]: &lt;open file 'attempt.csv', mode 'w' at 0xaac89d0&gt; In [19]: opened Out[19]: True </code></pre> <p>my issue comes really with 'opened'. Well normally if two variables are being defined, there would be a comma and then whatever is there would define 'opened.' This is not the case. Even with that issue looming, 'opened' is equal to True which I assume is because 'return_opened = True.' Well that's weird because I don't remember in any tutorial that you could just add a 'return_' before a variable to affect that variable. </p> <p>I play with it some more and I change the True to False and I get this:</p> <pre><code>In [10]: fh, opened = cbook.to_filehandle(fname, 'w', return_opened = False) --------------------------------------------------------------------------- IOError Traceback (most recent call last) /home/blahblahblah/Documents/Programming/EXERCISES/piece.py in &lt;module&gt;() ----&gt; 1 2 3 4 5 IOError: [Errno 9] Bad file descriptor </code></pre> <p>so I guess it only accepts False. </p> <p>I guess I'd like if someone could explain what is going on here.</p> <p>Gracias amigos!</p> <p>here's the entire code:</p> <pre><code>if missingd is None: missingd = dict() def with_mask(func): def newfunc(val, mask, mval): if mask: return mval else: return func(val) return newfunc formatd = get_formatd(r, formatd) funcs = [] for i, name in enumerate(r.dtype.names): funcs.append(with_mask(csvformat_factory(formatd[name]).tostr)) fh, opened = cbook.to_filehandle(fname, 'w', return_opened=True) writer = csv.writer(fh, delimiter=delimiter) header = r.dtype.names writer.writerow(header) # Our list of specials for missing values mvals = [] for name in header: mvals.append(missingd.get(name, missing)) ismasked = False if len(r): row = r[0] ismasked = hasattr(row, '_fieldmask') for row in r: if ismasked: row, rowmask = row.item(), row._fieldmask.item() else: rowmask = [False] * len(row) writer.writerow([func(val, mask, mval) for func, val, mask, mval in zip(funcs, row, rowmask, mvals)]) if opened: fh.close() </code></pre>
1
2009-09-27T23:19:54Z
1,484,781
<p>Unpacking is not a magic process : every tuple (for example, <code>(1, 2, 3)</code> is a tuple with three values) can be unpacked into three values. But the tuple itself is also a value, so you can assign it to a variable or return it from a function :</p> <pre><code>x = (1, 2, 3) a, b, c = x # Or, for example : def function_returning_a_tuple(): return (True, False) a, b = function_returning_a_tuple() </code></pre> <p>As you may now understand, <code>cbook.to_filehandle</code> is only a function returning a tuple of two values <code>(file, opened)</code>. There is no magic behind that, nothing about <code>return_something</code> parameters handled differently.</p>
1
2009-09-27T23:33:01Z
[ "python", "variables" ]
how are these two variables unpacked?
1,484,748
<p>Through tutorials I had learned that you can define two variables in the same statement, e.g.:</p> <pre><code>In [15]: a, b = 'hello', 'hi!' In [16]: a Out[16]: 'hello' In [17]: b Out[17]: 'hi!' </code></pre> <p>well how does that apply to here?</p> <pre><code>fh, opened = cbook.to_filehandle(fname, 'w', return_opened = True) </code></pre> <p>I prodded further:</p> <pre><code>In [18]: fh Out[18]: &lt;open file 'attempt.csv', mode 'w' at 0xaac89d0&gt; In [19]: opened Out[19]: True </code></pre> <p>my issue comes really with 'opened'. Well normally if two variables are being defined, there would be a comma and then whatever is there would define 'opened.' This is not the case. Even with that issue looming, 'opened' is equal to True which I assume is because 'return_opened = True.' Well that's weird because I don't remember in any tutorial that you could just add a 'return_' before a variable to affect that variable. </p> <p>I play with it some more and I change the True to False and I get this:</p> <pre><code>In [10]: fh, opened = cbook.to_filehandle(fname, 'w', return_opened = False) --------------------------------------------------------------------------- IOError Traceback (most recent call last) /home/blahblahblah/Documents/Programming/EXERCISES/piece.py in &lt;module&gt;() ----&gt; 1 2 3 4 5 IOError: [Errno 9] Bad file descriptor </code></pre> <p>so I guess it only accepts False. </p> <p>I guess I'd like if someone could explain what is going on here.</p> <p>Gracias amigos!</p> <p>here's the entire code:</p> <pre><code>if missingd is None: missingd = dict() def with_mask(func): def newfunc(val, mask, mval): if mask: return mval else: return func(val) return newfunc formatd = get_formatd(r, formatd) funcs = [] for i, name in enumerate(r.dtype.names): funcs.append(with_mask(csvformat_factory(formatd[name]).tostr)) fh, opened = cbook.to_filehandle(fname, 'w', return_opened=True) writer = csv.writer(fh, delimiter=delimiter) header = r.dtype.names writer.writerow(header) # Our list of specials for missing values mvals = [] for name in header: mvals.append(missingd.get(name, missing)) ismasked = False if len(r): row = r[0] ismasked = hasattr(row, '_fieldmask') for row in r: if ismasked: row, rowmask = row.item(), row._fieldmask.item() else: rowmask = [False] * len(row) writer.writerow([func(val, mask, mval) for func, val, mask, mval in zip(funcs, row, rowmask, mvals)]) if opened: fh.close() </code></pre>
1
2009-09-27T23:19:54Z
1,484,792
<p>As @dcrosta says, there is nothing magical about the variable names. To better see what's going on, try:</p> <pre><code>result = cbook.to_filehandle(fname, 'w', return_opened=True) </code></pre> <p>and examine <code>result</code>, <code>type(result)</code>, etc: you'll see it's a tuple (could conceivably be a list or other sequence, but that's not likely) with exactly two items. <code>result[0]</code> will be an open file, <code>result[1]</code> will be a bool. Most likely, that's because function <code>to_filehandle</code> is coded with a <code>return thefile, thebool</code>-like statement, as dcrosta also surmises.</p> <p>So, this part is "packing" -- two things are packed into one return value, making the latter a tuple with two items. The "unpacking" part is when you later do:</p> <pre><code>fh, opened = result </code></pre> <p>and the two-item sequence is unpacked into two variables. By doing the unpacking directly, you're just "cutting out the middleman", the variable I here named <code>result</code> (to make it easier for you to examine exactly what result comes from that function call, before it gets unpacked). If you know in advance you'll always get a 2-item sequence, and don't need the sequence as such but rather each item with a separate name, then you might as well unpack at once and save one "intermediate step" -- that's all there is to it!</p>
2
2009-09-27T23:35:30Z
[ "python", "variables" ]
There’s PyQuery… is there one for Ruby?
1,484,963
<p>You guys know <a href="http://pypi.python.org/pypi/pyquery" rel="nofollow">PyQuery</a>?</p> <p>I was wondering if there’s an equivalent for Ruby.</p>
1
2009-09-28T00:56:35Z
1,484,996
<p>There's JRails, but it's outdated. If you're just looking for a way to use JQuery with Rails though: <a href="http://railscasts.com/episodes/136-jquery" rel="nofollow">http://railscasts.com/episodes/136-jquery</a></p>
1
2009-09-28T01:11:24Z
[ "python", "ruby" ]
There’s PyQuery… is there one for Ruby?
1,484,963
<p>You guys know <a href="http://pypi.python.org/pypi/pyquery" rel="nofollow">PyQuery</a>?</p> <p>I was wondering if there’s an equivalent for Ruby.</p>
1
2009-09-28T00:56:35Z
1,500,608
<p>Hpricot - <a href="http://stackoverflow.com/questions/1223793/most-jquery-like-html-parser-for-ruby">http://stackoverflow.com/questions/1223793/most-jquery-like-html-parser-for-ruby</a></p>
1
2009-09-30T20:54:47Z
[ "python", "ruby" ]
Putting in extra restrictions when filtering on foreignkey in django-admin
1,485,103
<p>When getting members based on Unit, I only want to get the ones who are <em>actually in that unit as of now</em>.</p> <p>I've got a model looking like this:</p> <pre><code>class Member(models.Model): name = models.CharField(max_length=256) unit = models.ManyToManyField(Unit, through='Membership') class Membership(models.Model): member = models.ForeignKey(Member) unit = models.ForeignKey(Unit) start = models.DateField(default=date.today) stop = models.DateField(blank=True, null=True) class Unit(models.Model): name = models.CharField(max_length=256) </code></pre> <p>As you can see, members can have a "fake" membership in unit, that is only history and should not be considered in the searches and listings of the admin. They <em>should</em> be shown in the change-page for a single object though.</p> <p>The admin looks like this:</p> <pre><code>class MembershipInline(admin.TabularInline): model = Membership extra = 1 class MemberAdmin(admin.ModelAdmin): list_filter = ('unit',) inlines = [MembershipInline,] </code></pre> <p>So how can I (if at all possible this way), when filtering on unit only get those units whose <code>membership__stop__isnull=True</code>?</p> <p>I tried Managers, I can make them work on the model in the admin itself, but not on the filtering/searches. There is also a <code>def queryset(self)</code> method that is overrideable, but I can't wrap my head around how to use it to fix my problem.</p> <p><strong>Edit</strong>, how this is used: A member has only one membership in a unit, however, they could be members from before, but they are ended (with stop). So I only want to filter (and show, in the list view) those members who have an open-ended membership (like, that they are members of that unit now).</p> <p>Any ideas?</p>
1
2009-09-28T02:03:53Z
1,485,173
<p>So you're trying to get the members of a specific Unit, right?</p> <pre><code>unit = Unit.objects.select_related().get(id=some_id) </code></pre> <p>This will pull the unit out of the database for you, along with the Memberships and Users that belong to it. You can access and filter the users by:</p> <pre><code>for member in unit.membership__set.filter(stop__isnull=True): print member.name </code></pre> <p>I hope this helps? I may be wrong, I haven't tested this.</p>
0
2009-09-28T02:44:46Z
[ "python", "django", "filter", "django-admin", "many-to-many" ]
Putting in extra restrictions when filtering on foreignkey in django-admin
1,485,103
<p>When getting members based on Unit, I only want to get the ones who are <em>actually in that unit as of now</em>.</p> <p>I've got a model looking like this:</p> <pre><code>class Member(models.Model): name = models.CharField(max_length=256) unit = models.ManyToManyField(Unit, through='Membership') class Membership(models.Model): member = models.ForeignKey(Member) unit = models.ForeignKey(Unit) start = models.DateField(default=date.today) stop = models.DateField(blank=True, null=True) class Unit(models.Model): name = models.CharField(max_length=256) </code></pre> <p>As you can see, members can have a "fake" membership in unit, that is only history and should not be considered in the searches and listings of the admin. They <em>should</em> be shown in the change-page for a single object though.</p> <p>The admin looks like this:</p> <pre><code>class MembershipInline(admin.TabularInline): model = Membership extra = 1 class MemberAdmin(admin.ModelAdmin): list_filter = ('unit',) inlines = [MembershipInline,] </code></pre> <p>So how can I (if at all possible this way), when filtering on unit only get those units whose <code>membership__stop__isnull=True</code>?</p> <p>I tried Managers, I can make them work on the model in the admin itself, but not on the filtering/searches. There is also a <code>def queryset(self)</code> method that is overrideable, but I can't wrap my head around how to use it to fix my problem.</p> <p><strong>Edit</strong>, how this is used: A member has only one membership in a unit, however, they could be members from before, but they are ended (with stop). So I only want to filter (and show, in the list view) those members who have an open-ended membership (like, that they are members of that unit now).</p> <p>Any ideas?</p>
1
2009-09-28T02:03:53Z
1,491,167
<p>One way to certainly achieve this is by adding a denormalized field for <code>has_open_ended_membership</code>.</p> <p>To do this just add a BooleaneField like that to the Member and <strong>make sure it's consistent</strong>.</p> <p>From the django documentation this seems to be the only way without writing specialized code in the ModelAdmin object:</p> <blockquote> <p>Set list_filter to activate filters in the right sidebar of the change list page of the admin. This should be a list of field names, and each specified field should be either a BooleanField, CharField, DateField, DateTimeField, IntegerField or ForeignKey.</p> </blockquote> <p>I'm curious about other approaches - list_filter certainly is limited.</p>
0
2009-09-29T08:06:36Z
[ "python", "django", "filter", "django-admin", "many-to-many" ]
Putting in extra restrictions when filtering on foreignkey in django-admin
1,485,103
<p>When getting members based on Unit, I only want to get the ones who are <em>actually in that unit as of now</em>.</p> <p>I've got a model looking like this:</p> <pre><code>class Member(models.Model): name = models.CharField(max_length=256) unit = models.ManyToManyField(Unit, through='Membership') class Membership(models.Model): member = models.ForeignKey(Member) unit = models.ForeignKey(Unit) start = models.DateField(default=date.today) stop = models.DateField(blank=True, null=True) class Unit(models.Model): name = models.CharField(max_length=256) </code></pre> <p>As you can see, members can have a "fake" membership in unit, that is only history and should not be considered in the searches and listings of the admin. They <em>should</em> be shown in the change-page for a single object though.</p> <p>The admin looks like this:</p> <pre><code>class MembershipInline(admin.TabularInline): model = Membership extra = 1 class MemberAdmin(admin.ModelAdmin): list_filter = ('unit',) inlines = [MembershipInline,] </code></pre> <p>So how can I (if at all possible this way), when filtering on unit only get those units whose <code>membership__stop__isnull=True</code>?</p> <p>I tried Managers, I can make them work on the model in the admin itself, but not on the filtering/searches. There is also a <code>def queryset(self)</code> method that is overrideable, but I can't wrap my head around how to use it to fix my problem.</p> <p><strong>Edit</strong>, how this is used: A member has only one membership in a unit, however, they could be members from before, but they are ended (with stop). So I only want to filter (and show, in the list view) those members who have an open-ended membership (like, that they are members of that unit now).</p> <p>Any ideas?</p>
1
2009-09-28T02:03:53Z
1,517,792
<p>I fixed it with putting in a denormalized field in member, with a foreign-key to the active unit. Then, to make it work and be automatically updated in the admin, I made the specialized save-function for Membership.</p> <pre><code>class Member(models.Model): name = models.CharField(max_length=256) unit = models.ManyToManyField(Unit, through='Membership') unit_denorm = models.ForeignKey(Unit) class Membership(models.Model): member = models.ForeignKey(Member) unit = models.ForeignKey(Unit) start = models.DateField(default=date.today) stop = models.DateField(blank=True, null=True) def save(self, *args, **kwargs): if not self.stop: self.member.unit_denorm = self.unit self.member.save() super(Membership, self).save(*args, **kwargs) class Unit(models.Model): name = models.CharField(max_length=256) </code></pre> <p>And with <code>list_filter = ('unit_denorm',)</code> in the admin, it does exactly what I want.</p> <p>Great! Of course, there should only be one field with <code>stop__isnull=True</code>. I haven't figured out how to make that restriction. but people using the system know they shouldn't do that anyway.</p>
0
2009-10-05T00:40:05Z
[ "python", "django", "filter", "django-admin", "many-to-many" ]
How to pack a tkinter widget underneath an existing widget that has been packed to the left side?
1,485,408
<p>I'm attempting to write a basic Tkinter GUI that has a <code>Text</code> widget at the top, then a <code>Button</code> widget left aligned under it, then another <code>Text</code> widget underneath the button. The problem I'm having is, after packing the <code>Button</code> widget to the left, when I then go to pack the second <code>Text</code> widget, it puts it next to the button on the right, rather than underneath the button. This happens regardless of what I set the <code>side</code> argument to for the second <code>Text</code> widget Here's a simple piece of code that demonstrates this behaviour:</p> <pre><code>from Tkinter import * root = Tk() w = Text(root) w.pack() x = Button(root, text="Hi there!") x.pack(side=LEFT) y = Text(root) y.pack(side=BOTTOM) root.mainloop() </code></pre> <p>So how would I go about setting up the second <code>Text</code> widget so that it appears below the button, rather than to the right of it?</p>
5
2009-09-28T04:25:57Z
1,485,522
<p>Packing happens in the order the .pack methods are called, so once x has "claimed" the left side, that's it -- it will take up the left portion of its parent and everything else within its parent will be to its right. You need a Frame to "mediate", e.g....:</p> <pre><code>from Tkinter import * root = Tk() w = Button(root, text="Mysterious W") w.pack() f = Frame(root) x = Button(f, text="Hi there!") x.pack() y = Button(f, text="I be Y") y.pack(side=BOTTOM) f.pack(side=LEFT) root.mainloop() </code></pre> <p>(changed Texts to Buttons for more immediate visibility of layout only -- the Tkinter on this Mac doesn't show Texts clearly until they have focus, but Buttons are quite clear;-).</p>
2
2009-09-28T05:15:17Z
[ "python", "widget", "tkinter", "pack" ]
How to pack a tkinter widget underneath an existing widget that has been packed to the left side?
1,485,408
<p>I'm attempting to write a basic Tkinter GUI that has a <code>Text</code> widget at the top, then a <code>Button</code> widget left aligned under it, then another <code>Text</code> widget underneath the button. The problem I'm having is, after packing the <code>Button</code> widget to the left, when I then go to pack the second <code>Text</code> widget, it puts it next to the button on the right, rather than underneath the button. This happens regardless of what I set the <code>side</code> argument to for the second <code>Text</code> widget Here's a simple piece of code that demonstrates this behaviour:</p> <pre><code>from Tkinter import * root = Tk() w = Text(root) w.pack() x = Button(root, text="Hi there!") x.pack(side=LEFT) y = Text(root) y.pack(side=BOTTOM) root.mainloop() </code></pre> <p>So how would I go about setting up the second <code>Text</code> widget so that it appears below the button, rather than to the right of it?</p>
5
2009-09-28T04:25:57Z
1,485,677
<p>I was initially misunderstanding how packing worked and didn't realise that the entire left side was being "claimed" when i did <code>x.pack(side=LEFT)</code>. What I found after reading <a href="http://www.ferg.org/thinking%5Fin%5Ftkinter/tt100%5Fpy.txt">this</a> and the answer by Alex here is that I was not really after having <code>x</code> packed to the left side at all, but rather having it <strong>anchored</strong> to the left, using <code>anchor=W</code> (W for West) instead of <code>side=LEFT</code>. My revised code snippet which does what I was after looks like this:</p> <pre><code>from Tkinter import * root = Tk() w = Text(root) w.pack() x = Button(root, text="Hi there!") x.pack(anchor=W) y = Text(root) y.pack(side=BOTTOM) root.mainloop() </code></pre> <p>This way <code>x</code> is not "claiming" the left side anymore, it's just aligned to the left (or West) within its block of space.</p>
5
2009-09-28T06:22:03Z
[ "python", "widget", "tkinter", "pack" ]
How to pack a tkinter widget underneath an existing widget that has been packed to the left side?
1,485,408
<p>I'm attempting to write a basic Tkinter GUI that has a <code>Text</code> widget at the top, then a <code>Button</code> widget left aligned under it, then another <code>Text</code> widget underneath the button. The problem I'm having is, after packing the <code>Button</code> widget to the left, when I then go to pack the second <code>Text</code> widget, it puts it next to the button on the right, rather than underneath the button. This happens regardless of what I set the <code>side</code> argument to for the second <code>Text</code> widget Here's a simple piece of code that demonstrates this behaviour:</p> <pre><code>from Tkinter import * root = Tk() w = Text(root) w.pack() x = Button(root, text="Hi there!") x.pack(side=LEFT) y = Text(root) y.pack(side=BOTTOM) root.mainloop() </code></pre> <p>So how would I go about setting up the second <code>Text</code> widget so that it appears below the button, rather than to the right of it?</p>
5
2009-09-28T04:25:57Z
1,492,025
<p>There are generally two solutions to layout problems:</p> <ol> <li><p>switch to using grid. It becomes real easy to do layouts like what you are trying to accomplish. Grid can solve probably 95% of all layout issues (it's amazing when you think about it -- Tk does with one manager what most toolkits need half a dozen to accomplish!)</p></li> <li><p>use multiple frames. If some widgets need to be stacked top-to-bottom and some left-to-right you can't always get what you want packing everything in a single frame. Use one frame for the top-to-bottom parts of the layout and additional frames for the left-to-right content.</p></li> </ol> <p>Also realize that widgets don't have to be children of the widget in which they are packed/gridded. You can use the "in" parameter to put widgets in some other container than their parent. </p> <p>For example, in your specific example you can create three frames, top, middle, bottom. Pack these top-to-bottom in your toplevel window. Then you can pack the first text widget in the top, the button or buttons horizontally in the middle, and the other text widget in the bottom. </p> <p>The advantage to such an approach is that it makes it much easier to change the layout in the future (which in my experience <em>always</em> happens at some point). You don't have to re-parent any of your widgets, just pack/place/grid them in some other container. </p> <p>In your short example it doesn't make much difference, but for complex apps this strategy can be a life saver. </p> <p>My best advice is this: layout isn't an afterthought. Do a little planning, maybe even spend five minutes drawing on some graph paper. First decide on the major regions of your app and use a frame or some other container for each (paned window, notebook, etc). Once you have those, do the same divide-and-conquer approach for each section. This lets you use different types of layout for different sections of your app. Toolbars get horizontal layout, forms might get vertical layout, etc.</p>
10
2009-09-29T11:40:58Z
[ "python", "widget", "tkinter", "pack" ]
Resize image twice in Django using PIL
1,485,569
<p>I have a function in which I'm trying to resize a photo twice from request.FILES['image']. I'm using the image.thumbnail() with the Parser as well. This works fine when I create one thumbnail, but in my view if I repeat the exact same thing again, it fails in the parser via IOError cannot parse image. I'm very confused. I've created StringIO files in memory instead of using Django's UploadedFile object as-is and it still does the same thing. Any help is much appreciated.</p> <p>Suppose I wanted to do the following twice (with two different thumbnailing sizes) all without retrieving the URL twice:</p> <pre><code>import urllib2 from PIL import Image, ImageFile, ImageEnhance # create Image instance file = urllib2.urlopen(r'http://animals.nationalgeographic.com/staticfiles/NGS/Shared/StaticFiles/animals/images/primary/kemps-ridley-sea-turtle.jpg') parser = ImageFile.Parser() while True: s = file.read(1024) if not s: break parser.feed(s) image = parser.close() # make thumbnail size = (75, 75) image.thumbnail(size, Image.ANTIALIAS) background = Image.new('RGBA', size, (255, 255, 255, 0)) background.paste( image, ((size[0] - image.size[0]) / 2, (size[1] - image.size[1]) / 2)) background.save('copy.jpg') </code></pre> <p>For instance:</p> <pre><code>image = parser.close() image2 = parser.close() # Obviously this doens't work image2 = image # Obviously this doesn't either but you get what I need to do here # Do 2 thumbnails with only one original source. </code></pre> <p>... other code ommitted ...</p> <pre><code>image.save('copy.jpg') image2.save('copy.jpg') </code></pre>
1
2009-09-28T05:39:33Z
1,485,904
<p>I'm assuming it's failing on the <code>image = parser.close()</code> line with an <code>IOError</code>. so there's probably something wrong with the way <code>ImageFile</code> is getting the image data. Have you tried making reading from a local file instead?</p> <blockquote> <p>If the parser managed to decode an image, it returns an <code>Image</code> object. Otherwise, this method raises an <code>IOError</code> exception.</p> </blockquote> <p><a href="http://www.pythonware.com/library/pil/handbook/imagefile.htm" rel="nofollow">Source</a>.</p>
0
2009-09-28T07:54:06Z
[ "python", "django", "image-manipulation", "python-imaging-library" ]
Resize image twice in Django using PIL
1,485,569
<p>I have a function in which I'm trying to resize a photo twice from request.FILES['image']. I'm using the image.thumbnail() with the Parser as well. This works fine when I create one thumbnail, but in my view if I repeat the exact same thing again, it fails in the parser via IOError cannot parse image. I'm very confused. I've created StringIO files in memory instead of using Django's UploadedFile object as-is and it still does the same thing. Any help is much appreciated.</p> <p>Suppose I wanted to do the following twice (with two different thumbnailing sizes) all without retrieving the URL twice:</p> <pre><code>import urllib2 from PIL import Image, ImageFile, ImageEnhance # create Image instance file = urllib2.urlopen(r'http://animals.nationalgeographic.com/staticfiles/NGS/Shared/StaticFiles/animals/images/primary/kemps-ridley-sea-turtle.jpg') parser = ImageFile.Parser() while True: s = file.read(1024) if not s: break parser.feed(s) image = parser.close() # make thumbnail size = (75, 75) image.thumbnail(size, Image.ANTIALIAS) background = Image.new('RGBA', size, (255, 255, 255, 0)) background.paste( image, ((size[0] - image.size[0]) / 2, (size[1] - image.size[1]) / 2)) background.save('copy.jpg') </code></pre> <p>For instance:</p> <pre><code>image = parser.close() image2 = parser.close() # Obviously this doens't work image2 = image # Obviously this doesn't either but you get what I need to do here # Do 2 thumbnails with only one original source. </code></pre> <p>... other code ommitted ...</p> <pre><code>image.save('copy.jpg') image2.save('copy.jpg') </code></pre>
1
2009-09-28T05:39:33Z
1,485,913
<p>If this works once, as you say, the image you retrieved is just fine. There are at least two different ways to get multiple thumbnails out of single PIL images.</p> <ol> <li>You can use PIL's <code>resize</code> method, which will return a resized copy of the original. You just have to calculate the dimensions you'll need if you want to keep the proportions intact.</li> <li>Use Image.copy() to get a copy of the image.</li> </ol> <p>Like this: </p> <pre><code>original = parser.close() ... thumb1 = original.copy() size = (75,75) thumb1.thumbnail(size, Image.ANTIALIAS) ... thumb2 = original.copy() thumbnail2 = original.resize(size2, Image.ANTIALIAS) ... </code></pre> <p>This way, the original will not be altered and you can get as many copies as you need.</p>
2
2009-09-28T07:57:57Z
[ "python", "django", "image-manipulation", "python-imaging-library" ]
Resize image twice in Django using PIL
1,485,569
<p>I have a function in which I'm trying to resize a photo twice from request.FILES['image']. I'm using the image.thumbnail() with the Parser as well. This works fine when I create one thumbnail, but in my view if I repeat the exact same thing again, it fails in the parser via IOError cannot parse image. I'm very confused. I've created StringIO files in memory instead of using Django's UploadedFile object as-is and it still does the same thing. Any help is much appreciated.</p> <p>Suppose I wanted to do the following twice (with two different thumbnailing sizes) all without retrieving the URL twice:</p> <pre><code>import urllib2 from PIL import Image, ImageFile, ImageEnhance # create Image instance file = urllib2.urlopen(r'http://animals.nationalgeographic.com/staticfiles/NGS/Shared/StaticFiles/animals/images/primary/kemps-ridley-sea-turtle.jpg') parser = ImageFile.Parser() while True: s = file.read(1024) if not s: break parser.feed(s) image = parser.close() # make thumbnail size = (75, 75) image.thumbnail(size, Image.ANTIALIAS) background = Image.new('RGBA', size, (255, 255, 255, 0)) background.paste( image, ((size[0] - image.size[0]) / 2, (size[1] - image.size[1]) / 2)) background.save('copy.jpg') </code></pre> <p>For instance:</p> <pre><code>image = parser.close() image2 = parser.close() # Obviously this doens't work image2 = image # Obviously this doesn't either but you get what I need to do here # Do 2 thumbnails with only one original source. </code></pre> <p>... other code ommitted ...</p> <pre><code>image.save('copy.jpg') image2.save('copy.jpg') </code></pre>
1
2009-09-28T05:39:33Z
1,781,378
<p>A simpler solution than copying the original image is to instead reset the file pointer between calls to thumbnail(...) like so:</p> <pre><code>original.seek(0) </code></pre>
2
2009-11-23T06:11:41Z
[ "python", "django", "image-manipulation", "python-imaging-library" ]
Using mechanize to visit a site that requires SSL
1,485,571
<p>I need to visit a site (https://*) that requires me to install two certificates in Firefox before I can visit it successfully. One I can export as a .p12 file (Client Certificate), and one is a .crt file (CA Certificate). If I try accessing this site without these certificates, I get a "failed handshake error".</p> <p>How do I visit this site in Python? I was thinking of using mechanize. Thanks.</p>
2
2009-09-28T05:40:23Z
1,486,139
<p>I'd suggest you use <a href="http://code.google.com/p/webdriver/" rel="nofollow">webdriver</a> to automate Firefox. It has a Python interface too.</p>
1
2009-09-28T09:22:37Z
[ "python", "ssl", "ssl-certificate", "mechanize" ]
Return a list of dictionaries that match the corresponding list of values in python
1,485,660
<p>For example, this is my list of dictionaries: </p> <pre><code>[{'name': 'John', 'color': 'red' }, {'name': 'Bob', 'color': 'green'}, {'name': 'Tom', 'color': 'blue' }] </code></pre> <p>Based on the list <code>['blue', 'red', 'green']</code> I want to return the following:</p> <pre><code>[{'name': 'Tom', 'color': 'blue' }, {'name': 'John', 'color': 'red' }, {'name': 'Bob', 'color': 'green'}] </code></pre>
2
2009-09-28T06:15:14Z
1,485,695
<p>Update:</p> <pre><code>&gt;&gt;&gt; list_ = [{'c': 3}, {'c': 2}, {'c': 5}] &gt;&gt;&gt; mp = [3, 5, 2] &gt;&gt;&gt; sorted(list_, cmp=lambda x, y: cmp(mp.index(x.get('c')), mp.index(y.get('c')))) [{'c': 3}, {'c': 5}, {'c': 2}] </code></pre>
2
2009-09-28T06:32:46Z
[ "python", "dictionary" ]
Return a list of dictionaries that match the corresponding list of values in python
1,485,660
<p>For example, this is my list of dictionaries: </p> <pre><code>[{'name': 'John', 'color': 'red' }, {'name': 'Bob', 'color': 'green'}, {'name': 'Tom', 'color': 'blue' }] </code></pre> <p>Based on the list <code>['blue', 'red', 'green']</code> I want to return the following:</p> <pre><code>[{'name': 'Tom', 'color': 'blue' }, {'name': 'John', 'color': 'red' }, {'name': 'Bob', 'color': 'green'}] </code></pre>
2
2009-09-28T06:15:14Z
1,485,698
<p>Here is a simple loop function:</p> <pre><code># Heres the people: people = [{'name':'John', 'color':'red'}, {'name':'Bob', 'color':'green'}, {'name':'Tom', 'color':'blue'}] # Now we can make a method to get people out in order by color: def orderpeople(order): for color in order: for person in people: if person['color'] == color: yield person order = ['blue', 'red', 'green'] print(list(orderpeople(order))) </code></pre> <p>Now that will be VERY slow if you have many people. Then you can loop through them only once, but build an index by color:</p> <pre><code># Here's the people: people = [{'name':'John', 'color':'red'}, {'name':'Bob', 'color':'green'}, {'name':'Tom', 'color':'blue'}] # Now make an index: colorindex = {} for each in people: color = each['color'] if color not in colorindex: # Note that we want a list here, if several people have the same color. colorindex[color] = [] colorindex[color].append(each) # Now we can make a method to get people out in order by color: def orderpeople(order): for color in order: for each in colorindex[color]: yield each order = ['blue', 'red', 'green'] print(list(orderpeople(order))) </code></pre> <p>This will be quite fast even for really big lists.</p>
0
2009-09-28T06:35:07Z
[ "python", "dictionary" ]
Return a list of dictionaries that match the corresponding list of values in python
1,485,660
<p>For example, this is my list of dictionaries: </p> <pre><code>[{'name': 'John', 'color': 'red' }, {'name': 'Bob', 'color': 'green'}, {'name': 'Tom', 'color': 'blue' }] </code></pre> <p>Based on the list <code>['blue', 'red', 'green']</code> I want to return the following:</p> <pre><code>[{'name': 'Tom', 'color': 'blue' }, {'name': 'John', 'color': 'red' }, {'name': 'Bob', 'color': 'green'}] </code></pre>
2
2009-09-28T06:15:14Z
1,485,721
<p>Given:</p> <pre><code>people = [{'name':'John', 'color':'red'}, {'name':'Bob', 'color':'green'}, {'name':'Tom', 'color':'blue'}] colors = ['blue', 'red', 'green'] </code></pre> <p>you can do something like this: </p> <pre><code>def people_by_color(people, colors): index = {} for person in people: if person.has_key('color'): index[person['color']] = person return [index.get(color) for color in colors] </code></pre> <p>If you're going to do this many times with the same list of dictionaries but different lists of colors you'll want to split the index building out and keep the index around so you don't need to rebuild it every time.</p>
0
2009-09-28T06:41:57Z
[ "python", "dictionary" ]
Return a list of dictionaries that match the corresponding list of values in python
1,485,660
<p>For example, this is my list of dictionaries: </p> <pre><code>[{'name': 'John', 'color': 'red' }, {'name': 'Bob', 'color': 'green'}, {'name': 'Tom', 'color': 'blue' }] </code></pre> <p>Based on the list <code>['blue', 'red', 'green']</code> I want to return the following:</p> <pre><code>[{'name': 'Tom', 'color': 'blue' }, {'name': 'John', 'color': 'red' }, {'name': 'Bob', 'color': 'green'}] </code></pre>
2
2009-09-28T06:15:14Z
1,485,722
<p>This might be a little naieve, but it works:</p> <pre><code>data = [ {'name':'John', 'color':'red'}, {'name':'Bob', 'color':'green'}, {'name':'Tom', 'color':'blue'} ] colors = ['blue', 'red', 'green'] result = [] for c in colors: result.extend([d for d in data if d['color'] == c]) print result </code></pre>
4
2009-09-28T06:42:11Z
[ "python", "dictionary" ]
Return a list of dictionaries that match the corresponding list of values in python
1,485,660
<p>For example, this is my list of dictionaries: </p> <pre><code>[{'name': 'John', 'color': 'red' }, {'name': 'Bob', 'color': 'green'}, {'name': 'Tom', 'color': 'blue' }] </code></pre> <p>Based on the list <code>['blue', 'red', 'green']</code> I want to return the following:</p> <pre><code>[{'name': 'Tom', 'color': 'blue' }, {'name': 'John', 'color': 'red' }, {'name': 'Bob', 'color': 'green'}] </code></pre>
2
2009-09-28T06:15:14Z
1,487,244
<p>You can <a href="http://docs.python.org/library/functions.html#sorted" rel="nofollow">sort</a> using any custom key function.</p> <pre><code>&gt;&gt;&gt; people = [ {'name': 'John', 'color': 'red'}, {'name': 'Bob', 'color': 'green'}, {'name': 'Tom', 'color': 'blue'}, ] &gt;&gt;&gt; colors = ['blue', 'red', 'green'] &gt;&gt;&gt; sorted(people, key=lambda person: colors.index(person['color'])) [{'color': 'blue', 'name': 'Tom'}, {'color': 'red', 'name': 'John'}, {'color': 'green', 'name': 'Bob'}] </code></pre> <p>list.index takes linear time though, so if the number of colors can grow, then convert to a faster key lookup.</p> <pre><code>&gt;&gt;&gt; colorkeys = dict((color, index) for index, color in enumerate(colors)) &gt;&gt;&gt; sorted(people, key=lambda person: colorkeys[person['color']]) [{'color': 'blue', 'name': 'Tom'}, {'color': 'red', 'name': 'John'}, {'color': 'green', 'name': 'Bob'}] </code></pre>
1
2009-09-28T14:09:36Z
[ "python", "dictionary" ]
Return a list of dictionaries that match the corresponding list of values in python
1,485,660
<p>For example, this is my list of dictionaries: </p> <pre><code>[{'name': 'John', 'color': 'red' }, {'name': 'Bob', 'color': 'green'}, {'name': 'Tom', 'color': 'blue' }] </code></pre> <p>Based on the list <code>['blue', 'red', 'green']</code> I want to return the following:</p> <pre><code>[{'name': 'Tom', 'color': 'blue' }, {'name': 'John', 'color': 'red' }, {'name': 'Bob', 'color': 'green'}] </code></pre>
2
2009-09-28T06:15:14Z
1,488,578
<p>Riffing on Harto's solution:</p> <pre><code>&gt;&gt;&gt; from pprint import pprint &gt;&gt;&gt; [{'color': 'red', 'name': 'John'}, ... {'color': 'green', 'name': 'Bob'}, ... {'color': 'blue', 'name': 'Tom'}] [{'color': 'red', 'name': 'John'}, {'color': 'green', 'name': 'Bob'}, {'color': 'blue', 'name': 'Tom'}] &gt;&gt;&gt; data = [ ... {'name':'John', 'color':'red'}, ... {'name':'Bob', 'color':'green'}, ... {'name':'Tom', 'color':'blue'} ... ] &gt;&gt;&gt; colors = ['blue', 'red', 'green'] &gt;&gt;&gt; result = [d for d in data for c in colors if d['color'] == c] &gt;&gt;&gt; pprint(result) [{'color': 'red', 'name': 'John'}, {'color': 'green', 'name': 'Bob'}, {'color': 'blue', 'name': 'Tom'}] &gt;&gt;&gt; </code></pre> <p>The main difference is in using a list comprehension to build <em>result</em>.</p> <p>Edit: What was I thinking? This clearly calls out for the use of the any() expression:</p> <pre><code>&gt;&gt;&gt; from pprint import pprint &gt;&gt;&gt; data = [{'name':'John', 'color':'red'}, {'name':'Bob', 'color':'green'}, {'name':'Tom', 'color':'blue'}] &gt;&gt;&gt; colors = ['blue', 'red', 'green'] &gt;&gt;&gt; result = [d for d in data if any(d['color'] == c for c in colors)] &gt;&gt;&gt; pprint(result) [{'color': 'red', 'name': 'John'}, {'color': 'green', 'name': 'Bob'}, {'color': 'blue', 'name': 'Tom'}] &gt;&gt;&gt; </code></pre>
1
2009-09-28T18:26:14Z
[ "python", "dictionary" ]
Behaviour of increment and decrement operators in Python
1,485,841
<p>I notice that a pre-increment/decrement operator can be applied on a variable (like <code>++count</code>). It compiles, but it does not actually change the value of the variable!</p> <p>What is the behavior of the pre-increment/decrement operators (++/--) in Python? </p> <p>Why does Python deviate from the behavior of these operators seen in C/C++?</p>
397
2009-09-28T07:33:19Z
1,485,854
<p><code>++</code> is not an operator. It is two <code>+</code> operators. The <code>+</code> operator is the <strong>identity</strong> operator, which does nothing. (Clarification: the <code>+</code> and <code>-</code> unary operators only work on numbers, but I presume that you wouldn't expect a hypothetical <code>++</code> operator to work on strings.)</p> <pre><code>++count </code></pre> <p>Parses as</p> <pre><code>+(+count) </code></pre> <p>Which translates to</p> <pre><code>count </code></pre> <p>You have to use the slightly longer <code>+=</code> operator to do what you want to do:</p> <pre><code>count += 1 </code></pre> <p>I suspect the <code>++</code> and <code>--</code> operators were left out for consistency and simplicity. I don't know the exact argument Guido van Rossum gave for the decision, but I can imagine a few arguments:</p> <ul> <li>Simpler parsing. Technically, parsing <code>++count</code> is ambiguous, as it could be <code>+</code>, <code>+</code>, <code>count</code> (two unary <code>+</code> operators) just as easily as it could be <code>++</code>, <code>count</code> (one unary <code>++</code> operator). It's not a significant syntactic ambiguity, but it does exist.</li> <li>Simpler language. <code>++</code> is nothing more than a synonym for <code>+= 1</code>. It was a shorthand invented because C compilers were stupid and didn't know how to optimize <code>a += 1</code> into the <code>inc</code> instruction most computers have. In this day of optimizing compilers and bytecode interpreted languages, adding operators to a language to allow programmers to optimize their code is usually frowned upon, especially in a language like Python that is designed to be consistent and readable.</li> <li>Confusing side-effects. One common newbie error in languages with <code>++</code> operators is mixing up the differences (both in precedence and in return value) between the pre- and post-incremend/decrement operators, and Python likes to eliminate language "gotcha"-s. The precedence issues of pre-/post-increment in C are pretty hairy, and incredibly easy to mess up.</li> </ul>
529
2009-09-28T07:39:36Z
[ "python", "operators", "increment", "decrement" ]
Behaviour of increment and decrement operators in Python
1,485,841
<p>I notice that a pre-increment/decrement operator can be applied on a variable (like <code>++count</code>). It compiles, but it does not actually change the value of the variable!</p> <p>What is the behavior of the pre-increment/decrement operators (++/--) in Python? </p> <p>Why does Python deviate from the behavior of these operators seen in C/C++?</p>
397
2009-09-28T07:33:19Z
1,486,086
<p>When you want to increment or decrement, you typically want to do that on an integer. Like so:</p> <pre><code>b++ </code></pre> <p>But in Python, integers are <strong>immutable</strong>. That is you can't change them. This is because the integer objects can be used under several names. Try this:</p> <pre><code>&gt;&gt;&gt; b = 5 &gt;&gt;&gt; a = 5 &gt;&gt;&gt; id(a) 162334512 &gt;&gt;&gt; id(b) 162334512 &gt;&gt;&gt; a is b True </code></pre> <p>a and b above are actually the same object. If you incremented a, you would also increment b. That's not what you want. So you have to reassign. Like this:</p> <pre><code>b = b + 1 </code></pre> <p>Or simpler:</p> <pre><code>b += 1 </code></pre> <p>Which will reassign b to b+1. That is not an increment operator, because it does not increment b, it reassigns it.</p> <p>In short: Python behaves differently here, because it is not C, and is not a low level wrapper around machine code, but a high-level dynamic language, where increments don't make sense, and also are not as necessary as in C, where you use them every time you have a loop, for example.</p>
251
2009-09-28T09:05:01Z
[ "python", "operators", "increment", "decrement" ]
Behaviour of increment and decrement operators in Python
1,485,841
<p>I notice that a pre-increment/decrement operator can be applied on a variable (like <code>++count</code>). It compiles, but it does not actually change the value of the variable!</p> <p>What is the behavior of the pre-increment/decrement operators (++/--) in Python? </p> <p>Why does Python deviate from the behavior of these operators seen in C/C++?</p>
397
2009-09-28T07:33:19Z
8,537,187
<blockquote> <p>In Python, a distinction between expressions and statements is rigidly enforced, in contrast to languages such as Common Lisp, Scheme, or Ruby.</p> </blockquote> <p><a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29#Expressions" rel="nofollow">Wikipedia</a></p> <p>So by introducing such operators, you would break the expression/statement split. </p> <p>For the same reason you can't write</p> <pre><code>if x = 0: y = 1 </code></pre> <p>as you can in some other languages where such distinction is not preserved.</p>
3
2011-12-16T16:33:46Z
[ "python", "operators", "increment", "decrement" ]
Behaviour of increment and decrement operators in Python
1,485,841
<p>I notice that a pre-increment/decrement operator can be applied on a variable (like <code>++count</code>). It compiles, but it does not actually change the value of the variable!</p> <p>What is the behavior of the pre-increment/decrement operators (++/--) in Python? </p> <p>Why does Python deviate from the behavior of these operators seen in C/C++?</p>
397
2009-09-28T07:33:19Z
11,210,198
<p>While the others answers are correct in so far as they show what a mere <code>+</code> usually does (namely, leave the number as it is, if it is one), they are incomplete in so far as they don't explain what happens.</p> <p>To be exact, <code>+x</code> evaluates to <code>x.__pos__()</code> and <code>++x</code> to <code>x.__pos__().__pos__()</code>.</p> <p>I could imagine a VERY weird class structure (Children, don't do this at home!) like this:</p> <pre><code>class ValueKeeper(object): def __init__(self, value): self.value = value def __str__(self): return str(self.value) class A(ValueKeeper): def __pos__(self): print 'called A.__pos__' return B(self.value - 3) class B(ValueKeeper): def __pos__(self): print 'called B.__pos__' return A(self.value + 19) x = A(430) print x, type(x) print +x, type(+x) print ++x, type(++x) print +++x, type(+++x) </code></pre>
30
2012-06-26T14:59:33Z
[ "python", "operators", "increment", "decrement" ]
Behaviour of increment and decrement operators in Python
1,485,841
<p>I notice that a pre-increment/decrement operator can be applied on a variable (like <code>++count</code>). It compiles, but it does not actually change the value of the variable!</p> <p>What is the behavior of the pre-increment/decrement operators (++/--) in Python? </p> <p>Why does Python deviate from the behavior of these operators seen in C/C++?</p>
397
2009-09-28T07:33:19Z
26,204,203
<p>Python does not have these operators, but if you really need them you can write a function having the same functionality.</p> <pre><code>def PreIncrement(name, local={}): #Equivalent to ++name if name in local: local[name]+=1 return local[name] globals()[name]+=1 return globals()[name] def PostIncrement(name, local={}): #Equivalent to name++ if name in local: local[name]+=1 return local[name]-1 globals()[name]+=1 return globals()[name]-1 </code></pre> <p>Usage:</p> <pre><code>x = 1 y = PreIncrement('x') #y and x are both 2 a = 1 b = PostIncrement('a') #b is 1 and a is 2 </code></pre> <p>Inside a function you have to add locals() as a second argument if you want to change local variable, otherwise it will try to change global.</p> <pre><code>x = 1 def test(): x = 10 y = PreIncrement('x') #y will be 2, local x will be still 10 and global x will be changed to 2 z = PreIncrement('x', locals()) #z will be 11, local x will be 11 and global x will be unaltered test() </code></pre> <p>Also with these functions you can do:</p> <pre><code>x = 1 print(PreIncrement('x')) #print(x+=1) is illegal! </code></pre> <p>But in my opinion following approach is much clearer:</p> <pre><code>x = 1 x+=1 print(x) </code></pre> <p>Decrement operators:</p> <pre><code>def PreDecrement(name, local={}): #Equivalent to --name if name in local: local[name]-=1 return local[name] globals()[name]-=1 return globals()[name] def PostDecrement(name, local={}): #Equivalent to name-- if name in local: local[name]-=1 return local[name]+1 globals()[name]-=1 return globals()[name]+1 </code></pre> <p>I used these functions in my module translating javascript to python.</p>
4
2014-10-05T15:37:15Z
[ "python", "operators", "increment", "decrement" ]
Behaviour of increment and decrement operators in Python
1,485,841
<p>I notice that a pre-increment/decrement operator can be applied on a variable (like <code>++count</code>). It compiles, but it does not actually change the value of the variable!</p> <p>What is the behavior of the pre-increment/decrement operators (++/--) in Python? </p> <p>Why does Python deviate from the behavior of these operators seen in C/C++?</p>
397
2009-09-28T07:33:19Z
30,335,713
<p>Yeah, I missed ++ and -- functionality as well. A few million lines of c code engrained that kind of thinking in my old head, and rather than fight it... Here's a class I cobbled up that implements:</p> <pre><code>pre- and post-increment, pre- and post-decrement, addition, subtraction, multiplication, division, results assignable as integer, printable, settable. </code></pre> <p>Here 'tis:</p> <pre><code>class counter(object): def __init__(self,v=0): self.set(v) def preinc(self): self.v += 1 return self.v def predec(self): self.v -= 1 return self.v def postinc(self): self.v += 1 return self.v - 1 def postdec(self): self.v -= 1 return self.v + 1 def __add__(self,addend): return self.v + addend def __sub__(self,subtrahend): return self.v - subtrahend def __mul__(self,multiplier): return self.v * multiplier def __div__(self,divisor): return self.v / divisor def __getitem__(self): return self.v def __str__(self): return str(self.v) def set(self,v): if type(v) != int: v = 0 self.v = v </code></pre> <p>You might use it like this:</p> <pre><code>c = counter() # defaults to zero for listItem in myList: # imaginary task doSomething(c.postinc(),listItem) # passes c, but becomes c+1 </code></pre> <p>...already having c, you could do this...</p> <pre><code>c.set(11) while c.predec() &gt; 0: print c </code></pre> <p>....or just...</p> <pre><code>d = counter(11) while d.predec() &gt; 0: print d </code></pre> <p>...and for (re-)assignment into integer...</p> <pre><code>c = counter(100) d = c + 223 # assignment as integer c = c + 223 # re-assignment as integer print type(c),c # &lt;type 'int'&gt; 323 </code></pre> <p>...while this will maintain c as type counter:</p> <pre><code>c = counter(100) c.set(c + 223) print type(c),c # &lt;class '__main__.counter'&gt; 323 </code></pre> <p>EDIT:</p> <p><strong>And then there's this bit of unexpected (and thoroughly unwanted) behavior</strong>,</p> <pre><code>c = counter(42) s = '%s: %d' % ('Expecting 42',c) # but getting non-numeric exception print s </code></pre> <p>...because inside that tuple, <strong>getitem</strong>() isn't what used, instead a reference to the object is passed to the formatting function. Sigh. So:</p> <pre><code>c = counter(42) s = '%s: %d' % ('Expecting 42',c.v) # and getting 42. print s </code></pre> <p>...or, more verbosely, and explicitly what we actually wanted to happen, although counter-indicated in actual form by the verbosity (use <code>c.v</code> instead)...</p> <pre><code>c = counter(42) s = '%s: %d' % ('Expecting 42',c.__getitem__()) # and getting 42. print s </code></pre>
1
2015-05-19T20:40:43Z
[ "python", "operators", "increment", "decrement" ]
Get django-paypal working with pycrypto?
1,485,903
<p>I would like to use the button encryption in django-paypal, but it requires M2Crypto which will not build on webfaction servers. Tech support at Webfaction told me that pycrypto is already installed on the system, but I am too dumb to translate from M2Crypto to pycrypto.</p> <p>Can anyone tell me how to convert the following to work with pycrypto (if possible)? This is just a small snip showing he encryption, I can post the entire function if needed.</p> <pre><code> s = SMIME.SMIME() s.load_key_bio(BIO.openfile(CERT), BIO.openfile(PUB_CERT)) p7 = s.sign(BIO.MemoryBuffer(plaintext), flags=SMIME.PKCS7_BINARY) x509 = X509.load_cert_bio(BIO.openfile(settings.PAYPAL_CERT)) sk = X509.X509_Stack() sk.push(x509) s.set_x509_stack(sk) s.set_cipher(SMIME.Cipher('des_ede3_cbc')) tmp = BIO.MemoryBuffer() p7.write_der(tmp) p7 = s.encrypt(tmp, flags=SMIME.PKCS7_BINARY) out = BIO.MemoryBuffer() p7.write(out) return out.read() </code></pre>
1
2009-09-28T07:53:53Z
1,486,435
<p>pycrypto is very incomplete. It does not support the padding schemes and formats that you need. Adding support for those formats is not trivial and will require a lot of time.</p>
1
2009-09-28T10:52:09Z
[ "python", "django", "encryption", "paypal" ]
Get django-paypal working with pycrypto?
1,485,903
<p>I would like to use the button encryption in django-paypal, but it requires M2Crypto which will not build on webfaction servers. Tech support at Webfaction told me that pycrypto is already installed on the system, but I am too dumb to translate from M2Crypto to pycrypto.</p> <p>Can anyone tell me how to convert the following to work with pycrypto (if possible)? This is just a small snip showing he encryption, I can post the entire function if needed.</p> <pre><code> s = SMIME.SMIME() s.load_key_bio(BIO.openfile(CERT), BIO.openfile(PUB_CERT)) p7 = s.sign(BIO.MemoryBuffer(plaintext), flags=SMIME.PKCS7_BINARY) x509 = X509.load_cert_bio(BIO.openfile(settings.PAYPAL_CERT)) sk = X509.X509_Stack() sk.push(x509) s.set_x509_stack(sk) s.set_cipher(SMIME.Cipher('des_ede3_cbc')) tmp = BIO.MemoryBuffer() p7.write_der(tmp) p7 = s.encrypt(tmp, flags=SMIME.PKCS7_BINARY) out = BIO.MemoryBuffer() p7.write(out) return out.read() </code></pre>
1
2009-09-28T07:53:53Z
1,509,462
<p>You may be able to set up a virtual machine locally and duplicate enough of the webfaction server environment to build it yourself. Then upload to somewhere on your pythonpath</p>
0
2009-10-02T13:18:50Z
[ "python", "django", "encryption", "paypal" ]
Get django-paypal working with pycrypto?
1,485,903
<p>I would like to use the button encryption in django-paypal, but it requires M2Crypto which will not build on webfaction servers. Tech support at Webfaction told me that pycrypto is already installed on the system, but I am too dumb to translate from M2Crypto to pycrypto.</p> <p>Can anyone tell me how to convert the following to work with pycrypto (if possible)? This is just a small snip showing he encryption, I can post the entire function if needed.</p> <pre><code> s = SMIME.SMIME() s.load_key_bio(BIO.openfile(CERT), BIO.openfile(PUB_CERT)) p7 = s.sign(BIO.MemoryBuffer(plaintext), flags=SMIME.PKCS7_BINARY) x509 = X509.load_cert_bio(BIO.openfile(settings.PAYPAL_CERT)) sk = X509.X509_Stack() sk.push(x509) s.set_x509_stack(sk) s.set_cipher(SMIME.Cipher('des_ede3_cbc')) tmp = BIO.MemoryBuffer() p7.write_der(tmp) p7 = s.encrypt(tmp, flags=SMIME.PKCS7_BINARY) out = BIO.MemoryBuffer() p7.write(out) return out.read() </code></pre>
1
2009-09-28T07:53:53Z
1,723,932
<p>I was able to get it to build. Here is all you need to do to make it happen:</p> <pre><code>cat &gt;&gt; ~/.pydistutils.cfg &lt;&lt; EOF [build_ext] include_dirs=/usr/include/openssl EOF easy_install-2.5 --install-dir=$HOME/lib/python2.5 --script-dir=$HOME/bin m2crypto </code></pre>
2
2009-11-12T17:24:22Z
[ "python", "django", "encryption", "paypal" ]
an auth method over HTTP(s) and/or REST with libraries for Python and/or C++
1,486,056
<p>Because I don't exactly know how any auth method works I want to write my own. So, what I want to do is the following. A client sends over HTTPs username+password(or SHA1(username+password)) the server gets the username+password and generates a big random number and stores it in a table called TOKENS(in some database) along with his IP, then it give the client that exact number. From now on, all the requests made by the client are accompanied by that TOKEN and if the TOKEN is not in the table TOKENS then any such request will fail. If the user hasn't made any requests in 2 hours the TOKEN will expire. If the user wants to log out he makes a request '/logout' to the server and the server deletes from the table TOKENS the entry containing his token but <em>ONLY</em> if the request to '/logout' originates from his IP.</p> <p>Maybe I am reinventing the wheel... this wouldn't be very good so my question is if there is some auth system that already works like this , what is it's name , does it have any OSS C++ libraries or Python libraries available ?</p> <p>I am not sure if finding such an auth system and configuring it would take longer than writing it myself, on the other hand I know security is a delicate problem so I am approaching this with some doubt that I am capable of writing something secure enough.</p> <p>Also, is there a good OSS C++ HTTP library ? I'm planning to write a RESTful Desktop client for a web app. Depending on the available libraries I will choose if I'll write it in C++ or Python.</p>
0
2009-09-28T08:57:06Z
1,486,073
<p>If you are implementing such authentication system over ordinary HTTP, you are vulnerable to replay attacks. Attacker could sniff out the SHA1(username+password) and just resend it every time he/she wants to log in. To make such authentication system work, you will need to use a <a href="http://en.wikipedia.org/wiki/Cryptographic%5Fnonce" rel="nofollow">nonce</a>.</p> <p>You might want to look at <a href="http://en.wikipedia.org/wiki/Digest%5Faccess%5Fauthentication" rel="nofollow">HTTP Digest authentication</a> for tips.</p>
0
2009-09-28T09:01:34Z
[ "c++", "python", "http", "authentication", "rest" ]
an auth method over HTTP(s) and/or REST with libraries for Python and/or C++
1,486,056
<p>Because I don't exactly know how any auth method works I want to write my own. So, what I want to do is the following. A client sends over HTTPs username+password(or SHA1(username+password)) the server gets the username+password and generates a big random number and stores it in a table called TOKENS(in some database) along with his IP, then it give the client that exact number. From now on, all the requests made by the client are accompanied by that TOKEN and if the TOKEN is not in the table TOKENS then any such request will fail. If the user hasn't made any requests in 2 hours the TOKEN will expire. If the user wants to log out he makes a request '/logout' to the server and the server deletes from the table TOKENS the entry containing his token but <em>ONLY</em> if the request to '/logout' originates from his IP.</p> <p>Maybe I am reinventing the wheel... this wouldn't be very good so my question is if there is some auth system that already works like this , what is it's name , does it have any OSS C++ libraries or Python libraries available ?</p> <p>I am not sure if finding such an auth system and configuring it would take longer than writing it myself, on the other hand I know security is a delicate problem so I am approaching this with some doubt that I am capable of writing something secure enough.</p> <p>Also, is there a good OSS C++ HTTP library ? I'm planning to write a RESTful Desktop client for a web app. Depending on the available libraries I will choose if I'll write it in C++ or Python.</p>
0
2009-09-28T08:57:06Z
1,607,123
<blockquote> <p>Because I don't exactly know how any auth method works I want to write my own</p> </blockquote> <p>How could you ever write something you don't understand? Learn at least one, the underlaying concepts are similar in every library.</p> <p>Python has <a href="http://what.repoze.org/docs/1.x/" rel="nofollow">repoze.what</a>.</p>
0
2009-10-22T13:17:54Z
[ "c++", "python", "http", "authentication", "rest" ]
an auth method over HTTP(s) and/or REST with libraries for Python and/or C++
1,486,056
<p>Because I don't exactly know how any auth method works I want to write my own. So, what I want to do is the following. A client sends over HTTPs username+password(or SHA1(username+password)) the server gets the username+password and generates a big random number and stores it in a table called TOKENS(in some database) along with his IP, then it give the client that exact number. From now on, all the requests made by the client are accompanied by that TOKEN and if the TOKEN is not in the table TOKENS then any such request will fail. If the user hasn't made any requests in 2 hours the TOKEN will expire. If the user wants to log out he makes a request '/logout' to the server and the server deletes from the table TOKENS the entry containing his token but <em>ONLY</em> if the request to '/logout' originates from his IP.</p> <p>Maybe I am reinventing the wheel... this wouldn't be very good so my question is if there is some auth system that already works like this , what is it's name , does it have any OSS C++ libraries or Python libraries available ?</p> <p>I am not sure if finding such an auth system and configuring it would take longer than writing it myself, on the other hand I know security is a delicate problem so I am approaching this with some doubt that I am capable of writing something secure enough.</p> <p>Also, is there a good OSS C++ HTTP library ? I'm planning to write a RESTful Desktop client for a web app. Depending on the available libraries I will choose if I'll write it in C++ or Python.</p>
0
2009-09-28T08:57:06Z
1,656,178
<p>I would highly recommend <a href="http://oauth.net/" rel="nofollow">OAuth</a> here, for which many open source <a href="http://oauth.net/code" rel="nofollow">libraries</a> are available.</p>
0
2009-11-01T02:09:34Z
[ "c++", "python", "http", "authentication", "rest" ]
Python PIL cannot locate my "libjpeg"
1,486,157
<p>I cannot use PIL because it cannot find my libjpeg!</p> <p>First, I installed PIL default. And when I ran the <code>selftest.py</code>, it gave me:</p> <pre><code>IOError: decoder jpeg not available 1 items had failures: 1 of 57 in selftest.testimage ***Test Failed*** 1 failures. *** 1 tests of 57 failed. </code></pre> <p>Then, I followed instructions online to change PIL's <code>setup.py</code> to</p> <pre><code>JPEG_ROOT = "/usr/lib" </code></pre> <p>Because when I <code>locate libjpeg</code>, this is what I get:</p> <pre><code>locate libjpeg /usr/lib/libjpeg.so.62 /usr/lib/libjpeg.so.62.0.0 /usr/lib64/libjpeg.so.62 /usr/lib64/libjpeg.so.62.0.0 /usr/share/doc/libjpeg-6b /usr/share/doc/libjpeg-6b/README /usr/share/doc/libjpeg-6b/usage.doc /var/cache/yum/base/packages/libjpeg-6b-37.i386.rpm /var/cache/yum/base/packages/libjpeg-6b-37.x86_64.rpm </code></pre> <p>So, I ran <code>setup.py install</code> again...and did <code>selftest.py</code>. And I still get the same error!</p>
11
2009-09-28T09:29:42Z
1,486,262
<p>You need the libjpeg headers as well, not only the library itself. Those packages are typically called something ending in headers or dev, depending on what distribution you have.</p>
3
2009-09-28T10:00:17Z
[ "python", "python-imaging-library" ]
Python PIL cannot locate my "libjpeg"
1,486,157
<p>I cannot use PIL because it cannot find my libjpeg!</p> <p>First, I installed PIL default. And when I ran the <code>selftest.py</code>, it gave me:</p> <pre><code>IOError: decoder jpeg not available 1 items had failures: 1 of 57 in selftest.testimage ***Test Failed*** 1 failures. *** 1 tests of 57 failed. </code></pre> <p>Then, I followed instructions online to change PIL's <code>setup.py</code> to</p> <pre><code>JPEG_ROOT = "/usr/lib" </code></pre> <p>Because when I <code>locate libjpeg</code>, this is what I get:</p> <pre><code>locate libjpeg /usr/lib/libjpeg.so.62 /usr/lib/libjpeg.so.62.0.0 /usr/lib64/libjpeg.so.62 /usr/lib64/libjpeg.so.62.0.0 /usr/share/doc/libjpeg-6b /usr/share/doc/libjpeg-6b/README /usr/share/doc/libjpeg-6b/usage.doc /var/cache/yum/base/packages/libjpeg-6b-37.i386.rpm /var/cache/yum/base/packages/libjpeg-6b-37.x86_64.rpm </code></pre> <p>So, I ran <code>setup.py install</code> again...and did <code>selftest.py</code>. And I still get the same error!</p>
11
2009-09-28T09:29:42Z
1,489,390
<p>There at least 3 header sets that you will want to install. 1 more if you want to deal with Tiff's</p> <p>freetype, libjpeg, zlib all of which will be in the following packages on CentOS:</p> <p>== 32 Bit: zlib-devel.i386 libjpeg-devel.i386 freetype-devel.i386</p> <p>== 64 Bit: zlib-devel.x86_64 libjpeg-devel.x86_64 freetype-devel.x86_64</p> <p>As you did before you will want to edit the following variables in the setup.py file:</p> <p>FREETYPE_ROOT JPEG_ROOT ZLIB_ROOT</p> <p>Setting there values to /usr/lib or /usr/lib64 based on your platform. Once done you will most likely want to run </p> <pre><code>python setup.py build --force python setup.py install </code></pre> <p>That will force rebuild all your lib for PIL and reinstall them raw.</p>
19
2009-09-28T21:09:49Z
[ "python", "python-imaging-library" ]
Python PIL cannot locate my "libjpeg"
1,486,157
<p>I cannot use PIL because it cannot find my libjpeg!</p> <p>First, I installed PIL default. And when I ran the <code>selftest.py</code>, it gave me:</p> <pre><code>IOError: decoder jpeg not available 1 items had failures: 1 of 57 in selftest.testimage ***Test Failed*** 1 failures. *** 1 tests of 57 failed. </code></pre> <p>Then, I followed instructions online to change PIL's <code>setup.py</code> to</p> <pre><code>JPEG_ROOT = "/usr/lib" </code></pre> <p>Because when I <code>locate libjpeg</code>, this is what I get:</p> <pre><code>locate libjpeg /usr/lib/libjpeg.so.62 /usr/lib/libjpeg.so.62.0.0 /usr/lib64/libjpeg.so.62 /usr/lib64/libjpeg.so.62.0.0 /usr/share/doc/libjpeg-6b /usr/share/doc/libjpeg-6b/README /usr/share/doc/libjpeg-6b/usage.doc /var/cache/yum/base/packages/libjpeg-6b-37.i386.rpm /var/cache/yum/base/packages/libjpeg-6b-37.x86_64.rpm </code></pre> <p>So, I ran <code>setup.py install</code> again...and did <code>selftest.py</code>. And I still get the same error!</p>
11
2009-09-28T09:29:42Z
7,839,593
<p>Today I was facing the same problem, and I've found the solution. Basically it involves remove the PIL, install lipjpeg through Fink and re-install the PIL.</p> <p>I wrote an <a href="http://marciogarcia.com/?p=289" rel="nofollow">article</a> telling step by step how to do that. If interesting check this out.</p>
0
2011-10-20T17:11:33Z
[ "python", "python-imaging-library" ]
Python PIL cannot locate my "libjpeg"
1,486,157
<p>I cannot use PIL because it cannot find my libjpeg!</p> <p>First, I installed PIL default. And when I ran the <code>selftest.py</code>, it gave me:</p> <pre><code>IOError: decoder jpeg not available 1 items had failures: 1 of 57 in selftest.testimage ***Test Failed*** 1 failures. *** 1 tests of 57 failed. </code></pre> <p>Then, I followed instructions online to change PIL's <code>setup.py</code> to</p> <pre><code>JPEG_ROOT = "/usr/lib" </code></pre> <p>Because when I <code>locate libjpeg</code>, this is what I get:</p> <pre><code>locate libjpeg /usr/lib/libjpeg.so.62 /usr/lib/libjpeg.so.62.0.0 /usr/lib64/libjpeg.so.62 /usr/lib64/libjpeg.so.62.0.0 /usr/share/doc/libjpeg-6b /usr/share/doc/libjpeg-6b/README /usr/share/doc/libjpeg-6b/usage.doc /var/cache/yum/base/packages/libjpeg-6b-37.i386.rpm /var/cache/yum/base/packages/libjpeg-6b-37.x86_64.rpm </code></pre> <p>So, I ran <code>setup.py install</code> again...and did <code>selftest.py</code>. And I still get the same error!</p>
11
2009-09-28T09:29:42Z
9,573,684
<p>I had the same issue. In my case, I need to set:</p> <pre><code>JPEG_ROOT="/usr/lib64/" </code></pre> <p>instead of:</p> <pre><code>JPEG_ROOT="/usr/lib/" </code></pre> <p>Good luck.</p>
3
2012-03-05T20:42:49Z
[ "python", "python-imaging-library" ]
Python PIL cannot locate my "libjpeg"
1,486,157
<p>I cannot use PIL because it cannot find my libjpeg!</p> <p>First, I installed PIL default. And when I ran the <code>selftest.py</code>, it gave me:</p> <pre><code>IOError: decoder jpeg not available 1 items had failures: 1 of 57 in selftest.testimage ***Test Failed*** 1 failures. *** 1 tests of 57 failed. </code></pre> <p>Then, I followed instructions online to change PIL's <code>setup.py</code> to</p> <pre><code>JPEG_ROOT = "/usr/lib" </code></pre> <p>Because when I <code>locate libjpeg</code>, this is what I get:</p> <pre><code>locate libjpeg /usr/lib/libjpeg.so.62 /usr/lib/libjpeg.so.62.0.0 /usr/lib64/libjpeg.so.62 /usr/lib64/libjpeg.so.62.0.0 /usr/share/doc/libjpeg-6b /usr/share/doc/libjpeg-6b/README /usr/share/doc/libjpeg-6b/usage.doc /var/cache/yum/base/packages/libjpeg-6b-37.i386.rpm /var/cache/yum/base/packages/libjpeg-6b-37.x86_64.rpm </code></pre> <p>So, I ran <code>setup.py install</code> again...and did <code>selftest.py</code>. And I still get the same error!</p>
11
2009-09-28T09:29:42Z
15,498,524
<p>You could also try to use <a href="https://pypi.python.org/pypi/Pillow" rel="nofollow">Pillow</a> instead of PIL. </p> <p>Pillow is a PIL fork to "foster active development of PIL". In versions 1.7.0 and 1.7.1 they made some changes to support multi-arch (see the <a href="https://pypi.python.org/pypi/Pillow/2.0.0#changelog-pillow" rel="nofollow">changelog</a>).</p>
1
2013-03-19T11:41:54Z
[ "python", "python-imaging-library" ]
pyinotify.ThreadedNotifier, process_* not called
1,486,271
<p>I have a problem with pyinotify: the methods <code>process_*()</code> of the <code>ProcessEvent</code> are not called</p> <p>The code</p> <pre><code>import sys, time, syslog from pyinotify import WatchManager, Notifier, ThreadedNotifier, ProcessEvent, EventsCodes from daemon import Daemon class PTmp(ProcessEvent): def process_IN_CREATE(self, event): syslog.syslog("creating: " + event.pathname) def process_IN_DELETE(self, event): syslog.syslog("creating: " + event.pathname) def process_default(self, event): syslog.syslog("default: " + event.pathname) class MyDaemon(Daemon): def run(self): syslog.openlog('archmind',syslog.LOG_PID,syslog.LOG_DAEMON) syslog.syslog('daemon started, entering loop') wm = WatchManager() mask = IN_DELETE | IN_CREATE notifier = ThreadedNotifier(wm, PTmp()) notifier.start() wdd = wm.add_watch('/tmp', mask, rec=True) while True: time.sleep(1) wm.rm_watch(wdd.values()) notifier.stop() syslog.syslog('exiting loop') syslog.closelog() if __name__ == "__main__": daemon = MyDaemon('/tmp/archmind.pid') if len(sys.argv) == 2: if 'start' == sys.argv[1]: daemon.start() elif 'stop' == sys.argv[1]: daemon.stop() elif 'restart' == sys.argv[1]: daemon.restart() else: print "Unknown command" sys.exit(2) sys.exit(0) else: print "usage: %s start|stop|restart" % sys.argv[0] sys.exit(2) </code></pre> <p>Everything else is logged. inofity works correctly, I have tested it with inotifywait. What may I be missing?</p>
3
2009-09-28T10:02:14Z
1,486,845
<p>The problem was missing the import of IN_*, which has to be done manually. I've found that out after calling </p> <pre><code>daemon.run() </code></pre> <p>instead of </p> <pre><code>daemon.start() </code></pre> <p>thus making the script run in foreground.</p>
1
2009-09-28T12:50:21Z
[ "python", "inotify", "pyinotify" ]
pyinotify.ThreadedNotifier, process_* not called
1,486,271
<p>I have a problem with pyinotify: the methods <code>process_*()</code> of the <code>ProcessEvent</code> are not called</p> <p>The code</p> <pre><code>import sys, time, syslog from pyinotify import WatchManager, Notifier, ThreadedNotifier, ProcessEvent, EventsCodes from daemon import Daemon class PTmp(ProcessEvent): def process_IN_CREATE(self, event): syslog.syslog("creating: " + event.pathname) def process_IN_DELETE(self, event): syslog.syslog("creating: " + event.pathname) def process_default(self, event): syslog.syslog("default: " + event.pathname) class MyDaemon(Daemon): def run(self): syslog.openlog('archmind',syslog.LOG_PID,syslog.LOG_DAEMON) syslog.syslog('daemon started, entering loop') wm = WatchManager() mask = IN_DELETE | IN_CREATE notifier = ThreadedNotifier(wm, PTmp()) notifier.start() wdd = wm.add_watch('/tmp', mask, rec=True) while True: time.sleep(1) wm.rm_watch(wdd.values()) notifier.stop() syslog.syslog('exiting loop') syslog.closelog() if __name__ == "__main__": daemon = MyDaemon('/tmp/archmind.pid') if len(sys.argv) == 2: if 'start' == sys.argv[1]: daemon.start() elif 'stop' == sys.argv[1]: daemon.stop() elif 'restart' == sys.argv[1]: daemon.restart() else: print "Unknown command" sys.exit(2) sys.exit(0) else: print "usage: %s start|stop|restart" % sys.argv[0] sys.exit(2) </code></pre> <p>Everything else is logged. inofity works correctly, I have tested it with inotifywait. What may I be missing?</p>
3
2009-09-28T10:02:14Z
8,779,752
<p>masks are defined in EventCodes.ALL_FLAGS</p> <pre><code> mask = EventsCodes.ALL_FLAGS['IN_DELETE'] mask = EventsCodes.ALL_FLAGS['ALL_EVENTS'] </code></pre>
1
2012-01-08T17:47:04Z
[ "python", "inotify", "pyinotify" ]
Parsing commandline output progression containing carriage returns in real time with python
1,486,305
<p>I am able to transform carriage returns into new lines. The problem however is to get it running in nearly 'real time'. It will be quite stupid looking if progres bar only values are 0 and 100 :-)</p> <p>This code returns output at once:</p> <pre><code>import subprocess p = subprocess.Popen(['mplayer', '/home/user/sample.mkv'], stdout=subprocess.PIPE).communicate()[0] for line in p.splitlines(): if line.strip(): print line </code></pre>
1
2009-09-28T10:13:33Z
1,486,561
<p>You need to do two things:</p> <ol> <li><p>You must make sure that <code>mplayer</code> flushes the output for every line (should happen with progress output that gets printed into the same line).</p></li> <li><p>You must read the output line by line. Instead of calling <code>communicate()</code>, you must close the <code>p.stdin</code> and then read <code>p.stdout</code> until EOF.</p></li> </ol>
-1
2009-09-28T11:26:35Z
[ "python", "parsing", "real-time", "carriage-return" ]
Parsing commandline output progression containing carriage returns in real time with python
1,486,305
<p>I am able to transform carriage returns into new lines. The problem however is to get it running in nearly 'real time'. It will be quite stupid looking if progres bar only values are 0 and 100 :-)</p> <p>This code returns output at once:</p> <pre><code>import subprocess p = subprocess.Popen(['mplayer', '/home/user/sample.mkv'], stdout=subprocess.PIPE).communicate()[0] for line in p.splitlines(): if line.strip(): print line </code></pre>
1
2009-09-28T10:13:33Z
1,486,925
<p>You are in for a world of pain with buffering in my experience. The reason being is that the standard C library will detect stdout isn't connected to a terminal and use more buffering. There is nothing you can do about that except hack the source of <code>mplayer</code>.</p> <p>If you use <a href="http://pexpect.sourceforge.net/pexpect.html" rel="nofollow">python-pexpect</a> though, it will start your subprocess using pseudo-ttys which the C library believes to be a terminal and it won't reset the buffering.</p> <p>It is very easy to make subprocess deadlock when doing this sort of thing too which is another problem python-pexpect gets over.</p>
1
2009-09-28T13:07:28Z
[ "python", "parsing", "real-time", "carriage-return" ]
Parsing commandline output progression containing carriage returns in real time with python
1,486,305
<p>I am able to transform carriage returns into new lines. The problem however is to get it running in nearly 'real time'. It will be quite stupid looking if progres bar only values are 0 and 100 :-)</p> <p>This code returns output at once:</p> <pre><code>import subprocess p = subprocess.Popen(['mplayer', '/home/user/sample.mkv'], stdout=subprocess.PIPE).communicate()[0] for line in p.splitlines(): if line.strip(): print line </code></pre>
1
2009-09-28T10:13:33Z
1,487,556
<p><a href="http://pexpect.sourceforge.net/pexpect.html" rel="nofollow">pexpect</a> anywhere but Windows, and <a href="http://sage.math.washington.edu/home/goreckc/sage/wexpect/" rel="nofollow">wexpect</a> on Windows, are always my recommendations when you need to "defeat buffering" and read a subprocess's output "in near real-time", as you put it. Since the subprocess you're running most likely buffers its output differently when it's outputting to a terminal vs. anything else (as that's the normal behavior of the C runtime libraries), you need to trick it into believing it IS outputting to a terminal rather than to your program, and that's what <code>pexpect</code> achieves (by building a pseudo-terminal via the lower-level <code>pty</code> module). I'm actually amazed that <code>wexpect</code> was able to do much the same on Windows, yet, while occasionally imperfect, it does also appear to work;-).</p>
2
2009-09-28T15:04:19Z
[ "python", "parsing", "real-time", "carriage-return" ]
Parsing commandline output progression containing carriage returns in real time with python
1,486,305
<p>I am able to transform carriage returns into new lines. The problem however is to get it running in nearly 'real time'. It will be quite stupid looking if progres bar only values are 0 and 100 :-)</p> <p>This code returns output at once:</p> <pre><code>import subprocess p = subprocess.Popen(['mplayer', '/home/user/sample.mkv'], stdout=subprocess.PIPE).communicate()[0] for line in p.splitlines(): if line.strip(): print line </code></pre>
1
2009-09-28T10:13:33Z
1,501,457
<p>Ok, Thanks! I will keep on eye for pexpect. But I found out that there is cosplatform way to do it: PyQt4 and QProcess. While it is not certainly solution for every program, it certainly fits for Qt4 frontend application :)</p>
0
2009-10-01T01:20:42Z
[ "python", "parsing", "real-time", "carriage-return" ]
Evaluating into two or more lists
1,486,558
<p>Howdy, codeboys and codegirls!</p> <p>I have came across a simple problem with seemingly easy solution. But being a Python neophyte I feel that there is a better approach somewhere.</p> <p>Say you have a list of mixed strings. There are two basic types of strings in the sack - ones with "=" in them (a=potato) and ones without (Lady Jane). What you need is to sort them into two lists.</p> <p>The obvious approach is to:</p> <pre><code>for arg in arguments: if '=' in arg: equal.append(arg) else: plain.append(arg) </code></pre> <p>Is there any other, more elegant way into it? Something like:</p> <pre><code>equal = [arg for arg in arguments if '=' in arg] </code></pre> <p>but to sort into multiple lists?</p> <p>And what if you have more than one type of data?</p>
5
2009-09-28T11:24:59Z
1,486,574
<p>Try</p> <pre><code>for arg in arguments: lst = equal if '=' in arg else plain lst.append(arg) </code></pre> <p>or (holy ugly)</p> <pre><code>for arg in arguments: (equal if '=' in arg else plain).append(arg) </code></pre> <p>A third option: Create a class which offers <code>append()</code> and which sorts into several lists.</p>
4
2009-09-28T11:30:21Z
[ "python", "list" ]
Evaluating into two or more lists
1,486,558
<p>Howdy, codeboys and codegirls!</p> <p>I have came across a simple problem with seemingly easy solution. But being a Python neophyte I feel that there is a better approach somewhere.</p> <p>Say you have a list of mixed strings. There are two basic types of strings in the sack - ones with "=" in them (a=potato) and ones without (Lady Jane). What you need is to sort them into two lists.</p> <p>The obvious approach is to:</p> <pre><code>for arg in arguments: if '=' in arg: equal.append(arg) else: plain.append(arg) </code></pre> <p>Is there any other, more elegant way into it? Something like:</p> <pre><code>equal = [arg for arg in arguments if '=' in arg] </code></pre> <p>but to sort into multiple lists?</p> <p>And what if you have more than one type of data?</p>
5
2009-09-28T11:24:59Z
1,486,611
<p>You can use <a href="http://docs.python.org/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby()</code></a> for this:</p> <pre><code>import itertools f = lambda x: '=' in x groups = itertools.groupby(sorted(data, key=f), key=f) for k, g in groups: print k, list(g) </code></pre>
4
2009-09-28T11:39:45Z
[ "python", "list" ]
Evaluating into two or more lists
1,486,558
<p>Howdy, codeboys and codegirls!</p> <p>I have came across a simple problem with seemingly easy solution. But being a Python neophyte I feel that there is a better approach somewhere.</p> <p>Say you have a list of mixed strings. There are two basic types of strings in the sack - ones with "=" in them (a=potato) and ones without (Lady Jane). What you need is to sort them into two lists.</p> <p>The obvious approach is to:</p> <pre><code>for arg in arguments: if '=' in arg: equal.append(arg) else: plain.append(arg) </code></pre> <p>Is there any other, more elegant way into it? Something like:</p> <pre><code>equal = [arg for arg in arguments if '=' in arg] </code></pre> <p>but to sort into multiple lists?</p> <p>And what if you have more than one type of data?</p>
5
2009-09-28T11:24:59Z
1,486,663
<p>Another approach is to use the <code>filter</code> function, although it's not the most efficient solution.<br /> Example:</p> <pre><code>&gt;&gt;&gt; l = ['a=s','aa','bb','=', 'a+b'] &gt;&gt;&gt; l2 = filter(lambda s: '=' in s, l) &gt;&gt;&gt; l3 = filter(lambda s: '+' in s, l) &gt;&gt;&gt; l2 ['a=s', '='] &gt;&gt;&gt; l3 ['a+b'] </code></pre>
1
2009-09-28T11:54:58Z
[ "python", "list" ]
Evaluating into two or more lists
1,486,558
<p>Howdy, codeboys and codegirls!</p> <p>I have came across a simple problem with seemingly easy solution. But being a Python neophyte I feel that there is a better approach somewhere.</p> <p>Say you have a list of mixed strings. There are two basic types of strings in the sack - ones with "=" in them (a=potato) and ones without (Lady Jane). What you need is to sort them into two lists.</p> <p>The obvious approach is to:</p> <pre><code>for arg in arguments: if '=' in arg: equal.append(arg) else: plain.append(arg) </code></pre> <p>Is there any other, more elegant way into it? Something like:</p> <pre><code>equal = [arg for arg in arguments if '=' in arg] </code></pre> <p>but to sort into multiple lists?</p> <p>And what if you have more than one type of data?</p>
5
2009-09-28T11:24:59Z
1,486,676
<pre><code>def which_list(s): if "=" in s: return 1 return 0 lists = [[], []] for arg in arguments: lists[which_list(arg)].append(arg) plain, equal = lists </code></pre> <p>If you have more types of data, add an if clause to <code>which_list</code>, and initialize <code>lists</code> to more empty lists.</p>
2
2009-09-28T11:57:39Z
[ "python", "list" ]
Evaluating into two or more lists
1,486,558
<p>Howdy, codeboys and codegirls!</p> <p>I have came across a simple problem with seemingly easy solution. But being a Python neophyte I feel that there is a better approach somewhere.</p> <p>Say you have a list of mixed strings. There are two basic types of strings in the sack - ones with "=" in them (a=potato) and ones without (Lady Jane). What you need is to sort them into two lists.</p> <p>The obvious approach is to:</p> <pre><code>for arg in arguments: if '=' in arg: equal.append(arg) else: plain.append(arg) </code></pre> <p>Is there any other, more elegant way into it? Something like:</p> <pre><code>equal = [arg for arg in arguments if '=' in arg] </code></pre> <p>but to sort into multiple lists?</p> <p>And what if you have more than one type of data?</p>
5
2009-09-28T11:24:59Z
1,486,714
<p>I would just go for two list comprehensions. While that does incur some overhead (two loops on the list), it is more Pythonic to use a list comprehension than to use a for. It's also (in my mind) much more readable than using all sorts of really cool tricks, but that less people know about.</p>
3
2009-09-28T12:12:03Z
[ "python", "list" ]
Evaluating into two or more lists
1,486,558
<p>Howdy, codeboys and codegirls!</p> <p>I have came across a simple problem with seemingly easy solution. But being a Python neophyte I feel that there is a better approach somewhere.</p> <p>Say you have a list of mixed strings. There are two basic types of strings in the sack - ones with "=" in them (a=potato) and ones without (Lady Jane). What you need is to sort them into two lists.</p> <p>The obvious approach is to:</p> <pre><code>for arg in arguments: if '=' in arg: equal.append(arg) else: plain.append(arg) </code></pre> <p>Is there any other, more elegant way into it? Something like:</p> <pre><code>equal = [arg for arg in arguments if '=' in arg] </code></pre> <p>but to sort into multiple lists?</p> <p>And what if you have more than one type of data?</p>
5
2009-09-28T11:24:59Z
1,486,820
<p>I put this together, and then see that Ned Batchelder was already on this same tack. I chose to package the splitting method instead of the list chooser, though, and to just use the implicit 0/1 values for False and True.</p> <pre><code>def split_on_condition(source, condition): ret = [],[] for s in source: ret[condition(s)].append(s) return ret src = "z=1;q=2;lady jane;y=a;lucy in the sky".split(';') plain,equal = split_on_condition(src, lambda s:'=' in s) </code></pre>
1
2009-09-28T12:43:58Z
[ "python", "list" ]
Evaluating into two or more lists
1,486,558
<p>Howdy, codeboys and codegirls!</p> <p>I have came across a simple problem with seemingly easy solution. But being a Python neophyte I feel that there is a better approach somewhere.</p> <p>Say you have a list of mixed strings. There are two basic types of strings in the sack - ones with "=" in them (a=potato) and ones without (Lady Jane). What you need is to sort them into two lists.</p> <p>The obvious approach is to:</p> <pre><code>for arg in arguments: if '=' in arg: equal.append(arg) else: plain.append(arg) </code></pre> <p>Is there any other, more elegant way into it? Something like:</p> <pre><code>equal = [arg for arg in arguments if '=' in arg] </code></pre> <p>but to sort into multiple lists?</p> <p>And what if you have more than one type of data?</p>
5
2009-09-28T11:24:59Z
1,486,870
<p>Your approach is the best one. For sorting just into two lists it can't get clearer than that. If you want it to be a one-liner, encapsulate it in a function:</p> <pre><code>def classify(arguments): equal, plain = [], [] for arg in arguments: if '=' in arg: equal.append(arg) else: plain.append(arg) return equal, plain equal, plain = classify(lst) </code></pre>
1
2009-09-28T12:54:19Z
[ "python", "list" ]
Evaluating into two or more lists
1,486,558
<p>Howdy, codeboys and codegirls!</p> <p>I have came across a simple problem with seemingly easy solution. But being a Python neophyte I feel that there is a better approach somewhere.</p> <p>Say you have a list of mixed strings. There are two basic types of strings in the sack - ones with "=" in them (a=potato) and ones without (Lady Jane). What you need is to sort them into two lists.</p> <p>The obvious approach is to:</p> <pre><code>for arg in arguments: if '=' in arg: equal.append(arg) else: plain.append(arg) </code></pre> <p>Is there any other, more elegant way into it? Something like:</p> <pre><code>equal = [arg for arg in arguments if '=' in arg] </code></pre> <p>but to sort into multiple lists?</p> <p>And what if you have more than one type of data?</p>
5
2009-09-28T11:24:59Z
1,486,915
<p>I would go for Edan's approach, e.g.</p> <pre><code>equal = [arg for arg in arguments if '=' in arg] plain = [arg for arg in arguments if '=' not in arg] </code></pre>
2
2009-09-28T13:05:50Z
[ "python", "list" ]
Evaluating into two or more lists
1,486,558
<p>Howdy, codeboys and codegirls!</p> <p>I have came across a simple problem with seemingly easy solution. But being a Python neophyte I feel that there is a better approach somewhere.</p> <p>Say you have a list of mixed strings. There are two basic types of strings in the sack - ones with "=" in them (a=potato) and ones without (Lady Jane). What you need is to sort them into two lists.</p> <p>The obvious approach is to:</p> <pre><code>for arg in arguments: if '=' in arg: equal.append(arg) else: plain.append(arg) </code></pre> <p>Is there any other, more elegant way into it? Something like:</p> <pre><code>equal = [arg for arg in arguments if '=' in arg] </code></pre> <p>but to sort into multiple lists?</p> <p>And what if you have more than one type of data?</p>
5
2009-09-28T11:24:59Z
1,489,938
<p>I read somewhere here that you might be interested in a solution that will work for <em>more</em> than two identifiers (equals sign and space). </p> <p>The following solution just requires you update the <code>uniques</code> set with anything you would like to match, the results are placed in a dictionary of lists with the identifier as the key. </p> <pre><code>uniques = set('= ') matches = dict((key, []) for key in uniques) for arg in args: key = set(arg) &amp; uniques try: matches[key.pop()].append(arg) except KeyError: # code to handle where arg does not contain = or ' '. </code></pre> <p>Now the above code assumes that you will only have a single match for your identifier in your <code>arg</code>. I.e that you don't have an <code>arg</code> that looks like this <code>'John= equalspace'</code>. You will have to also think about how you would like to treat cases that don't match anything in the set (<code>KeyError</code> occurs.)</p>
2
2009-09-29T00:06:19Z
[ "python", "list" ]
Global statements v. variables available throughout a classes
1,486,708
<p>I try to avoid "global" statements in python and <a href="http://stackoverflow.com/questions/146557/do-you-use-the-global-statement-in-python">http://stackoverflow.com/questions/146557/do-you-use-the-global-statement-in-python</a> suggests this is a common view. Values go into a function through its arguments and come out through its return statement (or reading/writing files or exceptions or probably something else I'm forgetting).</p> <p>Within a class, self.variable statements are in effect global to each instance of the class. You can access the variable in any method in the class. </p> <p>Do the same reasons we should avoid globals apply within classes, so that we should only use values in methods that come in through its arguments? I'm especially thinking about long classes that can be just about an entire program. Does the encapsulation inherent in a class eliminate the concern? In any case, we should make inputs, outputs and side effects clear in comments?</p>
0
2009-09-28T12:08:46Z
1,486,759
<p>self.variable is not global to the class, it's global to the instance. There's a big difference:</p> <pre><code>class MyClass: def __init__(self, a): self.a = a mc1 = MyClass(1) mc2 = MyClass(2) assert mc1.a == 1 assert mc2.a == 2 </code></pre> <p>You should definitely use self to encapsulate data in your classes. </p> <p>That said, it is definitely possible to create huge overgrown classes that abuse instance variables in all the ways regular variables can be abused. This is where skill and craftsmanship come into play: properly dividing up your code into manageable chunks.</p>
1
2009-09-28T12:27:43Z
[ "python", "design" ]
Global statements v. variables available throughout a classes
1,486,708
<p>I try to avoid "global" statements in python and <a href="http://stackoverflow.com/questions/146557/do-you-use-the-global-statement-in-python">http://stackoverflow.com/questions/146557/do-you-use-the-global-statement-in-python</a> suggests this is a common view. Values go into a function through its arguments and come out through its return statement (or reading/writing files or exceptions or probably something else I'm forgetting).</p> <p>Within a class, self.variable statements are in effect global to each instance of the class. You can access the variable in any method in the class. </p> <p>Do the same reasons we should avoid globals apply within classes, so that we should only use values in methods that come in through its arguments? I'm especially thinking about long classes that can be just about an entire program. Does the encapsulation inherent in a class eliminate the concern? In any case, we should make inputs, outputs and side effects clear in comments?</p>
0
2009-09-28T12:08:46Z
1,486,913
<blockquote> <p>Do the same reasons we should avoid globals apply within classes, so that we should only use values in methods that come in through its arguments? I'm especially thinking about long classes that can be just about an entire program.</p> </blockquote> <p>Classes exist to couple behaviour with state. If you take away the state part (which is what you're suggesting) then you have no need for classes. Nothing wrong with that, of course - much good software has been written without object-orientation.</p> <p>Generally, if you're following the <a href="http://en.wikipedia.org/wiki/Single%5Fresponsibility%5Fprinciple" rel="nofollow">Single Responsibility Principle</a> when making your classes, then these variables will be typically used together by a class that needs access to most or all of them in each method. You don't pass them in explicitly because the class exclusively works with behaviour that could reasonably access the entire state.</p> <p>To put it another way, if you find yourself with a class that doesn't use half of its variables in a lot of its methods, that's probably a sign that you should split it into two classes.</p>
1
2009-09-28T13:05:29Z
[ "python", "design" ]
Global statements v. variables available throughout a classes
1,486,708
<p>I try to avoid "global" statements in python and <a href="http://stackoverflow.com/questions/146557/do-you-use-the-global-statement-in-python">http://stackoverflow.com/questions/146557/do-you-use-the-global-statement-in-python</a> suggests this is a common view. Values go into a function through its arguments and come out through its return statement (or reading/writing files or exceptions or probably something else I'm forgetting).</p> <p>Within a class, self.variable statements are in effect global to each instance of the class. You can access the variable in any method in the class. </p> <p>Do the same reasons we should avoid globals apply within classes, so that we should only use values in methods that come in through its arguments? I'm especially thinking about long classes that can be just about an entire program. Does the encapsulation inherent in a class eliminate the concern? In any case, we should make inputs, outputs and side effects clear in comments?</p>
0
2009-09-28T12:08:46Z
1,486,922
<p>Ideally, no instance-wide variables would be used and everything would be passed as a parameter and well-documented in comments. That being said, it can get very tedious to comment every little thing and method parameter lists can start to look ridiculous (unless you have a hierarchy of partially-applied methods). Pragmatically, a balance should be sought between using non-local variables and making everything excruciatingly explicit.</p> <p>There is at least one case where you have to have instance- or class-level variables and that's when an implementation-specific value has to be retained between method calls.</p> <p>Scalability and concurrency depend on minimization if not complete elimination of state and side effects except for the most local and exclusive of runtime scopes. OOP without objects or display classes (i.e., closures) would be procedural, yes. Languages are increasingly becoming multiparadigm, but a lot of them have a primary paradigm. C# is object oriented with functional features. F# is functional with objects. </p> <p>If the data is immutable, then instance variables are <em>always</em> okay in my books. </p>
-1
2009-09-28T13:07:07Z
[ "python", "design" ]
python multiprocessing proxy
1,486,835
<p>I have a 2 processes:</p> <p>the first process is <strong>manager.py</strong> starts in <strong>backgroung</strong>:</p> <pre><code>from multiprocessing.managers import SyncManager, BaseProxy from CompositeDict import * class CompositeDictProxy(BaseProxy): _exposed_ = ('addChild', 'setName') def addChild(self, child): return self._callmethod('addChild', [child]) def setName(self, name): return self._callmethod('setName', [name]) class Manager(SyncManager): def __init__(self): super(Manager, self).__init__(address=('127.0.0.1', 50000), authkey='abracadabra') def start_Manager(): Manager().get_server().serve_forever() if __name__=="__main__": Manager.register('get_plant', CompositeDict, proxytype=CompositeDictProxy) start_Manager() </code></pre> <p><hr /></p> <p>and the second is <strong>consumer.py</strong> supposed to use registered objects defined into the manager:</p> <pre><code>from manager import * import time import random class Consumer(): def __init__(self): Manager.register('get_plant') m = Manager() m.connect() plant = m.get_plant() #plant.setName('alfa') plant.addChild('beta') if __name__=="__main__": Consumer() </code></pre> <p><hr /></p> <p>Running the <strong>manager</strong> in background, and than the <strong>consumer</strong> I get the error message: <strong><em>RuntimeError: maximum recursion depth exceeded</em></strong>, when using <strong>addChild</strong> into the <strong>consumer</strong>, while I can correctly use <strong>setName</strong>.</p> <p>Methods <strong>addChild</strong> and <strong>setName</strong> belongs to <strong>CompositeDict</strong>, I suppose to be proxied.</p> <p>What's wrong? </p> <p><strong>CompositeDict</strong> overwrites native <strong>__getattr__**</strong> method and is involved in the error message. I suppose, in some way, it's not used the right one <strong>__getattr__</strong> method. If so how could I solve this problem?? </p> <p><hr /></p> <p>The detailed error message is:</p> <pre><code>Traceback (most recent call last): File "consumer.py", line 21, in &lt;module&gt; Consumer() File "consumer.py", line 17, in __init__ plant.addChild('beta') File "&lt;string&gt;", line 2, in addChild File "/usr/lib/python2.5/site-packages/multiprocessing-2.6.1.1-py2.5-linux-i686.egg/multiprocessing/managers.py", line 729, in _callmethod kind, result = conn.recv() File "/home/--/--/CompositeDict.py", line 99, in __getattr__ child = self.findChild(name) File "/home/--/--/CompositeDict.py", line 185, in findChild for child in self.getAllChildren(): File "/home/--/--/CompositeDict.py", line 167, in getAllChildren l.extend(child.getAllChildren()) File "/home/--/--/CompositeDict.py", line 165, in getAllChildren for child in self._children: File "/home/--/--/CompositeDict.py", line 99, in __getattr__ child = self.findChild(name) File "/home/--/--/CompositeDict.py", line 185, in findChild for child in self.getAllChildren(): File "/--/--/prove/CompositeDict.py", line 165, in getAllChildren for child in self._children: ... File "/home/--/--/CompositeDict.py", line 99, in __getattr__ child = self.findChild(name) File "/home/--/--/CompositeDict.py", line 185, in findChild for child in self.getAllChildren(): RuntimeError: maximum recursion depth exceeded </code></pre>
1
2009-09-28T12:47:28Z
1,487,717
<p>Besides fixing many other bugs in the above which I assume are accidental (<code>init</code> must be <code>__init__</code>, you're missing several instances of <code>self</code>, misindentation, etc, etc), the key bit is to make the registration in <code>manager.py</code> into:</p> <pre><code>Manager.register('get_plant', CompositeDict, proxytype=CompositeDictProxy) </code></pre> <p>no idea what you're trying to accomplish w/that <code>lambda</code> as the second arg, but the second arg must be the callable that makes the type you need, not one that makes a two-items tuple like you're using.</p>
1
2009-09-28T15:29:57Z
[ "python", "proxy", "multiprocessing", "composite" ]
Python: pass c++ object to a script, then invoke extending c++ function from script
1,487,001
<p>First of all, the problem is that program fails with double memory freeing ...</p> <p>The deal is: I have </p> <pre><code>FooCPlusPlus *obj; </code></pre> <p>and I pass it to my script. It works fine. Like this:</p> <pre><code>PyObject *pArgs, *pValue; pArgs = Py_BuildValue("((O))", obj); pValue = PyObject_CallObject(pFunc, pArgs); </code></pre> <p>where pFunc is a python function... So, my script has function, where I use obj. </p> <pre><code>def main(args) ... pythonObj = FooPython(args[0]) ... # hardcore calculation of "x" ... ... pythonObj.doWork(x) </code></pre> <p>Of course I've defined python class </p> <pre><code>class FooPython: def __init__(self, data): self._base = data def doWork(arg): import extend_module extend_module.bar(self._base, arg) </code></pre> <p>"Extend_module" is an extension c++ module where I've defined function "bar".</p> <p>I expected that "bar" function would work fine, but instead of it I got memory errors: "double memory free or corruption".</p> <p>Here is "bar" function:</p> <pre><code>static PyObject* bar(PyObject *self, PyObject *args) { PyObject *pyFooObject = 0; int arg; int ok = PyArg_ParseTuple(args,"Oi",&amp;pyRuleHandler, &amp;arg); if(!ok) return 0; void * temp = PyCObject_AsVoidPtr(pyFooObject); FooCPlusPlus* obj = static_cast&lt;FooCPlusPlus*&gt;(temp); obj-&gt;method(arg); // some c++ method return PyCObject_FromVoidPtr((void *) ruleHandler, NULL); } </code></pre> <p>It fails at "bar"'s return statement...</p>
0
2009-09-28T13:22:57Z
1,488,017
<p>Well, finally I know where the problem was:</p> <p>we should return from "bar" function input args:</p> <pre><code>return args; </code></pre> <p>instead of</p> <pre><code>return PyCObject_FromVoidPtr((void *) ruleHandler, NULL); </code></pre>
0
2009-09-28T16:30:23Z
[ "python", "reference-counting" ]
python/scapy mac flooding script
1,487,389
<p>I'm trying to make a small mac flood tool in python to fill my switches cam tables but i cant make the magic happen? can you see what im doing wrong? </p> <pre><code>from scapy.all import * while 1: dest_mac = RandMAC() src_mac = RandMAC() sendp(Ether(src=src_mac, dst=dest_mac)/ARP(op=2, psrc="0.0.0.0", hwsrc=src_mac, hwdst=dest_mac)/Padding(load="X"*18), verbose=0) </code></pre> <p>while the code seems to run fine it just dont do its job. to test it i used wireshark to look at the packets then ran THC's parasite "which works" and the packets are almost the same so im not sure what is going on. Thank you for any help.</p>
1
2009-09-28T14:35:52Z
3,515,056
<p>You can only use some mac address: a mac address is composed by six groups of two hexadecimal digits, separated by hyphens (-) or colons (:). The first three fields must be filled with some values, different for every vendor. If this fields are not set with any vendor code the server (or the client) will drop the packet. You can find mac vendors list on wireshark manuf file, or simply looking for it with google. You can check the address by typing "sudo ifcofig IFACE ether hw ADDRESS" in the terminal.</p>
1
2010-08-18T17:53:52Z
[ "python", "scapy" ]
python/scapy mac flooding script
1,487,389
<p>I'm trying to make a small mac flood tool in python to fill my switches cam tables but i cant make the magic happen? can you see what im doing wrong? </p> <pre><code>from scapy.all import * while 1: dest_mac = RandMAC() src_mac = RandMAC() sendp(Ether(src=src_mac, dst=dest_mac)/ARP(op=2, psrc="0.0.0.0", hwsrc=src_mac, hwdst=dest_mac)/Padding(load="X"*18), verbose=0) </code></pre> <p>while the code seems to run fine it just dont do its job. to test it i used wireshark to look at the packets then ran THC's parasite "which works" and the packets are almost the same so im not sure what is going on. Thank you for any help.</p>
1
2009-09-28T14:35:52Z
10,209,040
<p>Emada,</p> <p>Mac addresses are learned by switches by using the source address only so no need to worry about destination randomizing.</p> <p>I have tested this and it seems to work well..you might also want to try the sendpfast option for flooding, however in my testing here sendp seemed to work faster?</p> <pre><code>from scapy.all import * while 1: sendp(Ether(src=RandMAC(),dst="FF:FF:FF:FF:FF:FF")/ARP(op=2, psrc="0.0.0.0", hwdst="FF:FF:FF:FF:FF:FF")/Padding(load="X"*18))) </code></pre>
0
2012-04-18T12:06:57Z
[ "python", "scapy" ]
Time difference between system date and string, e.g. from directory name?
1,487,450
<p>I would like to write a small script that does the following (and that I can then run using my crontab):</p> <ul> <li><p>Look into a directory that contains directories whose names are in some date format, e.g. 30-10-09.</p></li> <li><p>Convert the directory name to the date it represents (of course, I could put this information as a string into a file in these directories, that doesn't matter to me).</p></li> <li><p>Compare each date with the current system time and find the one that has a specific time difference to the current system date, e.g. less than two days. </p></li> <li><p>Then, do something with the files in that directory (e.g., paste them together and send an email).</p></li> </ul> <p>I know a little bash scripting, but I don't know whether bash can itself handle this. I think I could do this in R, but the server where this needs to run doesn't have R. </p> <p>I'm curious anyway to learn a little bit of either Python or Ruby (both of which are on the server).</p> <p>Can someone point me in the right direction what might be the best way to do this?</p>
0
2009-09-28T14:45:52Z
1,487,702
<p>I would suggest using Python. You'll need the following functions:</p> <ul> <li>os.listdir gives you the directory contents, as a list of strings</li> <li><code>time.strptime(name, "%d-%m-%y")</code> will try to parse such a string, and return a time tuple. You get a ValueError exception if parsing fails.</li> <li>time.mktime will convert a time tuple into seconds since the epoch.</li> <li>time.time returns seconds since the epoch</li> <li>the smtplib module can send emails, assuming you know what SMTP server to use. Alternatively, you can run <code>/usr/lib/sendmail</code>, through the subprocess module (assuming <code>/usr/lib/sendmail</code> is correctly configured)</li> </ul>
1
2009-09-28T15:28:13Z
[ "python", "date", "scripting" ]
Pytom matplotlib 3d bar function
1,487,463
<p>How to add strings to the axes in Axes3D instead of numbers?</p> <p>I just started using the matplotlib. I have used Axes3dD to plot similar to the example given on their website (http://matplotlib.sourceforge.net/examples/mplot3d/bars3d_demo.html). Note that one must use the last verson (matplotlib 0.99.1), otherwise the axis gets a bit freaky. The example use this code:</p> <pre><code>from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = Axes3D(fig) for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]): xs = np.arange(20) ys = np.random.rand(20) ax.bar(xs, ys, zs=z, zdir='y', color=c, alpha=0.8) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') plt.show() </code></pre> <p>Now to my problem, I cant rename the axis to what I want. Instead of numbers i need to name the staples to string names. This I only want to do in two dimensions - the x dimension, and the z dimension (depth). I have tried to use this command:</p> <pre><code>ax.set_xticklabels('First staple',(0,0)) </code></pre> <p>I get no errormessage but nevertheless no sting. If anyone can answer this question I would be most delighted!</p>
1
2009-09-28T14:47:27Z
1,489,446
<p>Your actually on the right path there. but instead of a string you will want to pass a list or tuple to set_xticklabels(). You may also wish to adjust the center location for the label with set_xticks().</p> <p>You may also find this function of use get_xmajorticklabels(). It will return the rendered tick labels. So you may also be able to adjust the value from its results.</p>
2
2009-09-28T21:20:39Z
[ "python", "matplotlib" ]
Pytom matplotlib 3d bar function
1,487,463
<p>How to add strings to the axes in Axes3D instead of numbers?</p> <p>I just started using the matplotlib. I have used Axes3dD to plot similar to the example given on their website (http://matplotlib.sourceforge.net/examples/mplot3d/bars3d_demo.html). Note that one must use the last verson (matplotlib 0.99.1), otherwise the axis gets a bit freaky. The example use this code:</p> <pre><code>from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = Axes3D(fig) for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]): xs = np.arange(20) ys = np.random.rand(20) ax.bar(xs, ys, zs=z, zdir='y', color=c, alpha=0.8) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') plt.show() </code></pre> <p>Now to my problem, I cant rename the axis to what I want. Instead of numbers i need to name the staples to string names. This I only want to do in two dimensions - the x dimension, and the z dimension (depth). I have tried to use this command:</p> <pre><code>ax.set_xticklabels('First staple',(0,0)) </code></pre> <p>I get no errormessage but nevertheless no sting. If anyone can answer this question I would be most delighted!</p>
1
2009-09-28T14:47:27Z
1,489,727
<p>Also retrieve the axis data, work on that and set it back to the renderer, turned out to be much simpler for me ;) other than that, what NerdyNick says</p>
0
2009-09-28T22:43:30Z
[ "python", "matplotlib" ]