title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Search functionality for Django
932,255
<p>I'm developing a web app using Django, and I'll need to add search functionality soon. Search will be implemented for two models, one being an extension of the auth user class and another one with the fields <code>name</code>, <code>tags</code>, and <code>description</code>. So I guess nothing too scary here in context of searching text.</p> <p>For development I am using <a href="http://en.wikipedia.org/wiki/SQLite" rel="nofollow">SQLite</a> and as no database specific work has been done, I am at liberty to use any database in production. I'm thinking of choosing between <a href="http://en.wikipedia.org/wiki/PostgreSQL" rel="nofollow">PostgreSQL</a> or <a href="http://en.wikipedia.org/wiki/MySQL" rel="nofollow">MySQL</a>.</p> <p>I have gone through several posts on Internet about search solutions, nevertheless I'd like to get opinions for my simple case. Here are my questions: </p> <ol> <li><p>is full-text search an overkill in my case?</p></li> <li><p>is it better to rely on the database's full-text search support? If so, which database should I use?</p></li> <li><p>should I use an external search library, such as <a href="http://whoosh.ca/" rel="nofollow">Whoosh</a>, <a href="http://en.wikipedia.org/wiki/Sphinx%5F%28search%5Fengine%29" rel="nofollow">Sphinx</a>, or <a href="http://en.wikipedia.org/wiki/Xapian" rel="nofollow">Xapian</a>? If so, which one?</p></li> </ol> <p><strong>EDIT:</strong> <code>tags</code> is a Tagfield (from the django-tagging app) that sits on a m2m relationship. <code>description</code> is a field that holds HTML and has a max_length of 1024 bytes.</p>
2
2009-05-31T15:33:44Z
932,604
<p>Django has <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#search" rel="nofollow">full text searching</a> support in its QuerySet filters. Right now, if you only have two models that need searching, just make a view that searches the fields on both:</p> <pre><code>search_string = "+Django -jazz Python" first_models = FirstModel.objects.filter(headline__search=search_string) second_models = SecondModel.objects.filter(headline__search=search_string) </code></pre> <p>You could further filter them to make sure the results are unique, if necessary.</p> <p>Additionally, there is a <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#regex" rel="nofollow">regex filter</a> that may be even better for dealing with your html fields and tags since the regex can instruct the filter on exactly how to process any delimiters or markup.</p>
1
2009-05-31T18:38:27Z
[ "python", "database", "django", "search", "full-text-search" ]
Python: defining my own operators?
932,328
<p>I would like to define my own operator. Does python support such a thing?</p>
33
2009-05-31T16:01:39Z
932,333
<p>no, python comes with a predefined, yet overridable, <a href="http://docs.python.org/library/operator.html#mapping-operators-to-functions">set of operators</a>.</p>
27
2009-05-31T16:03:03Z
[ "python", "operators" ]
Python: defining my own operators?
932,328
<p>I would like to define my own operator. Does python support such a thing?</p>
33
2009-05-31T16:01:39Z
932,347
<p>No, you can't create new operators. However, if you are just evaluating expressions, you could process the string yourself and calculate the results of the new operators.</p>
22
2009-05-31T16:06:16Z
[ "python", "operators" ]
Python: defining my own operators?
932,328
<p>I would like to define my own operator. Does python support such a thing?</p>
33
2009-05-31T16:01:39Z
932,385
<p>If you intend to apply the operation on a particular class of objects, you could just override the operator that matches your function the closest... for instance, overriding <code>__eq__()</code> will override the <code>==</code> operator to return whatever you want. This works for almost all the operators.</p>
7
2009-05-31T16:27:43Z
[ "python", "operators" ]
Python: defining my own operators?
932,328
<p>I would like to define my own operator. Does python support such a thing?</p>
33
2009-05-31T16:01:39Z
932,580
<p>While technically you cannot define new operators in Python, this <a href="http://code.activestate.com/recipes/384122/">clever hack</a> works around this limitation. It allows you to define infix operators like this:</p> <pre><code># simple multiplication x=Infix(lambda x,y: x*y) print 2 |x| 4 # =&gt; 8 # class checking isa=Infix(lambda x,y: x.__class__==y.__class__) print [1,2,3] |isa| [] print [1,2,3] &lt;&lt;isa&gt;&gt; [] # =&gt; True </code></pre>
107
2009-05-31T18:18:32Z
[ "python", "operators" ]
Python: defining my own operators?
932,328
<p>I would like to define my own operator. Does python support such a thing?</p>
33
2009-05-31T16:01:39Z
20,667,084
<p>Sage provides this functionality, essentially using the "clever hack" described by @Ayman Hourieh, but incorporated into a module as a decorator to give a cleaner appearance and additional functionality – you can choose the operator to overload and therefore the order of evaluation.</p> <pre><code>from sage.misc.decorators import infix_operator @infix_operator('multiply') def dot(a,b): return a.dot_product(b) u=vector([1,2,3]) v=vector([5,4,3]) print(u *dot* v) # =&gt; 22 @infix_operator('or') def plus(x,y): return x*y print(2 |plus| 4) # =&gt; 6 </code></pre> <p>See <a href="http://www.sagemath.org/doc/reference/misc/sage/misc/decorators.html">the Sage documentation</a> and <a href="http://trac.sagemath.org/ticket/6245">this enhancement tracking ticket</a> for more information.</p>
5
2013-12-18T19:47:32Z
[ "python", "operators" ]
Python: defining my own operators?
932,328
<p>I would like to define my own operator. Does python support such a thing?</p>
33
2009-05-31T16:01:39Z
27,858,621
<p>Python 3.5 introduces the symbol <code>@</code> for an extra operator.</p> <p><a href="http://legacy.python.org/dev/peps/pep-0465/" rel="nofollow">PEP465</a> introduced this new operator for matrix multiplication, to simplify the notation of many numerical code. The operator will not be implemented for all types, but just for arrays-like-objects.</p> <p>You can support the operator for your classes/objects by implementing <code>__matmul__()</code>.</p> <p>The PEP leaves space for a different usage of the operator for non-arrays-like objects.</p> <p>Of course you can implement with <code>@</code> any sort of operation different from matrix multiplication also for arrays-like objects, but the user experience will be affected, because everybody will expect your data type to behave in a different way.</p>
3
2015-01-09T10:32:36Z
[ "python", "operators" ]
How can I get the next string, in alphanumeric ordering, in Python?
932,506
<p>I need a simple program that given a string, returns to me the next one in the alphanumeric ordering (or just the alphabetic ordering).</p> <pre><code>f("aaa")="aab" f("aaZ")="aba" </code></pre> <p>And so on.</p> <p>Is there a function for this in one of the modules already?</p>
5
2009-05-31T17:33:15Z
932,525
<p>Are the answers at <a href="http://stackoverflow.com/questions/604721/how-would-you-translate-this-from-perl-to-python/604777">http://stackoverflow.com/questions/604721/how-would-you-translate-this-from-perl-to-python/604777</a> sufficient? Not 100% what you're asking, but close...</p>
3
2009-05-31T17:42:06Z
[ "python", "string" ]
How can I get the next string, in alphanumeric ordering, in Python?
932,506
<p>I need a simple program that given a string, returns to me the next one in the alphanumeric ordering (or just the alphabetic ordering).</p> <pre><code>f("aaa")="aab" f("aaZ")="aba" </code></pre> <p>And so on.</p> <p>Is there a function for this in one of the modules already?</p>
5
2009-05-31T17:33:15Z
932,536
<p>I don't think there's a built-in function to do this. The following should work:</p> <pre><code>def next_string(s): strip_zs = s.rstrip('z') if strip_zs: return strip_zs[:-1] + chr(ord(strip_zs[-1]) + 1) + 'a' * (len(s) - len(strip_zs)) else: return 'a' * (len(s) + 1) </code></pre> <p>Explanation: you find the last character which is not a <code>z</code>, increment it, and replace all of the characters after it with <code>a</code>'s. If the entire string is <code>z</code>'s, then return a string of all <code>a</code>'s that is one longer.</p>
12
2009-05-31T17:46:17Z
[ "python", "string" ]
How can I get the next string, in alphanumeric ordering, in Python?
932,506
<p>I need a simple program that given a string, returns to me the next one in the alphanumeric ordering (or just the alphabetic ordering).</p> <pre><code>f("aaa")="aab" f("aaZ")="aba" </code></pre> <p>And so on.</p> <p>Is there a function for this in one of the modules already?</p>
5
2009-05-31T17:33:15Z
932,719
<p>A different, longer, but perhaps more readable and flexible solution:</p> <pre><code>def toval(s): """Converts an 'azz' string into a number""" v = 0 for c in s.lower(): v = v * 26 + ord(c) - ord('a') return v def tostr(v, minlen=0): """Converts a number into 'azz' string""" s = '' while v or len(s) &lt; minlen: s = chr(ord('a') + v % 26) + s v /= 26 return s def next(s, minlen=0): return tostr(toval(s) + 1, minlen) s = "" for i in range(100): s = next(s, 5) print s </code></pre> <p>You convert the string into a number where each letter represents a digit in base 26, increase the number by one and convert the number back into the string. This way you can do arbitrary math on values represented as strings of letters.</p> <p>The ''minlen'' parameter controls how many digits the result will have (since 0 == a == aaaaa).</p>
2
2009-05-31T19:51:51Z
[ "python", "string" ]
How can I get the next string, in alphanumeric ordering, in Python?
932,506
<p>I need a simple program that given a string, returns to me the next one in the alphanumeric ordering (or just the alphabetic ordering).</p> <pre><code>f("aaa")="aab" f("aaZ")="aba" </code></pre> <p>And so on.</p> <p>Is there a function for this in one of the modules already?</p>
5
2009-05-31T17:33:15Z
12,358,681
<p>Sucks that python doesn't have what ruby has: <code>String#next</code> So here's a shitty solution to deal with alpha-numerical strings:</p> <pre><code>def next_string(s): a1 = range(65, 91) # capital letters a2 = range(97, 123) # letters a3 = range(48, 58) # numbers char = ord(s[-1]) for a in [a1, a2, a3]: if char in a: if char + 1 in a: return s[:-1] + chr(char + 1) else: ns = next_string(s[:-1]) if s[:-1] else chr(a[0]) return ns + chr(a[0]) print next_string('abc') # abd print next_string('123') # 124 print next_string('ABC') # ABD # all together now print next_string('a0') # a1 print next_string('1a') # 1b print next_string('9A') # 9B # with carry-over print next_string('9') # 00 print next_string('z') # aa print next_string('Z') # AA # cascading carry-over print next_string('a9') # b0 print next_string('0z') # 1a print next_string('Z9') # AA0 print next_string('199') # 200 print next_string('azz') # baa print next_string('Zz9') # AAa0 print next_string('$a') # $b print next_string('$_') # None... fix it yourself </code></pre> <p>Not great. Kinda works for me.</p>
1
2012-09-10T20:06:12Z
[ "python", "string" ]
Expression up to comment or end of line
932,783
<p>Although this question is similar to <a href="http://stackoverflow.com/questions/175103/regex-to-match-url-end-of-line-or-character">this thread</a></p> <p>I think I might be doing something wrong at the time of constructing the code with the Regular Expression.</p> <p>I want to match anything in a line up to a comment ("#") or the end of the line (if it doesn't have a comment).</p> <p>The regex I am using is: <code>(.*)(#|$)</code></p> <p><code>(.*)</code> = Everything<br /> <code>(#|$)</code> = comment or end of line</p> <p>The code:</p> <pre><code>OPTION = re.compile(r'(?P&lt;value&gt;.*)(#|$)') file = open('file.txt') lines = file.read() for line in lines.split('\n'): get_match = OPTION.match(line) if get_match: line_value = get_match.group('value') print "Match= %s" % line_value </code></pre> <p>The above works but does not strip out the comment. If the file has a line like:</p> <pre><code>this is a line # and this is a comment </code></pre> <p>I still get the whole line when running the code. </p> <p>Am I missing additional values/information in the regular expression or do I need to have a change on the code?</p>
2
2009-05-31T20:23:33Z
932,786
<p>Here's the correct regex to do something like this:</p> <pre><code>([^#]*)(#.*)? </code></pre> <p>Also, why don't you just use</p> <pre><code>file = open('file.txt') for line in file: </code></pre>
3
2009-05-31T20:27:35Z
[ "python", "regex" ]
Expression up to comment or end of line
932,783
<p>Although this question is similar to <a href="http://stackoverflow.com/questions/175103/regex-to-match-url-end-of-line-or-character">this thread</a></p> <p>I think I might be doing something wrong at the time of constructing the code with the Regular Expression.</p> <p>I want to match anything in a line up to a comment ("#") or the end of the line (if it doesn't have a comment).</p> <p>The regex I am using is: <code>(.*)(#|$)</code></p> <p><code>(.*)</code> = Everything<br /> <code>(#|$)</code> = comment or end of line</p> <p>The code:</p> <pre><code>OPTION = re.compile(r'(?P&lt;value&gt;.*)(#|$)') file = open('file.txt') lines = file.read() for line in lines.split('\n'): get_match = OPTION.match(line) if get_match: line_value = get_match.group('value') print "Match= %s" % line_value </code></pre> <p>The above works but does not strip out the comment. If the file has a line like:</p> <pre><code>this is a line # and this is a comment </code></pre> <p>I still get the whole line when running the code. </p> <p>Am I missing additional values/information in the regular expression or do I need to have a change on the code?</p>
2
2009-05-31T20:23:33Z
932,805
<p>The * is greedy (consumes as much of the string as it can) and is thus consuming the entire line (past the # and to the end-of-line). Change ".*" to ".*?" and it will work.</p> <p>See the <a href="http://docs.python.org/howto/regex.html#repeating-things">Regular Expression HOWTO</a> for more information.</p>
6
2009-05-31T20:36:46Z
[ "python", "regex" ]
Expression up to comment or end of line
932,783
<p>Although this question is similar to <a href="http://stackoverflow.com/questions/175103/regex-to-match-url-end-of-line-or-character">this thread</a></p> <p>I think I might be doing something wrong at the time of constructing the code with the Regular Expression.</p> <p>I want to match anything in a line up to a comment ("#") or the end of the line (if it doesn't have a comment).</p> <p>The regex I am using is: <code>(.*)(#|$)</code></p> <p><code>(.*)</code> = Everything<br /> <code>(#|$)</code> = comment or end of line</p> <p>The code:</p> <pre><code>OPTION = re.compile(r'(?P&lt;value&gt;.*)(#|$)') file = open('file.txt') lines = file.read() for line in lines.split('\n'): get_match = OPTION.match(line) if get_match: line_value = get_match.group('value') print "Match= %s" % line_value </code></pre> <p>The above works but does not strip out the comment. If the file has a line like:</p> <pre><code>this is a line # and this is a comment </code></pre> <p>I still get the whole line when running the code. </p> <p>Am I missing additional values/information in the regular expression or do I need to have a change on the code?</p>
2
2009-05-31T20:23:33Z
932,846
<p>Use this regular expression:</p> <pre><code>^(.*?)(?:#|$) </code></pre> <p>With the non-greedy modifier (<code>?</code>), the <code>.*</code> expression will match as <em>soon</em> as either a hash sign or end-of-line is reached. The default is to match as <em>much</em> as possible, and that is why you always got the whole line.</p>
0
2009-05-31T20:56:14Z
[ "python", "regex" ]
Expression up to comment or end of line
932,783
<p>Although this question is similar to <a href="http://stackoverflow.com/questions/175103/regex-to-match-url-end-of-line-or-character">this thread</a></p> <p>I think I might be doing something wrong at the time of constructing the code with the Regular Expression.</p> <p>I want to match anything in a line up to a comment ("#") or the end of the line (if it doesn't have a comment).</p> <p>The regex I am using is: <code>(.*)(#|$)</code></p> <p><code>(.*)</code> = Everything<br /> <code>(#|$)</code> = comment or end of line</p> <p>The code:</p> <pre><code>OPTION = re.compile(r'(?P&lt;value&gt;.*)(#|$)') file = open('file.txt') lines = file.read() for line in lines.split('\n'): get_match = OPTION.match(line) if get_match: line_value = get_match.group('value') print "Match= %s" % line_value </code></pre> <p>The above works but does not strip out the comment. If the file has a line like:</p> <pre><code>this is a line # and this is a comment </code></pre> <p>I still get the whole line when running the code. </p> <p>Am I missing additional values/information in the regular expression or do I need to have a change on the code?</p>
2
2009-05-31T20:23:33Z
932,855
<p>@Can, @Benji and @ ΤΖΩΤΖΙΟΥ give three excellent solutions, and it's fun to time them to see how fast they match (that's what <code>timeit</code> is for -- fun meaningless micro-benchmarks;-). E.g.:</p> <pre><code>$ python -mtimeit -s'import re; r=re.compile(r"([^#]*)(#.*)?"); s="this is a line # and this is a comment"' 'm=r.match(s); g=m.group(1)' 100000 loops, best of 3: 2.02 usec per loop </code></pre> <p>vs</p> <pre><code>$ python -mtimeit -s'import re; r=re.compile(r"^(.*?)(?:#|$)"); s="this is a line # and this is a comment"' 'm=r.match(s); g=m.group(1)' 100000 loops, best of 3: 4.19 usec per loop </code></pre> <p>vs</p> <pre><code>$ python -mtimeit -s'import re; r=re.compile(r"(.*?)(#|$)"); s="this is a line # and this is a comment"' 'm=r.match(s); g=m.group(1)' 100000 loops, best of 3: 4.37 usec per loop </code></pre> <p>and the winner is... a mix of the patterns!-)</p> <pre><code>$ python -mtimeit -s'import re; r=re.compile(r"(.*?)(#.*)?"); s="this is a line # and this is a comment"' 'm=r.match(s); g=m.group(1)' 1000000 loops, best of 3: 1.73 usec per loop </code></pre> <p>Disclaimer: of course if this were a real benchmarking exercise and speed did truly matter, one would try on many different and relevant values for <code>s</code>, on tests beyond such a microbenchmark, etc, etc. But, I still find <code>timeit</code> an inexhaustible source of fun!-)</p>
1
2009-05-31T21:00:17Z
[ "python", "regex" ]
How to parse angular values using regular expressions
932,796
<p>I have very little experience using regular expressions and I need to parse an angle value expressed as bearings, using regular expressions, example:</p> <p>"N45°20'15.3"E" </p> <p>Which represents: 45 degrees, 20 minutes with 15.3 seconds, located at the NE quadrant.</p> <p>The restrictions are:</p> <ul> <li>The first character can be "N" or "S"</li> <li>The last character can be "E" or "W"</li> <li>0 &lt;= degrees &lt;= 59 </li> <li>0 &lt;= minutes &lt;= 59 </li> <li>0 &lt;= second &lt; 60, this can be ommited.</li> </ul> <p>Python preferably or any other language.</p> <p>Thanks</p>
3
2009-05-31T20:33:01Z
932,806
<p>A pattern you could use:</p> <pre><code>pat = r"^([NS])(\d+)°(\d+)'([\d.]*)\"?([EW])$" </code></pre> <p>one way to use it:</p> <pre><code>import re r = re.compile(pat) m = r.match(thestring) if m is None: print "%r does not match!" % thestring else: print "%r matches: %s" % (thestring, m.groups()) </code></pre> <p>as you'll notice, upon a match, <code>m.groups()</code> gives you the various parts of <code>thestring</code> matching each parentheses-enclosed "group" in <code>pat</code> -- a letter that's N or S, then one or more digits for the degrees, etc. I imagine that's what you mean by "parsing" here.</p>
4
2009-05-31T20:36:55Z
[ "python", "regex", "angle" ]
How to parse angular values using regular expressions
932,796
<p>I have very little experience using regular expressions and I need to parse an angle value expressed as bearings, using regular expressions, example:</p> <p>"N45°20'15.3"E" </p> <p>Which represents: 45 degrees, 20 minutes with 15.3 seconds, located at the NE quadrant.</p> <p>The restrictions are:</p> <ul> <li>The first character can be "N" or "S"</li> <li>The last character can be "E" or "W"</li> <li>0 &lt;= degrees &lt;= 59 </li> <li>0 &lt;= minutes &lt;= 59 </li> <li>0 &lt;= second &lt; 60, this can be ommited.</li> </ul> <p>Python preferably or any other language.</p> <p>Thanks</p>
3
2009-05-31T20:33:01Z
932,812
<p>Try this regular expression:</p> <pre><code>^([NS])([0-5]?\d)°([0-5]?\d)'(?:([0-5]?\d)(?:\.\d)?")?([EW])$ </code></pre> <p>It matches any string that …</p> <ul> <li><strong><code>^([NS])</code></strong>   begins with <code>N</code> or <code>S</code></li> <li><strong><code>([0-5]?\d)°</code></strong>   followed by a degree value, either a single digit between <code>0</code> and <code>9</code> (<code>\d</code>) or two digits with the first bewteen <code>0</code> and <code>5</code> (<code>[0-5]</code>) and the second <code>0</code> and <code>9</code>, thus between <code>0</code> and <code>59</code>, followed by <code>°</code></li> <li><strong><code>([0-5]?\d)'</code></strong>   followed by a minutes value (again between <code>0</code> and <code>59</code>) and <code>'</code></li> <li><strong><code>(?:([0-5]?\d)(?:\.\d)?")?</code></strong>   optionally followed by a seconds value and <code>"</code> sign, seconds value between <code>0</code> and <code>59</code> with an optional additional decimal point, and</li> <li><strong><code>([EW])$</code></strong>   ends with either <code>E</code> or <code>W</code>.</li> </ul> <p>If you don’t want to allow the values under ten to have preceeding zeros, change the <code>[0-5]</code> to <code>[1-5]</code>.</p>
8
2009-05-31T20:41:01Z
[ "python", "regex", "angle" ]
retrieving a variable's name in python at runtime?
932,818
<p>is there a way to know, during run-time, a variable's name (from the code) ? or do var names forgotten during compilation (byte-code or not) ?</p> <p>e.g.</p> <pre> >>> vari = 15 >>> print vari.~~name~~() 'vari' </pre> <p>note: i'm talking about plain data-type variables (int, str, list...)</p>
26
2009-05-31T20:44:07Z
932,829
<p>Variable names persist in the compiled code (that's how e.g. the <code>dir</code> built-in can work), but the mapping that's there goes from name to value, not vice versa. So if there are several variables all worth, for example, <code>23</code>, there's no way to tell them from each other base only on the value <code>23</code> .</p>
10
2009-05-31T20:48:26Z
[ "python" ]
retrieving a variable's name in python at runtime?
932,818
<p>is there a way to know, during run-time, a variable's name (from the code) ? or do var names forgotten during compilation (byte-code or not) ?</p> <p>e.g.</p> <pre> >>> vari = 15 >>> print vari.~~name~~() 'vari' </pre> <p>note: i'm talking about plain data-type variables (int, str, list...)</p>
26
2009-05-31T20:44:07Z
932,835
<p>Variable names don't get forgotten, you can access variables (and look which variables you have) by introspection, e.g. </p> <pre><code>&gt;&gt;&gt; i = 1 &gt;&gt;&gt; locals()["i"] 1 </code></pre> <p>However, because there are no pointers in Python, there's no way to reference a variable without actually writing its name. So if you wanted to print a variable name and its value, you could go via <code>locals()</code> or a similar function. (<code>[i]</code> becomes <code>[1]</code> and there's no way to retrieve the information that the <code>1</code> actually came from <code>i</code>.)</p>
28
2009-05-31T20:52:27Z
[ "python" ]
retrieving a variable's name in python at runtime?
932,818
<p>is there a way to know, during run-time, a variable's name (from the code) ? or do var names forgotten during compilation (byte-code or not) ?</p> <p>e.g.</p> <pre> >>> vari = 15 >>> print vari.~~name~~() 'vari' </pre> <p>note: i'm talking about plain data-type variables (int, str, list...)</p>
26
2009-05-31T20:44:07Z
932,906
<p>Just yesterday I saw a blog post with working code that does just this. Here's the link:</p> <p><a href="http://pyside.blogspot.com/2009/05/finding-objects-names.html" rel="nofollow">http://pyside.blogspot.com/2009/05/finding-objects-names.html</a></p>
0
2009-05-31T21:31:11Z
[ "python" ]
retrieving a variable's name in python at runtime?
932,818
<p>is there a way to know, during run-time, a variable's name (from the code) ? or do var names forgotten during compilation (byte-code or not) ?</p> <p>e.g.</p> <pre> >>> vari = 15 >>> print vari.~~name~~() 'vari' </pre> <p>note: i'm talking about plain data-type variables (int, str, list...)</p>
26
2009-05-31T20:44:07Z
1,101,302
<p>I tried the following link from the post above with no success: Googling returned this one.</p> <p><a href="http://pythonic.pocoo.org/2009/5/30/finding-objects-names" rel="nofollow">http://pythonic.pocoo.org/2009/5/30/finding-objects-names</a></p>
1
2009-07-09T00:56:42Z
[ "python" ]
retrieving a variable's name in python at runtime?
932,818
<p>is there a way to know, during run-time, a variable's name (from the code) ? or do var names forgotten during compilation (byte-code or not) ?</p> <p>e.g.</p> <pre> >>> vari = 15 >>> print vari.~~name~~() 'vari' </pre> <p>note: i'm talking about plain data-type variables (int, str, list...)</p>
26
2009-05-31T20:44:07Z
6,504,447
<p>This will work for simple data types (str, int, float, list etc.)</p> <pre><code>def my_print(var_str) : print var_str+':', globals()[var_str] </code></pre>
3
2011-06-28T09:35:49Z
[ "python" ]
retrieving a variable's name in python at runtime?
932,818
<p>is there a way to know, during run-time, a variable's name (from the code) ? or do var names forgotten during compilation (byte-code or not) ?</p> <p>e.g.</p> <pre> >>> vari = 15 >>> print vari.~~name~~() 'vari' </pre> <p>note: i'm talking about plain data-type variables (int, str, list...)</p>
26
2009-05-31T20:44:07Z
15,220,835
<p>Here is a function I use to print the value of variables, it works for local as well as globals:</p> <pre><code>import sys def print_var(var_name): calling_frame = sys._getframe().f_back var_val = calling_frame.f_locals.get(var_name, calling_frame.f_globals.get(var_name, None)) print (var_name+':', str(var_val)) </code></pre> <p>So the following code:</p> <pre><code>global_var = 123 def some_func(): local_var = 456 print_var("global_var") print_var("local_var") print_var("some_func") some_func() </code></pre> <p>produces:</p> <pre><code>global_var: 123 local_var: 456 some_func: &lt;function some_func at 0x10065b488&gt; </code></pre>
4
2013-03-05T09:59:55Z
[ "python" ]
retrieving a variable's name in python at runtime?
932,818
<p>is there a way to know, during run-time, a variable's name (from the code) ? or do var names forgotten during compilation (byte-code or not) ?</p> <p>e.g.</p> <pre> >>> vari = 15 >>> print vari.~~name~~() 'vari' </pre> <p>note: i'm talking about plain data-type variables (int, str, list...)</p>
26
2009-05-31T20:44:07Z
19,681,131
<p>You can do it, it's just not pretty.</p> <pre><code>import inspect, sys def addVarToDict(d, variable): lineNumber = inspect.currentframe().f_back.f_lineno with open(sys.argv[0]) as f: lines = f.read().split("\n") line = lines[lineNumber-1] varName = line.split("addVarToDict")[1].split("(")[1].split(",")[1].split(")")[0].strip() d[varName] = variable d = {} a=1 print d # {} addVarToDict(d,a) print d # {'a': 1} </code></pre>
2
2013-10-30T11:36:24Z
[ "python" ]
retrieving a variable's name in python at runtime?
932,818
<p>is there a way to know, during run-time, a variable's name (from the code) ? or do var names forgotten during compilation (byte-code or not) ?</p> <p>e.g.</p> <pre> >>> vari = 15 >>> print vari.~~name~~() 'vari' </pre> <p>note: i'm talking about plain data-type variables (int, str, list...)</p>
26
2009-05-31T20:44:07Z
29,522,250
<p>here a basic (maybe weird) function that shows the name of its argument... the idea is to analyze code and search for the calls to the function (added in the <strong>init</strong> method it could help to find the instance name, although with a more complex code analysis)</p> <pre><code>def display(var): import inspect, re callingframe = inspect.currentframe().f_back cntext = "".join(inspect.getframeinfo(callingframe, 5)[3]) #gets 5 lines m = re.search("display\s+\(\s+(\w+)\s+\)", cntext, re.MULTILINE) print m.group(1), type(var), var </code></pre> <p>please note: getting multiple lines from the calling code helps in case the call was split as in the below example:</p> <pre><code>display( my_var ) </code></pre> <p>but will produce unexpected result on this:</p> <pre><code>display(first_var) display(second_var) </code></pre> <p>If you don't have control on the format of your project you can still improve the code to detect and manage different situations... </p> <p>Overall I guess a static code analysis could produce a more reliable result, but I'm too lazy to check it now</p>
1
2015-04-08T18:11:55Z
[ "python" ]
XML characters in python xml.dom
933,004
<p>I am working on producing an xml document from python. We are using the xml.dom package to create the xml document. We are having a problem where we want to produce the character &amp;#x03c6; which is a &#x03c6;. However, when we put that string in a text node and call toxml() on it we get &amp;amp;#x03c6;. Our current solution is to use saxutils.unescape() on the result of toxml() but this is not ideal because we will have to parse the xml twice. </p> <p>Is there someway to get the dom package to recognize "&amp;#x03c6;" as an xml character?</p>
1
2009-05-31T22:16:45Z
933,091
<p>I think you need to use a Unicode string with <code>\u03c6</code> in it, because the <code>.data</code> field of a text node is supposed (as far as I understand) to be "parsed" data, not including XML entities (whence the <code>&amp;amp;</code> when made back into XML). If you want to ensure that, on output, non-ascii characters are expressed as entities, you could do:</p> <pre><code>import codecs def ent_replace(exc): if isinstance(exc, (UnicodeEncodeError, UnicodeTranslateError)): s = [] for c in exc.object[exc.start:exc.end]: s.append(u'&amp;#x%4.4x;' % ord(c)) return (''.join(s), exc.end) else: raise TypeError("can't handle %s" % exc.__name__) codecs.register_error('ent_replace', ent_replace) </code></pre> <p>and use <code>x.toxml().encode('ascii', 'ent_replace')</code>.</p>
1
2009-05-31T23:17:08Z
[ "python", "xml", "dom" ]
Python module globals versus __init__ globals
933,042
<p>Apologies, somewhat confused Python newbie question. Let's say I have a module called <code>animals.py</code>.......</p> <pre><code>globvar = 1 class dog: def bark(self): print globvar class cat: def miaow(self): print globvar </code></pre> <p>What is the difference between this and</p> <pre><code>class dog: def __init__(self): global globvar def bark(self): print globvar class cat: def miaow(self): print globvar </code></pre> <p>Assuming I always instantiate a dog first?</p> <p>I guess my question is, is there any difference? In the second example, does initiating the <code>dog</code> create a module level <code>globvar</code> just like in the first example, that will behave the same and have the same scope? </p>
4
2009-05-31T22:44:09Z
933,062
<p>No, the <code>global</code> statement only matters when you're <em>assigning</em> to a global variable within a method or function. So that <code>__init__</code> is irrelevant -- it does <strong>not</strong> create the global, because it's not assigning anything to it.</p>
4
2009-05-31T22:53:45Z
[ "python", "global" ]
Python module globals versus __init__ globals
933,042
<p>Apologies, somewhat confused Python newbie question. Let's say I have a module called <code>animals.py</code>.......</p> <pre><code>globvar = 1 class dog: def bark(self): print globvar class cat: def miaow(self): print globvar </code></pre> <p>What is the difference between this and</p> <pre><code>class dog: def __init__(self): global globvar def bark(self): print globvar class cat: def miaow(self): print globvar </code></pre> <p>Assuming I always instantiate a dog first?</p> <p>I guess my question is, is there any difference? In the second example, does initiating the <code>dog</code> create a module level <code>globvar</code> just like in the first example, that will behave the same and have the same scope? </p>
4
2009-05-31T22:44:09Z
933,084
<p><code>global</code> doesn't create a new variable, it just states that this name should refer to a global variable instead of a local one. Usually assignments to variables in a function/class/... refer to local variables. For example take a function like this:</p> <pre><code>def increment(n) # this creates a new local m m = n+1 return m </code></pre> <p>Here a new local variable <code>m</code> is created, even if there might be a global variable <code>m</code> already existing. This is what you usually want since some function call shouldn't unexpectedly modify variables in the surrounding scopes. If you indeed want to modify a global variable and not create a new local one, you can use the <code>global</code> keyword:</p> <pre><code>def increment(n) global increment_calls increment_calls += 1 return n+1 </code></pre> <p>In your case <code>global</code> in the constructor doesn't create any variables, further attempts to access <code>globvar</code> fail:</p> <pre><code>&gt;&gt;&gt; import animals &gt;&gt;&gt; d = animals.dog() &gt;&gt;&gt; d.bark() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "animals.py", line 7, in bark print globvar NameError: global name 'globvar' is not defined </code></pre> <p>But if you would actually assign a value to <code>globvar</code> in the constructor, a module-global variable would be created when you create a dog:</p> <pre><code>class dog: def __init__(self): global globvar globvar = 1 ... </code></pre> <p>Execution:</p> <pre><code>&gt;&gt;&gt; import animals &gt;&gt;&gt; d = animals.dog() &gt;&gt;&gt; d.bark() 1 &gt;&gt;&gt; print animals.globvar 1 </code></pre>
8
2009-05-31T23:12:13Z
[ "python", "global" ]
Python Regex combined with string substitution?
933,046
<p>I'm wondering if its possible to use string substitution along with the python re module?</p> <p>For example I'm using optparse and have a variable named options.hostname which will change each time the user executes the script. </p> <p>I have the following regex matching 3 strings in each line of the log file.</p> <pre><code> match = re.search (r'^\[(\d+)\] (SERVICE NOTIFICATION:).*(\bCRITICAL)', line) </code></pre> <p>I want to be able to perform string substitution by matching options.hostname as the last match group however I can't get any variations to work. Is this possible?</p> <pre><code> match = re.search (r'^\[(\d+)\] (SERVICE NOTIFICATION:).*(\bCRITICAL).*(s%), line) % options.hostname </code></pre>
-1
2009-05-31T22:47:24Z
933,060
<pre><code> match = re.search (r'^\[(\d+)\] (SERVICE NOTIFICATION:).*(\bCRITICAL).*(%s)' % options.hostname, line) </code></pre>
2
2009-05-31T22:52:15Z
[ "python", "regex" ]
Clipping FFT Matrix
933,088
<p>Audio processing is pretty new for me. And currently using Python Numpy for processing wave files. After calculating FFT matrix I am getting noisy power values for non-existent frequencies. I am interested in visualizing the data and accuracy is not a high priority. Is there a safe way to calculate the clipping value to remove these values, or should I use all FFT matrices for each sample set to come up with an average number ? </p> <p>regards</p> <p>Edit:</p> <pre><code> from numpy import * import wave import pymedia.audio.sound as sound import time, struct from pylab import ion, plot, draw, show fp = wave.open("500-200f.wav", "rb") sample_rate = fp.getframerate() total_num_samps = fp.getnframes() fft_length = 2048. num_fft = (total_num_samps / fft_length ) - 2 temp = zeros((num_fft,fft_length), float) for i in range(num_fft): tempb = fp.readframes(fft_length); data = struct.unpack("%dH"%(fft_length), tempb) temp[i,:] = array(data, short) pts = fft_length/2+1 data = (abs(fft.rfft(temp, fft_length)) / (pts))[:pts] x_axis = arange(pts)*sample_rate*.5/pts spec_range = pts plot(x_axis, data[0]) show() </code></pre> <p>Here is the plot in non-logarithmic scale, for synthetic wave file containing 500hz(fading out) + 200hz sine wave created using Goldwave.</p> <p><img src="http://i.stack.imgur.com/rr9OE.png"/></p>
2
2009-05-31T23:15:35Z
933,144
<p>FFT's because they are windowed and <a href="http://en.wikipedia.org/wiki/Sampling%5F(signal%5Fprocessing)" rel="nofollow">sampled cause <a href="http://en.wikipedia.org/wiki/Aliasing" rel="nofollow">aliasing</a> and sampling in the frequency domain as well. Filtering in the time domain is just multiplication in the frequency domain so you may want to just apply a filter which is just multiplying each frequency by a value for the function for the filter you are using. For example multiply by 1 in the passband and by zero every were else. The unexpected values are probably caused by aliasing where higher frequencies are being folded down to the ones you are seeing. The original signal needs to be band limited to half your sampling rate</a> or you will get <a href="http://en.wikipedia.org/wiki/Aliasing" rel="nofollow">aliasing</a>. Of more concern is aliasing that is distorting the area of interest because for this band of frequencies you want to know that the frequency is from the expected one. </p> <p>The other thing to keep in mind is that when you grab a piece of data from a wave file you are mathmatically multiplying it by a square wave. This causes a sinx/x to be convolved with the frequency response to minimize this you can multiply the original windowed signal with something like a <a href="http://en.wikipedia.org/wiki/Window%5Ffunction" rel="nofollow">Hanning window</a>. </p>
2
2009-05-31T23:49:36Z
[ "python", "audio", "signal-processing", "fft" ]
Clipping FFT Matrix
933,088
<p>Audio processing is pretty new for me. And currently using Python Numpy for processing wave files. After calculating FFT matrix I am getting noisy power values for non-existent frequencies. I am interested in visualizing the data and accuracy is not a high priority. Is there a safe way to calculate the clipping value to remove these values, or should I use all FFT matrices for each sample set to come up with an average number ? </p> <p>regards</p> <p>Edit:</p> <pre><code> from numpy import * import wave import pymedia.audio.sound as sound import time, struct from pylab import ion, plot, draw, show fp = wave.open("500-200f.wav", "rb") sample_rate = fp.getframerate() total_num_samps = fp.getnframes() fft_length = 2048. num_fft = (total_num_samps / fft_length ) - 2 temp = zeros((num_fft,fft_length), float) for i in range(num_fft): tempb = fp.readframes(fft_length); data = struct.unpack("%dH"%(fft_length), tempb) temp[i,:] = array(data, short) pts = fft_length/2+1 data = (abs(fft.rfft(temp, fft_length)) / (pts))[:pts] x_axis = arange(pts)*sample_rate*.5/pts spec_range = pts plot(x_axis, data[0]) show() </code></pre> <p>Here is the plot in non-logarithmic scale, for synthetic wave file containing 500hz(fading out) + 200hz sine wave created using Goldwave.</p> <p><img src="http://i.stack.imgur.com/rr9OE.png"/></p>
2
2009-05-31T23:15:35Z
933,271
<p>Simulated waveforms shouldn't show FFTs like your figure, so something is very wrong, and probably not with the FFT, but with the input waveform. The main problem in your plot is not the ripples, but the harmonics around 1000 Hz, and the subharmonic at 500 Hz. A simulated waveform shouldn't show any of this (for example, see my plot below).</p> <p>First, you probably want to just try plotting out the raw waveform, and this will likely point to an obvious problem. Also, it seems odd to have a wave unpack to unsigned shorts, i.e. "H", and especially after this to not have a large zero-frequency component.</p> <p>I was able to get a pretty close duplicate to your FFT by applying clipping to the waveform, as was suggested by both the subharmonic and higher harmonics (and Trevor). You could be introducing clipping either in the simulation or the unpacking. Either way, I bypassed this by creating the waveforms in numpy to start with.</p> <p>Here's what the proper FFT should look like (i.e. basically perfect, except for the broadening of the peaks due to the windowing)</p> <p><img src="http://i43.tinypic.com/1rvsqx.png" alt="alt text" /></p> <p>Here's one from a waveform that's been clipped (and is very similar to your FFT, from the subharmonic to the precise pattern of the three higher harmonics around 1000 Hz)</p> <p><img src="http://i44.tinypic.com/mt4avd.png" alt="alt text" /> Here's the code I used to generate these</p> <pre><code>from numpy import * from pylab import ion, plot, draw, show, xlabel, ylabel, figure sample_rate = 20000. times = arange(0, 10., 1./sample_rate) wfm0 = sin(2*pi*200.*times) wfm1 = sin(2*pi*500.*times) *(10.-times)/10. wfm = wfm0+wfm1 # int test #wfm *= 2**8 #wfm = wfm.astype(int16) #wfm = wfm.astype(float) # abs test #wfm = abs(wfm) # clip test #wfm = clip(wfm, -1.2, 1.2) fft_length = 5*2048. total_num_samps = len(times) num_fft = (total_num_samps / fft_length ) - 2 temp = zeros((num_fft,fft_length), float) for i in range(num_fft): temp[i,:] = wfm[i*fft_length:(i+1)*fft_length] pts = fft_length/2+1 data = (abs(fft.rfft(temp, fft_length)) / (pts))[:pts] x_axis = arange(pts)*sample_rate*.5/pts spec_range = pts plot(x_axis, data[2], linewidth=3) xlabel("freq (Hz)") ylabel('abs(FFT)') show() </code></pre>
3
2009-06-01T01:27:00Z
[ "python", "audio", "signal-processing", "fft" ]
Clipping FFT Matrix
933,088
<p>Audio processing is pretty new for me. And currently using Python Numpy for processing wave files. After calculating FFT matrix I am getting noisy power values for non-existent frequencies. I am interested in visualizing the data and accuracy is not a high priority. Is there a safe way to calculate the clipping value to remove these values, or should I use all FFT matrices for each sample set to come up with an average number ? </p> <p>regards</p> <p>Edit:</p> <pre><code> from numpy import * import wave import pymedia.audio.sound as sound import time, struct from pylab import ion, plot, draw, show fp = wave.open("500-200f.wav", "rb") sample_rate = fp.getframerate() total_num_samps = fp.getnframes() fft_length = 2048. num_fft = (total_num_samps / fft_length ) - 2 temp = zeros((num_fft,fft_length), float) for i in range(num_fft): tempb = fp.readframes(fft_length); data = struct.unpack("%dH"%(fft_length), tempb) temp[i,:] = array(data, short) pts = fft_length/2+1 data = (abs(fft.rfft(temp, fft_length)) / (pts))[:pts] x_axis = arange(pts)*sample_rate*.5/pts spec_range = pts plot(x_axis, data[0]) show() </code></pre> <p>Here is the plot in non-logarithmic scale, for synthetic wave file containing 500hz(fading out) + 200hz sine wave created using Goldwave.</p> <p><img src="http://i.stack.imgur.com/rr9OE.png"/></p>
2
2009-05-31T23:15:35Z
933,558
<p>It's worth mentioning for a 1D FFT that the first element (index <code>[0]</code>) contains the DC (zero-frequency) term, the elements <code>[1:N/2]</code> contain the positive frequencies and the elements <code>[N/2+1:N-1]</code> contain the negative frequencies. Since you didn't provide a code sample or additional information about the output of your FFT, I can't rule out the possibility that the "noisy power values at non-existent frequencies" aren't just the negative frequencies of your spectrum.</p> <p><hr /></p> <p><strong>EDIT</strong>: <a href="http://www.refactory.org/s/radix%5F2%5Fcooley%5Ftukey%5Ffast%5Ffourier%5Ftransform%5Ffft/view/latest" rel="nofollow">Here</a> is an example of a radix-2 FFT implemented in pure Python with a simple test routine that finds the FFT of a rectangular pulse, <code>[1.,1.,1.,1.,0.,0.,0.,0.]</code>. You can run the example on <a href="http://codepad.org" rel="nofollow">codepad</a> and see that the FFT of that sequence is</p> <pre><code>[0j, Negative frequencies (1+0.414213562373j), ^ 0j, | (1+2.41421356237j), | (4+0j), &lt;= DC term (1-2.41421356237j), | 0j, v (1-0.414213562373j)] Positive frequencies </code></pre> <p>Note that the code prints out the Fourier coefficients in order of ascending frequency, i.e. from the highest negative frequency up to DC, and then up to the highest positive frequency.</p>
1
2009-06-01T04:24:43Z
[ "python", "audio", "signal-processing", "fft" ]
Clipping FFT Matrix
933,088
<p>Audio processing is pretty new for me. And currently using Python Numpy for processing wave files. After calculating FFT matrix I am getting noisy power values for non-existent frequencies. I am interested in visualizing the data and accuracy is not a high priority. Is there a safe way to calculate the clipping value to remove these values, or should I use all FFT matrices for each sample set to come up with an average number ? </p> <p>regards</p> <p>Edit:</p> <pre><code> from numpy import * import wave import pymedia.audio.sound as sound import time, struct from pylab import ion, plot, draw, show fp = wave.open("500-200f.wav", "rb") sample_rate = fp.getframerate() total_num_samps = fp.getnframes() fft_length = 2048. num_fft = (total_num_samps / fft_length ) - 2 temp = zeros((num_fft,fft_length), float) for i in range(num_fft): tempb = fp.readframes(fft_length); data = struct.unpack("%dH"%(fft_length), tempb) temp[i,:] = array(data, short) pts = fft_length/2+1 data = (abs(fft.rfft(temp, fft_length)) / (pts))[:pts] x_axis = arange(pts)*sample_rate*.5/pts spec_range = pts plot(x_axis, data[0]) show() </code></pre> <p>Here is the plot in non-logarithmic scale, for synthetic wave file containing 500hz(fading out) + 200hz sine wave created using Goldwave.</p> <p><img src="http://i.stack.imgur.com/rr9OE.png"/></p>
2
2009-05-31T23:15:35Z
934,841
<p>I don't know enough from your question to actually answer anything specific.</p> <p>But here are a couple of things to try from my own experience writing FFTs:</p> <ul> <li>Make sure you are following Nyquist rule</li> <li>If you are viewing the linear output of the FFT... you will have trouble seeing your own signal and think everything is broken. Make sure you are looking at the dB of your FFT magnitude. (i.e. "plot(10*log10(abs(fft(x))))" )</li> <li>Create a unitTest for your FFT() function by feeding generated data like a pure tone. Then feed the same generated data to Matlab's FFT(). Do a absolute value diff between the two output data series and make sure the max absolute value difference is something like 10^-6 (i.e. the only difference is caused by small floating point errors)</li> <li>Make sure you are <a href="http://en.wikipedia.org/wiki/Window%5Ffunction#High-%5Fand%5Fmoderate-resolution%5Fwindows" rel="nofollow">windowing your data</a> </li> </ul> <p>If all of those three things work, then your fft is fine. And your input data is probably the issue.</p> <ul> <li>Check the input data to see if there is <img src="http://www.users.globalnet.co.uk/~bunce/clip.gif" alt="clipping" /></li> </ul> <p>Time doamin clipping shows up as mirror images of the signal in the frequency domain at specific regular intervals with less amplitude.</p>
1
2009-06-01T13:34:16Z
[ "python", "audio", "signal-processing", "fft" ]
Generic many-to-many relationships
933,092
<p>I'm trying to create a messaging system where a message's sender and recipients can be generic entities. This seems fine for the sender, where there is only object to reference (GenericForeignKey) but I can't figure out how to go about this for the recipients (GenericManyToManyKey ??)</p> <p>Below is a simplified example. PersonClient and CompanyClient inherit attributes from Client but have their own specific details. The last line is the sticking point. How do you allow message recipients to be a set of CompanyClients and PersonClients</p> <pre><code> class Client(models.Model): city = models.CharField(max_length=16) class Meta: abstract = True class PersonClient(Client): first_name = models.CharField(max_length=16) last_name = models.CharField(max_length=16) gender = models.CharField(max_length=1) class CompanyClient(Client): name = models.CharField(max_length=32) tax_no = PositiveIntegerField() class Message(models.Model): msg_body = models.CharField(max_length=1024) sender = models.ForeignKey(ContentType) recipients = models.ManyToManyField(ContentType) </code></pre>
34
2009-05-31T23:18:01Z
933,315
<p>You might get around this problem by simplifying your schema to include a single <code>Client</code> table with a flag to indicate what type of client it was, instead of having two separate models.</p> <pre><code>from django.db import models from django.utils.translation import ugettext_lazy as _ class Client(models.Model): PERSON, CORPORATION = range(2) CLIENT_TYPES = ( (PERSON, _('Person')), (CORPORATION, _('Corporation')), ) type = models.PositiveIntegerField(choices=CLIENT_TYPES, default=PERSON) city = models.CharField(max_length=16) first_name = models.CharField(max_length=16, blank=True, null=True) last_name = models.CharField(max_length=16, blank=True, null=True) corporate_name = models.CharField(max_length=16, blank=True, null=True) tax_no = models.PositiveIntegerField(blank=True, null=True) def save(self, *args, **kwargs): """ Does some validation ensuring that the person specific fields are filled in when self.type == self.PERSON, and corporation specific fields are filled in when self.type == self.CORPORATION ... """ # conditional save logic goes here super(Client, self).save(*args, **kwargs) </code></pre> <p>If you do things this way you might not have to mess around with Generic Foreign Keys at all. As an added convenience you can also write custom managers for the Client model like <code>Client.corporate.all()</code>, <code>Client.person.all()</code>, to return pre-filtered querysets containing only the type of clients that you want.</p> <p>This also may not be the best way of solving your problem. I'm just throwing it out there as one potential possibility. I don't know if there's conventional wisdom about smashing together two similar models and using a save override to ensure data integrity. It seems like it could be potentially problematic ... I'll let the community learn me on this one.</p>
4
2009-06-01T02:02:47Z
[ "python", "django", "generics", "django-models", "many-to-many" ]
Generic many-to-many relationships
933,092
<p>I'm trying to create a messaging system where a message's sender and recipients can be generic entities. This seems fine for the sender, where there is only object to reference (GenericForeignKey) but I can't figure out how to go about this for the recipients (GenericManyToManyKey ??)</p> <p>Below is a simplified example. PersonClient and CompanyClient inherit attributes from Client but have their own specific details. The last line is the sticking point. How do you allow message recipients to be a set of CompanyClients and PersonClients</p> <pre><code> class Client(models.Model): city = models.CharField(max_length=16) class Meta: abstract = True class PersonClient(Client): first_name = models.CharField(max_length=16) last_name = models.CharField(max_length=16) gender = models.CharField(max_length=1) class CompanyClient(Client): name = models.CharField(max_length=32) tax_no = PositiveIntegerField() class Message(models.Model): msg_body = models.CharField(max_length=1024) sender = models.ForeignKey(ContentType) recipients = models.ManyToManyField(ContentType) </code></pre>
34
2009-05-31T23:18:01Z
937,385
<p>You can implement this using generic relationships by manually creating the junction table between message and recipient:</p> <pre><code>from django.db import models from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType class Client(models.Model): city = models.CharField(max_length=16) # These aren't required, but they'll allow you do cool stuff # like "person.sent_messages.all()" to get all messages sent # by that person, and "person.received_messages.all()" to # get all messages sent to that person. # Well...sort of, since "received_messages.all()" will return # a queryset of "MessageRecipient" instances. sent_messages = generic.GenericRelation('Message', content_type_field='sender_content_type', object_id_field='sender_id' ) received_messages = generic.GenericRelation('MessageRecipient', content_type_field='recipient_content_type', object_id_field='recipient_id' ) class Meta: abstract = True class PersonClient(Client): first_name = models.CharField(max_length=16) last_name = models.CharField(max_length=16) gender = models.CharField(max_length=1) def __unicode__(self): return u'%s %s' % (self.last_name, self.first_name) class CompanyClient(Client): name = models.CharField(max_length=32) tax_no = models.PositiveIntegerField() def __unicode__(self): return self.name class Message(models.Model): sender_content_type = models.ForeignKey(ContentType) sender_id = models.PositiveIntegerField() sender = generic.GenericForeignKey('sender_content_type', 'sender_id') msg_body = models.CharField(max_length=1024) def __unicode__(self): return u'%s...' % self.msg_body[:25] class MessageRecipient(models.Model): message = models.ForeignKey(Message) recipient_content_type = models.ForeignKey(ContentType) recipient_id = models.PositiveIntegerField() recipient = generic.GenericForeignKey('recipient_content_type', 'recipient_id') def __unicode__(self): return u'%s sent to %s' % (self.message, self.recipient) </code></pre> <p>You'd use the above models like so:</p> <pre><code>&gt;&gt;&gt; person1 = PersonClient.objects.create(first_name='Person', last_name='One', gender='M') &gt;&gt;&gt; person2 = PersonClient.objects.create(first_name='Person', last_name='Two', gender='F') &gt;&gt;&gt; company = CompanyClient.objects.create(name='FastCompany', tax_no='4220') &gt;&gt;&gt; company_ct = ContentType.objects.get_for_model(CompanyClient) &gt;&gt;&gt; person_ct = ContentType.objects.get_for_model(person1) # works for instances too. # now we create a message: &gt;&gt;&gt; msg = Message.objects.create(sender_content_type=person_ct, sender_id=person1.pk, msg_body='Hey, did any of you move my cheese?') # and send it to a coupla recipients: &gt;&gt;&gt; MessageRecipient.objects.create(message=msg, recipient_content_type=person_ct, recipient_id=person2.pk) &gt;&gt;&gt; MessageRecipient.objects.create(message=msg, recipient_content_type=company_ct, recipient_id=company.pk) &gt;&gt;&gt; MessageRecipient.objects.count() 2 </code></pre> <p>As you can see, this is a far more verbose (complicated?) solution. I'd probably keep it simple and go with Prariedogg's solution above.</p>
45
2009-06-02T00:10:47Z
[ "python", "django", "generics", "django-models", "many-to-many" ]
Generic many-to-many relationships
933,092
<p>I'm trying to create a messaging system where a message's sender and recipients can be generic entities. This seems fine for the sender, where there is only object to reference (GenericForeignKey) but I can't figure out how to go about this for the recipients (GenericManyToManyKey ??)</p> <p>Below is a simplified example. PersonClient and CompanyClient inherit attributes from Client but have their own specific details. The last line is the sticking point. How do you allow message recipients to be a set of CompanyClients and PersonClients</p> <pre><code> class Client(models.Model): city = models.CharField(max_length=16) class Meta: abstract = True class PersonClient(Client): first_name = models.CharField(max_length=16) last_name = models.CharField(max_length=16) gender = models.CharField(max_length=1) class CompanyClient(Client): name = models.CharField(max_length=32) tax_no = PositiveIntegerField() class Message(models.Model): msg_body = models.CharField(max_length=1024) sender = models.ForeignKey(ContentType) recipients = models.ManyToManyField(ContentType) </code></pre>
34
2009-05-31T23:18:01Z
32,989,576
<p>The absolute best way to go about this is to use a library called django-gm2m</p> <pre><code>pip install django-gm2m </code></pre> <p>Then if we have our models</p> <pre><code>&gt;&gt;&gt; from django.db import models &gt;&gt;&gt; &gt;&gt;&gt; class Video(models.Model): &gt;&gt;&gt; pass &gt;&gt;&gt; &gt;&gt;&gt; class Movie(Video): &gt;&gt;&gt; pass &gt;&gt;&gt; &gt;&gt;&gt; class Documentary(Video): &gt;&gt;&gt; pass </code></pre> <p>And a user</p> <pre><code>&gt;&gt;&gt; from gm2m import GM2MField &gt;&gt;&gt; &gt;&gt;&gt; class User(models.Model): &gt;&gt;&gt; preferred_videos = GM2MField() </code></pre> <p>We can do</p> <pre><code>&gt;&gt;&gt; user = User.objects.create() &gt;&gt;&gt; movie = Movie.objects.create() &gt;&gt;&gt; documentary = Documentary.objects.create() &gt;&gt;&gt; &gt;&gt;&gt; user.preferred_videos.add(movie) &gt;&gt;&gt; user.preferred_videos.add(documentary) </code></pre> <p>Sweet right?</p> <p>For more info go here:</p> <p><a href="http://django-gm2m.readthedocs.org/en/stable/quick_start.html" rel="nofollow">http://django-gm2m.readthedocs.org/en/stable/quick_start.html</a></p>
1
2015-10-07T10:13:16Z
[ "python", "django", "generics", "django-models", "many-to-many" ]
Django-like abstract database API for non-Django projects
933,232
<p>I love the abstract database API that comes with Django, I was wondering if I could use this (or something similar) to model, access, and manage my (postgres) database for my non-Django Python projects.</p>
5
2009-06-01T00:58:06Z
933,235
<p>What you're looking for is an <a href="http://en.wikipedia.org/wiki/Object-relational%5Fmapping">object-relational mapper</a> (ORM). Django has its own, built-in.</p> <p>To use Django's ORM by itself:</p> <ul> <li><a href="http://jystewart.net/process/2008/02/using-the-django-orm-as-a-standalone-component/">Using the Django ORM as a standalone component</a></li> <li><a href="http://pascal.nextrem.ch/2008/08/17/use-django-orm-as-standalone/">Use Django ORM as standalone</a></li> <li><a href="http://docs.djangoproject.com/en/dev/topics/settings/#using-settings-without-setting-django-settings-module">Using settings without setting DJANGO_SETTINGS_MODULE</a></li> </ul> <p>If you want to use something else:</p> <ul> <li><a href="http://stackoverflow.com/questions/53428/what-are-some-good-python-orm-solutions">What are some good Python ORM solutions?</a></li> </ul>
16
2009-06-01T01:00:11Z
[ "python", "database", "django", "orm", "django-models" ]
Django-like abstract database API for non-Django projects
933,232
<p>I love the abstract database API that comes with Django, I was wondering if I could use this (or something similar) to model, access, and manage my (postgres) database for my non-Django Python projects.</p>
5
2009-06-01T00:58:06Z
933,238
<p>Popular stand-alone ORMs for Python:</p> <ul> <li><a href="http://www.sqlalchemy.org/">SQLAlchemy</a></li> <li><a href="http://www.sqlobject.org/">SQLObject</a></li> <li><a href="https://storm.canonical.com/">Storm</a></li> </ul> <p>They all support MySQL and PostgreSQL (among others).</p>
7
2009-06-01T01:01:55Z
[ "python", "database", "django", "orm", "django-models" ]
Django-like abstract database API for non-Django projects
933,232
<p>I love the abstract database API that comes with Django, I was wondering if I could use this (or something similar) to model, access, and manage my (postgres) database for my non-Django Python projects.</p>
5
2009-06-01T00:58:06Z
933,834
<p>I especially like <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a> with following tools:</p> <ul> <li><a href="http://elixir.ematia.de/" rel="nofollow">Elixir</a> (declarative syntax)</li> <li><a href="http://code.google.com/p/sqlalchemy-migrate/" rel="nofollow">Migrate</a> (schema migration)</li> </ul> <p>They really remind me of <a href="http://ar.rubyonrails.org/" rel="nofollow">ActiveRecord</a>.</p>
2
2009-06-01T07:20:15Z
[ "python", "database", "django", "orm", "django-models" ]
Control an embedded into website flash player with Python?
933,441
<p>I am trying to write few simple python scripts, which will allow me to control one of the Internet radio (which I listen) with an keybinded python scripts.</p> <p>I am now able to connect and log into the website, I am able to get out the song data ( that is - all the data which are passed to the player).</p> <p>I noticed, that the player is controlled with javascript, lets assume, that it's address is <a href="http://www.sitesite.com/player.swf" rel="nofollow">http://www.sitesite.com/player.swf</a></p> <p>If the player can be controlled with javascript, then I think that there should be an way, to control it with python. If I am right, can someone please give me an example how can this be done?</p>
0
2009-06-01T03:20:33Z
933,478
<p>No you can't control the player with Python, flash and javascript can talk to each other because of how the Flash player works when embedded in a web page. Sounds like you're circumventing the flash player anyhow, so why do you need to control a player you're not using?</p>
1
2009-06-01T03:41:23Z
[ "javascript", "python", "flash", "control", "embedded-resource" ]
Is there a way to invoke a Python function with the wrong number of arguments without invoking a TypeError?
933,484
<p>When you invoke a function with the wrong number of arguments, or with a keyword argument that isn't in its definition, you get a TypeError. I'd like a piece of code to take a callback and invoke it with variable arguments, based on what the callback supports. One way of doing it would be to, for a callback <code>cb</code>, use <code>cb.__code__.cb_argcount</code> and <code>cb.__code__.co_varnames</code>, but I would rather abstract that into something like <code>apply</code>, but that only applies the arguments which "fit".</p> <p>For example:</p> <pre><code> def foo(x,y,z): pass cleanvoke(foo, 1) # should call foo(1, None, None) cleanvoke(foo, y=2) # should call foo(None, 2, None) cleanvoke(foo, 1,2,3,4,5) # should call foo(1, 2, 3) # etc. </code></pre> <p>Is there anything like this already in Python, or is it something I should write from scratch?</p>
1
2009-06-01T03:43:49Z
933,493
<p>Rather than digging down into the details yourself, you can <a href="http://docs.python.org/library/inspect.html" rel="nofollow">inspect</a> the function's signature -- you probably want <code>inspect.getargspec(cb)</code>.</p> <p>Exactly how you want to use that info, and the args you have, to call the function "properly", is not completely clear to me. Assuming for simplicity that you only care about simple named args, and the values you'd like to pass are in dict <code>d</code>...</p> <pre><code>args = inspect.getargspec(cb)[0] cb( **dict((a,d.get(a)) for a in args) ) </code></pre> <p>Maybe you want something fancier, and can elaborate on exactly what?</p>
7
2009-06-01T03:47:31Z
[ "python", "apply", "invocation" ]
Is there a way to invoke a Python function with the wrong number of arguments without invoking a TypeError?
933,484
<p>When you invoke a function with the wrong number of arguments, or with a keyword argument that isn't in its definition, you get a TypeError. I'd like a piece of code to take a callback and invoke it with variable arguments, based on what the callback supports. One way of doing it would be to, for a callback <code>cb</code>, use <code>cb.__code__.cb_argcount</code> and <code>cb.__code__.co_varnames</code>, but I would rather abstract that into something like <code>apply</code>, but that only applies the arguments which "fit".</p> <p>For example:</p> <pre><code> def foo(x,y,z): pass cleanvoke(foo, 1) # should call foo(1, None, None) cleanvoke(foo, y=2) # should call foo(None, 2, None) cleanvoke(foo, 1,2,3,4,5) # should call foo(1, 2, 3) # etc. </code></pre> <p>Is there anything like this already in Python, or is it something I should write from scratch?</p>
1
2009-06-01T03:43:49Z
933,513
<p>This maybe?</p> <pre><code>def fnVariableArgLength(*args, **kwargs): """ - args is a list of non keywords arguments - kwargs is a dict of keywords arguments (keyword, arg) pairs """ print args, kwargs fnVariableArgLength() # () {} fnVariableArgLength(1, 2, 3) # (1, 2, 3) {} fnVariableArgLength(foo='bar') # () {'foo': 'bar'} fnVariableArgLength(1, 2, 3, foo='bar') # (1, 2, 3) {'foo': 'bar'} </code></pre> <p><hr /></p> <p><strong>Edit</strong> Your use cases</p> <pre><code>def foo(*args,*kw): x= kw.get('x',None if len(args) &lt; 1 else args[0]) y= kw.get('y',None if len(args) &lt; 2 else args[1]) z= kw.get('z',None if len(args) &lt; 3 else args[2]) # the rest of foo foo(1) # should call foo(1, None, None) foo(y=2) # should call foo(None, 2, None) foo(1,2,3,4,5) # should call foo(1, 2, 3) </code></pre>
3
2009-06-01T03:57:23Z
[ "python", "apply", "invocation" ]
Custom Markup in Django
933,500
<p>Can anyone give me an idea or perhaps some references on how to create custom markups for django using textile or Markdown(or am I thinking wrong here)?</p> <p>For example: I'd like to convert the following markups(the outer bracket mean they are grouped as one tag:<br /> [<br /> [Contacts]<br /> * Contact #1<br /> * Contact #2<br /> * Contact #3<br /> [Friend Requests]<br /> * Jose<br /> ]</p> <p>to have them converted to: </p> <pre><code>&lt;div class="tabs"&gt; &lt;ul&gt; &lt;li class="tab"&gt;Contacts&lt;/li&gt; &lt;li&gt;Contact #1&lt;/li&gt; (etc.. etc..) &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>or is regex more recommended for my needs?</p>
1
2009-06-01T03:53:08Z
933,504
<p>A quick google search resulted with <a href="http://www.freewisdom.org/projects/python-markdown/Django" rel="nofollow">this</a></p>
0
2009-06-01T03:55:02Z
[ "python", "django", "markdown" ]
Custom Markup in Django
933,500
<p>Can anyone give me an idea or perhaps some references on how to create custom markups for django using textile or Markdown(or am I thinking wrong here)?</p> <p>For example: I'd like to convert the following markups(the outer bracket mean they are grouped as one tag:<br /> [<br /> [Contacts]<br /> * Contact #1<br /> * Contact #2<br /> * Contact #3<br /> [Friend Requests]<br /> * Jose<br /> ]</p> <p>to have them converted to: </p> <pre><code>&lt;div class="tabs"&gt; &lt;ul&gt; &lt;li class="tab"&gt;Contacts&lt;/li&gt; &lt;li&gt;Contact #1&lt;/li&gt; (etc.. etc..) &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>or is regex more recommended for my needs?</p>
1
2009-06-01T03:53:08Z
934,715
<p>Django comes with a built-in contrib app that provides filters to display data using several different markup languages, including textile and markdown.</p> <p>See <a href="http://docs.djangoproject.com/en/dev/ref/contrib/#markup" rel="nofollow">the relevant docs</a> for more info.</p>
1
2009-06-01T12:59:55Z
[ "python", "django", "markdown" ]
Custom Markup in Django
933,500
<p>Can anyone give me an idea or perhaps some references on how to create custom markups for django using textile or Markdown(or am I thinking wrong here)?</p> <p>For example: I'd like to convert the following markups(the outer bracket mean they are grouped as one tag:<br /> [<br /> [Contacts]<br /> * Contact #1<br /> * Contact #2<br /> * Contact #3<br /> [Friend Requests]<br /> * Jose<br /> ]</p> <p>to have them converted to: </p> <pre><code>&lt;div class="tabs"&gt; &lt;ul&gt; &lt;li class="tab"&gt;Contacts&lt;/li&gt; &lt;li&gt;Contact #1&lt;/li&gt; (etc.. etc..) &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>or is regex more recommended for my needs?</p>
1
2009-06-01T03:53:08Z
935,344
<p>The built in <a href="http://docs.djangoproject.com/en/dev/ref/contrib/#markup" rel="nofollow">markup</a> app uses a filter template tag to render textile, markdown and restructuredtext. If that is not what your looking for, another option is to use a 'markup' field. e.g.,</p> <pre><code>class TownHallUpdate(models.Model): content = models.TextField() content_html = models.TextField(editable=False) def save(self, **kwargs): self.content_html = textile.textile(sanitize_html(self.content)) super(TownHallUpdate, self).save(**kwargs) </code></pre> <p><em>Example from James Tauber's (and Brian Rosner's) <a href="http://eldarion.com/talks/2009/05/eurodjangocon%5Fdjangopatterns.pdf" rel="nofollow">django patterns</a> talk.</em></p>
3
2009-06-01T15:36:57Z
[ "python", "django", "markdown" ]
Custom Markup in Django
933,500
<p>Can anyone give me an idea or perhaps some references on how to create custom markups for django using textile or Markdown(or am I thinking wrong here)?</p> <p>For example: I'd like to convert the following markups(the outer bracket mean they are grouped as one tag:<br /> [<br /> [Contacts]<br /> * Contact #1<br /> * Contact #2<br /> * Contact #3<br /> [Friend Requests]<br /> * Jose<br /> ]</p> <p>to have them converted to: </p> <pre><code>&lt;div class="tabs"&gt; &lt;ul&gt; &lt;li class="tab"&gt;Contacts&lt;/li&gt; &lt;li&gt;Contact #1&lt;/li&gt; (etc.. etc..) &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>or is regex more recommended for my needs?</p>
1
2009-06-01T03:53:08Z
948,022
<p>Well it seems the best way is still use a regex and create my own filter. </p> <p>here are some links that helped me out:<br /> <a href="http://showmedo.com/videos/video?name=1100010&amp;fromSeriesID=110" rel="nofollow">http://showmedo.com/videos/video?name=1100010&amp;fromSeriesID=110</a><br /> <a href="http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/" rel="nofollow">http://www.smashingmagazine.com/2009/05/06/introduction-to-advanced-regular-expressions/</a> </p> <p>hope this helps someone who had the same problem as me!</p>
0
2009-06-04T00:36:22Z
[ "python", "django", "markdown" ]
What is the best way to fetch/render one-to-many relationships?
933,612
<p>I have 2 models which look like that:</p> <pre><code>class Entry(models.Model): user = models.ForeignKey(User) dataname = models.TextField() datadesc = models.TextField() timestamp = models.DateTimeField(auto_now=True) class EntryFile(models.Model): entry = models.ForeignKey(Entry) datafile = models.FileField(upload_to="uploads/%Y/%m/%d/%H-%M-%S") </code></pre> <p>I want to render all the entries with their related files for a specific user. Now I am doing it that way in my view to get the values:</p> <pre><code> entries = Entry.objects.filter(user=request.user).order_by("-timestamp") files = {} for entry in entries: entryfiles = EntryFile.objects.filter(entry=entry) files[entry] = entryfiles return render_to_response("index.html", {'user': request.user, 'entries': entries, 'files': files, 'message': message}) </code></pre> <p>But I am not able/don't know how to work with these data in my template. This what I do now, but isn't working:</p> <pre><code>{% for entry in entries %} &lt;td&gt;{{ entry.datadesc }}&lt;/td&gt; &lt;td&gt;&lt;table&gt; {{ files.entry }} {% for file in files.entry %} &lt;td&gt;{{ file.datafile.name|split:"/"|last }}&lt;/td&gt; &lt;td&gt;{{ file.datafile.size|filesizeformat }}&lt;/td&gt; &lt;td&gt;&lt;a href="{{ object.datafile.url }}"&gt;download&lt;/a&gt;&lt;/td&gt; &lt;td&gt;&lt;a href="{% url main.views.delete object.id %}"&gt;delete&lt;/a&gt;&lt;/td&gt; {% endfor %} &lt;/table&gt;&lt;/td&gt; {% endfor %} </code></pre> <p>Anyone can tell me if I am doing it the right way in view and then how to access these data in the template?</p> <p>Thank you!</p>
2
2009-06-01T05:01:38Z
933,633
<p>Just cut your view code to this line:</p> <pre><code>entries = Entry.objects.filter(user=request.user).order_by("-timestamp") </code></pre> <p>And do this in the template:</p> <pre><code>{% for entry in entries %} &lt;td&gt;{{ entry.datadesc }}&lt;/td&gt; &lt;td&gt;&lt;table&gt; {% for file in entry.entryfile_set.all %} &lt;td&gt;{{ file.datafile.name|split:"/"|last }}&lt;/td&gt; &lt;td&gt;{{ file.datafile.size|filesizeformat }}&lt;/td&gt; &lt;td&gt;&lt;a href="{{ object.datafile.url }}"&gt;download&lt;/a&gt;&lt;/td&gt; &lt;td&gt;&lt;a href="{% url main.views.delete object.id %}"&gt;delete&lt;/a&gt;&lt;/td&gt; {% endfor %} &lt;/table&gt;&lt;/td&gt; {% endfor %} </code></pre> <p>I am a big fan of using <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward" rel="nofollow"><code>related_name</code></a> in Models, however, so you could change this line:</p> <pre><code>entry = models.ForeignKey(Entry) </code></pre> <p>To this:</p> <pre><code>entry = models.ForeignKey(Entry, related_name='files') </code></pre> <p>And then you can access all the files for a particular entry by changing this:</p> <pre><code>{% for file in files.entryfile_set.all %} </code></pre> <p>To the more readable/obvious:</p> <pre><code>{% for file in entry.files.all %} </code></pre>
5
2009-06-01T05:13:44Z
[ "python", "django" ]
Packaging script source files in IronPython and IronRuby
933,822
<p>Does anyone know how to add python and ruby libs as a resource in a dll for deployment? I want to host a script engine in my app, but dont want to have to deploy the entire standard libraries of the respective languages in source files. Is there a simple way to do this so that a require or import statement will find the embedded resources? </p>
3
2009-06-01T07:14:45Z
933,954
<p>You can create StreamContentProviders for example</p> <p>In the ironrubymvc project under IronRubyMVC/Core/ you will find what you need.</p> <p><a href="http://github.com/casualjim/ironrubymvc/blob/01fc9e5f4cd6b3c0f96a75acd9521673b3f0701e/IronRubyMvc/Core/AssemblyStreamContentProvider.cs" rel="nofollow">AssemblyStreamContentProvider</a></p> <p><a href="http://github.com/casualjim/ironrubymvc/blob/01fc9e5f4cd6b3c0f96a75acd9521673b3f0701e/IronRubyMvc/Core/RubyEngine.cs#L246" rel="nofollow">Usage of the ContentProvider</a></p>
0
2009-06-01T08:19:01Z
[ "c#", "python", "ruby", "ironpython", "ironruby" ]
Packaging script source files in IronPython and IronRuby
933,822
<p>Does anyone know how to add python and ruby libs as a resource in a dll for deployment? I want to host a script engine in my app, but dont want to have to deploy the entire standard libraries of the respective languages in source files. Is there a simple way to do this so that a require or import statement will find the embedded resources? </p>
3
2009-06-01T07:14:45Z
933,988
<p>IronPython 2.0 has a sample compiler called PYC on Codeplex.com/ironpython which can create DLL's (and applications if you need them too).</p> <p>IronPython 2.6 has a newer version of PYC under Tools\script.</p> <p>Cheers, Davy</p>
0
2009-06-01T08:35:49Z
[ "c#", "python", "ruby", "ironpython", "ironruby" ]
Packaging script source files in IronPython and IronRuby
933,822
<p>Does anyone know how to add python and ruby libs as a resource in a dll for deployment? I want to host a script engine in my app, but dont want to have to deploy the entire standard libraries of the respective languages in source files. Is there a simple way to do this so that a require or import statement will find the embedded resources? </p>
3
2009-06-01T07:14:45Z
934,609
<p>You could add custom import hook that looks for embedded resources when an import is executed. This is slightly complex and probably not worth the trouble.</p> <p>A better technique would be to fetch all of the embedded modules at startup time, execute them with the ScriptEngine and put the modules you have created into the sys.modules dictionary associated with the engine. This automatically makes them available for import by Python code executed by the engine.</p>
1
2009-06-01T12:23:55Z
[ "c#", "python", "ruby", "ironpython", "ironruby" ]
Python Regex Search And Replace
933,824
<p>I'm not new to Python but a complete newbie with regular expressions (on my to do list)</p> <p>I am trying to use python re to convert a string such as</p> <pre><code>[Hollywood Holt](http://www.hollywoodholt.com) </code></pre> <p>to</p> <pre><code>&lt;a href="http://www.hollywoodholt.com"&gt;Hollywood Holt&lt;/a&gt; </code></pre> <p>and a string like</p> <pre><code>*Hello world* </code></pre> <p>to</p> <pre><code>&lt;strong&gt;Hello world&lt;/strong&gt; </code></pre>
4
2009-06-01T07:15:04Z
933,826
<p>Why are you bothering to use a regex? Your content is Markdown, why not simply take the string and run it through the markdown module?</p> <p>First, make sure Markdown is installed. It has a dependancy on ElementTree so easy_install the two of them as follows. If you're running Windows, you can use the <a href="http://pypi.python.org/packages/any/M/Markdown/Markdown-2.0.win32.exe" rel="nofollow">Windows installer</a> instead.</p> <pre><code>easy_install ElementTree easy_install Markdown </code></pre> <p>To use the Markdown module and convert your string to html simply do the following (tripple quotes are used for literal strings):</p> <pre><code>import markdown markdown_text = """[Hollywood Holt](http://www.hollywoodholt.com)""" html = markdown.markdown(markdown_text) </code></pre>
12
2009-06-01T07:16:50Z
[ "python", "regex", "string", "markdown" ]
Python module for editing text in CLI
933,941
<p>Is there some python module or commands that would allow me to make my python program enter a CLI text editor, populate the editor with some text, and when it exits, get out the text into some variable?</p> <p>At the moment I have users enter stuff in using raw_input(), but I would like something a bit more powerful than that, and have it displayed on the CLI.</p>
2
2009-06-01T08:10:22Z
933,952
<p>If you don't need windows support you can use the <a href="http://docs.python.org/library/readline.html" rel="nofollow">readline module</a> to get basic command line editing like at the shell prompt.</p>
0
2009-06-01T08:18:28Z
[ "python", "text-editor", "command-line-interface" ]
Python module for editing text in CLI
933,941
<p>Is there some python module or commands that would allow me to make my python program enter a CLI text editor, populate the editor with some text, and when it exits, get out the text into some variable?</p> <p>At the moment I have users enter stuff in using raw_input(), but I would like something a bit more powerful than that, and have it displayed on the CLI.</p>
2
2009-06-01T08:10:22Z
933,962
<p>You could have a look at <a href="http://excess.org/urwid/" rel="nofollow">urwid</a>, a curses-based, full-fledged UI toolkit for python. It allows you to define very sophisticated interfaces and it includes different edit box types for different types of text.</p>
2
2009-06-01T08:22:51Z
[ "python", "text-editor", "command-line-interface" ]
Python module for editing text in CLI
933,941
<p>Is there some python module or commands that would allow me to make my python program enter a CLI text editor, populate the editor with some text, and when it exits, get out the text into some variable?</p> <p>At the moment I have users enter stuff in using raw_input(), but I would like something a bit more powerful than that, and have it displayed on the CLI.</p>
2
2009-06-01T08:10:22Z
933,965
<p>Well, you can launch the user's $EDITOR with subprocess, editing a temporary file:</p> <pre><code>import tempfile import subprocess import os t = tempfile.NamedTemporaryFile(delete=False) try: editor = os.environ['EDITOR'] except KeyError: editor = 'nano' subprocess.call([editor, t.name]) </code></pre>
7
2009-06-01T08:24:56Z
[ "python", "text-editor", "command-line-interface" ]
Comparison of data in SQL through Python
934,117
<p>I have to parse a very complex dump (whatever it is). I have done the parsing through Python. Since the parsed data is very huge in amount, I have to feed it in the database (SQL). I have also done this. Now the thing is I have to compare the data now present in the SQL.</p> <p>Actually I have to compare the data of 1st dump with the data of the 2nd dump. Both dumps have the same fields (attributes) but the values of their fields may be different. So I have to detect this change. For this, I have to do the comparison. But I don't have the idea how to do this all using Python as my front end.</p>
0
2009-06-01T09:27:51Z
934,761
<p>Why not do the 'dectect change' in SQL? Something like:</p> <pre><code>select foo.data1, foo.data2 from foo where foo.id = 'dump1' minus select foo.data1, foo.data2 from foo where foo.id = 'dump2' </code></pre>
0
2009-06-01T13:11:42Z
[ "python", "sql" ]
Comparison of data in SQL through Python
934,117
<p>I have to parse a very complex dump (whatever it is). I have done the parsing through Python. Since the parsed data is very huge in amount, I have to feed it in the database (SQL). I have also done this. Now the thing is I have to compare the data now present in the SQL.</p> <p>Actually I have to compare the data of 1st dump with the data of the 2nd dump. Both dumps have the same fields (attributes) but the values of their fields may be different. So I have to detect this change. For this, I have to do the comparison. But I don't have the idea how to do this all using Python as my front end.</p>
0
2009-06-01T09:27:51Z
936,733
<p>If you don't have <code>MINUS</code> or <code>EXCEPT</code>, there is also this, which will show all non-matching rows using a <code>UNION</code>/<code>GROUP BY</code> trick</p> <pre><code>SELECT MAX(table), data1, data2 FROM ( SELECT 'foo1' AS table, foo1.data1, foo1.data2 FROM foo1 UNION ALL SELECT 'foo2' AS table, foo2.data1, foo2.data2 FROM foo2 ) AS X GROUP BY data1, data2 HAVING COUNT(*) = 1 ORDER BY data1, data2 </code></pre> <p>I have a general purpose table compare SP which also can do a more complex table compare with left and right and inner joins and monetary threshold (or threshold percentage) and subset criteria.</p>
1
2009-06-01T20:53:28Z
[ "python", "sql" ]
Write to UTF-8 file in Python
934,160
<p>I'm really confused with the <code>codecs.open function</code>. When I do:</p> <pre><code>file = codecs.open("temp", "w", "utf-8") file.write(codecs.BOM_UTF8) file.close() </code></pre> <p>It gives me the error</p> <blockquote> <p>UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128)</p> </blockquote> <p>If I do:</p> <pre><code>file = open("temp", "w") file.write(codecs.BOM_UTF8) file.close() </code></pre> <p>It works fine.</p> <p><strong>Question</strong> is why does the first method fail? And how do I insert the bom?</p> <p>If the second method is the correct way of doing it, what the point of using <code>codecs.open(filename, "w", "utf-8")</code>?</p>
113
2009-06-01T09:42:23Z
934,173
<p>Disclaimer: I'm not a Python programmer.</p> <p>I believe the problem is that <a href="https://docs.python.org/library/codecs.html#codecs.BOM_UTF8"><code>codecs.BOM_UTF8</code></a> is a byte string, not a Unicode string. I suspect the file handler is trying to guess what you really mean based on "I'm meant to be writing Unicode as UTF-8-encoded text, but you've given me a byte string!"</p> <p>Try writing the Unicode string for the byte order mark (i.e. Unicode U+FEFF) directly, so that the file just encodes that as UTF-8:</p> <pre><code>import codecs file = codecs.open("lol", "w", "utf-8") file.write(u'\ufeff') file.close() </code></pre> <p>(That seems to give the right answer - a file with bytes EF BB BF.)</p> <p>EDIT: S. Lott's <a href="http://stackoverflow.com/a/934203/12892">suggestion</a> of using "utf-8-sig" as the encoding is a better one than explicitly writing the BOM yourself, but I'll leave this answer here as it explains what was going wrong before.</p>
168
2009-06-01T09:46:58Z
[ "python", "utf-8", "byte-order-mark" ]
Write to UTF-8 file in Python
934,160
<p>I'm really confused with the <code>codecs.open function</code>. When I do:</p> <pre><code>file = codecs.open("temp", "w", "utf-8") file.write(codecs.BOM_UTF8) file.close() </code></pre> <p>It gives me the error</p> <blockquote> <p>UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128)</p> </blockquote> <p>If I do:</p> <pre><code>file = open("temp", "w") file.write(codecs.BOM_UTF8) file.close() </code></pre> <p>It works fine.</p> <p><strong>Question</strong> is why does the first method fail? And how do I insert the bom?</p> <p>If the second method is the correct way of doing it, what the point of using <code>codecs.open(filename, "w", "utf-8")</code>?</p>
113
2009-06-01T09:42:23Z
934,203
<p>Read the following: <a href="http://docs.python.org/library/codecs.html#module-encodings.utf_8_sig">http://docs.python.org/library/codecs.html#module-encodings.utf_8_sig</a></p> <p>Do this </p> <pre><code>with codecs.open("test_output", "w", "utf-8-sig") as temp: temp.write("hi mom\n") temp.write(u"This has ♭") </code></pre> <p>The resulting file is UTF-8 with the expected BOM.</p>
129
2009-06-01T09:58:14Z
[ "python", "utf-8", "byte-order-mark" ]
Write to UTF-8 file in Python
934,160
<p>I'm really confused with the <code>codecs.open function</code>. When I do:</p> <pre><code>file = codecs.open("temp", "w", "utf-8") file.write(codecs.BOM_UTF8) file.close() </code></pre> <p>It gives me the error</p> <blockquote> <p>UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128)</p> </blockquote> <p>If I do:</p> <pre><code>file = open("temp", "w") file.write(codecs.BOM_UTF8) file.close() </code></pre> <p>It works fine.</p> <p><strong>Question</strong> is why does the first method fail? And how do I insert the bom?</p> <p>If the second method is the correct way of doing it, what the point of using <code>codecs.open(filename, "w", "utf-8")</code>?</p>
113
2009-06-01T09:42:23Z
934,228
<p>@S-Lott gives the right procedure, but expanding on the <em>Unicode</em> issues, the <em>Python</em> interpreter can provide more insights.</p> <p>Jon Skeet is right (unusual) about the <a href="http://docs.python.org/library/codecs.html#codecs.BOM"><code>codecs</code></a> module - it contains byte strings:</p> <pre><code>&gt;&gt;&gt; import codecs &gt;&gt;&gt; codecs.BOM '\xff\xfe' &gt;&gt;&gt; codecs.BOM_UTF8 '\xef\xbb\xbf' &gt;&gt;&gt; </code></pre> <p>Picking another nit, the <code>BOM</code> has a standard <em>Unicode</em> name, and it can be entered as:</p> <pre><code>&gt;&gt;&gt; bom= u"\N{ZERO WIDTH NO-BREAK SPACE}" &gt;&gt;&gt; bom u'\ufeff' </code></pre> <p>It is also accessible via <a href="http://docs.python.org/library/unicodedata.html#module-unicodedata"><code>unicodedata</code></a>:</p> <pre><code>&gt;&gt;&gt; import unicodedata &gt;&gt;&gt; unicodedata.lookup('ZERO WIDTH NO-BREAK SPACE') u'\ufeff' &gt;&gt;&gt; </code></pre>
11
2009-06-01T10:12:39Z
[ "python", "utf-8", "byte-order-mark" ]
Write to UTF-8 file in Python
934,160
<p>I'm really confused with the <code>codecs.open function</code>. When I do:</p> <pre><code>file = codecs.open("temp", "w", "utf-8") file.write(codecs.BOM_UTF8) file.close() </code></pre> <p>It gives me the error</p> <blockquote> <p>UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128)</p> </blockquote> <p>If I do:</p> <pre><code>file = open("temp", "w") file.write(codecs.BOM_UTF8) file.close() </code></pre> <p>It works fine.</p> <p><strong>Question</strong> is why does the first method fail? And how do I insert the bom?</p> <p>If the second method is the correct way of doing it, what the point of using <code>codecs.open(filename, "w", "utf-8")</code>?</p>
113
2009-06-01T09:42:23Z
9,200,975
<p>I use the file *nix command to convert a unknown charset file in a utf-8 file</p> <pre><code># -*- encoding: utf-8 -*- # converting a unknown formatting file in utf-8 import codecs import commands file_location = "jumper.sub" file_encoding = commands.getoutput('file -b --mime-encoding %s' % file_location) file_stream = codecs.open(file_location, 'r', file_encoding) file_output = codecs.open(file_location+"b", 'w', 'utf-8') for l in file_stream: file_output.write(l) file_stream.close() file_output.close() </code></pre>
4
2012-02-08T20:35:11Z
[ "python", "utf-8", "byte-order-mark" ]
python db connection
934,221
<p>I am having a script which makes a db connection and pereform some select operation.accroding to the fetch data i am calling different functions which also perform db operations.How can i pass db connection to the functions which are being called as i donot want to make new connection</p>
0
2009-06-01T10:08:00Z
934,709
<p>Why to pass connection itself? Maybe build a class that handles all the DB-operation and just pass this class' instance around, calling it's methods to perform selects, inserts and all that DB-specific code? </p>
2
2009-06-01T12:58:26Z
[ "python" ]
Getting response from bluetooth device
934,460
<p>I'm trying to write a simple module that will enable sending SMS. I using bluetooth to connect to the mobile using the below example:</p> <h1>file: bt-sendsms.py</h1> <pre><code>import bluetooth target = '00:32:AC:32:36:E8' # Mobile address print "Trying to send SMS on %s" % target BTSocket = bluetooth.BluetoothSocket(bluetooth.RFCOMM) BTSocket.connect((target, 2)) # BT Address BTSocket.send('ATZ\r') BTSocket.send('AT+CMGF=1\r') #sockfd.send('AT+CSCA="+972547716507"\r') # This line changes the SMSC address - do not modify unless required BTSocket.send('AT+CMGS="+972547877763"\r') # TO Phone Number BTSocket.send('This is a test message - port 2.\n') BTSocket.send(chr(26)) # CTRL+Z print "SMS sent" sockfd.close() print "Closed" </code></pre> <p>My problem is that I'm unable to verify or get an error code for the SMS sending or any of the socket operation.</p> <p>Any referral to the right direction will be appreciated </p>
2
2009-06-01T11:35:07Z
934,543
<p>From the Python you look like you are opening any old RFCOMM channel and hoping it will magically take the AT commands and do the messaging.</p> <p>I think (and I could be wrong) that you need to connect to a specific profile/sevice channel and I think for SMS it is the the Messaging Access Profile (MAP), which is not yet standardised so finding a phone with it on, well I won't say impossible but very, very unlikely. Otherwise, some phones will support AT commands for messaging but this is outside the specs e.g. I have it on authority that Sony-Ericson phones will support it though the Dial-Up Networking profile (DUN). </p> <p>So, first of all, does your mobile device support some out of spec AT commands for SMS and if so, on a certain profile or on an ad-hoc proprietary one? Next, you need to connect to that profile.</p> <p>You can browse the supported services etc... using the following Python (checks all surrounding BT devices)...</p> <pre><code>import bluetooth def whats_nearby(): name_by_addr = {} nearby = bluetooth.discover_devices(flush_cache=True) for bd_addr in nearby: name = bluetooth.lookup_name( bd_addr, 5) print bd_addr, name name_by_addr[bd_addr] = name return name_by_addr def what_services( addr, name ): print " %s - %s" % ( addr, name ) for services in bluetooth.find_service(address = addr): print "\t Name: %s" % (services["name"]) print "\t Description: %s" % (services["description"]) print "\t Protocol: %s" % (services["protocol"]) print "\t Provider: %s" % (services["provider"]) print "\t Port: %s" % (services["port"]) print "\t service-classes %s" % (services["service-classes"]) print "\t profiles %s" % (services["profiles"]) print "\t Service id: %s" % (services["service-id"]) print "" if __name__ == "__main__": name_by_addr = whats_nearby() for addr in name_by_addr.keys(): what_services(addr, name_by_addr[addr]) </code></pre> <p>Once you find the correct service/profile, your next problem will be negotiating security (pin code for pairing), which I haven't worked out how to do yet!</p> <p>See the <a href="http://www.bluetooth.org" rel="nofollow">www.bluetooth.org</a> for all your Bluetooth needs!</p>
3
2009-06-01T12:02:02Z
[ "python", "sms", "bluetooth", "mobile-phones" ]
Java equivalent of function mapping in Python
934,509
<p>In python, if I have a few functions that I would like to call based on an input, i can do this:</p> <pre><code>lookup = {'function1':function1, 'function2':function2, 'function3':function3} lookup[input]() </code></pre> <p>That is I have a dictionary of function name mapped to the function, and call the function by a dictionary lookup.</p> <p>How to do this in java?</p>
7
2009-06-01T11:48:37Z
934,520
<p>You could use a Map&lt;String,Method> or Map&lt;String,Callable> etc,and then use map.get("function1").invoke(...). But usually these kinds of problems are tackled more cleanly by using polymorphism instead of a lookup.</p>
2
2009-06-01T11:52:36Z
[ "java", "python", "function" ]
Java equivalent of function mapping in Python
934,509
<p>In python, if I have a few functions that I would like to call based on an input, i can do this:</p> <pre><code>lookup = {'function1':function1, 'function2':function2, 'function3':function3} lookup[input]() </code></pre> <p>That is I have a dictionary of function name mapped to the function, and call the function by a dictionary lookup.</p> <p>How to do this in java?</p>
7
2009-06-01T11:48:37Z
934,532
<p>Java doesn't have first-class methods, so the <a href="http://en.wikipedia.org/wiki/Command%5Fpattern">command pattern</a> is your friend...</p> <p>disclamer: code not tested!</p> <pre><code>public interface Command { void invoke(); } Map&lt;String, Command&gt; commands = new HashMap&lt;String, Command&gt;(); commands.put("function1", new Command() { public void invoke() { System.out.println("hello world"); } }); commands.get("function1").invoke(); </code></pre>
14
2009-06-01T11:58:09Z
[ "java", "python", "function" ]
Java equivalent of function mapping in Python
934,509
<p>In python, if I have a few functions that I would like to call based on an input, i can do this:</p> <pre><code>lookup = {'function1':function1, 'function2':function2, 'function3':function3} lookup[input]() </code></pre> <p>That is I have a dictionary of function name mapped to the function, and call the function by a dictionary lookup.</p> <p>How to do this in java?</p>
7
2009-06-01T11:48:37Z
934,676
<p>Polymorphic example..</p> <pre><code>public interface Animal {public void speak();}; public class Dog implements Animal {public void speak(){System.out.println("treat? treat? treat?");}} public class Cat implements Animal {public void speak(){System.out.println("leave me alone");}} public class Hamster implements Animal {public void speak(){System.out.println("I run, run, run, but never get anywhere");}} Map&lt;String,Animal&gt; animals = new HashMap&lt;String,Animal&gt;(); animals.put("dog",new Dog()); animals.put("cat",new Cat()); animals.put("hamster",new Hamster()); for(Animal animal : animals){animal.speak();} </code></pre>
1
2009-06-01T12:45:54Z
[ "java", "python", "function" ]
Java equivalent of function mapping in Python
934,509
<p>In python, if I have a few functions that I would like to call based on an input, i can do this:</p> <pre><code>lookup = {'function1':function1, 'function2':function2, 'function3':function3} lookup[input]() </code></pre> <p>That is I have a dictionary of function name mapped to the function, and call the function by a dictionary lookup.</p> <p>How to do this in java?</p>
7
2009-06-01T11:48:37Z
934,843
<p>There are several ways to approach this problem. Most of these were posted already:</p> <ul> <li><a href="http://stackoverflow.com/questions/934509/java-equivalent-of-function-mapping-in-python/934532#934532">Commands</a> - Keep a bunch of objects that have an execute() or invoke() method in a map; lookup the command by name, then invoke the method.</li> <li><a href="http://stackoverflow.com/questions/934509/java-equivalent-of-function-mapping-in-python/934676#934676">Polymorphism</a> - More generally than commands, you can invoke methods on any related set of objects.</li> <li>Finally there is Reflection - You can use reflection to get references to java.lang.Method objects. For a set of known classes/methods, this works fairly well and there isn't too much overhead once you load the Method objects. You could use this to, for example, allow a user to type java code into a command line, which you execute in real time.</li> </ul> <p>Personally I would use the Command approach. Commands combine well with <a href="http://en.wikipedia.org/wiki/Template%5Fmethod%5Fpattern" rel="nofollow">Template Methods</a>, allowing you to enforce certain patterns on all your command objects. Example:</p> <pre><code>public abstract class Command { public final Object execute(Map&lt;String, Object&gt; args) { // do permission checking here or transaction management Object retval = doExecute(args); // do logging, cleanup, caching, etc here return retval; } // subclasses override this to do the real work protected abstract Object doExecute(Map&lt;String, Object&gt; args); } </code></pre> <p>I would resort to reflection only when you need to use this kind of mapping for classes whose design you don't control, and for which it's not practical to make commands. For example, you couldn't expose the Java API in a command-shell by making commands for each method.</p>
3
2009-06-01T13:35:27Z
[ "java", "python", "function" ]
Java equivalent of function mapping in Python
934,509
<p>In python, if I have a few functions that I would like to call based on an input, i can do this:</p> <pre><code>lookup = {'function1':function1, 'function2':function2, 'function3':function3} lookup[input]() </code></pre> <p>That is I have a dictionary of function name mapped to the function, and call the function by a dictionary lookup.</p> <p>How to do this in java?</p>
7
2009-06-01T11:48:37Z
935,077
<p>As mentioned in other questions, a <code>Map&lt;String,MyCommandType&gt;</code> with anonymous inner classes is one verbose way to do it.</p> <p>A variation is to use enums in place of the anonymous inner classes. Each constant of the enum can implement/override methods of the enum or implemented interface, much the same as the anonymous inner class technique but with a little less mess. I believe Effective Java 2nd Ed deals with how to initialise a map of enums. To map from the enum name merely requires calling <code>MyEnumType.valueOf(name)</code>.</p>
0
2009-06-01T14:30:33Z
[ "java", "python", "function" ]
Java equivalent of function mapping in Python
934,509
<p>In python, if I have a few functions that I would like to call based on an input, i can do this:</p> <pre><code>lookup = {'function1':function1, 'function2':function2, 'function3':function3} lookup[input]() </code></pre> <p>That is I have a dictionary of function name mapped to the function, and call the function by a dictionary lookup.</p> <p>How to do this in java?</p>
7
2009-06-01T11:48:37Z
935,788
<p>Unfortunately, Java does not have first-class functions, but consider the following interface:</p> <pre><code>public interface F&lt;A, B&gt; { public B f(A a); } </code></pre> <p>This models the type for functions from type <code>A</code> to type <code>B</code>, as first-class values that you can pass around. What you want is a <code>Map&lt;String, F&lt;A, B&gt;&gt;</code>.</p> <p><a href="http://code.google.com/p/functionaljava" rel="nofollow">Functional Java</a> is a fairly complete library centered around first-class functions.</p>
0
2009-06-01T17:13:49Z
[ "java", "python", "function" ]
Java equivalent of function mapping in Python
934,509
<p>In python, if I have a few functions that I would like to call based on an input, i can do this:</p> <pre><code>lookup = {'function1':function1, 'function2':function2, 'function3':function3} lookup[input]() </code></pre> <p>That is I have a dictionary of function name mapped to the function, and call the function by a dictionary lookup.</p> <p>How to do this in java?</p>
7
2009-06-01T11:48:37Z
936,122
<p>As everyone else said, Java doesn't support functions as first-level objects. To achieve this, you use a Functor, which is a class that wraps a function. Steve Yegge has a <a href="http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html" rel="nofollow">nice rant</a> about that.</p> <p>To help you with this limitation, people write functor libraries: <a href="http://jga.sourceforge.net/" rel="nofollow">jga</a>, <a href="http://commons.apache.org/sandbox/functor/" rel="nofollow">Commons Functor</a></p>
0
2009-06-01T18:33:46Z
[ "java", "python", "function" ]
Insert/Delete performance
934,602
<pre><code>DB Table: id int(6) message char(5) </code></pre> <p>I have to add a record (message) to the DB table. In case of duplicate message(this message already exists with different id) I want to delete (or inactivate somehow) the both of the messages and get their ID's in reply.</p> <p>Is it possible to perform with only one query? Any performance tips ?...</p> <p>P.S. I use PostgreSQL. </p> <p>The main my problem I worried about, is a need to use locks when performing this with two or more queries...</p> <p>Many thanks!</p>
1
2009-06-01T12:19:54Z
934,607
<p>You could write a procedure with both of those commands in it, but it may make more sense to use an insert trigger to check for duplicates (or a nightly job, if it's not time-sensitive).</p>
1
2009-06-01T12:22:51Z
[ "python", "database", "performance", "database-design" ]
Insert/Delete performance
934,602
<pre><code>DB Table: id int(6) message char(5) </code></pre> <p>I have to add a record (message) to the DB table. In case of duplicate message(this message already exists with different id) I want to delete (or inactivate somehow) the both of the messages and get their ID's in reply.</p> <p>Is it possible to perform with only one query? Any performance tips ?...</p> <p>P.S. I use PostgreSQL. </p> <p>The main my problem I worried about, is a need to use locks when performing this with two or more queries...</p> <p>Many thanks!</p>
1
2009-06-01T12:19:54Z
934,726
<p>It is a little difficult to understand your exact requirement. Let me rephrase it two ways:</p> <ol> <li><p>You want both the entries with same messages in the table (with different IDs), and want to know the IDs for some further processing (marking them as inactive, etc.). For this, You could write a procedure with the separate queries. I don't think you can achieve this with one query.</p></li> <li><p>You do not want either of the entries in the table (i got this from 'i want to delete'). For this, you only have to check if the message already exists and then delete the row if it does, else insert it. I don't think this too can be achieved with one query.</p></li> </ol> <p>If performance is a constraint during insert, you could insert without any checks and then periodically, sanitize the database.</p>
0
2009-06-01T13:03:08Z
[ "python", "database", "performance", "database-design" ]
Insert/Delete performance
934,602
<pre><code>DB Table: id int(6) message char(5) </code></pre> <p>I have to add a record (message) to the DB table. In case of duplicate message(this message already exists with different id) I want to delete (or inactivate somehow) the both of the messages and get their ID's in reply.</p> <p>Is it possible to perform with only one query? Any performance tips ?...</p> <p>P.S. I use PostgreSQL. </p> <p>The main my problem I worried about, is a need to use locks when performing this with two or more queries...</p> <p>Many thanks!</p>
1
2009-06-01T12:19:54Z
935,952
<p>If you really want to worry about locking do this.</p> <ol> <li><p>UPDATE table SET status='INACTIVE' WHERE id = 'key';</p> <p>If this succeeds, there was a duplicate.</p> <ul> <li>INSERT the additional inactive record. Do whatever else you want with your duplicates.</li> </ul> <p>If this fails, there was no duplicate.</p> <ul> <li>INSERT the new active record. </li> </ul></li> <li><p>Commit.</p></li> </ol> <p>This seizes an exclusive lock right away. The alternatives aren't quite as nice.</p> <ul> <li><p>Start with an INSERT and check for duplicates doesn't seize a lock until you start updating. It's not clear if this is a problem or not.</p></li> <li><p>Start with a SELECT would need to add a LOCK TABLE to assure that the select held the row found so it could be updated. If no row is found, the insert will work fine.</p></li> </ul> <p>If you have multiple concurrent writers and two writers could attempt access at the same time, you may not be able to tolerate row-level locking.</p> <p>Consider this.</p> <ol> <li><p>Process A does a LOCK ROW and a SELECT but finds no row.</p></li> <li><p>Process B does a LOCK ROW and a SELECT but finds no row.</p></li> <li><p>Process A does an INSERT and a COMMIT.</p></li> <li><p>Process B does an INSERT and a COMMIT. You now have duplicate active records.</p></li> </ol> <p>Multiple concurrent insert/update transactions will only work with table-level locking. Yes, it's a potential slow-down. Three rules: (1) Keep your transactions as short as possible, (2) release the locks as quickly as possible, (3) handle deadlocks by retrying.</p>
2
2009-06-01T18:00:45Z
[ "python", "database", "performance", "database-design" ]
How do I find out if a numpy array contains integers?
934,616
<p>I know there is a simple solution to this but can't seem to find it at the moment.</p> <p>Given a numpy array, I need to know if the array contains integers.</p> <p>Checking the dtype per-se is not enough, as there are multiple int dtypes (int8, int16, int32, int64 ...). </p>
24
2009-06-01T12:27:46Z
934,652
<p>Found it in the <a href="http://templatelab.com/numpybook/">numpy book</a>! Page 23:</p> <blockquote> <p>The other types in the hierarchy define particular categories of types. These categories can be useful for testing whether or not the object returned by self.dtype.type is of a particular class (using issubclass).</p> </blockquote> <pre><code>issubclass(n.dtype('int8').type, n.integer) &gt;&gt;&gt; True issubclass(n.dtype('int16').type, n.integer) &gt;&gt;&gt; True </code></pre>
27
2009-06-01T12:39:12Z
[ "python", "numpy" ]
How do I find out if a numpy array contains integers?
934,616
<p>I know there is a simple solution to this but can't seem to find it at the moment.</p> <p>Given a numpy array, I need to know if the array contains integers.</p> <p>Checking the dtype per-se is not enough, as there are multiple int dtypes (int8, int16, int32, int64 ...). </p>
24
2009-06-01T12:27:46Z
1,168,729
<p>This also works: </p> <pre><code> n.dtype('int8').kind == 'i' </code></pre>
6
2009-07-22T22:52:30Z
[ "python", "numpy" ]
How do I find out if a numpy array contains integers?
934,616
<p>I know there is a simple solution to this but can't seem to find it at the moment.</p> <p>Given a numpy array, I need to know if the array contains integers.</p> <p>Checking the dtype per-se is not enough, as there are multiple int dtypes (int8, int16, int32, int64 ...). </p>
24
2009-06-01T12:27:46Z
7,236,784
<p>Checking for an integer type does not work for floats that are integers, e.g. <code>4.</code> Better solution is <code>np.equal(np.mod(x, 1), 0)</code>, as in:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; def isinteger(x): ... return np.equal(np.mod(x, 1), 0) ... &gt;&gt;&gt; foo = np.array([0., 1.5, 1.]) &gt;&gt;&gt; bar = np.array([-5, 1, 2, 3, -4, -2, 0, 1, 0, 0, -1, 1]) &gt;&gt;&gt; isinteger(foo) array([ True, False, True], dtype=bool) &gt;&gt;&gt; isinteger(bar) array([ True, True, True, True, True, True, True, True, True, True, True, True], dtype=bool) &gt;&gt;&gt; isinteger(1.5) False &gt;&gt;&gt; isinteger(1.) True &gt;&gt;&gt; isinteger(1) True </code></pre>
9
2011-08-29T22:34:52Z
[ "python", "numpy" ]
How do I find out if a numpy array contains integers?
934,616
<p>I know there is a simple solution to this but can't seem to find it at the moment.</p> <p>Given a numpy array, I need to know if the array contains integers.</p> <p>Checking the dtype per-se is not enough, as there are multiple int dtypes (int8, int16, int32, int64 ...). </p>
24
2009-06-01T12:27:46Z
36,203,582
<p>Numpy's issubdtype() function can be used as follows:</p> <pre><code>import numpy as np size=(3,3) A = np.random.randint(0, 255, size) B = np.random.random(size) print 'Array A:\n', A print 'Integers:', np.issubdtype(A[0,0], int) print 'Floats:', np.issubdtype(A[0,0], float) print '\nArray B:\n', B print 'Integers:', np.issubdtype(B[0,0], int) print 'Floats:', np.issubdtype(B[0,0], float) </code></pre> <p><strong>Results:</strong></p> <pre><code>Array A: [[ 9 224 33] [210 117 83] [206 139 60]] Integers: True Floats: False Array B: [[ 0.54221849 0.96021118 0.72322367] [ 0.02207826 0.55162813 0.52167972] [ 0.74106348 0.72457807 0.9705301 ]] Integers: False Floats: True </code></pre> <p>PS. Keep in mind that the elements of an array are always of the same datatype. </p>
2
2016-03-24T15:12:23Z
[ "python", "numpy" ]
Implimenting NSText delegate methods in PyObjc and Cocoa
934,628
<p>In the project that I'm building, I'd like to have a method called when I paste some text into a specific text field. I can't seem to get this to work, but here's what I've tried</p> <p>I implimented a custom class (based on NSObject) to be a delegate for my textfield, then gave it the method: textDidChange:</p> <pre><code>class textFieldDelegate(NSObject): def textDidChange_(self, notification): NSLog("textdidchange") </code></pre> <p>I then instantiated an object of this class in interface builder, and set it to be the delegate of the NSTextField. This however, doesn't seem to do anything. However, when I build the example code from <a href="http://www.programmish.com/?p=30" rel="nofollow">http://www.programmish.com/?p=30</a>, everything seems to work perfectly fine. How do I impliment this delegate code so that it actually works?</p>
3
2009-06-01T12:31:57Z
936,075
<p>The reason this isn't working for you is that <code>textDidChange_</code> isn't a delegate method. It's a method on the <code>NSTextField</code> that posts the notification of the change. If you have peek at the docs for <code>textDidChange</code>, you'll see that it mentions the actual name of the delegate method:</p> <blockquote> <p>This method causes the receiver’s delegate to receive a controlTextDidChange: message. See the NSControl class specification for more information on the text delegate method.</p> </blockquote> <p>The delegate method is actually called <code>controlTextDidChange_</code> and is declared on the <code>NSTextField</code> superclass, <code>NSControl</code>.</p> <p>Change your delegate method to:</p> <pre><code>def controlTextDidChange_(self, notification): NSLog("textdidchange") </code></pre> <p>and it should work for you.</p>
3
2009-06-01T18:24:44Z
[ "python", "cocoa", "pyobjc" ]
Python3.0 - tokenize and untokenize
934,661
<p>I am using something similar to the following simplified script to parse snippets of python from a larger file:</p> <pre><code>import io import tokenize src = 'foo="bar"' src = bytes(src.encode()) src = io.BytesIO(src) src = list(tokenize.tokenize(src.readline)) for tok in src: print(tok) src = tokenize.untokenize(src) </code></pre> <p>Although the code is not the same in python2.x, it uses the same idiom and works just fine. However, running the above snippet using python3.0, I get this output:</p> <pre><code>(57, 'utf-8', (0, 0), (0, 0), '') (1, 'foo', (1, 0), (1, 3), 'foo="bar"') (53, '=', (1, 3), (1, 4), 'foo="bar"') (3, '"bar"', (1, 4), (1, 9), 'foo="bar"') (0, '', (2, 0), (2, 0), '') Traceback (most recent call last): File "q.py", line 13, in &lt;module&gt; src = tokenize.untokenize(src) File "/usr/local/lib/python3.0/tokenize.py", line 236, in untokenize out = ut.untokenize(iterable) File "/usr/local/lib/python3.0/tokenize.py", line 165, in untokenize self.add_whitespace(start) File "/usr/local/lib/python3.0/tokenize.py", line 151, in add_whitespace assert row &lt;= self.prev_row AssertionError </code></pre> <p>I have searched for references to this error and its causes, but have been unable to find any. What am I doing wrong and how can I correct it?</p> <h3>[edit]</h3> <p>After <a href="http://stackoverflow.com/users/54982/partisann">partisann</a>'s observation that appending a newline to the source causes the error to go away, I started messing with the list I was untokenizing. It seems that the <code>EOF</code> token causes an error if not immediately preceded by a newline so removing it gets rid of the error. The following script runs without error:</p> <pre><code>import io import tokenize src = 'foo="bar"' src = bytes(src.encode()) src = io.BytesIO(src) src = list(tokenize.tokenize(src.readline)) for tok in src: print(tok) src = tokenize.untokenize(src[:-1]) </code></pre>
2
2009-06-01T12:41:21Z
934,681
<p>If you limit the input to <code>untokenize</code> to the first 2 items of the tokens, it seems to work.</p> <pre><code>import io import tokenize src = 'foo="bar"' src = bytes(src.encode()) src = io.BytesIO(src) src = list(tokenize.tokenize(src.readline)) for tok in src: print(tok) src = [t[:2] for t in src] src = tokenize.untokenize(src) </code></pre>
0
2009-06-01T12:48:53Z
[ "python", "python-3.x", "tokenize", "lexical-analysis" ]
Python3.0 - tokenize and untokenize
934,661
<p>I am using something similar to the following simplified script to parse snippets of python from a larger file:</p> <pre><code>import io import tokenize src = 'foo="bar"' src = bytes(src.encode()) src = io.BytesIO(src) src = list(tokenize.tokenize(src.readline)) for tok in src: print(tok) src = tokenize.untokenize(src) </code></pre> <p>Although the code is not the same in python2.x, it uses the same idiom and works just fine. However, running the above snippet using python3.0, I get this output:</p> <pre><code>(57, 'utf-8', (0, 0), (0, 0), '') (1, 'foo', (1, 0), (1, 3), 'foo="bar"') (53, '=', (1, 3), (1, 4), 'foo="bar"') (3, '"bar"', (1, 4), (1, 9), 'foo="bar"') (0, '', (2, 0), (2, 0), '') Traceback (most recent call last): File "q.py", line 13, in &lt;module&gt; src = tokenize.untokenize(src) File "/usr/local/lib/python3.0/tokenize.py", line 236, in untokenize out = ut.untokenize(iterable) File "/usr/local/lib/python3.0/tokenize.py", line 165, in untokenize self.add_whitespace(start) File "/usr/local/lib/python3.0/tokenize.py", line 151, in add_whitespace assert row &lt;= self.prev_row AssertionError </code></pre> <p>I have searched for references to this error and its causes, but have been unable to find any. What am I doing wrong and how can I correct it?</p> <h3>[edit]</h3> <p>After <a href="http://stackoverflow.com/users/54982/partisann">partisann</a>'s observation that appending a newline to the source causes the error to go away, I started messing with the list I was untokenizing. It seems that the <code>EOF</code> token causes an error if not immediately preceded by a newline so removing it gets rid of the error. The following script runs without error:</p> <pre><code>import io import tokenize src = 'foo="bar"' src = bytes(src.encode()) src = io.BytesIO(src) src = list(tokenize.tokenize(src.readline)) for tok in src: print(tok) src = tokenize.untokenize(src[:-1]) </code></pre>
2
2009-06-01T12:41:21Z
934,682
<p><pre><code>src = 'foo="bar"\n'</code></pre>You forgot newline.</p>
3
2009-06-01T12:49:16Z
[ "python", "python-3.x", "tokenize", "lexical-analysis" ]
Using easy_install inside a python script?
935,111
<p>easy_install python extension allows to install python eggs from console like:</p> <pre><code>easy_install py2app </code></pre> <p>But is it possible to access easy_install functionality inside a python script? I means, without calling os.system( "easy_install py2app" ) but instead importing easy_install as a python module and using it's native methods?</p>
15
2009-06-01T14:39:05Z
935,186
<p>I think you can get to that by using either importing setuptools.</p>
-2
2009-06-01T14:57:33Z
[ "python", "setuptools" ]
Using easy_install inside a python script?
935,111
<p>easy_install python extension allows to install python eggs from console like:</p> <pre><code>easy_install py2app </code></pre> <p>But is it possible to access easy_install functionality inside a python script? I means, without calling os.system( "easy_install py2app" ) but instead importing easy_install as a python module and using it's native methods?</p>
15
2009-06-01T14:39:05Z
935,219
<p>When I look at the setup tools source, it looks like you can try the following.</p> <pre><code>from setuptools.command import easy_install easy_install.main( ["-U","py2app"] ) </code></pre>
17
2009-06-01T15:05:46Z
[ "python", "setuptools" ]
Using easy_install inside a python script?
935,111
<p>easy_install python extension allows to install python eggs from console like:</p> <pre><code>easy_install py2app </code></pre> <p>But is it possible to access easy_install functionality inside a python script? I means, without calling os.system( "easy_install py2app" ) but instead importing easy_install as a python module and using it's native methods?</p>
15
2009-06-01T14:39:05Z
935,254
<p>What specifically are you trying to do? Unless you have some weird requirements, I'd recommend declaring the package as a dependency in your setup.py:</p> <pre><code>from setuptools import setup, find_packages setup( name = "HelloWorld", version = "0.1", packages = find_packages(), scripts = ['say_hello.py'], # Project uses reStructuredText, so ensure that the docutils get # installed or upgraded on the target machine install_requires = ['docutils&gt;=0.3'], package_data = { # If any package contains *.txt or *.rst files, include them: '': ['*.txt', '*.rst'], # And include any *.msg files found in the 'hello' package, too: 'hello': ['*.msg'], } # metadata for upload to PyPI author = "Me", author_email = "me@example.com", description = "This is an Example Package", license = "PSF", keywords = "hello world example examples", url = "http://example.com/HelloWorld/", # project home page, if any # could also include long_description, download_url, classifiers, etc. ) </code></pre> <p>The key line here is <code>install_requires = ['docutils&gt;=0.3']</code>. This will cause the setup.py file to automatically install this dependency unless the user specifies otherwise. You can find more documentation on this <a href="http://peak.telecommunity.com/DevCenter/setuptools#declaring-dependencies" rel="nofollow">here</a> (note that the setuptools website is extremely slow!).</p> <p>If you do have some kind of requirement that can't be satisfied this way, you should probably look at <a href="http://stackoverflow.com/questions/935111/using-easyinstall-inside-a-python-script/935219#935219">S.Lott's answer</a> (although I've never tried that myself).</p>
2
2009-06-01T15:13:47Z
[ "python", "setuptools" ]
Using easy_install inside a python script?
935,111
<p>easy_install python extension allows to install python eggs from console like:</p> <pre><code>easy_install py2app </code></pre> <p>But is it possible to access easy_install functionality inside a python script? I means, without calling os.system( "easy_install py2app" ) but instead importing easy_install as a python module and using it's native methods?</p>
15
2009-06-01T14:39:05Z
935,351
<pre><code>from setuptools.command import easy_install def install_with_easyinstall(package): easy_install.main(["-U", package]). install_with_easyinstall('py2app') </code></pre>
4
2009-06-01T15:38:08Z
[ "python", "setuptools" ]
Using easy_install inside a python script?
935,111
<p>easy_install python extension allows to install python eggs from console like:</p> <pre><code>easy_install py2app </code></pre> <p>But is it possible to access easy_install functionality inside a python script? I means, without calling os.system( "easy_install py2app" ) but instead importing easy_install as a python module and using it's native methods?</p>
15
2009-06-01T14:39:05Z
5,944,496
<p>The answer about invoking <code>setuptools.main()</code> is correct. However, if setuptools creates a .egg, the script will be unable to import the module after installing it. Eggs are added automatically to sys.path at python start time.</p> <p>One solution is to use require() to add the new egg to the path:</p> <pre><code>from setuptools.command import easy_install import pkg_resources easy_install.main( ['mymodule'] ) pkg_resources.require('mymodule') </code></pre>
0
2011-05-10T02:19:52Z
[ "python", "setuptools" ]
Cast a class instance to a subclass
935,448
<p>I'm using <a href="http://code.google.com/p/boto/" rel="nofollow">boto</a> to manage some <a href="http://aws.amazon.com/ec2/" rel="nofollow">EC2</a> instances. It provides an Instance class. I'd like to subclass it to meet my particular needs. Since boto provides a query interface to get your instances, I need something to convert between classes. This solution seems to work, but changing the class attribute seems dodgy. Is there a better way?</p> <pre><code>from boto.ec2.instance import Instance as _Instance class Instance(_Instance): @classmethod def from_instance(cls, instance): instance.__class__ = cls # set other attributes that this subclass cares about return instance </code></pre>
3
2009-06-01T15:55:54Z
936,498
<p>I wouldn't subclass and cast. I don't think casting is ever a good policy. </p> <p>Instead, consider a Wrapper or Façade.</p> <pre><code>class MyThing( object ): def __init__( self, theInstance ): self.ec2_instance = theInstance </code></pre> <p>Now, you can subclass <code>MyThing</code> as much as you want and you shouldn't need to be casting your <code>boto.ec2.instance.Instance</code> at all. It remains as a more-or-less opaque element in your object.</p>
7
2009-06-01T20:03:39Z
[ "python", "class", "subclass", "boto" ]
Python Mod_WSGI Output Buffer
935,978
<p>This is a bit of a tricky question; </p> <p>I'm working with mod_wsgi in python and want to make an output buffer that yields HTML on an ongoing basis (until the page is done loading). </p> <p>Right now I have my script set up so that the Application() function creates a separate 'Page' thread for the page code, then immediately after, it runs a continuous loop for the Output Buffer using python's Queue lib.</p> <p>Is there a better way to have this set up? I thought about making the Output Buffer be the thread (instead of Page), but the problem with that, is the Application() function is the only function that can be yielding the HTML to Apache, which (as far as I can tell, makes this idea impossible).</p> <p>The downside I'm seeing with my current setup, is in the event of an error, I can't easily interrupt the buffer and exit without the Page thread continuing on for a bit.</p> <p>(It kinda sucks that mod_wsgi doesn't have a build in output buffer to handle this, I hate loading the entire page then sending output just once, it results in a much slower page load).</p>
0
2009-06-01T18:05:40Z
936,160
<p>mod_wsgi should have built in support for Generators. So if your using a Framework like CherryPy you just need to do:</p> <pre><code>def index(): yield "Some output" #Do Somemore work yield "Some more output" </code></pre> <p>Where each yield will return to the user a chunk of the page. </p> <p>Here is some basics from CherrPy on there implementation and how it works <a href="http://www.cherrypy.org/wiki/ReturnVsYield" rel="nofollow">http://www.cherrypy.org/wiki/ReturnVsYield</a></p>
2
2009-06-01T18:45:04Z
[ "python", "buffer", "mod-wsgi", "output-buffering" ]
Python Mod_WSGI Output Buffer
935,978
<p>This is a bit of a tricky question; </p> <p>I'm working with mod_wsgi in python and want to make an output buffer that yields HTML on an ongoing basis (until the page is done loading). </p> <p>Right now I have my script set up so that the Application() function creates a separate 'Page' thread for the page code, then immediately after, it runs a continuous loop for the Output Buffer using python's Queue lib.</p> <p>Is there a better way to have this set up? I thought about making the Output Buffer be the thread (instead of Page), but the problem with that, is the Application() function is the only function that can be yielding the HTML to Apache, which (as far as I can tell, makes this idea impossible).</p> <p>The downside I'm seeing with my current setup, is in the event of an error, I can't easily interrupt the buffer and exit without the Page thread continuing on for a bit.</p> <p>(It kinda sucks that mod_wsgi doesn't have a build in output buffer to handle this, I hate loading the entire page then sending output just once, it results in a much slower page load).</p>
0
2009-06-01T18:05:40Z
937,324
<blockquote> <p>(It kinda sucks that mod_wsgi doesn't have a build in output buffer to handle this, I hate loading the entire page then sending output just once, it results in a much slower page load).</p> </blockquote> <p>Unless you're doing some kind of streaming or asynchronous application, you want to send the entire page all at once 99.9% of the time. The only exception that I can think of is if you're sending a <em>big</em> webpage (and by big, I mean in the hundreds of Megabytes).</p> <p>The reason why I mention this is to point out that if you're having performance problems, it's likely not because you're buffering output. The simplest way to handle this is to do something like this:</p> <pre><code>def Application(environ, start_response): start_response('200 Ok', [('Content-type','text/plain')]) response = [] response.append('&lt;h1&gt;') response.append('hello, world!') response.append('&lt;/h1&gt;') return [''.join(response)] #returns ['&lt;h1&gt;hello, world!&lt;/h1&gt;'] </code></pre> <p>Your best bet is to use a mutable data structure like a list to hold the chunks of the message and then join them together in a string as I did above. Unless you have some kind of special need, this is probably the best general approach.</p>
2
2009-06-01T23:41:08Z
[ "python", "buffer", "mod-wsgi", "output-buffering" ]
An algorithm to generate subsets of a set satisfying certian conditions
936,015
<p>Suppose I am given a sorted list of elements and I want to generate all subsets satisfying some condition, so that if a given set does not satisfy the condition, then a larger subset will also not satisfy it, and all sets of one element do satisfy it.</p> <p>For example, given a list of all positive integers smaller than 100, determine subsets whose sum is smaller than 130: (100,29) (0,1,40), (0), etc...</p> <p>How can I do that (preferably in Python)?</p> <p>Thanks! :)</p>
0
2009-06-01T18:13:13Z
936,053
<p>There are certainly ways to do it, but unless you can constrain the condition somehow, it's going to take O(2^n) steps. If you consider, for example a condition on 1–100 where all the subsets would be selected (eg, &lt; &Sigma; <em>i</em> for <em>i</em> in 1-<em>n</em>), then you would end up enumerating all the subsets.</p> <p>You'd be looking at</p> <pre><code>for i in the powerset of {1-n} if cond(i) note that set </code></pre> <p>You can get the powerset of the set by simply generating all binary numbers from 0 to s<em>n</em>-1, and choosing element i for the subset when bit i is 1.</p>
1
2009-06-01T18:20:22Z
[ "python", "algorithm", "subset" ]
An algorithm to generate subsets of a set satisfying certian conditions
936,015
<p>Suppose I am given a sorted list of elements and I want to generate all subsets satisfying some condition, so that if a given set does not satisfy the condition, then a larger subset will also not satisfy it, and all sets of one element do satisfy it.</p> <p>For example, given a list of all positive integers smaller than 100, determine subsets whose sum is smaller than 130: (100,29) (0,1,40), (0), etc...</p> <p>How can I do that (preferably in Python)?</p> <p>Thanks! :)</p>
0
2009-06-01T18:13:13Z
936,124
<p>You can generate all the subsets using a <a href="http://en.wikipedia.org/wiki/Branch%5Fand%5Fbound" rel="nofollow">Branch-and-bound</a> technique: you can generate all the subsets in an incremental fashion (generating superset of subsets already determined), using as a prune condition "does not explore this branch of the tree if the root does not satify the constraint".</p> <p>If you want to be generic regarding the constraint, I think this is the best strategy.</p> <p>Be sure to write in a correct manner the code that generates the subsets, otherwise you generate many time the same subsets: in order to avoid memoization, which can be time-consuming due to map lookups and introduce memory overhead, you can generate the subsets in that manner:</p> <pre><code>GetAllSubsets(List objects) { List generated = {}; GetAllSubsets(generated, [], objects); return generated; } GetAllSubsets(List subsetGenerated, List objectFixed, List objectsToFix) { GetAllSubsets(subsetGenerated, objectFixed, objectsToFix.sublist(1, objectsToFix.length()); if (satisfy(toCheck = objectsFixed.add(objectsToFix.get(0)))) { subsetGenerated.add(toCheck); GetAllSubsets(subsetGenerated, toCheck, objectsToFix.sublist(1, objectsToFix.length()); } } </code></pre> <p>In fact, the subsets added by the first invocation of GetAllSubsets doesn't have the first element of objectsToFix, where the subsets added by the second call (if the pruning condition isn't violated) have that element, so the intersection of the two sets of subsets generated is empty.</p>
4
2009-06-01T18:34:04Z
[ "python", "algorithm", "subset" ]
An algorithm to generate subsets of a set satisfying certian conditions
936,015
<p>Suppose I am given a sorted list of elements and I want to generate all subsets satisfying some condition, so that if a given set does not satisfy the condition, then a larger subset will also not satisfy it, and all sets of one element do satisfy it.</p> <p>For example, given a list of all positive integers smaller than 100, determine subsets whose sum is smaller than 130: (100,29) (0,1,40), (0), etc...</p> <p>How can I do that (preferably in Python)?</p> <p>Thanks! :)</p>
0
2009-06-01T18:13:13Z
936,189
<p>You could construct your sets recursively, starting with the empty set and attempting to add more elements, giving up on a recursive line of execution if one of the subsets (and thus all of its supersets) fails to meet the condition. Here's some pseudocode, assuming a set S whose condition-satisfying subsets you would like to list. For convenience, assume that the elements of S can be indexed as x(0), x(1), x(2), ... </p> <pre><code>EnumerateQualifyingSets(Set T) { foreach (x in S with an index larger than the index of any element in T) { U = T union {x} if (U satisfies condition) { print U EnumerateQualifyingSets(U) } } } </code></pre> <p>The first call would be with T as the empty set. Then, all the subsets of S matching the condition would be printed. This strategy relies crucially on the fact that a subset of S which does not meet the condition cannot be contained in one that does.</p>
2
2009-06-01T18:55:35Z
[ "python", "algorithm", "subset" ]
An algorithm to generate subsets of a set satisfying certian conditions
936,015
<p>Suppose I am given a sorted list of elements and I want to generate all subsets satisfying some condition, so that if a given set does not satisfy the condition, then a larger subset will also not satisfy it, and all sets of one element do satisfy it.</p> <p>For example, given a list of all positive integers smaller than 100, determine subsets whose sum is smaller than 130: (100,29) (0,1,40), (0), etc...</p> <p>How can I do that (preferably in Python)?</p> <p>Thanks! :)</p>
0
2009-06-01T18:13:13Z
936,274
<p>I've done something similar for a class schedule generating algorithm. Our schedule class had 2 elements - a list of courses added to the schedule, and a list of courses available to add.</p> <p>Pseudocode:</p> <pre><code>queue.add(new schedule(null, available_courses)) while( queue is not empty ) sched = queue.next() foreach class in sched.available_courses temp_sched = sched.copy() temp_sched.add(class) if(temp_sched.is_valid()) results.add(temp_sched) queue.add(temp_sched) </code></pre> <p>The idea is to start with an empty schedule and the list of available classes, and to search down the tree for valid schedules (valid meaning fits the requirements given by the user, doesn't have time conflicts, etc). If a schedule is invalid, it is thrown away - we can't make an invalid schedule valid by adding classes (ie, pruning the tree).</p> <p>It should be pretty easy to modify this to work with your problem.</p>
1
2009-06-01T19:13:33Z
[ "python", "algorithm", "subset" ]
An algorithm to generate subsets of a set satisfying certian conditions
936,015
<p>Suppose I am given a sorted list of elements and I want to generate all subsets satisfying some condition, so that if a given set does not satisfy the condition, then a larger subset will also not satisfy it, and all sets of one element do satisfy it.</p> <p>For example, given a list of all positive integers smaller than 100, determine subsets whose sum is smaller than 130: (100,29) (0,1,40), (0), etc...</p> <p>How can I do that (preferably in Python)?</p> <p>Thanks! :)</p>
0
2009-06-01T18:13:13Z
936,335
<p>Here's a concrete example of akappa's answer, using a recursive function to generate the subsets:</p> <pre><code>def restofsubsets(goodsubset, remainingels, condition): answers = [] for j in range(len(remainingels)): nextsubset = goodsubset + remainingels[j:j+1] if condition(nextsubset): answers.append(nextsubset) answers += restofsubsets(nextsubset, remainingels[j+1:], condition) return answers #runs slowly easieranswer = restofsubsets([], range(101), lambda l:sum(l)&lt;40) #runs much faster due to eliminating big numbers first fasteranswer = restofsubsets([], range(100,-1,-1), lambda l:sum(l)&lt;40) #runs extremely slow even with big-numbers-first strategy finalanswer = restofsubsets([], range(100,-1,-1), lambda l:sum(l)&lt;130) </code></pre>
1
2009-06-01T19:26:26Z
[ "python", "algorithm", "subset" ]
An algorithm to generate subsets of a set satisfying certian conditions
936,015
<p>Suppose I am given a sorted list of elements and I want to generate all subsets satisfying some condition, so that if a given set does not satisfy the condition, then a larger subset will also not satisfy it, and all sets of one element do satisfy it.</p> <p>For example, given a list of all positive integers smaller than 100, determine subsets whose sum is smaller than 130: (100,29) (0,1,40), (0), etc...</p> <p>How can I do that (preferably in Python)?</p> <p>Thanks! :)</p>
0
2009-06-01T18:13:13Z
18,223,946
<p>I think in the worst case, you still have to generate all subsets and calculate the sum of each set to determine if it is qualify or not. Asymptotically, it is the cost of subsets generating procedure.</p> <p>The following is the method I implemented in javascript for the same idea. </p> <pre><code>//this is to generate an array to test var numbers = (function(start, end){ var result = [], i = start; for(; i &lt;= end; i++){ result.push(i); } return result; })(1, 12); //this is the qualifying function to determine if the generated array is qualified var fn = (function(maxSum){ return function(set){ var sum = 0; for(var i = 0 ; i&lt; set.length; i++){ sum += set[i]; if( sum &gt; maxSum ){ return false; } } return true; } })(30); //main function (function(input, qualifyingFn){ var result, mask, total = Math.pow(2, input.length); for(mask = 0; mask &lt; total; mask++){ result = []; sum = 0; i = input.length - 1; do{ if( (mask &amp; (1 &lt;&lt; i)) !== 0){ result.push(input[i]); sum += input[i]; if( sum &gt; 30 ){ break; } } }while(i--); if( qualifyingFn(result) ){ console.log(JSON.stringify(result)); } } })(numbers, fn); </code></pre>
0
2013-08-14T05:37:54Z
[ "python", "algorithm", "subset" ]
Is there an Oracle wrapper for Python that supports xmltype columns?
936,381
<p>It seems cx_Oracle doesn't.</p> <p>Any other suggestion for handling xml with Oracle and Python is appreciated.</p> <p>Thanks.</p>
5
2009-06-01T19:36:17Z
936,404
<p>(edited to remove mention of a non-Oracle Python DB-API module and add some more relevant and hopefully useful info).</p> <p>Don't know of any alternative to <code>cx_oracle</code> (as the DCOracle2 author <a href="http://www.zope.org/Members/matt/dco2/" rel="nofollow">says</a>, "DCOracle2 is currently unmaintained, and no support is available." so it's not really an alternative).</p> <p>However, a recent <a href="http://www.oracle.com/technology/pub/articles/vasiliev-python-persistence.html" rel="nofollow">article</a> on Oracle's own site asserts that (at least with recent releases such as Oracle 10g XE -- and presumably recent cx_oracle releases) Python can work with Oracle's XML support -- I don't know if the examples in that article can help you address your issues, but I sure hope so!</p>
0
2009-06-01T19:41:55Z
[ "python", "xml", "oracle", "xmltype" ]
Is there an Oracle wrapper for Python that supports xmltype columns?
936,381
<p>It seems cx_Oracle doesn't.</p> <p>Any other suggestion for handling xml with Oracle and Python is appreciated.</p> <p>Thanks.</p>
5
2009-06-01T19:36:17Z
946,854
<p>I managed to do this with cx_Oracle.</p> <p>I used the sys.xmltype.createxml() function in the statement that inserts the rows in a table with XMLTYPE fields; then I used prepare() and setinputsizes() to specify that the bind variables I used for XMLTYPE fields were of cx_Oracle.CLOB type.</p>
1
2009-06-03T20:00:08Z
[ "python", "xml", "oracle", "xmltype" ]
Is there an Oracle wrapper for Python that supports xmltype columns?
936,381
<p>It seems cx_Oracle doesn't.</p> <p>Any other suggestion for handling xml with Oracle and Python is appreciated.</p> <p>Thanks.</p>
5
2009-06-01T19:36:17Z
2,858,568
<p>I managed to get this to work by wrapping the XMLElement call in a call to <code>XMLType.GetClobVal()</code>:</p> <p>For example:</p> <pre><code>select xmltype.getclobval(xmlelement("rowcount", count(1))) from... </code></pre> <p>No idea of the limitations yet but it got me out of trouble. Found the relelvant info on Oracle site: <a href="http://www.oracle.com/technology/pub/articles/prez-python-queries.html" rel="nofollow">Mastering Oracle+Python, Part 1: Querying Best Practices</a></p>
1
2010-05-18T15:13:49Z
[ "python", "xml", "oracle", "xmltype" ]
Retrieving network mask in Python
936,444
<p>How would one go about retrieving a network device's netmask (In Linux preferably, but if it's cross-platform then cool)? I know how in C on Linux but I can't find a way in Python -- minus ctypes perhaps. That or parsing ifconfig. Any other way?</p> <pre><code>ioctl(socknr, SIOCGIFNETMASK, &amp;ifreq) // C version </code></pre>
3
2009-06-01T19:50:14Z
936,469
<p>Did you look here?</p> <p><a href="http://docs.python.org/library/fcntl.html" rel="nofollow">http://docs.python.org/library/fcntl.html</a></p> <p>This works for me in python 2.5.2 on Linux. Was finishing it when Ben got ahead, but still here it goes (sad to waste the effort :-) ):</p> <pre><code>vinko@parrot:~$ more get_netmask.py # get_netmask.py by Vinko Vrsalovic 2009 # Inspired by http://code.activestate.com/recipes/439093/ # and http://code.activestate.com/recipes/439094/ # Code: 0x891b SIOCGIFNETMASK import socket import fcntl import struct import sys def get_netmask(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x891b, struct.pack('256 s',ifname))[20:24]) if len(sys.argv) == 2: print get_netmask(sys.argv[1]) vinko@parrot:~$ python get_netmask.py lo 255.0.0.0 vinko@parrot:~$ python get_netmask.py eth0 255.255.255.0 </code></pre>
3
2009-06-01T19:57:33Z
[ "python" ]
Retrieving network mask in Python
936,444
<p>How would one go about retrieving a network device's netmask (In Linux preferably, but if it's cross-platform then cool)? I know how in C on Linux but I can't find a way in Python -- minus ctypes perhaps. That or parsing ifconfig. Any other way?</p> <pre><code>ioctl(socknr, SIOCGIFNETMASK, &amp;ifreq) // C version </code></pre>
3
2009-06-01T19:50:14Z
936,536
<p><a href="http://code.activestate.com/recipes/439094/">This</a> works for me in Python 2.2 on Linux:</p> <pre><code>iface = "eth0" socket.inet_ntoa(fcntl.ioctl(socket.socket(socket.AF_INET, socket.SOCK_DGRAM), 35099, struct.pack('256s', iface))[20:24]) </code></pre>
5
2009-06-01T20:13:31Z
[ "python" ]
Retrieving network mask in Python
936,444
<p>How would one go about retrieving a network device's netmask (In Linux preferably, but if it's cross-platform then cool)? I know how in C on Linux but I can't find a way in Python -- minus ctypes perhaps. That or parsing ifconfig. Any other way?</p> <pre><code>ioctl(socknr, SIOCGIFNETMASK, &amp;ifreq) // C version </code></pre>
3
2009-06-01T19:50:14Z
937,213
<p>In Windows this piece of code may be useful:</p> <pre> import os import sys import _winreg def main(): adapter_list_key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards') adapter_count = _winreg.QueryInfoKey(adapter_list_key)[0] for i in xrange(adapter_count): sub_key_name = _winreg.EnumKey(adapter_list_key, i) adapter_key = _winreg.OpenKey(adapter_list_key, sub_key_name) (adapter_service_name, _) = _winreg.QueryValueEx(adapter_key, "ServiceName") (description, _) = _winreg.QueryValueEx(adapter_key, "Description") adapter_registry_path = os.path.join(r'SYSTEM\ControlSet001\Services', adapter_service_name, "Parameters", "Tcpip") adapter_service_key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, adapter_registry_path) (subnet_mask, _) = _winreg.QueryValueEx(adapter_service_key, "SubnetMask") (ip_address, _) = _winreg.QueryValueEx(adapter_service_key, "IpAddress") sys.stdout.write("Name: %s\n" % adapter_service_name) sys.stdout.write("Description: %s\n" % description) sys.stdout.write("SubnetMask: %s\n" % subnet_mask) sys.stdout.write("IpAdress: %s\n" % ip_address) if __name__ == "__main__": main() </pre> <p>Get network adapters list from <strong>HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards</strong> registry key and than extract more info about each adapter from <strong>HKLM\SYSTEM\ControlSet001\Services{adapter_guid}\Parameters\Tcpip</strong> key. </p> <p>I test it on Windows XP with 2 virtual adapters, it works fine. Should work in 2000,2003, Vista too.</p>
1
2009-06-01T22:57:53Z
[ "python" ]
Retrieving network mask in Python
936,444
<p>How would one go about retrieving a network device's netmask (In Linux preferably, but if it's cross-platform then cool)? I know how in C on Linux but I can't find a way in Python -- minus ctypes perhaps. That or parsing ifconfig. Any other way?</p> <pre><code>ioctl(socknr, SIOCGIFNETMASK, &amp;ifreq) // C version </code></pre>
3
2009-06-01T19:50:14Z
2,649,654
<p>You can use this library: <a href="http://github.com/rlisagor/pynetlinux" rel="nofollow">http://github.com/rlisagor/pynetlinux</a>. Note: I'm the author of the library.</p>
1
2010-04-15T23:25:03Z
[ "python" ]