title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Why saving of MSWord document can silently fail? | 1,340,950 | <p>I need to change some custom properties values in many files. Here is an example of code - how I do it for a single file:</p>
<pre><code>import win32com.client
MSWord = win32com.client.Dispatch("Word.Application")
MSWord.Visible = False
doc = MSWord.Documents.Open(file)
doc.CustomDocumentProperties('Some Property').Value = 'Some New Value'
doc.Save()
doc.Close()
MSWord.Quit()
</code></pre>
<p>Running the same code for <code>"Excel.Application"</code> (with minor changes - just to make it work) gives me excellent result. However when I'm using <code>doc.Save()</code> or <code>doc.SaveAs(same_file)</code> for MSWord it silently fails. I don't know why, but changes are not saved. </p>
<p>Now my workaround is to use <code>SaveAs</code> to a different file, it also works good. But I want to understand why I have such strange behaviour for MSWord files and how it can be fixed?</p>
<p><strong>Edit</strong>: I changed my code, not to misdirect people with silent fail cause of try/except.
However, thanks to all of them for finding that defect in my code :)</p>
| 3 | 2009-08-27T13:02:27Z | 1,341,028 | <p>It fails silently since you ignore errors (<code>except: pass</code>).</p>
<p>The most common reason why saving a Word file usually fails is that it's open in Word.</p>
| 0 | 2009-08-27T13:14:58Z | [
"python",
"automation",
"ms-word",
"ole"
] |
Why saving of MSWord document can silently fail? | 1,340,950 | <p>I need to change some custom properties values in many files. Here is an example of code - how I do it for a single file:</p>
<pre><code>import win32com.client
MSWord = win32com.client.Dispatch("Word.Application")
MSWord.Visible = False
doc = MSWord.Documents.Open(file)
doc.CustomDocumentProperties('Some Property').Value = 'Some New Value'
doc.Save()
doc.Close()
MSWord.Quit()
</code></pre>
<p>Running the same code for <code>"Excel.Application"</code> (with minor changes - just to make it work) gives me excellent result. However when I'm using <code>doc.Save()</code> or <code>doc.SaveAs(same_file)</code> for MSWord it silently fails. I don't know why, but changes are not saved. </p>
<p>Now my workaround is to use <code>SaveAs</code> to a different file, it also works good. But I want to understand why I have such strange behaviour for MSWord files and how it can be fixed?</p>
<p><strong>Edit</strong>: I changed my code, not to misdirect people with silent fail cause of try/except.
However, thanks to all of them for finding that defect in my code :)</p>
| 3 | 2009-08-27T13:02:27Z | 1,341,031 | <p>you're saving file only if <code>Value</code> was successfully changed. May be you could try to remove <code>try</code>-<code>except</code> clause and see what is actually happening when you're file is not saved. And, btw, using bare <code>except</code> is not a good practice.</p>
| 1 | 2009-08-27T13:15:17Z | [
"python",
"automation",
"ms-word",
"ole"
] |
Why saving of MSWord document can silently fail? | 1,340,950 | <p>I need to change some custom properties values in many files. Here is an example of code - how I do it for a single file:</p>
<pre><code>import win32com.client
MSWord = win32com.client.Dispatch("Word.Application")
MSWord.Visible = False
doc = MSWord.Documents.Open(file)
doc.CustomDocumentProperties('Some Property').Value = 'Some New Value'
doc.Save()
doc.Close()
MSWord.Quit()
</code></pre>
<p>Running the same code for <code>"Excel.Application"</code> (with minor changes - just to make it work) gives me excellent result. However when I'm using <code>doc.Save()</code> or <code>doc.SaveAs(same_file)</code> for MSWord it silently fails. I don't know why, but changes are not saved. </p>
<p>Now my workaround is to use <code>SaveAs</code> to a different file, it also works good. But I want to understand why I have such strange behaviour for MSWord files and how it can be fixed?</p>
<p><strong>Edit</strong>: I changed my code, not to misdirect people with silent fail cause of try/except.
However, thanks to all of them for finding that defect in my code :)</p>
| 3 | 2009-08-27T13:02:27Z | 1,361,808 | <p>You were using the <code>CustomDocumentProperties</code> in the wrong way, and as other people pointed out, you could not see it, because you were swallowing the exception.</p>
<p>Moreover - and here I could not find anything in the documentation - the <code>Saved</code> property was not reset while changing properties, and for this reason the file was not changed.</p>
<p>This is the correct code:</p>
<pre><code>msoPropertyTypeBoolean = 0
msoPropertyTypeDate = 1
msoPropertyTypeFloat = 2
msoPropertyTypeNumber = 3
msoPropertyTypeString = 4
import win32com.client
MSWord = win32com.client.Dispatch("Word.Application")
MSWord.Visible = False
doc = MSWord.Documents.Open(file)
csp = doc.CustomDocumentProperties
csp.Add('Some Property', False, msoPropertyTypeString, 'Some New Value')
doc.Saved = False
doc.Save()
doc.Close()
MSWord.Quit()
</code></pre>
<p>Note: there is no error handling, and it is definitely not of production quality, but it should be enough for you to implement your functionality.<br />
Finally, I am guessing the values of the property types (and for the string type the guess is correct) but for the others there could be some issue.</p>
| 3 | 2009-09-01T11:00:32Z | [
"python",
"automation",
"ms-word",
"ole"
] |
How do I get PyParsing set up on the Google App Engine? | 1,341,137 | <p>I saw on the Google App Engine documentation that <a href="http://www.antlr.org/" rel="nofollow">http://www.antlr.org/</a> Antlr3 is used as the parsing third party library.</p>
<p>But from what I know Pyparsing seems to be the easier to use and I am only aiming to parse some simple syntax. </p>
<p>Is there an alternative? Can I get pyparsing working on the App Engine?</p>
| 1 | 2009-08-27T13:35:21Z | 1,341,822 | <p>"Just do it"!-) Get pyparsing.py, e.g. from <a href="http://pyparsing.svn.sourceforge.net/viewvc/pyparsing/src/pyparsing.py?revision=181" rel="nofollow">here</a>, and put it in your app engine app's directory; now you can just <code>import pyparsing</code> in your app code and use it.</p>
<p>For example, tweak the greeting.py from <a href="http://pyparsing.wikispaces.com/page/view/home/81583791" rel="nofollow">here</a> to be:</p>
<pre><code>from pyparsing import Word, alphas
greet = Word( alphas ) + "," + Word( alphas ) + "!" # <-- grammar defined here
hello = "Hello, World!"
print "Content-type: text/plain\n"
print hello, "->", greet.parseString( hello )
</code></pre>
<p>add to your app.yaml right under <code>handlers:</code> the two lines:</p>
<pre><code>- url: /parshello
script: greeting.py
</code></pre>
<p>start your app, visit <code>http://localhost:8083/parshello</code> (or whatever port you're running on;-), and you'll see in your browser the plain text output:</p>
<pre><code>Hello, World! -> ['Hello', ',', 'World', '!']
</code></pre>
| 1 | 2009-08-27T15:27:32Z | [
"python",
"google-app-engine",
"pyparsing"
] |
How do I get PyParsing set up on the Google App Engine? | 1,341,137 | <p>I saw on the Google App Engine documentation that <a href="http://www.antlr.org/" rel="nofollow">http://www.antlr.org/</a> Antlr3 is used as the parsing third party library.</p>
<p>But from what I know Pyparsing seems to be the easier to use and I am only aiming to parse some simple syntax. </p>
<p>Is there an alternative? Can I get pyparsing working on the App Engine?</p>
| 1 | 2009-08-27T13:35:21Z | 1,351,445 | <p>Pyparsing's runtime footprint is intentionally small for just this purpose. It is a single source file, pyparsing.py, so just drop it in amongst your own source files and parse away!</p>
<p>-- Paul</p>
| 4 | 2009-08-29T13:29:24Z | [
"python",
"google-app-engine",
"pyparsing"
] |
python: dictionaries of lists are somehow coupled | 1,341,208 | <p>I wrote a small python program to iterate over data file (*input_file*) and perform calculations. If calculation result reaches certain states (<em>stateA</em> or <em>stateB</em>), information (<em>hits</em>) are extracted from the results. The hits to extract depend on parameters from three parameter sets.<br />
I used a dictionary of dictionaries to store my parameter sets (*param_sets*) and a dictionary of lists to store the hits (<em>hits</em>). The dictionaries *param_sets* and <em>hits</em> have the same keys. </p>
<p>The problem is, </p>
<p>that the lists within the <em>hits</em> dictionary are somehow coupled. When one list changes (by calling *extract_hits* function), the others change, too. </p>
<p>Here, the (shortened) code: </p>
<pre><code>import os, sys, csv, pdb
from operator import itemgetter
# define three parameter sets
param_sets = {
'A' : {'MIN_LEN' : 8, 'MAX_X' : 0, 'MAX_Z' : 0},
'B' : {'MIN_LEN' : 8, 'MAX_X' : 1, 'MAX_Z' : 5},
'C' : {'MIN_LEN' : 9, 'MAX_X' : 1, 'MAX_Z' : 5}}
# to store hits corresponding to each parameter set
hits = dict.fromkeys(param_sets, [])
# calculations
result = []
for input_values in input_file:
# do some calculations
result = do_some_calculations(result, input_values)
if result == stateA:
for key in param_sets.keys():
hits[key] = extract_hits(key, result,
hits[key],
param_sets[key]['MIN_LEN'],
param_sets[key]['MAX_X'],
param_sets[key]['MAX_Z'])
result = [] # discard results, start empty result list
elif result == stateB:
for key in param_sets.keys():
local_heli[key] = extract_hits(key,
result,
hits[key],
param_sets[key]['MIN_LEN'],
param_sets[key]['MAX_X'],
param_sets[key]['MAX_Z'])
result = [] # discard results
result = some_calculation(input_values) # start new result list
else:
result = some_other_calculation(result) # append result list
def extract_hits(k, seq, hits, min_len, max_au, max_gu):
max_len = len(seq)
for sub_seq_size in reversed(range(min_len, max_len+1)):
for start_pos in range(0,(max_len-sub_seq_size+1)):
from_inc = start_pos
to_exc = start_pos + sub_seq_size
sub_seq = seq[from_inc:to_exc]
# complete information about helical fragment sub_seq
helical_fragment = get_helix_data(sub_seq, max_au, max_gu)
if helical_fragment:
hits.append(helical_fragment)
# search seq regions left and right from sub_seq for further hits
left_seq = seq[0:from_inc]
right_seq = seq[to_exc:max_len]
if len(left_seq) >= min_len:
hits = sub_check_helical(left_seq, hits, min_len, max_au, max_gu)
if len(right_seq) >= min_len:
hits = sub_check_helical(right_seq, hits, min_len, max_au, max_gu)
print 'key', k # just for testing purpose
print 'new', hits # just for testing purpose
print 'frag', helical_fragment # just for testing purpose
pdb.set_trace() # just for testing purpose
return hits # appended
return hits # unchanged
</code></pre>
<p>here, some output from the python debugger: </p>
<pre><code>key A
new ['x', 'x', 'x', {'y': 'GGCCGGGCUUGGU'}]
frag {'y': 'GGCCGGGCUUGGU'}
>
-> return hits
(Pdb) c
key B
new [{'y': 'GGCCGGGCUUGGU'}, {'y': 'CCGGCCCGAGCCG'}]
frag {'y': 'CCGGCCCGAGCCG'}
> extract_hits()
-> return hits
(Pdb) c
key C
new [{'y': 'GGCCGGGCUUGGU'}, {'y': 'CCGGCCCGAGCCG'}, {'y': 'CCGGCCCG'}]
frag {'y': 'CCGGCCCG'}
> extract_hits()
-> return hits
</code></pre>
<p>the elements from <em>key A</em> should not be present in <em>key B</em> and elements from key A and key B should not be present in <em>key C</em>. </p>
| 1 | 2009-08-27T13:45:37Z | 1,341,240 | <p>Dictionaries and lists are passed around by reference by default. For a dictionary, instead of:</p>
<pre><code>hits_old = hits # just for testing purpose
</code></pre>
<p>it would be:</p>
<pre><code>hits_old = hits.copy() # just for testing purpose
</code></pre>
<p>This will copy the dictionary's key/value pairings, resulting in an equivalent dictionary, that would not contain future changes to the hits dictionary.</p>
<p>Of course, hits_old in the second function is actually a list, not a dictionary, so you would want to do something akin to the following to copy it:</p>
<pre><code>hits_old = hits[:]
</code></pre>
<p>I haven't a clue why lists don't also have the copy() function, in case you're wondering.</p>
| 4 | 2009-08-27T13:50:08Z | [
"python",
"variables",
"dictionary"
] |
python: dictionaries of lists are somehow coupled | 1,341,208 | <p>I wrote a small python program to iterate over data file (*input_file*) and perform calculations. If calculation result reaches certain states (<em>stateA</em> or <em>stateB</em>), information (<em>hits</em>) are extracted from the results. The hits to extract depend on parameters from three parameter sets.<br />
I used a dictionary of dictionaries to store my parameter sets (*param_sets*) and a dictionary of lists to store the hits (<em>hits</em>). The dictionaries *param_sets* and <em>hits</em> have the same keys. </p>
<p>The problem is, </p>
<p>that the lists within the <em>hits</em> dictionary are somehow coupled. When one list changes (by calling *extract_hits* function), the others change, too. </p>
<p>Here, the (shortened) code: </p>
<pre><code>import os, sys, csv, pdb
from operator import itemgetter
# define three parameter sets
param_sets = {
'A' : {'MIN_LEN' : 8, 'MAX_X' : 0, 'MAX_Z' : 0},
'B' : {'MIN_LEN' : 8, 'MAX_X' : 1, 'MAX_Z' : 5},
'C' : {'MIN_LEN' : 9, 'MAX_X' : 1, 'MAX_Z' : 5}}
# to store hits corresponding to each parameter set
hits = dict.fromkeys(param_sets, [])
# calculations
result = []
for input_values in input_file:
# do some calculations
result = do_some_calculations(result, input_values)
if result == stateA:
for key in param_sets.keys():
hits[key] = extract_hits(key, result,
hits[key],
param_sets[key]['MIN_LEN'],
param_sets[key]['MAX_X'],
param_sets[key]['MAX_Z'])
result = [] # discard results, start empty result list
elif result == stateB:
for key in param_sets.keys():
local_heli[key] = extract_hits(key,
result,
hits[key],
param_sets[key]['MIN_LEN'],
param_sets[key]['MAX_X'],
param_sets[key]['MAX_Z'])
result = [] # discard results
result = some_calculation(input_values) # start new result list
else:
result = some_other_calculation(result) # append result list
def extract_hits(k, seq, hits, min_len, max_au, max_gu):
max_len = len(seq)
for sub_seq_size in reversed(range(min_len, max_len+1)):
for start_pos in range(0,(max_len-sub_seq_size+1)):
from_inc = start_pos
to_exc = start_pos + sub_seq_size
sub_seq = seq[from_inc:to_exc]
# complete information about helical fragment sub_seq
helical_fragment = get_helix_data(sub_seq, max_au, max_gu)
if helical_fragment:
hits.append(helical_fragment)
# search seq regions left and right from sub_seq for further hits
left_seq = seq[0:from_inc]
right_seq = seq[to_exc:max_len]
if len(left_seq) >= min_len:
hits = sub_check_helical(left_seq, hits, min_len, max_au, max_gu)
if len(right_seq) >= min_len:
hits = sub_check_helical(right_seq, hits, min_len, max_au, max_gu)
print 'key', k # just for testing purpose
print 'new', hits # just for testing purpose
print 'frag', helical_fragment # just for testing purpose
pdb.set_trace() # just for testing purpose
return hits # appended
return hits # unchanged
</code></pre>
<p>here, some output from the python debugger: </p>
<pre><code>key A
new ['x', 'x', 'x', {'y': 'GGCCGGGCUUGGU'}]
frag {'y': 'GGCCGGGCUUGGU'}
>
-> return hits
(Pdb) c
key B
new [{'y': 'GGCCGGGCUUGGU'}, {'y': 'CCGGCCCGAGCCG'}]
frag {'y': 'CCGGCCCGAGCCG'}
> extract_hits()
-> return hits
(Pdb) c
key C
new [{'y': 'GGCCGGGCUUGGU'}, {'y': 'CCGGCCCGAGCCG'}, {'y': 'CCGGCCCG'}]
frag {'y': 'CCGGCCCG'}
> extract_hits()
-> return hits
</code></pre>
<p>the elements from <em>key A</em> should not be present in <em>key B</em> and elements from key A and key B should not be present in <em>key C</em>. </p>
| 1 | 2009-08-27T13:45:37Z | 1,341,718 | <p>Your line:</p>
<pre><code>hits = dict.fromkeys(param_sets, [])
</code></pre>
<p>is equivalent to:</p>
<pre><code>hits = dict()
onelist = []
for k in param_sets:
hits[k] = onelist
</code></pre>
<p>That is, every entry in <code>hits</code> has as its value the SAME list object, initially empty, no matter what key it has. Remember that assignment does NOT perform implicit copies: rather, it assigns "one more reference to the RHS object".</p>
<p>What you want is:</p>
<pre><code>hits = dict()
for k in param_sets:
hits[k] = []
</code></pre>
<p>that is, a NEW AND SEPARATE list object as each entry's value. Equivalently,</p>
<pre><code>hits = dict((k, []) for k in param_sets)
</code></pre>
<p>BTW, when you <em>do</em> need to make a (shallow) copy of a container, the most general approach is generally to call the container's type, with the old container as the argument, as in:</p>
<pre><code>newdict = dict(olddict)
newlist = list(oldlist)
newset = set(oldset)
</code></pre>
<p>and so forth; this also work to transform containers among types (<code>newlist = list(oldset)</code> makes a list out of a set, and so on).</p>
| 8 | 2009-08-27T15:10:05Z | [
"python",
"variables",
"dictionary"
] |
How to make the python interpreter correctly handle non-ASCII characters in string operations? | 1,342,000 | <p>I have a string that looks like so:</p>
<pre><code>6ÃÂ 918ÃÂ 417ÃÂ 712
</code></pre>
<p>The clear cut way to trim this string (as I understand Python) is simply to say the string is in a variable called <code>s</code>, we get:</p>
<pre><code>s.replace('Ã ', '')
</code></pre>
<p>That should do the trick. But of course it complains that the non-ASCII character <code>'\xc2'</code> in file blabla.py is not encoded.</p>
<p>I never quite could understand how to switch between different encodings.</p>
<p>Here's the code, it really is just the same as above, but now it's in context. The file is saved as UTF-8 in notepad and has the following header:</p>
<pre><code>#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
</code></pre>
<p>The code:</p>
<pre><code>f = urllib.urlopen(url)
soup = BeautifulSoup(f)
s = soup.find('div', {'id':'main_count'})
#making a print 's' here goes well. it shows 6Ã 918Ã 417Ã 712
s.replace('Ã ','')
save_main_count(s)
</code></pre>
<p>It gets no further than <code>s.replace</code>...</p>
| 74 | 2009-08-27T15:53:31Z | 1,342,036 | <pre><code>s.replace(u'Ã ', '') # u before string is important
</code></pre>
<p>and make your <code>.py</code> file unicode.</p>
| 1 | 2009-08-27T15:58:37Z | [
"python",
"unicode"
] |
How to make the python interpreter correctly handle non-ASCII characters in string operations? | 1,342,000 | <p>I have a string that looks like so:</p>
<pre><code>6ÃÂ 918ÃÂ 417ÃÂ 712
</code></pre>
<p>The clear cut way to trim this string (as I understand Python) is simply to say the string is in a variable called <code>s</code>, we get:</p>
<pre><code>s.replace('Ã ', '')
</code></pre>
<p>That should do the trick. But of course it complains that the non-ASCII character <code>'\xc2'</code> in file blabla.py is not encoded.</p>
<p>I never quite could understand how to switch between different encodings.</p>
<p>Here's the code, it really is just the same as above, but now it's in context. The file is saved as UTF-8 in notepad and has the following header:</p>
<pre><code>#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
</code></pre>
<p>The code:</p>
<pre><code>f = urllib.urlopen(url)
soup = BeautifulSoup(f)
s = soup.find('div', {'id':'main_count'})
#making a print 's' here goes well. it shows 6Ã 918Ã 417Ã 712
s.replace('Ã ','')
save_main_count(s)
</code></pre>
<p>It gets no further than <code>s.replace</code>...</p>
| 74 | 2009-08-27T15:53:31Z | 1,342,042 | <pre><code>>>> unicode_string = u"hello aåbäcö"
>>> unicode_string.encode("ascii", "ignore")
'hello abc'
</code></pre>
| 24 | 2009-08-27T15:59:53Z | [
"python",
"unicode"
] |
How to make the python interpreter correctly handle non-ASCII characters in string operations? | 1,342,000 | <p>I have a string that looks like so:</p>
<pre><code>6ÃÂ 918ÃÂ 417ÃÂ 712
</code></pre>
<p>The clear cut way to trim this string (as I understand Python) is simply to say the string is in a variable called <code>s</code>, we get:</p>
<pre><code>s.replace('Ã ', '')
</code></pre>
<p>That should do the trick. But of course it complains that the non-ASCII character <code>'\xc2'</code> in file blabla.py is not encoded.</p>
<p>I never quite could understand how to switch between different encodings.</p>
<p>Here's the code, it really is just the same as above, but now it's in context. The file is saved as UTF-8 in notepad and has the following header:</p>
<pre><code>#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
</code></pre>
<p>The code:</p>
<pre><code>f = urllib.urlopen(url)
soup = BeautifulSoup(f)
s = soup.find('div', {'id':'main_count'})
#making a print 's' here goes well. it shows 6Ã 918Ã 417Ã 712
s.replace('Ã ','')
save_main_count(s)
</code></pre>
<p>It gets no further than <code>s.replace</code>...</p>
| 74 | 2009-08-27T15:53:31Z | 1,342,068 | <pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
s = u"6Ã 918Ã 417Ã 712"
s = s.replace(u"Ã", "")
print s
</code></pre>
<p>This will print out <code>6 918 417 712</code></p>
| 3 | 2009-08-27T16:03:47Z | [
"python",
"unicode"
] |
How to make the python interpreter correctly handle non-ASCII characters in string operations? | 1,342,000 | <p>I have a string that looks like so:</p>
<pre><code>6ÃÂ 918ÃÂ 417ÃÂ 712
</code></pre>
<p>The clear cut way to trim this string (as I understand Python) is simply to say the string is in a variable called <code>s</code>, we get:</p>
<pre><code>s.replace('Ã ', '')
</code></pre>
<p>That should do the trick. But of course it complains that the non-ASCII character <code>'\xc2'</code> in file blabla.py is not encoded.</p>
<p>I never quite could understand how to switch between different encodings.</p>
<p>Here's the code, it really is just the same as above, but now it's in context. The file is saved as UTF-8 in notepad and has the following header:</p>
<pre><code>#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
</code></pre>
<p>The code:</p>
<pre><code>f = urllib.urlopen(url)
soup = BeautifulSoup(f)
s = soup.find('div', {'id':'main_count'})
#making a print 's' here goes well. it shows 6Ã 918Ã 417Ã 712
s.replace('Ã ','')
save_main_count(s)
</code></pre>
<p>It gets no further than <code>s.replace</code>...</p>
| 74 | 2009-08-27T15:53:31Z | 1,342,079 | <p>Python 2 uses <code>ascii</code> as the default encoding for source files, which means you must specify another encoding at the top of the file to use non-ascii unicode characters in literals. Python 3 uses <code>utf-8</code> as the default encoding for source files, so this is less of an issue.</p>
<p>See:
<a href="http://docs.python.org/tutorial/interpreter.html#source-code-encoding">http://docs.python.org/tutorial/interpreter.html#source-code-encoding</a></p>
<p>To enable utf-8 source encoding, this would go in one of the top two lines:</p>
<pre><code># -*- coding: utf-8 -*-
</code></pre>
<p>The above is in the docs, but this also works:</p>
<pre><code># coding: utf-8
</code></pre>
<p>Additional considerations:</p>
<ul>
<li><p>The source file must be saved using the correct encoding in your text editor as well.</p></li>
<li><p>In Python 2, the unicode literal must have a <code>u</code> before it, as in <code>s.replace(u"Ã ", u"")</code> But in Python 3, just use quotes. In Python 2, you can <code>from __future__ import unicode_literals</code> to obtain the Python 3 behavior, but be aware this affects the entire current module.</p></li>
<li><p><code>s.replace(u"Ã ", u"")</code> will also fail if <code>s</code> is not a unicode string.</p></li>
<li><p><code>string.replace</code> returns a new string and does not edit in place, so make sure you're using the return value as well</p></li>
</ul>
| 46 | 2009-08-27T16:04:51Z | [
"python",
"unicode"
] |
How to make the python interpreter correctly handle non-ASCII characters in string operations? | 1,342,000 | <p>I have a string that looks like so:</p>
<pre><code>6ÃÂ 918ÃÂ 417ÃÂ 712
</code></pre>
<p>The clear cut way to trim this string (as I understand Python) is simply to say the string is in a variable called <code>s</code>, we get:</p>
<pre><code>s.replace('Ã ', '')
</code></pre>
<p>That should do the trick. But of course it complains that the non-ASCII character <code>'\xc2'</code> in file blabla.py is not encoded.</p>
<p>I never quite could understand how to switch between different encodings.</p>
<p>Here's the code, it really is just the same as above, but now it's in context. The file is saved as UTF-8 in notepad and has the following header:</p>
<pre><code>#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
</code></pre>
<p>The code:</p>
<pre><code>f = urllib.urlopen(url)
soup = BeautifulSoup(f)
s = soup.find('div', {'id':'main_count'})
#making a print 's' here goes well. it shows 6Ã 918Ã 417Ã 712
s.replace('Ã ','')
save_main_count(s)
</code></pre>
<p>It gets no further than <code>s.replace</code>...</p>
| 74 | 2009-08-27T15:53:31Z | 1,342,373 | <pre><code>def removeNonAscii(s): return "".join(filter(lambda x: ord(x)<128, s))
</code></pre>
<p>edit: my first impulse is always to use a filter, but the generator expression is more memory efficient (and shorter)...</p>
<pre><code>def removeNonAscii(s): return "".join(i for i in s if ord(i)<128)
</code></pre>
<p>Keep in mind that this is guaranteed to work with UTF-8 encoding (because all bytes in multi-byte characters have the highest bit set to 1).</p>
| 148 | 2009-08-27T16:57:23Z | [
"python",
"unicode"
] |
How to make the python interpreter correctly handle non-ASCII characters in string operations? | 1,342,000 | <p>I have a string that looks like so:</p>
<pre><code>6ÃÂ 918ÃÂ 417ÃÂ 712
</code></pre>
<p>The clear cut way to trim this string (as I understand Python) is simply to say the string is in a variable called <code>s</code>, we get:</p>
<pre><code>s.replace('Ã ', '')
</code></pre>
<p>That should do the trick. But of course it complains that the non-ASCII character <code>'\xc2'</code> in file blabla.py is not encoded.</p>
<p>I never quite could understand how to switch between different encodings.</p>
<p>Here's the code, it really is just the same as above, but now it's in context. The file is saved as UTF-8 in notepad and has the following header:</p>
<pre><code>#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
</code></pre>
<p>The code:</p>
<pre><code>f = urllib.urlopen(url)
soup = BeautifulSoup(f)
s = soup.find('div', {'id':'main_count'})
#making a print 's' here goes well. it shows 6Ã 918Ã 417Ã 712
s.replace('Ã ','')
save_main_count(s)
</code></pre>
<p>It gets no further than <code>s.replace</code>...</p>
| 74 | 2009-08-27T15:53:31Z | 1,342,407 | <p>This is a dirty hack, but may work.</p>
<pre><code>s2 = ""
for i in s:
if ord(i) < 128:
s2 += i
</code></pre>
| 1 | 2009-08-27T17:02:11Z | [
"python",
"unicode"
] |
How to make the python interpreter correctly handle non-ASCII characters in string operations? | 1,342,000 | <p>I have a string that looks like so:</p>
<pre><code>6ÃÂ 918ÃÂ 417ÃÂ 712
</code></pre>
<p>The clear cut way to trim this string (as I understand Python) is simply to say the string is in a variable called <code>s</code>, we get:</p>
<pre><code>s.replace('Ã ', '')
</code></pre>
<p>That should do the trick. But of course it complains that the non-ASCII character <code>'\xc2'</code> in file blabla.py is not encoded.</p>
<p>I never quite could understand how to switch between different encodings.</p>
<p>Here's the code, it really is just the same as above, but now it's in context. The file is saved as UTF-8 in notepad and has the following header:</p>
<pre><code>#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
</code></pre>
<p>The code:</p>
<pre><code>f = urllib.urlopen(url)
soup = BeautifulSoup(f)
s = soup.find('div', {'id':'main_count'})
#making a print 's' here goes well. it shows 6Ã 918Ã 417Ã 712
s.replace('Ã ','')
save_main_count(s)
</code></pre>
<p>It gets no further than <code>s.replace</code>...</p>
| 74 | 2009-08-27T15:53:31Z | 1,343,125 | <p>Using Regex:</p>
<pre><code>import re
strip_unicode = re.compile("([^-_a-zA-Z0-9!@#%&=,/'\";:~`\$\^\*\(\)\+\[\]\.\{\}\|\?\<\>\\]+|[^\s]+)")
print strip_unicode.sub('', u'6Ã 918Ã 417Ã 712')
</code></pre>
| 7 | 2009-08-27T18:54:33Z | [
"python",
"unicode"
] |
How to make the python interpreter correctly handle non-ASCII characters in string operations? | 1,342,000 | <p>I have a string that looks like so:</p>
<pre><code>6ÃÂ 918ÃÂ 417ÃÂ 712
</code></pre>
<p>The clear cut way to trim this string (as I understand Python) is simply to say the string is in a variable called <code>s</code>, we get:</p>
<pre><code>s.replace('Ã ', '')
</code></pre>
<p>That should do the trick. But of course it complains that the non-ASCII character <code>'\xc2'</code> in file blabla.py is not encoded.</p>
<p>I never quite could understand how to switch between different encodings.</p>
<p>Here's the code, it really is just the same as above, but now it's in context. The file is saved as UTF-8 in notepad and has the following header:</p>
<pre><code>#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
</code></pre>
<p>The code:</p>
<pre><code>f = urllib.urlopen(url)
soup = BeautifulSoup(f)
s = soup.find('div', {'id':'main_count'})
#making a print 's' here goes well. it shows 6Ã 918Ã 417Ã 712
s.replace('Ã ','')
save_main_count(s)
</code></pre>
<p>It gets no further than <code>s.replace</code>...</p>
| 74 | 2009-08-27T15:53:31Z | 6,113,618 | <p>I know it's an old thread, but I felt compelled to mention the translate method, which is always a good way to replace all character codes above 128 (or other if necessary).</p>
<p><em>Usage</em> : str.<strong>translate</strong>(<em>table[, deletechars]</em>)</p>
<pre><code>>>> trans_table = ''.join( [chr(i) for i in range(128)] + [' '] * 128 )
>>> 'Résultat'.translate(trans_table)
'R sultat'
>>> '6Ã 918Ã 417Ã 712'.translate(trans_table)
'6 918 417 712'
</code></pre>
<p>Starting with <em>Python 2.6</em>, you can also set the table to None, and use <em>deletechars</em> to delete the characters you don't want as in the examples shown in the standard docs at <a href="http://docs.python.org/library/stdtypes.html" rel="nofollow">http://docs.python.org/library/stdtypes.html</a>.</p>
<p>With unicode strings, the translation table is not a 256-character string but a dict with the ord() of relevant characters as keys. But anyway getting a proper ascii string from a unicode string is simple enough, using the method mentioned by truppo above, namely : unicode_string.encode("ascii", "ignore")</p>
<p>As a summary, if for some reason you absolutely need to get an ascii string (for instance, when you raise a standard exception with <code>raise Exception, ascii_message</code> ), you can use the following function:</p>
<pre><code>trans_table = ''.join( [chr(i) for i in range(128)] + ['?'] * 128 )
def ascii(s):
if isinstance(s, unicode):
return s.encode('ascii', 'replace')
else:
return s.translate(trans_table)
</code></pre>
<p>The good thing with translate is that you can actually convert accented characters to <em>relevant</em> non-accented ascii characters instead of simply deleting them or replacing them by '?'. This is often useful, for instance for indexing purposes.</p>
| 2 | 2011-05-24T16:24:34Z | [
"python",
"unicode"
] |
How to make the python interpreter correctly handle non-ASCII characters in string operations? | 1,342,000 | <p>I have a string that looks like so:</p>
<pre><code>6ÃÂ 918ÃÂ 417ÃÂ 712
</code></pre>
<p>The clear cut way to trim this string (as I understand Python) is simply to say the string is in a variable called <code>s</code>, we get:</p>
<pre><code>s.replace('Ã ', '')
</code></pre>
<p>That should do the trick. But of course it complains that the non-ASCII character <code>'\xc2'</code> in file blabla.py is not encoded.</p>
<p>I never quite could understand how to switch between different encodings.</p>
<p>Here's the code, it really is just the same as above, but now it's in context. The file is saved as UTF-8 in notepad and has the following header:</p>
<pre><code>#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
</code></pre>
<p>The code:</p>
<pre><code>f = urllib.urlopen(url)
soup = BeautifulSoup(f)
s = soup.find('div', {'id':'main_count'})
#making a print 's' here goes well. it shows 6Ã 918Ã 417Ã 712
s.replace('Ã ','')
save_main_count(s)
</code></pre>
<p>It gets no further than <code>s.replace</code>...</p>
| 74 | 2009-08-27T15:53:31Z | 8,045,344 | <p>For what it was worth, my character set was <code>utf-8</code> and I had included the classic "<code># -*- coding: utf-8 -*-</code>" line.</p>
<p>However, I discovered that I didn't have Universal Newlines when reading this data from a webpage. </p>
<p>My text had two words, separated by "<code>\r\n</code>". I was only splitting on the <code>\n</code> and replacing the <code>"\n"</code>.</p>
<p>Once I looped through and saw the character set in question, I realized the mistake.</p>
<p>So, it could also be within the <em>ASCII</em> character set, but a character that you didn't expect.</p>
| 0 | 2011-11-08T02:41:10Z | [
"python",
"unicode"
] |
How to make the python interpreter correctly handle non-ASCII characters in string operations? | 1,342,000 | <p>I have a string that looks like so:</p>
<pre><code>6ÃÂ 918ÃÂ 417ÃÂ 712
</code></pre>
<p>The clear cut way to trim this string (as I understand Python) is simply to say the string is in a variable called <code>s</code>, we get:</p>
<pre><code>s.replace('Ã ', '')
</code></pre>
<p>That should do the trick. But of course it complains that the non-ASCII character <code>'\xc2'</code> in file blabla.py is not encoded.</p>
<p>I never quite could understand how to switch between different encodings.</p>
<p>Here's the code, it really is just the same as above, but now it's in context. The file is saved as UTF-8 in notepad and has the following header:</p>
<pre><code>#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
</code></pre>
<p>The code:</p>
<pre><code>f = urllib.urlopen(url)
soup = BeautifulSoup(f)
s = soup.find('div', {'id':'main_count'})
#making a print 's' here goes well. it shows 6Ã 918Ã 417Ã 712
s.replace('Ã ','')
save_main_count(s)
</code></pre>
<p>It gets no further than <code>s.replace</code>...</p>
| 74 | 2009-08-27T15:53:31Z | 8,045,715 | <p>Way too late for an answer, but the original string was in UTF-8 and '\xc2\xa0' is UTF-8 for NO-BREAK SPACE. Simply decode the original string as <code>s.decode('utf-8')</code> (\xa0 displays as a space when decoded incorrectly as Windows-1252 or latin-1:</p>
<h3>Example (Python 3)</h3>
<pre><code>s = b'6\xc2\xa0918\xc2\xa0417\xc2\xa0712'
print(s.decode('latin-1')) # incorrectly decoded
u = s.decode('utf8') # correctly decoded
print(u)
print(u.replace('\N{NO-BREAK SPACE}','_'))
print(u.replace('\xa0','-')) # \xa0 is Unicode for NO-BREAK SPACE
</code></pre>
<h3>Output</h3>
<pre><code>6ÃÂ 918ÃÂ 417ÃÂ 712
6Â 918Â 417Â 712
6_918_417_712
6-918-417-712
</code></pre>
| 3 | 2011-11-08T03:48:31Z | [
"python",
"unicode"
] |
How to make the python interpreter correctly handle non-ASCII characters in string operations? | 1,342,000 | <p>I have a string that looks like so:</p>
<pre><code>6ÃÂ 918ÃÂ 417ÃÂ 712
</code></pre>
<p>The clear cut way to trim this string (as I understand Python) is simply to say the string is in a variable called <code>s</code>, we get:</p>
<pre><code>s.replace('Ã ', '')
</code></pre>
<p>That should do the trick. But of course it complains that the non-ASCII character <code>'\xc2'</code> in file blabla.py is not encoded.</p>
<p>I never quite could understand how to switch between different encodings.</p>
<p>Here's the code, it really is just the same as above, but now it's in context. The file is saved as UTF-8 in notepad and has the following header:</p>
<pre><code>#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
</code></pre>
<p>The code:</p>
<pre><code>f = urllib.urlopen(url)
soup = BeautifulSoup(f)
s = soup.find('div', {'id':'main_count'})
#making a print 's' here goes well. it shows 6Ã 918Ã 417Ã 712
s.replace('Ã ','')
save_main_count(s)
</code></pre>
<p>It gets no further than <code>s.replace</code>...</p>
| 74 | 2009-08-27T15:53:31Z | 10,268,212 | <p>The following code will replace all non ASCII characters with question marks.</p>
<pre><code>"".join([x if ord(x) < 128 else '?' for x in s])
</code></pre>
| 14 | 2012-04-22T13:12:10Z | [
"python",
"unicode"
] |
Problem with python and __import__ | 1,342,128 | <p>Sorry for the generic title, will change it once I understand the source of my problem
I have the following structure:</p>
<pre><code>foo/
foo/__init__.py
foo/bar/
foo/bar/__init__.py
foo/bar/some_module.py
</code></pre>
<p>When I try to import some_module by doing so:</p>
<pre><code>from foo.bar import some_module
</code></pre>
<p>it works like a charm.
But this is no good for me, since I only know the name of the module to import in runtime. so if I try:</p>
<pre><code>from foo.bar import *
mod=__import__('some_module')
</code></pre>
<p>I get an error. Am I doing something wrong? Is there a better way to do this? and why is this happening?</p>
<p>Why is that? I am not quite sure I completely understand the concept behind python packages. I thought they were equivalent to java's packages and thus </p>
| 1 | 2009-08-27T16:12:05Z | 1,342,164 | <p>I believe the proper way to do this is:</p>
<pre><code>mod = __import__('foo.bar', fromlist = ['some_module'])
</code></pre>
<p>This way even the 'foo.bar' part can be changed at runtime.
As a result <code>some_module</code>will be available as <code>mod.some_module</code>; use getattr if you want it in a separate variable:</p>
<pre><code>the_module = getattr(mod, 'some_module')
</code></pre>
| 7 | 2009-08-27T16:18:23Z | [
"python",
"import"
] |
Problem with python and __import__ | 1,342,128 | <p>Sorry for the generic title, will change it once I understand the source of my problem
I have the following structure:</p>
<pre><code>foo/
foo/__init__.py
foo/bar/
foo/bar/__init__.py
foo/bar/some_module.py
</code></pre>
<p>When I try to import some_module by doing so:</p>
<pre><code>from foo.bar import some_module
</code></pre>
<p>it works like a charm.
But this is no good for me, since I only know the name of the module to import in runtime. so if I try:</p>
<pre><code>from foo.bar import *
mod=__import__('some_module')
</code></pre>
<p>I get an error. Am I doing something wrong? Is there a better way to do this? and why is this happening?</p>
<p>Why is that? I am not quite sure I completely understand the concept behind python packages. I thought they were equivalent to java's packages and thus </p>
| 1 | 2009-08-27T16:12:05Z | 1,342,177 | <p>From the <a href="http://docs.python.org/library/functions.html#%5F%5Fimport%5F%5F" rel="nofollow">docs</a>:</p>
<blockquote>
<p>Direct use of <code>__import__()</code> is rare, except in cases where you want to import a module whose name is only known at runtime.</p>
</blockquote>
<p>However, the dotted notation should work:</p>
<pre><code>mod = __import__('foo.bar.some_module')
</code></pre>
| 0 | 2009-08-27T16:20:09Z | [
"python",
"import"
] |
Problem with python and __import__ | 1,342,128 | <p>Sorry for the generic title, will change it once I understand the source of my problem
I have the following structure:</p>
<pre><code>foo/
foo/__init__.py
foo/bar/
foo/bar/__init__.py
foo/bar/some_module.py
</code></pre>
<p>When I try to import some_module by doing so:</p>
<pre><code>from foo.bar import some_module
</code></pre>
<p>it works like a charm.
But this is no good for me, since I only know the name of the module to import in runtime. so if I try:</p>
<pre><code>from foo.bar import *
mod=__import__('some_module')
</code></pre>
<p>I get an error. Am I doing something wrong? Is there a better way to do this? and why is this happening?</p>
<p>Why is that? I am not quite sure I completely understand the concept behind python packages. I thought they were equivalent to java's packages and thus </p>
| 1 | 2009-08-27T16:12:05Z | 1,342,243 | <pre><code>from foo.bar import *
</code></pre>
<p>is a bad practice since it imports <code>some_module</code> into the global scope. </p>
<p>You should be able to access your module through:</p>
<pre><code>import foo.bar
mod = getattr(foo.bar, 'some_module')
</code></pre>
<p>It can be easily demonstrated that this approach works:</p>
<pre><code>>>> import os.path
>>> getattr(os.path, 'basename')
<function basename at 0x00BBA468>
>>> getattr(os.path, 'basename\n')
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
getattr(os.path, 'basename\n')
AttributeError: 'module' object has no attribute 'basename
'
</code></pre>
<p>P.S. If you're still interested in using your kind of import statement. You need an <code>eval</code>:</p>
<pre><code>from foo.bar import *
eval('some_module')
</code></pre>
<p>To clarify: not only it's bad practice to use <code>*</code>-import it's even <strong>worse</strong> in combination with <code>eval</code>. So just use <code>getattr</code>, it's designed exactly for situations like yours.</p>
| 1 | 2009-08-27T16:32:20Z | [
"python",
"import"
] |
nose tests of Pylons app with models in init_model? | 1,342,232 | <p>I have a stock Pylons app created using <code>paster create -t pylons</code> with one controller and matched functional test, added using <code>paster controller</code>, and a SQLAlchemy table and mapped ORM class. The SQLAlchemy stuff is defined in the <code>init_model()</code> function rather than in module scope (and needs to be there).</p>
<p>Running <code>python setup.py test</code> raises an exception because <code>nose</code> is somehow causing <code>init_model()</code> to be called twice within the same process, so it's trying to create a model that already exists.</p>
<p>I can hackishly fix this by setting and checking a global variable inside <code>init_model()</code>, but (a) I'd rather not, and (b) third-party libraries such as AuthKit that dynamically define models break the tests as well, and can't be so easily changed.</p>
<p>Is there a way to fix <code>nose</code> tests for Pylons, or should I write my own test script and just use <code>unittest</code>, <code>loadapp</code>, and <code>webtest</code> directly? Any working examples of this?</p>
| 1 | 2009-08-27T16:29:18Z | 1,344,479 | <p>I would try debugging your nosetest run. Why not put:</p>
<pre><code>import pdb;pdb.set_trace()
</code></pre>
<p>in the <code>init_model()</code> function and see how it is getting invoked more than once.</p>
<p>With PDB running you can see the stack trace using the <code>where</code> command:</p>
<pre><code>w(here)
Print a stack trace, with the most recent frame at the bottom.
An arrow indicates the "current frame", which determines the
context of most commands. 'bt' is an alias for this command.
</code></pre>
| 3 | 2009-08-28T00:43:46Z | [
"python",
"sqlalchemy",
"pylons",
"nose",
"nosetests"
] |
Can you really use the Visual Studio 2008 IDE to code in Python? | 1,342,377 | <p>I have a friend who I am trying to teach how to program. He comes from a very basic PHP background, and for some reason is ANTI C#, I guess because some of his PHP circles condemn anything that comes from Microsoft.</p>
<p>Anyways - I've told him its possible to use either Ruby or Python with the VS2008 IDE, because I've read somewhere that this is possible. </p>
<p>But I was wondering. Is it really that practical, can you do EVERYTHING with Python in VS2008 that you can do with C# or VB.net. </p>
<p>I guess without starting a debate... I want to know if you're a developer using VS IDE with a language other than VB.net or C#, then please leave an answer with your experience. </p>
<p>If you are (like me) either a VB.net or C# developer, please don't post speculative or subjective answers. This is a serious question, and I don't want it being closed as subjective. ...</p>
<p>Thank you very much.</p>
<p><strong>update</strong></p>
<p>So far we've established that IronPython is the right tool for the job. </p>
<p>Now how practical is it really?</p>
<p>Mono for example runs C# code in Linux, but... ever tried to use it? Not practical at all, lots of code refactoring needs to take place, no support for .net v3.5, etc...</p>
| 2 | 2009-08-27T16:57:39Z | 1,342,391 | <p>I don't know why you would want to - perhaps something like <a href="http://www.codeplex.com/IronPythonStudio" rel="nofollow">IronPython Studio</a> would be a happy medium. But as I said I don't know why you would want to use Visual Studio for Python development when there are <a href="http://wiki.python.org/moin/IntegratedDevelopmentEnvironments" rel="nofollow">much better options available.</a></p>
<p>Always choose the right tool for the right job - just because you can drive a nail with the butt-end of your cordless drill doesn't mean that you should. Visual Studio was not designed for Python development and as such will not be a perfect environment for developing in it. Please use the list I have linked to choose a more appropriate editor from that list.</p>
<p>As a side note, I am wondering why your PHP friend refuses to use C# (a free, industry standardized language) but is okay using Visual Studio (an expensive, closed-source integrated development environment).</p>
| 1 | 2009-08-27T16:59:49Z | [
"python",
"visual-studio",
"ironpython"
] |
Can you really use the Visual Studio 2008 IDE to code in Python? | 1,342,377 | <p>I have a friend who I am trying to teach how to program. He comes from a very basic PHP background, and for some reason is ANTI C#, I guess because some of his PHP circles condemn anything that comes from Microsoft.</p>
<p>Anyways - I've told him its possible to use either Ruby or Python with the VS2008 IDE, because I've read somewhere that this is possible. </p>
<p>But I was wondering. Is it really that practical, can you do EVERYTHING with Python in VS2008 that you can do with C# or VB.net. </p>
<p>I guess without starting a debate... I want to know if you're a developer using VS IDE with a language other than VB.net or C#, then please leave an answer with your experience. </p>
<p>If you are (like me) either a VB.net or C# developer, please don't post speculative or subjective answers. This is a serious question, and I don't want it being closed as subjective. ...</p>
<p>Thank you very much.</p>
<p><strong>update</strong></p>
<p>So far we've established that IronPython is the right tool for the job. </p>
<p>Now how practical is it really?</p>
<p>Mono for example runs C# code in Linux, but... ever tried to use it? Not practical at all, lots of code refactoring needs to take place, no support for .net v3.5, etc...</p>
| 2 | 2009-08-27T16:57:39Z | 1,342,405 | <p>This has been discussed before <a href="http://stackoverflow.com/questions/537689/python-ide-built-into-visual-studio-2008">in this thread.</a> I personally prefer eclipse and pyDev.</p>
| 1 | 2009-08-27T17:02:05Z | [
"python",
"visual-studio",
"ironpython"
] |
Can you really use the Visual Studio 2008 IDE to code in Python? | 1,342,377 | <p>I have a friend who I am trying to teach how to program. He comes from a very basic PHP background, and for some reason is ANTI C#, I guess because some of his PHP circles condemn anything that comes from Microsoft.</p>
<p>Anyways - I've told him its possible to use either Ruby or Python with the VS2008 IDE, because I've read somewhere that this is possible. </p>
<p>But I was wondering. Is it really that practical, can you do EVERYTHING with Python in VS2008 that you can do with C# or VB.net. </p>
<p>I guess without starting a debate... I want to know if you're a developer using VS IDE with a language other than VB.net or C#, then please leave an answer with your experience. </p>
<p>If you are (like me) either a VB.net or C# developer, please don't post speculative or subjective answers. This is a serious question, and I don't want it being closed as subjective. ...</p>
<p>Thank you very much.</p>
<p><strong>update</strong></p>
<p>So far we've established that IronPython is the right tool for the job. </p>
<p>Now how practical is it really?</p>
<p>Mono for example runs C# code in Linux, but... ever tried to use it? Not practical at all, lots of code refactoring needs to take place, no support for .net v3.5, etc...</p>
| 2 | 2009-08-27T16:57:39Z | 1,342,421 | <p>If you want to use Python together with the .NET Common Language Runtime, then you want one of:</p>
<ul>
<li><a href="http://pythonnet.sourceforge.net/" rel="nofollow">Python.NET</a> (extension to vanilla Python that adds .NET support)</li>
<li><a href="http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython" rel="nofollow">IronPython</a> (re-implementation of Python as a .NET language)</li>
<li><a href="http://boo.codehaus.org/" rel="nofollow">Boo</a> (Python-like language that compiles down to C#-equivalent MSIL code)</li>
</ul>
<p>Using Python in Visual Studio without using the CLR seems like a bit of a waste to me. Eclipse with PyDev would be a much better choice.</p>
| 8 | 2009-08-27T17:03:58Z | [
"python",
"visual-studio",
"ironpython"
] |
Can you really use the Visual Studio 2008 IDE to code in Python? | 1,342,377 | <p>I have a friend who I am trying to teach how to program. He comes from a very basic PHP background, and for some reason is ANTI C#, I guess because some of his PHP circles condemn anything that comes from Microsoft.</p>
<p>Anyways - I've told him its possible to use either Ruby or Python with the VS2008 IDE, because I've read somewhere that this is possible. </p>
<p>But I was wondering. Is it really that practical, can you do EVERYTHING with Python in VS2008 that you can do with C# or VB.net. </p>
<p>I guess without starting a debate... I want to know if you're a developer using VS IDE with a language other than VB.net or C#, then please leave an answer with your experience. </p>
<p>If you are (like me) either a VB.net or C# developer, please don't post speculative or subjective answers. This is a serious question, and I don't want it being closed as subjective. ...</p>
<p>Thank you very much.</p>
<p><strong>update</strong></p>
<p>So far we've established that IronPython is the right tool for the job. </p>
<p>Now how practical is it really?</p>
<p>Mono for example runs C# code in Linux, but... ever tried to use it? Not practical at all, lots of code refactoring needs to take place, no support for .net v3.5, etc...</p>
| 2 | 2009-08-27T16:57:39Z | 1,342,463 | <p>I find it odd that your friend is against C# but is ok with Visual Studio. There is, after all, an open source development environment for .NET called SharpDevelop. The C# language is a standard. .NET is free (as in beer) and there is an open source implementation of that platform called Mono. The only "un-free" thing is Visual Studio (though there are "Express" versions which are free as in beer).</p>
| 2 | 2009-08-27T17:11:27Z | [
"python",
"visual-studio",
"ironpython"
] |
Can you really use the Visual Studio 2008 IDE to code in Python? | 1,342,377 | <p>I have a friend who I am trying to teach how to program. He comes from a very basic PHP background, and for some reason is ANTI C#, I guess because some of his PHP circles condemn anything that comes from Microsoft.</p>
<p>Anyways - I've told him its possible to use either Ruby or Python with the VS2008 IDE, because I've read somewhere that this is possible. </p>
<p>But I was wondering. Is it really that practical, can you do EVERYTHING with Python in VS2008 that you can do with C# or VB.net. </p>
<p>I guess without starting a debate... I want to know if you're a developer using VS IDE with a language other than VB.net or C#, then please leave an answer with your experience. </p>
<p>If you are (like me) either a VB.net or C# developer, please don't post speculative or subjective answers. This is a serious question, and I don't want it being closed as subjective. ...</p>
<p>Thank you very much.</p>
<p><strong>update</strong></p>
<p>So far we've established that IronPython is the right tool for the job. </p>
<p>Now how practical is it really?</p>
<p>Mono for example runs C# code in Linux, but... ever tried to use it? Not practical at all, lots of code refactoring needs to take place, no support for .net v3.5, etc...</p>
| 2 | 2009-08-27T16:57:39Z | 1,343,191 | <p>Firstly, there seems to be a question as to whether python (or various implementations) are as 'powerful' as C#. I'm not quite sure what to take powerful to mean, but in my experience of both languages it will be somewhat easier and faster to write a given piece of code in python than in C#. C# is faster than cpython (although if speed is desired, the psyco python module is well worth a look).</p>
<p>Also I would object to your dismissal of Mono. Mono is great on Linux <em>if you write an application for it from scratch.</em> It is not really meant to be a compatibility layer between Windows and Linux (see Wine!), and if you treat it as such you will only be disappointed.</p>
<p>It just seems to me that you are taking the wrong approach. If you want to convince him that not everything Microsoft is evil, and he is adamant about not learning C#, get him to learn Python (or Ruby, or LUA or whatever) until he is competent, and then introduce him to C# and get him to make his own judgement - I'm fairly in favour of open source, and am far from a rabid Microsoft supporter, but I tried C#, and found I quite liked it.</p>
<p>I think that getting him to use python and visual studio in a suboptimal way will turn him against both of them - far from your desired goal!</p>
| 1 | 2009-08-27T19:07:51Z | [
"python",
"visual-studio",
"ironpython"
] |
Can you really use the Visual Studio 2008 IDE to code in Python? | 1,342,377 | <p>I have a friend who I am trying to teach how to program. He comes from a very basic PHP background, and for some reason is ANTI C#, I guess because some of his PHP circles condemn anything that comes from Microsoft.</p>
<p>Anyways - I've told him its possible to use either Ruby or Python with the VS2008 IDE, because I've read somewhere that this is possible. </p>
<p>But I was wondering. Is it really that practical, can you do EVERYTHING with Python in VS2008 that you can do with C# or VB.net. </p>
<p>I guess without starting a debate... I want to know if you're a developer using VS IDE with a language other than VB.net or C#, then please leave an answer with your experience. </p>
<p>If you are (like me) either a VB.net or C# developer, please don't post speculative or subjective answers. This is a serious question, and I don't want it being closed as subjective. ...</p>
<p>Thank you very much.</p>
<p><strong>update</strong></p>
<p>So far we've established that IronPython is the right tool for the job. </p>
<p>Now how practical is it really?</p>
<p>Mono for example runs C# code in Linux, but... ever tried to use it? Not practical at all, lots of code refactoring needs to take place, no support for .net v3.5, etc...</p>
| 2 | 2009-08-27T16:57:39Z | 1,343,342 | <p>Go <a href="http://knowbody.livejournal.com/15675.html" rel="nofollow">here</a> for a discussion on the Visual Studio IronPython IDEs.</p>
| 0 | 2009-08-27T19:34:19Z | [
"python",
"visual-studio",
"ironpython"
] |
write special characters into excel table by python package pyExcelerator/xlwt | 1,342,402 | <p>Task:<br />
I generate formated excel tables from csv-files by using the python package pyExcelerator (comparable with xlwt). I need to be able to write less-than-or-equal-to (â¤) and greater-than-or-equal-to (â¥) signs.</p>
<p>So far:<br />
I can save my table as csv-files with UTF-8 encoding, so that I can view the special characters in my text editor, by adding the following line to my python source code: </p>
<pre><code>#! /usr/bin/env python
# -*- coding: UTF-8 -*-
</code></pre>
<p>Problem:<br />
However, there is no option to choose UTF-8 as font in pyExcelerator's Font class. The only options are: </p>
<pre><code>CHARSET_ANSI_LATIN = 0x00
CHARSET_SYS_DEFAULT = 0x01
CHARSET_SYMBOL = 0x02
CHARSET_APPLE_ROMAN = 0x4D
CHARSET_ANSI_JAP_SHIFT_JIS = 0x80
CHARSET_ANSI_KOR_HANGUL = 0x81
CHARSET_ANSI_KOR_JOHAB = 0x82
CHARSET_ANSI_CHINESE_GBK = 0x86
CHARSET_ANSI_CHINESE_BIG5 = 0x88
CHARSET_ANSI_GREEK = 0xA1
CHARSET_ANSI_TURKISH = 0xA2
CHARSET_ANSI_VIETNAMESE = 0xA3
CHARSET_ANSI_HEBREW = 0xB1
CHARSET_ANSI_ARABIC = 0xB2
CHARSET_ANSI_BALTIC = 0xBA
CHARSET_ANSI_CYRILLIC = 0xCC
CHARSET_ANSI_THAI = 0xDE
CHARSET_ANSI_LATIN_II = 0xEE
CHARSET_OEM_LATIN_I = 0xFF
</code></pre>
<p>Do any of these character sets contain the less-than-or-equal-to and greater-than-or-equal-to signs? If so, which on?<br />
Which python encoding name corresponds to these sets?
Is there another way for generating these special characters?</p>
| 4 | 2009-08-27T17:01:41Z | 1,349,666 | <p>You may be overthinking the problem. The font shouldn't play into the matter, although character encoding might.</p>
<p>In any case, I was able to use xlwt to create an excel spreadsheet with less-than-equal and greater-than-equal signs with the following script:</p>
<pre><code>import xlwt
wb = xlwt.Workbook()
ws = wb.add_sheet('Test Sheet')
lte = u'\u2264'
gte = u'\u2265'
ws.write(0,0,lte+gte)
wb.save('foo.xls')
</code></pre>
<p>Note that -<em>- coding: utf-8 -</em>- is not required because the special characters are encoded with their unicode numeric indices. In general, I recommend using unicode where possible.</p>
<p>It's also possible to use utf-8 and type the characters directly into the Python code. This would be exactly the same except for how the characters are entered:</p>
<pre><code>#-*- coding: utf-8 -*-
import xlwt
wb = xlwt.Workbook()
ws = wb.add_sheet('Test Sheet')
lte = u'â¤'
gte = u'â¥'
ws.write(0,0,lte+gte)
wb.save('foo.xls')
</code></pre>
<p>Note, however, that you must be using an editor that is <em>aware</em> that you are saving the Python code as UTF-8. If your editor encodes the file in any other way, the special characters will not be parsed properly when loaded by the Python interpreter.</p>
| 4 | 2009-08-28T22:19:38Z | [
"python",
"excel",
"character-encoding",
"special-characters",
"xlwt"
] |
write special characters into excel table by python package pyExcelerator/xlwt | 1,342,402 | <p>Task:<br />
I generate formated excel tables from csv-files by using the python package pyExcelerator (comparable with xlwt). I need to be able to write less-than-or-equal-to (â¤) and greater-than-or-equal-to (â¥) signs.</p>
<p>So far:<br />
I can save my table as csv-files with UTF-8 encoding, so that I can view the special characters in my text editor, by adding the following line to my python source code: </p>
<pre><code>#! /usr/bin/env python
# -*- coding: UTF-8 -*-
</code></pre>
<p>Problem:<br />
However, there is no option to choose UTF-8 as font in pyExcelerator's Font class. The only options are: </p>
<pre><code>CHARSET_ANSI_LATIN = 0x00
CHARSET_SYS_DEFAULT = 0x01
CHARSET_SYMBOL = 0x02
CHARSET_APPLE_ROMAN = 0x4D
CHARSET_ANSI_JAP_SHIFT_JIS = 0x80
CHARSET_ANSI_KOR_HANGUL = 0x81
CHARSET_ANSI_KOR_JOHAB = 0x82
CHARSET_ANSI_CHINESE_GBK = 0x86
CHARSET_ANSI_CHINESE_BIG5 = 0x88
CHARSET_ANSI_GREEK = 0xA1
CHARSET_ANSI_TURKISH = 0xA2
CHARSET_ANSI_VIETNAMESE = 0xA3
CHARSET_ANSI_HEBREW = 0xB1
CHARSET_ANSI_ARABIC = 0xB2
CHARSET_ANSI_BALTIC = 0xBA
CHARSET_ANSI_CYRILLIC = 0xCC
CHARSET_ANSI_THAI = 0xDE
CHARSET_ANSI_LATIN_II = 0xEE
CHARSET_OEM_LATIN_I = 0xFF
</code></pre>
<p>Do any of these character sets contain the less-than-or-equal-to and greater-than-or-equal-to signs? If so, which on?<br />
Which python encoding name corresponds to these sets?
Is there another way for generating these special characters?</p>
| 4 | 2009-08-27T17:01:41Z | 1,349,905 | <p>(1) Re: """
I can save my table as csv-files with UTF-8 encoding, so that I can view the special characters in my text editor, by adding the following line to my python source code:</p>
<p><code>#! /usr/bin/env python</code><br />
<code># -*- coding: UTF-8 -*-</code><br />
"""</p>
<p>Being able to write a file with characters encoded in UTF-8 is NOT dependant on what encoding is used in the source of the program that writes the file!</p>
<p>(2) UTF-8 is an encoding, not a font. Those charsets in an Excel FONT record are a blast from the past AFAIK. I've not heard from any xlwt user who ever thought it necessary to use other than the default for the charset. Just feed unicode objects to xlwt as demonstrated by Jason ... if you have an appropriate font on your system (see if you can display the characters in OpenOffice Calc), you should be OK.</p>
<p>(3) Any particular reason for using pyExcelerator instead of xlwt?</p>
| 1 | 2009-08-28T23:39:36Z | [
"python",
"excel",
"character-encoding",
"special-characters",
"xlwt"
] |
write special characters into excel table by python package pyExcelerator/xlwt | 1,342,402 | <p>Task:<br />
I generate formated excel tables from csv-files by using the python package pyExcelerator (comparable with xlwt). I need to be able to write less-than-or-equal-to (â¤) and greater-than-or-equal-to (â¥) signs.</p>
<p>So far:<br />
I can save my table as csv-files with UTF-8 encoding, so that I can view the special characters in my text editor, by adding the following line to my python source code: </p>
<pre><code>#! /usr/bin/env python
# -*- coding: UTF-8 -*-
</code></pre>
<p>Problem:<br />
However, there is no option to choose UTF-8 as font in pyExcelerator's Font class. The only options are: </p>
<pre><code>CHARSET_ANSI_LATIN = 0x00
CHARSET_SYS_DEFAULT = 0x01
CHARSET_SYMBOL = 0x02
CHARSET_APPLE_ROMAN = 0x4D
CHARSET_ANSI_JAP_SHIFT_JIS = 0x80
CHARSET_ANSI_KOR_HANGUL = 0x81
CHARSET_ANSI_KOR_JOHAB = 0x82
CHARSET_ANSI_CHINESE_GBK = 0x86
CHARSET_ANSI_CHINESE_BIG5 = 0x88
CHARSET_ANSI_GREEK = 0xA1
CHARSET_ANSI_TURKISH = 0xA2
CHARSET_ANSI_VIETNAMESE = 0xA3
CHARSET_ANSI_HEBREW = 0xB1
CHARSET_ANSI_ARABIC = 0xB2
CHARSET_ANSI_BALTIC = 0xBA
CHARSET_ANSI_CYRILLIC = 0xCC
CHARSET_ANSI_THAI = 0xDE
CHARSET_ANSI_LATIN_II = 0xEE
CHARSET_OEM_LATIN_I = 0xFF
</code></pre>
<p>Do any of these character sets contain the less-than-or-equal-to and greater-than-or-equal-to signs? If so, which on?<br />
Which python encoding name corresponds to these sets?
Is there another way for generating these special characters?</p>
| 4 | 2009-08-27T17:01:41Z | 2,477,641 | <p>This should help with writing <code>UTF-8</code> chars using <strike>pyexcelerator or</strike> xlwt:</p>
<pre><code>wb = xlwt.Workbook(**encoding='utf-8'**)
</code></pre>
<p>edit:</p>
<p>Seems it's not working for pyexcelerator, but I havent confirmed it.</p>
| 4 | 2010-03-19T13:31:24Z | [
"python",
"excel",
"character-encoding",
"special-characters",
"xlwt"
] |
Slow regex in Python? | 1,342,589 | <p>I'm trying to match these kinds of strings</p>
<pre><code>{@csm.foo.bar}
</code></pre>
<p>without matching any of these</p>
<pre><code>{@csm.foo.bar-@csm.ooga.booga}
{@csm.foo.bar-42}
</code></pre>
<p>The regex I use is</p>
<pre><code>r"\{@csm.((?:[a-zA-Z0-9_]+\.?)+)\}"
</code></pre>
<p>It gets dog slow if the string contains multiple matches. Why? It runs very fast if I take away the brace matching, like this</p>
<pre><code>r"@csm.((?:[a-zA-Z0-9_]+\.?)+)"
</code></pre>
<p>but that's not what I want.</p>
<p>Any ideas?</p>
<p>Here is sample input:</p>
<pre><code><dockLayout id="popup" y="0" x="0" width="{@csm.screenWidth}" height="{@csm.screenHeight}">
<dataNumber id="selopacity_Volt" name="selopacity_Volt" value="0" />
<dataNumber id="selopacity_Amp" name="selopacity_Amp" value="0" />
<animate trigger="{@m_ds_ML.VIMPBM_BatteryVoltage.valstr}" triggerOn="*" targetNode="selopacity_Volt" targetAttr="value" to="1" dur="0ms" ease="in" />
<animate trigger="{@m_ds_ML.VIMPBM_BatteryVoltage.valstr}" triggerOn="65024" targetNode="selopacity_Volt" targetAttr="value" to="0" dur="0ms" ease="in" />
<animate trigger="{@m_ds_ML.VIMPBM_BatteryCurrent.valstr}" triggerOn="*" targetNode="selopacity_Amp" targetAttr="value" to="1" dur="0ms" ease="in" />
<animate trigger="{@m_ds_ML.VIMPBM_BatteryCurrent.valstr}" triggerOn="65024" targetNode="selopacity_Amp" targetAttr="value" to="0" dur="0ms" ease="in" />
<dockLayout id="item" width="{@csm.screenWidth}" height="{@csm.screenHeight}" depth="-1" clip="false" xmlns="http://www.tat.se/kastor/kml" >
<dockLayout id="list_item_title" x="0" width="{@csm.screenWidth}" height="{@csm.Gearselection.text_heght-@csm.pageVisualCP_y}">
<text id="volt_amp_text" x="0" ellipsize="false" font="{@csm.listUnselFont}" color="{@csm.itemUnselColor}" dockLayout.halign="left" dockLayout.valign="bottom" string="{ItemTitle}" />
</dockLayout>
<dockLayout id="gear_layout" y="0" x="0" width="{@csm.screenWidth}" height="{@csm.vmImage_y_gearselection-@csm.pageVisualCP_y}">
<image id="battery_image" x="0" dockLayout.halign="left" dockLayout.valign="bottom" opacity="1" src="{@m_MenuModel.Gauges.VoltAmpereMeter.image}"/>
</dockLayout>
<!--DockLayout for Voltage Value-->
<dockLayout id="volt_value" x="0" width="{@csm.VoltAmpereMeter.volt_value_x-@csm.VoltAmpereMeter.List_x}" height="{@csm.vmImage_y_gearselection-@csm.pageVisualCP_y}">
<text id="volt_value_text" x="0" opacity="{selopacity_Volt*selopacity_Amp}" ellipsize="false" font="{@csm.listUnselFont}" color="{@csm.itemSelColor}" dockLayout.halign="right" dockLayout.valign="bottom" string="{@m_ds_ML.VIMPBM_BatteryVoltage.valstr}" >
</text>
</dockLayout>
<!--DockLayout for Voltage Unit-->
<dockLayout id="volt_unit" x="{@csm.VoltAmpereMeter.volt_unit_x-@csm.VoltAmpereMeter.List_x}" width="{@csm.screenWidth}" height="{@csm.vmImage_y_gearselection-@csm.pageVisualCP_y}">
<text id="volt_unit_text" x="0" opacity="{selopacity_Volt*selopacity_Amp}" ellipsize="false" font="{@csm.listUnselFont}" color="{@csm.itemSelColor}" dockLayout.halign="left" dockLayout.valign="bottom" string="V" >
</text>
</dockLayout>
<!--DockLayout for Ampere Value-->
<dockLayout id="ampere_value" x="0" width="{@csm.VoltAmpereMeter.ampere_value_x-@csm.VoltAmpereMeter.List_x}" height="{@csm.vmImage_y_gearselection-@csm.pageVisualCP_y}">
<text id="ampere_value_text" x="0" opacity="{selopacity_Amp*selopacity_Volt}" ellipsize="false" font="{@csm.listUnselFont}" color="{@csm.itemSelColor}" dockLayout.halign="right" dockLayout.valign="bottom" string="{@m_ds_ML.VIMPBM_BatteryCurrent.valstr}" >
</text>
</dockLayout>
<!--DockLayout for Ampere Unit-->
<dockLayout id="ampere_unit" x="{@csm.VoltAmpereMeter.ampere_unit_x-@csm.VoltAmpereMeter.List_x}" width="{@csm.screenWidth}" height="{@csm.vmImage_y_gearselection-@csm.pageVisualCP_y}">
<text id="ampere_unit_text" x="0" opacity="{selopacity_Amp*selopacity_Volt}" ellipsize="false" font="{@csm.listUnselFont}" color="{@csm.itemSelColor}" dockLayout.halign="left" dockLayout.valign="bottom" string="A" >
</text>
</dockLayout>
<!--DockLayout for containing Data Not Available text-->
<dockLayout id="no_data_textline" x="{@csm.VoltAmpereMeter.List_x1-@csm.VoltAmpereMeter.List_x}" width="{@csm.screenWidth}" height="{@csm.vmImage_y_gearselection-@csm.pageVisualCP_y}">
<text id="no_data_text" x="0" opacity="{1-(selopacity_Amp*selopacity_Volt)}" ellipsize="false" font="{@csm.listSelFont}" color="{@csm.itemSelColor}" dockLayout.halign="left" dockLayout.valign="bottom" string="{text1}" >
</text>
</dockLayout>
<!--<rect id="test_rect1" x="{151-28}" y="0" width="1" height="240" opacity="1" fill="#00ff00" />
<rect id="test_rect1" x="{237-28}" y="0" width="1" height="240" opacity="1" fill="#00ff00" />
<rect id="test_rect1" x="{160-28}" y="0" width="1" height="240" opacity="1" fill="#00ff00" />
<rect id="test_rect1" x="{246-28}" y="0" width="1" height="240" opacity="1" fill="#00ff00" />
<rect id="test_rect8" x="0" y="{161-40}" width="320" height="1" opacity="1" fill="#00ff00" />
<rect id="test_rect1" x="{109-28}" y="0" width="1" height="240" opacity="1" fill="#00ff00" />-->
</dockLayout>
</dockLayout>
</code></pre>
| 0 | 2009-08-27T17:34:37Z | 1,342,646 | <p>I'm not exactly a regex expert, but it might be due to the brace at the end of the match. You might try to match <code>r"\{@csm.((?:[a-zA-Z0-9_]+\.?)+)"</code> and just check manually whether a closing brace occurs at the end or not.</p>
| 0 | 2009-08-27T17:43:15Z | [
"python",
"regex"
] |
Slow regex in Python? | 1,342,589 | <p>I'm trying to match these kinds of strings</p>
<pre><code>{@csm.foo.bar}
</code></pre>
<p>without matching any of these</p>
<pre><code>{@csm.foo.bar-@csm.ooga.booga}
{@csm.foo.bar-42}
</code></pre>
<p>The regex I use is</p>
<pre><code>r"\{@csm.((?:[a-zA-Z0-9_]+\.?)+)\}"
</code></pre>
<p>It gets dog slow if the string contains multiple matches. Why? It runs very fast if I take away the brace matching, like this</p>
<pre><code>r"@csm.((?:[a-zA-Z0-9_]+\.?)+)"
</code></pre>
<p>but that's not what I want.</p>
<p>Any ideas?</p>
<p>Here is sample input:</p>
<pre><code><dockLayout id="popup" y="0" x="0" width="{@csm.screenWidth}" height="{@csm.screenHeight}">
<dataNumber id="selopacity_Volt" name="selopacity_Volt" value="0" />
<dataNumber id="selopacity_Amp" name="selopacity_Amp" value="0" />
<animate trigger="{@m_ds_ML.VIMPBM_BatteryVoltage.valstr}" triggerOn="*" targetNode="selopacity_Volt" targetAttr="value" to="1" dur="0ms" ease="in" />
<animate trigger="{@m_ds_ML.VIMPBM_BatteryVoltage.valstr}" triggerOn="65024" targetNode="selopacity_Volt" targetAttr="value" to="0" dur="0ms" ease="in" />
<animate trigger="{@m_ds_ML.VIMPBM_BatteryCurrent.valstr}" triggerOn="*" targetNode="selopacity_Amp" targetAttr="value" to="1" dur="0ms" ease="in" />
<animate trigger="{@m_ds_ML.VIMPBM_BatteryCurrent.valstr}" triggerOn="65024" targetNode="selopacity_Amp" targetAttr="value" to="0" dur="0ms" ease="in" />
<dockLayout id="item" width="{@csm.screenWidth}" height="{@csm.screenHeight}" depth="-1" clip="false" xmlns="http://www.tat.se/kastor/kml" >
<dockLayout id="list_item_title" x="0" width="{@csm.screenWidth}" height="{@csm.Gearselection.text_heght-@csm.pageVisualCP_y}">
<text id="volt_amp_text" x="0" ellipsize="false" font="{@csm.listUnselFont}" color="{@csm.itemUnselColor}" dockLayout.halign="left" dockLayout.valign="bottom" string="{ItemTitle}" />
</dockLayout>
<dockLayout id="gear_layout" y="0" x="0" width="{@csm.screenWidth}" height="{@csm.vmImage_y_gearselection-@csm.pageVisualCP_y}">
<image id="battery_image" x="0" dockLayout.halign="left" dockLayout.valign="bottom" opacity="1" src="{@m_MenuModel.Gauges.VoltAmpereMeter.image}"/>
</dockLayout>
<!--DockLayout for Voltage Value-->
<dockLayout id="volt_value" x="0" width="{@csm.VoltAmpereMeter.volt_value_x-@csm.VoltAmpereMeter.List_x}" height="{@csm.vmImage_y_gearselection-@csm.pageVisualCP_y}">
<text id="volt_value_text" x="0" opacity="{selopacity_Volt*selopacity_Amp}" ellipsize="false" font="{@csm.listUnselFont}" color="{@csm.itemSelColor}" dockLayout.halign="right" dockLayout.valign="bottom" string="{@m_ds_ML.VIMPBM_BatteryVoltage.valstr}" >
</text>
</dockLayout>
<!--DockLayout for Voltage Unit-->
<dockLayout id="volt_unit" x="{@csm.VoltAmpereMeter.volt_unit_x-@csm.VoltAmpereMeter.List_x}" width="{@csm.screenWidth}" height="{@csm.vmImage_y_gearselection-@csm.pageVisualCP_y}">
<text id="volt_unit_text" x="0" opacity="{selopacity_Volt*selopacity_Amp}" ellipsize="false" font="{@csm.listUnselFont}" color="{@csm.itemSelColor}" dockLayout.halign="left" dockLayout.valign="bottom" string="V" >
</text>
</dockLayout>
<!--DockLayout for Ampere Value-->
<dockLayout id="ampere_value" x="0" width="{@csm.VoltAmpereMeter.ampere_value_x-@csm.VoltAmpereMeter.List_x}" height="{@csm.vmImage_y_gearselection-@csm.pageVisualCP_y}">
<text id="ampere_value_text" x="0" opacity="{selopacity_Amp*selopacity_Volt}" ellipsize="false" font="{@csm.listUnselFont}" color="{@csm.itemSelColor}" dockLayout.halign="right" dockLayout.valign="bottom" string="{@m_ds_ML.VIMPBM_BatteryCurrent.valstr}" >
</text>
</dockLayout>
<!--DockLayout for Ampere Unit-->
<dockLayout id="ampere_unit" x="{@csm.VoltAmpereMeter.ampere_unit_x-@csm.VoltAmpereMeter.List_x}" width="{@csm.screenWidth}" height="{@csm.vmImage_y_gearselection-@csm.pageVisualCP_y}">
<text id="ampere_unit_text" x="0" opacity="{selopacity_Amp*selopacity_Volt}" ellipsize="false" font="{@csm.listUnselFont}" color="{@csm.itemSelColor}" dockLayout.halign="left" dockLayout.valign="bottom" string="A" >
</text>
</dockLayout>
<!--DockLayout for containing Data Not Available text-->
<dockLayout id="no_data_textline" x="{@csm.VoltAmpereMeter.List_x1-@csm.VoltAmpereMeter.List_x}" width="{@csm.screenWidth}" height="{@csm.vmImage_y_gearselection-@csm.pageVisualCP_y}">
<text id="no_data_text" x="0" opacity="{1-(selopacity_Amp*selopacity_Volt)}" ellipsize="false" font="{@csm.listSelFont}" color="{@csm.itemSelColor}" dockLayout.halign="left" dockLayout.valign="bottom" string="{text1}" >
</text>
</dockLayout>
<!--<rect id="test_rect1" x="{151-28}" y="0" width="1" height="240" opacity="1" fill="#00ff00" />
<rect id="test_rect1" x="{237-28}" y="0" width="1" height="240" opacity="1" fill="#00ff00" />
<rect id="test_rect1" x="{160-28}" y="0" width="1" height="240" opacity="1" fill="#00ff00" />
<rect id="test_rect1" x="{246-28}" y="0" width="1" height="240" opacity="1" fill="#00ff00" />
<rect id="test_rect8" x="0" y="{161-40}" width="320" height="1" opacity="1" fill="#00ff00" />
<rect id="test_rect1" x="{109-28}" y="0" width="1" height="240" opacity="1" fill="#00ff00" />-->
</dockLayout>
</dockLayout>
</code></pre>
| 0 | 2009-08-27T17:34:37Z | 1,342,688 | <p>Can you supply a test case of a string for which the first match is "dog slow"? BTW, though I don't know if that matters to performance, there's an imprecision in the RE -- it matches any single character after the <code>{@csm</code> start, not just a dot; maybe a better expression (possibly faster as it doesn't make any dots "optional") could be:</p>
<pre><code>r'\{@csm((?:\.\w+)+)\}'
</code></pre>
| 4 | 2009-08-27T17:49:08Z | [
"python",
"regex"
] |
Slow regex in Python? | 1,342,589 | <p>I'm trying to match these kinds of strings</p>
<pre><code>{@csm.foo.bar}
</code></pre>
<p>without matching any of these</p>
<pre><code>{@csm.foo.bar-@csm.ooga.booga}
{@csm.foo.bar-42}
</code></pre>
<p>The regex I use is</p>
<pre><code>r"\{@csm.((?:[a-zA-Z0-9_]+\.?)+)\}"
</code></pre>
<p>It gets dog slow if the string contains multiple matches. Why? It runs very fast if I take away the brace matching, like this</p>
<pre><code>r"@csm.((?:[a-zA-Z0-9_]+\.?)+)"
</code></pre>
<p>but that's not what I want.</p>
<p>Any ideas?</p>
<p>Here is sample input:</p>
<pre><code><dockLayout id="popup" y="0" x="0" width="{@csm.screenWidth}" height="{@csm.screenHeight}">
<dataNumber id="selopacity_Volt" name="selopacity_Volt" value="0" />
<dataNumber id="selopacity_Amp" name="selopacity_Amp" value="0" />
<animate trigger="{@m_ds_ML.VIMPBM_BatteryVoltage.valstr}" triggerOn="*" targetNode="selopacity_Volt" targetAttr="value" to="1" dur="0ms" ease="in" />
<animate trigger="{@m_ds_ML.VIMPBM_BatteryVoltage.valstr}" triggerOn="65024" targetNode="selopacity_Volt" targetAttr="value" to="0" dur="0ms" ease="in" />
<animate trigger="{@m_ds_ML.VIMPBM_BatteryCurrent.valstr}" triggerOn="*" targetNode="selopacity_Amp" targetAttr="value" to="1" dur="0ms" ease="in" />
<animate trigger="{@m_ds_ML.VIMPBM_BatteryCurrent.valstr}" triggerOn="65024" targetNode="selopacity_Amp" targetAttr="value" to="0" dur="0ms" ease="in" />
<dockLayout id="item" width="{@csm.screenWidth}" height="{@csm.screenHeight}" depth="-1" clip="false" xmlns="http://www.tat.se/kastor/kml" >
<dockLayout id="list_item_title" x="0" width="{@csm.screenWidth}" height="{@csm.Gearselection.text_heght-@csm.pageVisualCP_y}">
<text id="volt_amp_text" x="0" ellipsize="false" font="{@csm.listUnselFont}" color="{@csm.itemUnselColor}" dockLayout.halign="left" dockLayout.valign="bottom" string="{ItemTitle}" />
</dockLayout>
<dockLayout id="gear_layout" y="0" x="0" width="{@csm.screenWidth}" height="{@csm.vmImage_y_gearselection-@csm.pageVisualCP_y}">
<image id="battery_image" x="0" dockLayout.halign="left" dockLayout.valign="bottom" opacity="1" src="{@m_MenuModel.Gauges.VoltAmpereMeter.image}"/>
</dockLayout>
<!--DockLayout for Voltage Value-->
<dockLayout id="volt_value" x="0" width="{@csm.VoltAmpereMeter.volt_value_x-@csm.VoltAmpereMeter.List_x}" height="{@csm.vmImage_y_gearselection-@csm.pageVisualCP_y}">
<text id="volt_value_text" x="0" opacity="{selopacity_Volt*selopacity_Amp}" ellipsize="false" font="{@csm.listUnselFont}" color="{@csm.itemSelColor}" dockLayout.halign="right" dockLayout.valign="bottom" string="{@m_ds_ML.VIMPBM_BatteryVoltage.valstr}" >
</text>
</dockLayout>
<!--DockLayout for Voltage Unit-->
<dockLayout id="volt_unit" x="{@csm.VoltAmpereMeter.volt_unit_x-@csm.VoltAmpereMeter.List_x}" width="{@csm.screenWidth}" height="{@csm.vmImage_y_gearselection-@csm.pageVisualCP_y}">
<text id="volt_unit_text" x="0" opacity="{selopacity_Volt*selopacity_Amp}" ellipsize="false" font="{@csm.listUnselFont}" color="{@csm.itemSelColor}" dockLayout.halign="left" dockLayout.valign="bottom" string="V" >
</text>
</dockLayout>
<!--DockLayout for Ampere Value-->
<dockLayout id="ampere_value" x="0" width="{@csm.VoltAmpereMeter.ampere_value_x-@csm.VoltAmpereMeter.List_x}" height="{@csm.vmImage_y_gearselection-@csm.pageVisualCP_y}">
<text id="ampere_value_text" x="0" opacity="{selopacity_Amp*selopacity_Volt}" ellipsize="false" font="{@csm.listUnselFont}" color="{@csm.itemSelColor}" dockLayout.halign="right" dockLayout.valign="bottom" string="{@m_ds_ML.VIMPBM_BatteryCurrent.valstr}" >
</text>
</dockLayout>
<!--DockLayout for Ampere Unit-->
<dockLayout id="ampere_unit" x="{@csm.VoltAmpereMeter.ampere_unit_x-@csm.VoltAmpereMeter.List_x}" width="{@csm.screenWidth}" height="{@csm.vmImage_y_gearselection-@csm.pageVisualCP_y}">
<text id="ampere_unit_text" x="0" opacity="{selopacity_Amp*selopacity_Volt}" ellipsize="false" font="{@csm.listUnselFont}" color="{@csm.itemSelColor}" dockLayout.halign="left" dockLayout.valign="bottom" string="A" >
</text>
</dockLayout>
<!--DockLayout for containing Data Not Available text-->
<dockLayout id="no_data_textline" x="{@csm.VoltAmpereMeter.List_x1-@csm.VoltAmpereMeter.List_x}" width="{@csm.screenWidth}" height="{@csm.vmImage_y_gearselection-@csm.pageVisualCP_y}">
<text id="no_data_text" x="0" opacity="{1-(selopacity_Amp*selopacity_Volt)}" ellipsize="false" font="{@csm.listSelFont}" color="{@csm.itemSelColor}" dockLayout.halign="left" dockLayout.valign="bottom" string="{text1}" >
</text>
</dockLayout>
<!--<rect id="test_rect1" x="{151-28}" y="0" width="1" height="240" opacity="1" fill="#00ff00" />
<rect id="test_rect1" x="{237-28}" y="0" width="1" height="240" opacity="1" fill="#00ff00" />
<rect id="test_rect1" x="{160-28}" y="0" width="1" height="240" opacity="1" fill="#00ff00" />
<rect id="test_rect1" x="{246-28}" y="0" width="1" height="240" opacity="1" fill="#00ff00" />
<rect id="test_rect8" x="0" y="{161-40}" width="320" height="1" opacity="1" fill="#00ff00" />
<rect id="test_rect1" x="{109-28}" y="0" width="1" height="240" opacity="1" fill="#00ff00" />-->
</dockLayout>
</dockLayout>
</code></pre>
| 0 | 2009-08-27T17:34:37Z | 1,342,809 | <p>You probably need to give a better example of exactly what's slow. For a reasonably long string containing stuff that does and doesn't match:</p>
<pre><code>x="".join(['{@csm.foo.bar-%d}\n{@csm.foo.%dx.baz}\n' % (a,a)
for a in xrange(10000)])
mymatch=r"\{@csm.((?:[a-zA-Z0-9_]+\.?)+)\}"
for y in re.finditer(mymatch,x):
print y.group(0)
</code></pre>
<p>works fine, but if you've got a long enough string and you're searching it poorly you could have problems.</p>
| 0 | 2009-08-27T18:07:26Z | [
"python",
"regex"
] |
In Django, how to control which DB connection and cursor a queryset will use | 1,342,594 | <p>I'm trying to get a queryset to issue its query over a different DB connection, using a different cursor class. Does anyone know if that's possible and if so how it might be done? In psuedo-code:</p>
<pre><code> # setup a new db connection:
db = db_connect(cursorclass=AlternateCursor)
# setup a generic queryset
qset = blah.objects.all()
# tell qset to use the new connection:
qset.use_db(db)
# and then apply some filters
qset = qset.filter(...)
# and execute the query:
for object in qset:
...
</code></pre>
<p>Thanks!</p>
| 3 | 2009-08-27T17:35:36Z | 1,343,429 | <p>This is possible from Django 1.0 on - the trick is to use a custom manager for your model and replace the manager's connection object. See the code at Eric Florenzano's post at <a href="http://www.eflorenzano.com/blog/post/easy-multi-database-support-django/" rel="nofollow">http://www.eflorenzano.com/blog/post/easy-multi-database-support-django/</a></p>
| 2 | 2009-08-27T19:52:37Z | [
"python",
"django",
"database"
] |
Pythonic way of checking if a condition holds for any element of a list | 1,342,601 | <p>I have a list in Python, and I want to check if any elements are negative. Specman has the <code>has()</code> method for lists which does:</p>
<pre><code>x: list of uint;
if (x.has(it < 0)) {
// do something
};
</code></pre>
<p>Where <code>it</code> is a Specman keyword mapped to each element of the list in turn.</p>
<p>I find this rather elegant. I looked through the <a href="http://docs.python.org/library/stdtypes.html#typesseq-mutable">Python documentation</a> and couldn't find anything similar. The best I could come up with was:</p>
<pre><code>if (True in [t < 0 for t in x]):
# do something
</code></pre>
<p>I find this rather inelegant. Is there a better way to do this in Python?</p>
| 29 | 2009-08-27T17:36:55Z | 1,342,617 | <p><a href="http://docs.python.org/library/functions.html#any">any()</a>:</p>
<pre><code>if any(t < 0 for t in x):
# do something
</code></pre>
<p>Also, if you're going to use "True in ...", make it a generator expression so it doesn't take O(n) memory:</p>
<pre><code>if True in (t < 0 for t in x):
</code></pre>
| 65 | 2009-08-27T17:38:53Z | [
"python",
"list"
] |
Pythonic way of checking if a condition holds for any element of a list | 1,342,601 | <p>I have a list in Python, and I want to check if any elements are negative. Specman has the <code>has()</code> method for lists which does:</p>
<pre><code>x: list of uint;
if (x.has(it < 0)) {
// do something
};
</code></pre>
<p>Where <code>it</code> is a Specman keyword mapped to each element of the list in turn.</p>
<p>I find this rather elegant. I looked through the <a href="http://docs.python.org/library/stdtypes.html#typesseq-mutable">Python documentation</a> and couldn't find anything similar. The best I could come up with was:</p>
<pre><code>if (True in [t < 0 for t in x]):
# do something
</code></pre>
<p>I find this rather inelegant. Is there a better way to do this in Python?</p>
| 29 | 2009-08-27T17:36:55Z | 1,342,622 | <p>Use <code>any()</code>.</p>
<pre><code>if any(t < 0 for t in x):
# do something
</code></pre>
| 18 | 2009-08-27T17:39:10Z | [
"python",
"list"
] |
Pythonic way of checking if a condition holds for any element of a list | 1,342,601 | <p>I have a list in Python, and I want to check if any elements are negative. Specman has the <code>has()</code> method for lists which does:</p>
<pre><code>x: list of uint;
if (x.has(it < 0)) {
// do something
};
</code></pre>
<p>Where <code>it</code> is a Specman keyword mapped to each element of the list in turn.</p>
<p>I find this rather elegant. I looked through the <a href="http://docs.python.org/library/stdtypes.html#typesseq-mutable">Python documentation</a> and couldn't find anything similar. The best I could come up with was:</p>
<pre><code>if (True in [t < 0 for t in x]):
# do something
</code></pre>
<p>I find this rather inelegant. Is there a better way to do this in Python?</p>
| 29 | 2009-08-27T17:36:55Z | 1,342,629 | <p>Python has a built in <a href="http://docs.python.org/library/functions.html#any">any()</a> function for exactly this purpose.</p>
| 8 | 2009-08-27T17:40:26Z | [
"python",
"list"
] |
Is it possible to reference the output of an IronPython project from within a c# project? | 1,342,645 | <p>I would like to build a code library in IronPython and have another C# project reference it. Can I do this? How?</p>
<p>Is this just as simple as building the project and referencing the dll? Is there any conflict with the dynamic aspect of it?</p>
| 0 | 2009-08-27T17:43:09Z | 1,380,583 | <p>There is currently no way to build <a href="http://msdn.microsoft.com/en-us/library/12a7a7h3.aspx" rel="nofollow">CLS</a>-compliant assemblies from IronPython. The <code>pyc</code> tool will generate a DLL from Python code, but it's really only useful from IronPython.</p>
<p>If you want to use IronPython from a C# app, you'll have to use the <a href="http://www.ironpython.info/index.php/Hosting%5FIronPython%5F2" rel="nofollow">hosting interfaces</a> (<a href="http://dlr.codeplex.com/Wiki/View.aspx?title=Docs%20and%20specs" rel="nofollow">gory details</a>). You could also check out <a href="http://rads.stackoverflow.com/amzn/click/1933988339" rel="nofollow">IronPython in Action</a>, which describes the hosting process quite well.</p>
| 1 | 2009-09-04T17:34:00Z | [
"c#",
"python",
"assemblies",
"ironpython"
] |
Django empty field fallback | 1,342,679 | <p>I have a model that holds user address. This model has to have first_name and last_name fields since one would like to set address to a recipient (like his company etc.). What I'm trying to achieve is:</p>
<ul>
<li>if the fist_name/last_name field in the address is filled - return simply that field</li>
<li>if the fist_name/last_name field in the address is empty - fetch corrresponding field data from a foreignkey pointing to a proper django.auth.models.User</li>
<li>I'd like this to be treated as normal django field that would be present in fields lookup</li>
<li>I don't want to create a method, since it's a refactoring and Address.first_name/last_name are used in various places of the application (also in model forms etc.), so I need this to me as smooth as possible or else I'll have to tinker around in a lot of places</li>
</ul>
<p>Thanks for help :)</p>
| 3 | 2009-08-27T17:47:49Z | 1,342,817 | <p>There are two options here. The first is to create a method to look it up dynamically, but use the <code>property</code> decorator so that other code can still use straight attribute access.</p>
<pre><code>class MyModel(models.Model):
_first_name = models.CharField(max_length=100, db_column='first_name')
@property
def first_name(self):
return self._first_name or self.user.first_name
@first_name.setter
def first_name(self, value):
self._first_name = value
</code></pre>
<p>This will always refer to the latest value of first_name, even if the related User is changed. You can get/set the property exactly as you would an attribute: <code>myinstance.first_name = 'daniel'</code></p>
<p>The other option is to override the model's <code>save()</code> method so that it does the lookup when you save:</p>
<pre><code>def save(self, *args, **kwargs):
if not self.first_name:
self.first_name = self.user.first_name
# now call the default save() method
super(MyModel, self).save(*args, **kwargs)
</code></pre>
<p>This way you don't have to change your db, but it is only refreshed on save - so if the related User object is changed but this object isn't, it will refer to the old User value.</p>
| 5 | 2009-08-27T18:09:17Z | [
"python",
"django",
"django-models",
"models",
"field"
] |
How can I force subtraction to be signed in Python? | 1,342,782 | <p>You can skip to the bottom line if you don't care about the background:</p>
<p>I have the following code in Python:</p>
<pre><code>ratio = (point.threshold - self.points[0].value) / (self.points[1].value - self.points[0].value)
</code></pre>
<p>Which is giving me wrong values. For instance, for:</p>
<pre><code>threshold: 25.0
self.points[0].value: 46
self.points[1].value: 21
</code></pre>
<p>I got:</p>
<pre><code>ratio: -0.000320556853048
</code></pre>
<p>Which is wrong.</p>
<p>Looking into it, I realized that <code>self.points[0].value</code> and <code>self.points[1].value] are of the type </code>numpy.uint16`, so I got:</p>
<pre><code>21 - 46 = 65511
</code></pre>
<p>While I never defined a type for <code>point.threshold</code>. I just assigned it. I imagine it got a plain vanilla <code>int</code>.</p>
<h1>The Bottom Line</h1>
<p>How can I force the the subtraction of two <code>uint</code>s to be signed?</p>
| 0 | 2009-08-27T18:03:38Z | 1,342,833 | <p>Well, the obvious solution would probably be to cast to floats:</p>
<pre><code>ratio = (float(point.threshold) - float(self.points[0].value)) / (float(self.points[1].value) - float(self.points[0].value))
</code></pre>
<p>Or I suppose you could cast to one of the numpy signed types.</p>
| 2 | 2009-08-27T18:11:59Z | [
"python",
"sign",
"subtraction",
"uint"
] |
How can I force subtraction to be signed in Python? | 1,342,782 | <p>You can skip to the bottom line if you don't care about the background:</p>
<p>I have the following code in Python:</p>
<pre><code>ratio = (point.threshold - self.points[0].value) / (self.points[1].value - self.points[0].value)
</code></pre>
<p>Which is giving me wrong values. For instance, for:</p>
<pre><code>threshold: 25.0
self.points[0].value: 46
self.points[1].value: 21
</code></pre>
<p>I got:</p>
<pre><code>ratio: -0.000320556853048
</code></pre>
<p>Which is wrong.</p>
<p>Looking into it, I realized that <code>self.points[0].value</code> and <code>self.points[1].value] are of the type </code>numpy.uint16`, so I got:</p>
<pre><code>21 - 46 = 65511
</code></pre>
<p>While I never defined a type for <code>point.threshold</code>. I just assigned it. I imagine it got a plain vanilla <code>int</code>.</p>
<h1>The Bottom Line</h1>
<p>How can I force the the subtraction of two <code>uint</code>s to be signed?</p>
| 0 | 2009-08-27T18:03:38Z | 1,342,899 | <p>Almost anything <strong>but</strong> uints will work here, so just cast these to something else before you do the subtraction. </p>
<p>Since threshold = 25.0 (note the decimal point), it's a float, so the subtraction and division will all work as long as you're not using uints.</p>
| 2 | 2009-08-27T18:24:35Z | [
"python",
"sign",
"subtraction",
"uint"
] |
How can I force subtraction to be signed in Python? | 1,342,782 | <p>You can skip to the bottom line if you don't care about the background:</p>
<p>I have the following code in Python:</p>
<pre><code>ratio = (point.threshold - self.points[0].value) / (self.points[1].value - self.points[0].value)
</code></pre>
<p>Which is giving me wrong values. For instance, for:</p>
<pre><code>threshold: 25.0
self.points[0].value: 46
self.points[1].value: 21
</code></pre>
<p>I got:</p>
<pre><code>ratio: -0.000320556853048
</code></pre>
<p>Which is wrong.</p>
<p>Looking into it, I realized that <code>self.points[0].value</code> and <code>self.points[1].value] are of the type </code>numpy.uint16`, so I got:</p>
<pre><code>21 - 46 = 65511
</code></pre>
<p>While I never defined a type for <code>point.threshold</code>. I just assigned it. I imagine it got a plain vanilla <code>int</code>.</p>
<h1>The Bottom Line</h1>
<p>How can I force the the subtraction of two <code>uint</code>s to be signed?</p>
| 0 | 2009-08-27T18:03:38Z | 1,342,902 | <p>Do those values actually NEED to be uint16 instead of int16? Unless they have to be able to take values of <code>2**15</code> or above (but still below <code>2**16</code>) you could simply keep them as int16 and be done with it -- unsigned ints, as you discovered, can be tricky (and not just in numpy;-). If you DO need the uint16, then casts as David suggests will work, but if you can simply use int16 it will be faster and more readable.</p>
<p>BTW, it looks like that point.threshold is a float, not an int (good thing too, otherwise that division the way you code it would be a truncating one, unless you're importing true division from the future, as has been supported in many <code>2.*</code> releases of Python -- and is finally THE way division works in <code>3.*</code>). The <code>.0</code> in <code>25.0</code> "gives it away" and shows it's a float, not an int.</p>
| 0 | 2009-08-27T18:24:44Z | [
"python",
"sign",
"subtraction",
"uint"
] |
How does python decide whether a parameter is a reference or a value? | 1,342,953 | <p>In C++, <code>void somefunction(int)</code> passes a value, while <code>void somefunction(int&)</code> passes a reference. In Java, primitives are passed by value, while objects are passed by reference. How does python make this decision?</p>
<p>Edit: Since everything is passed by reference, why does this:</p>
<pre><code>def foo(num):
num *= 2
a = 4
foo(a)
print(a)
</code></pre>
<p>print '4' instead of '8'?</p>
| 4 | 2009-08-27T18:31:35Z | 1,342,974 | <p>Everything is passed by reference. Everything is an object, too.</p>
| 1 | 2009-08-27T18:33:27Z | [
"python",
"pointers",
"reference"
] |
How does python decide whether a parameter is a reference or a value? | 1,342,953 | <p>In C++, <code>void somefunction(int)</code> passes a value, while <code>void somefunction(int&)</code> passes a reference. In Java, primitives are passed by value, while objects are passed by reference. How does python make this decision?</p>
<p>Edit: Since everything is passed by reference, why does this:</p>
<pre><code>def foo(num):
num *= 2
a = 4
foo(a)
print(a)
</code></pre>
<p>print '4' instead of '8'?</p>
| 4 | 2009-08-27T18:31:35Z | 1,342,976 | <p>It passes everything by reference. Even when you specify a numeric value, it is a reference against a table containing that value. This is the difference between static and dynamic languages. The type stays with the value, not with the container, and variables are just references towards a "value space" where all values live. You can assume this value space containing all the possible immutable objects (integers, floats, strings) plus all the mutable ones you create (lists, dicts, objects). Of course, their existence is made concrete only when you involve them (that means, if you never use the number 42 in your program, no allocated space exist for the value 42 in the "value space")</p>
<p>It does that because the number it is referring to is a immutable object. 4 is 4 no matter what.</p>
<pre><code>def foo(num): # here, num is referring to the immutable entity 4
num *= 2 # num now refers to the immutable entity 8
a = 4 # a now is pointing to the immutable entity 4
foo(a) # a is still referring to the same entity 4
print(a) # prints what a refers to, still 4
</code></pre>
<p>However, if you do this</p>
<pre><code>def foo(l): # here, l refers to the list it receives
l.append(5) # the list is appended with the number 5
a = [] # a now is pointing to a specific mutable list
foo(a) # a is still referring to the same specific mutable list
print(a) # prints what a refers to, the specific mutable list which now contains [5]
</code></pre>
| 11 | 2009-08-27T18:33:36Z | [
"python",
"pointers",
"reference"
] |
How does python decide whether a parameter is a reference or a value? | 1,342,953 | <p>In C++, <code>void somefunction(int)</code> passes a value, while <code>void somefunction(int&)</code> passes a reference. In Java, primitives are passed by value, while objects are passed by reference. How does python make this decision?</p>
<p>Edit: Since everything is passed by reference, why does this:</p>
<pre><code>def foo(num):
num *= 2
a = 4
foo(a)
print(a)
</code></pre>
<p>print '4' instead of '8'?</p>
| 4 | 2009-08-27T18:31:35Z | 1,343,052 | <p>In response to your edit, it is because integers are immutable in Python. So <code>a</code> is not changed for the same reason it is not changed when running this code:</p>
<pre><code>a = 4
num = a
num *= 2
print(a)
</code></pre>
<p>You aren't changing <code>num</code> (and therefore <code>a</code>) in place, you are creating a new number and assigning it to num.</p>
| 3 | 2009-08-27T18:43:10Z | [
"python",
"pointers",
"reference"
] |
How does python decide whether a parameter is a reference or a value? | 1,342,953 | <p>In C++, <code>void somefunction(int)</code> passes a value, while <code>void somefunction(int&)</code> passes a reference. In Java, primitives are passed by value, while objects are passed by reference. How does python make this decision?</p>
<p>Edit: Since everything is passed by reference, why does this:</p>
<pre><code>def foo(num):
num *= 2
a = 4
foo(a)
print(a)
</code></pre>
<p>print '4' instead of '8'?</p>
| 4 | 2009-08-27T18:31:35Z | 1,343,071 | <p>Arguments are actually passed by value. The function is passed the object the variable refers to, not the variable itself. A function cannot rebind a caller's variables. A function cannot change an immutable object, but can change (request changes to) a mutable one.</p>
| 3 | 2009-08-27T18:45:55Z | [
"python",
"pointers",
"reference"
] |
How does python decide whether a parameter is a reference or a value? | 1,342,953 | <p>In C++, <code>void somefunction(int)</code> passes a value, while <code>void somefunction(int&)</code> passes a reference. In Java, primitives are passed by value, while objects are passed by reference. How does python make this decision?</p>
<p>Edit: Since everything is passed by reference, why does this:</p>
<pre><code>def foo(num):
num *= 2
a = 4
foo(a)
print(a)
</code></pre>
<p>print '4' instead of '8'?</p>
| 4 | 2009-08-27T18:31:35Z | 1,343,188 | <p>There is disagreement on terminology here. In the Java community, they say that everything is passed by value: primitives are passed by value; references are passed by value. (Just search this site for Java and pass by reference if you don't believe this.) Note that "objects" are not values in the language; only references to objects are.</p>
<p>The distinction that they use is that, in Java, when you pass a reference, the original reference variable in the caller's scope can never be changed (i.e. made to point to a different object) by the callee, which should be possible in pass by reference. Only the object pointed to by the reference may be mutated, but that is irrelevant.</p>
<p>Python values work the exact same way as references in Java. If we use the same definition, then we would say that everything in Python is a reference, and everything is passed by value. Of course, some in the Python community use a different definition.</p>
<p>The disagreement on terminology is the source of most of the confusion.</p>
<p>Since you mention C++, the Python code you have would be equivalent to something like this in C++:</p>
<pre><code>void foo(const int *num) {
num = new int(*num * 2);
}
const int *a = new int(4);
foo(a);
print(a);
</code></pre>
<p>Note that the argument is a pointer, which is most similar to references in Java and Python.</p>
| 9 | 2009-08-27T19:07:23Z | [
"python",
"pointers",
"reference"
] |
How does python decide whether a parameter is a reference or a value? | 1,342,953 | <p>In C++, <code>void somefunction(int)</code> passes a value, while <code>void somefunction(int&)</code> passes a reference. In Java, primitives are passed by value, while objects are passed by reference. How does python make this decision?</p>
<p>Edit: Since everything is passed by reference, why does this:</p>
<pre><code>def foo(num):
num *= 2
a = 4
foo(a)
print(a)
</code></pre>
<p>print '4' instead of '8'?</p>
| 4 | 2009-08-27T18:31:35Z | 1,346,078 | <p>This is not really about the function call semantics but the assignment semantics. In Python assignment is done by rebinding the reference, not by overwriting the original object. This is why the example code prints 4 instead of 8 - it has nothing to do with mutability of objects as such, more that the *= operator is not a mutator but a multiplication followed by an assignment. Here the <strong>num *= 2</strong> is essentially rebinding the '<strong>num</strong>' name in that function to a new object of value '<strong>num * 2</strong>'. The original value you passed in is left unaltered throughout.</p>
| 1 | 2009-08-28T10:06:41Z | [
"python",
"pointers",
"reference"
] |
Python Packages? | 1,342,975 | <p>Ok, I think whatever I'm doing wrong, it's probably blindingly obvious, but I can't figure it out. I've read and re-read the tutorial section on packages and the only thing I can figure is that this won't work because I'm executing it directly. Here's the directory setup:</p>
<pre><code>eulerproject/
__init__.py
euler1.py
euler2.py
...
eulern.py
tests/
__init__.py
testeulern.py
</code></pre>
<p>Here are the contents of testeuler12.py (the first test module I've written):</p>
<pre><code>import unittest
from .. import euler12
class Euler12UnitTests(unittest.TestCase):
def testtriangle(self):
"""
Ensure that the triangle number generator returns the first 10
triangle numbers.
"""
self.seq = [1,3,6,10,15,21,28,36,45,55]
self.generator = euler12.trianglegenerator()
self.results = []
while len(self.results) != 10:
self.results.append(self.generator.next())
self.assertEqual(self.seq, self.results)
def testdivisors(self):
"""
Ensure that the divisors function can properly factor the number 28.
"""
self.number = 28
self.answer = [1,2,4,7,14,28]
self.assertEqual(self.answer, euler12.divisors(self.number))
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>Now, when I execute this from IDLE and from the command line while in the directory, I get the following error:</p>
<pre><code>Traceback (most recent call last):
File "C:\Documents and Settings\jbennet\My Documents\Python\eulerproject\tests\testeuler12.py", line 2, in <module>
from .. import euler12
ValueError: Attempted relative import in non-package
</code></pre>
<p>I think the problem is that since I'm running it directly, I can't do relative imports (because <code>__name__</code> changes, and my vague understanding of the packages description is that <code>__name__</code> is part of how it tells what package it's in), but in that case what do you guys suggest for how to import the 'production' code stored 1 level up from the test code?</p>
| 9 | 2009-08-27T18:33:28Z | 1,343,149 | <p>I had the same problem. I now use <a href="http://nose.readthedocs.org/en/latest/" rel="nofollow">nose</a> to run my tests, and relative imports are correctly handled.</p>
<p>Yeah, this whole relative import thing is confusing.</p>
| 8 | 2009-08-27T18:58:48Z | [
"python",
"unit-testing",
"packages"
] |
Python Packages? | 1,342,975 | <p>Ok, I think whatever I'm doing wrong, it's probably blindingly obvious, but I can't figure it out. I've read and re-read the tutorial section on packages and the only thing I can figure is that this won't work because I'm executing it directly. Here's the directory setup:</p>
<pre><code>eulerproject/
__init__.py
euler1.py
euler2.py
...
eulern.py
tests/
__init__.py
testeulern.py
</code></pre>
<p>Here are the contents of testeuler12.py (the first test module I've written):</p>
<pre><code>import unittest
from .. import euler12
class Euler12UnitTests(unittest.TestCase):
def testtriangle(self):
"""
Ensure that the triangle number generator returns the first 10
triangle numbers.
"""
self.seq = [1,3,6,10,15,21,28,36,45,55]
self.generator = euler12.trianglegenerator()
self.results = []
while len(self.results) != 10:
self.results.append(self.generator.next())
self.assertEqual(self.seq, self.results)
def testdivisors(self):
"""
Ensure that the divisors function can properly factor the number 28.
"""
self.number = 28
self.answer = [1,2,4,7,14,28]
self.assertEqual(self.answer, euler12.divisors(self.number))
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>Now, when I execute this from IDLE and from the command line while in the directory, I get the following error:</p>
<pre><code>Traceback (most recent call last):
File "C:\Documents and Settings\jbennet\My Documents\Python\eulerproject\tests\testeuler12.py", line 2, in <module>
from .. import euler12
ValueError: Attempted relative import in non-package
</code></pre>
<p>I think the problem is that since I'm running it directly, I can't do relative imports (because <code>__name__</code> changes, and my vague understanding of the packages description is that <code>__name__</code> is part of how it tells what package it's in), but in that case what do you guys suggest for how to import the 'production' code stored 1 level up from the test code?</p>
| 9 | 2009-08-27T18:33:28Z | 1,343,173 | <p>Generally you would have a directory, the name of which is your package name, somewhere on your PYTHONPATH. For example:</p>
<pre><code>eulerproject/
euler/
__init__.py
euler1.py
...
tests/
...
setup.py
</code></pre>
<p>Then, you can either install this systemwide, or make sure to set <code>PYTHONPATH=/path/to/eulerproject/:$PYTHONPATH</code> when invoking your script.</p>
<p>An absolute import like this will then work:</p>
<pre><code>from euler import euler1
</code></pre>
<p><em>Edit</em>:</p>
<p>According to the Python docs, "modules intended for use as the main module of a Python application should always use absolute imports." (<a href="http://docs.python.org/tutorial/modules.html">Cite</a>)</p>
<p>So a test harness like <code>nose</code>, mentioned by the other answer, works because it imports packages rather than running them from the command line.</p>
<p>If you want to do things by hand, your runnable script needs to be outside the package hierarchy, like this:</p>
<pre><code>eulerproject/
runtests.py
euler/
__init__.py
euler1.py
...
tests/
__init__.py
testeulern.py
</code></pre>
<p>Now, <code>runtests.py</code> can do <code>from euler.tests.testeulern import TestCase</code> and <code>testeulern.py</code> can do <code>from .. import euler1</code></p>
| 8 | 2009-08-27T19:03:55Z | [
"python",
"unit-testing",
"packages"
] |
Can Python's logging format be modified depending on the message log level? | 1,343,227 | <p>I'm using Python's <code>logging</code> mechanism to print output to the screen. I could do this with print statements, but I want to allow a finer-tuned granularity for the user to disable certain types of output. I like the format printed for errors, but would prefer a simpler format when the output level is "info."</p>
<p>For example:</p>
<pre><code> logger.error("Running cmd failed")
logger.info("Running cmd passed")
</code></pre>
<p>In this example, I would like the format of the error to be printed differently:</p>
<blockquote>
<pre><code># error
Aug 27, 2009 - ERROR: Running cmd failed
# info
Running cmd passed
</code></pre>
</blockquote>
<p>Is it possible to have different formats for different log levels without having multiple logging objects? I'd prefer to do this without modifying the logger once it's created since there are a high number of if/else statements to determine how the output should be logged.</p>
| 38 | 2009-08-27T19:13:52Z | 1,343,273 | <p>Yes, you can do this by having a custom <code>Formatter</code> class:</p>
<pre><code>class MyFormatter(logging.Formatter):
def format(self, record):
#compute s according to record.levelno
#for example, by setting self._fmt
#according to the levelno, then calling
#the superclass to do the actual formatting
return s
</code></pre>
<p>Then attach a <code>MyFormatter</code> instance to your handlers.</p>
| 25 | 2009-08-27T19:20:42Z | [
"python",
"logging"
] |
Can Python's logging format be modified depending on the message log level? | 1,343,227 | <p>I'm using Python's <code>logging</code> mechanism to print output to the screen. I could do this with print statements, but I want to allow a finer-tuned granularity for the user to disable certain types of output. I like the format printed for errors, but would prefer a simpler format when the output level is "info."</p>
<p>For example:</p>
<pre><code> logger.error("Running cmd failed")
logger.info("Running cmd passed")
</code></pre>
<p>In this example, I would like the format of the error to be printed differently:</p>
<blockquote>
<pre><code># error
Aug 27, 2009 - ERROR: Running cmd failed
# info
Running cmd passed
</code></pre>
</blockquote>
<p>Is it possible to have different formats for different log levels without having multiple logging objects? I'd prefer to do this without modifying the logger once it's created since there are a high number of if/else statements to determine how the output should be logged.</p>
| 38 | 2009-08-27T19:13:52Z | 8,349,076 | <p>I just ran into this issue and had trouble filling in the "holes" left in the above example. Here's a more complete, working version that I used. Hopefully this helps someone:</p>
<pre><code># Custom formatter
class MyFormatter(logging.Formatter):
err_fmt = "ERROR: %(msg)s"
dbg_fmt = "DBG: %(module)s: %(lineno)d: %(msg)s"
info_fmt = "%(msg)s"
def __init__(self, fmt="%(levelno)s: %(msg)s"):
logging.Formatter.__init__(self, fmt)
def format(self, record):
# Save the original format configured by the user
# when the logger formatter was instantiated
format_orig = self._fmt
# Replace the original format with one customized by logging level
if record.levelno == logging.DEBUG:
self._fmt = MyFormatter.dbg_fmt
elif record.levelno == logging.INFO:
self._fmt = MyFormatter.info_fmt
elif record.levelno == logging.ERROR:
self._fmt = MyFormatter.err_fmt
# Call the original formatter class to do the grunt work
result = logging.Formatter.format(self, record)
# Restore the original format configured by the user
self._fmt = format_orig
return result
</code></pre>
<p><strong>Edit:</strong></p>
<p>Compliments of Halloleo, here's an example of how to use the above in your script:</p>
<pre><code>fmt = MyFormatter()
hdlr = logging.StreamHandler(sys.stdout)
hdlr.setFormatter(fmt)
logging.root.addHandler(hdlr)
logging.root.setLevel(DEBUG)
</code></pre>
| 30 | 2011-12-01T22:15:30Z | [
"python",
"logging"
] |
Can Python's logging format be modified depending on the message log level? | 1,343,227 | <p>I'm using Python's <code>logging</code> mechanism to print output to the screen. I could do this with print statements, but I want to allow a finer-tuned granularity for the user to disable certain types of output. I like the format printed for errors, but would prefer a simpler format when the output level is "info."</p>
<p>For example:</p>
<pre><code> logger.error("Running cmd failed")
logger.info("Running cmd passed")
</code></pre>
<p>In this example, I would like the format of the error to be printed differently:</p>
<blockquote>
<pre><code># error
Aug 27, 2009 - ERROR: Running cmd failed
# info
Running cmd passed
</code></pre>
</blockquote>
<p>Is it possible to have different formats for different log levels without having multiple logging objects? I'd prefer to do this without modifying the logger once it's created since there are a high number of if/else statements to determine how the output should be logged.</p>
| 38 | 2009-08-27T19:13:52Z | 14,520,171 | <p>And again like JS answer but more compact.</p>
<pre><code>class SpecialFormatter(logging.Formatter):
FORMATS = {logging.DEBUG :"DBG: %(module)s: %(lineno)d: %(message)s",
logging.ERROR : "ERROR: %(message)s",
logging.INFO : "%(message)s",
'DEFAULT' : "%(levelname)s: %(message)s"}
def format(self, record):
self._fmt = self.FORMATS.get(record.levelno, self.FORMATS['DEFAULT'])
return logging.Formatter.format(self, record)
hdlr = logging.StreamHandler(sys.stderr)
hdlr.setFormatter(SpecialFormatter())
logging.root.addHandler(hdlr)
logging.root.setLevel(logging.INFO)
</code></pre>
| 9 | 2013-01-25T10:44:12Z | [
"python",
"logging"
] |
Can Python's logging format be modified depending on the message log level? | 1,343,227 | <p>I'm using Python's <code>logging</code> mechanism to print output to the screen. I could do this with print statements, but I want to allow a finer-tuned granularity for the user to disable certain types of output. I like the format printed for errors, but would prefer a simpler format when the output level is "info."</p>
<p>For example:</p>
<pre><code> logger.error("Running cmd failed")
logger.info("Running cmd passed")
</code></pre>
<p>In this example, I would like the format of the error to be printed differently:</p>
<blockquote>
<pre><code># error
Aug 27, 2009 - ERROR: Running cmd failed
# info
Running cmd passed
</code></pre>
</blockquote>
<p>Is it possible to have different formats for different log levels without having multiple logging objects? I'd prefer to do this without modifying the logger once it's created since there are a high number of if/else statements to determine how the output should be logged.</p>
| 38 | 2009-08-27T19:13:52Z | 16,660,369 | <p>This is an adaptation of <a href="http://stackoverflow.com/a/14520171/760767">estani's answer</a> to the new implementation of <code>logging.Formatter</code> which now relies on formatting styles. Mine relies on <code>'{'</code> style format, but it can be adapted. Could be refined to be more general and allow selection of formatting style and custom messages as arguments to <code>__init__</code>, too.</p>
<pre><code>class SpecialFormatter(logging.Formatter):
FORMATS = {logging.DEBUG : logging._STYLES['{']("{module} DEBUG: {lineno}: {message}"),
logging.ERROR : logging._STYLES['{']("{module} ERROR: {message}"),
logging.INFO : logging._STYLES['{']("{module}: {message}"),
'DEFAULT' : logging._STYLES['{']("{module}: {message}")}
def format(self, record):
# Ugly. Should be better
self._style = self.FORMATS.get(record.levelno, self.FORMATS['DEFAULT'])
return logging.Formatter.format(self, record)
hdlr = logging.StreamHandler(sys.stderr)
hdlr.setFormatter(SpecialFormatter())
logging.root.addHandler(hdlr)
logging.root.setLevel(logging.INFO)
</code></pre>
| 6 | 2013-05-21T00:37:39Z | [
"python",
"logging"
] |
Can Python's logging format be modified depending on the message log level? | 1,343,227 | <p>I'm using Python's <code>logging</code> mechanism to print output to the screen. I could do this with print statements, but I want to allow a finer-tuned granularity for the user to disable certain types of output. I like the format printed for errors, but would prefer a simpler format when the output level is "info."</p>
<p>For example:</p>
<pre><code> logger.error("Running cmd failed")
logger.info("Running cmd passed")
</code></pre>
<p>In this example, I would like the format of the error to be printed differently:</p>
<blockquote>
<pre><code># error
Aug 27, 2009 - ERROR: Running cmd failed
# info
Running cmd passed
</code></pre>
</blockquote>
<p>Is it possible to have different formats for different log levels without having multiple logging objects? I'd prefer to do this without modifying the logger once it's created since there are a high number of if/else statements to determine how the output should be logged.</p>
| 38 | 2009-08-27T19:13:52Z | 21,943,339 | <p>The above solution works with 3.3.3 release.
However with 3.3.4 you get the following error.</p>
<pre><code>FORMATS = { logging.DEBUG : logging._STYLES['{']("{module} DEBUG: {lineno}: {message}"),
</code></pre>
<p>TypeError: 'tuple' object is not callable</p>
<p>After some searching around in the logging class
Lib\logging__init__.py
I found that a data structure has changed from 3.3.3 to 3.3.4 that causes the issue</p>
<h2>3.3.3</h2>
<pre><code>_STYLES = {
'%': PercentStyle,
'{': StrFormatStyle,
'$': StringTemplateStyle
}
</code></pre>
<h2>3.3.4</h2>
<pre><code>_STYLES = {
'%': (PercentStyle, BASIC_FORMAT),
'{': (StrFormatStyle, '{levelname}:{name}:{message} AA'),
'$': (StringTemplateStyle, '${levelname}:${name}:${message} BB'),
}
</code></pre>
<p>The updated solution is therefore</p>
<pre><code>class SpecialFormatter(logging.Formatter):
FORMATS = {logging.DEBUG : logging._STYLES['{'][0]("{module} DEBUG: {lineno}: {message}"),
logging.ERROR : logging._STYLES['{'][0]("{module} ERROR: {message}"),
logging.INFO : logging._STYLES['{'][0]("{module}: {message}"),
'DEFAULT' : logging._STYLES['{'][0]("{module}: {message}")}
def format(self, record):
# Ugly. Should be better
self._style = self.FORMATS.get(record.levelno, self.FORMATS['DEFAULT'])
return logging.Formatter.format(self, record)
</code></pre>
| 2 | 2014-02-21T19:19:27Z | [
"python",
"logging"
] |
Can Python's logging format be modified depending on the message log level? | 1,343,227 | <p>I'm using Python's <code>logging</code> mechanism to print output to the screen. I could do this with print statements, but I want to allow a finer-tuned granularity for the user to disable certain types of output. I like the format printed for errors, but would prefer a simpler format when the output level is "info."</p>
<p>For example:</p>
<pre><code> logger.error("Running cmd failed")
logger.info("Running cmd passed")
</code></pre>
<p>In this example, I would like the format of the error to be printed differently:</p>
<blockquote>
<pre><code># error
Aug 27, 2009 - ERROR: Running cmd failed
# info
Running cmd passed
</code></pre>
</blockquote>
<p>Is it possible to have different formats for different log levels without having multiple logging objects? I'd prefer to do this without modifying the logger once it's created since there are a high number of if/else statements to determine how the output should be logged.</p>
| 38 | 2009-08-27T19:13:52Z | 25,101,727 | <p>If you are just looking to skip formatting certain levels, you can do something simpler than the other answers like the following:</p>
<pre><code>class FormatterNotFormattingInfo(logging.Formatter):
def __init__(self, fmt = '%(levelname)s:%(message)s'):
logging.Formatter.__init__(self, fmt)
def format(self, record):
if record.levelno == logging.INFO:
return record.getMessage()
return logging.Formatter.format(self, record)
</code></pre>
<p>This also has the advantage of working before and after the 3.2 release by not using internal variables like self._fmt nor self._style.</p>
| 2 | 2014-08-03T04:46:26Z | [
"python",
"logging"
] |
Can Python's logging format be modified depending on the message log level? | 1,343,227 | <p>I'm using Python's <code>logging</code> mechanism to print output to the screen. I could do this with print statements, but I want to allow a finer-tuned granularity for the user to disable certain types of output. I like the format printed for errors, but would prefer a simpler format when the output level is "info."</p>
<p>For example:</p>
<pre><code> logger.error("Running cmd failed")
logger.info("Running cmd passed")
</code></pre>
<p>In this example, I would like the format of the error to be printed differently:</p>
<blockquote>
<pre><code># error
Aug 27, 2009 - ERROR: Running cmd failed
# info
Running cmd passed
</code></pre>
</blockquote>
<p>Is it possible to have different formats for different log levels without having multiple logging objects? I'd prefer to do this without modifying the logger once it's created since there are a high number of if/else statements to determine how the output should be logged.</p>
| 38 | 2009-08-27T19:13:52Z | 27,835,318 | <p>Instead of relying on styles or internal fields, you could also create a Formatter that delegates to other formatters depending on record.levelno (or other criteria). This is a slightly cleaner solution in my humble opinion. Code below should work for any python version >= 2.7: </p>
<p>The simple way would look something like this:</p>
<pre><code>class MyFormatter(logging.Formatter):
default_fmt = logging.Formatter('%(levelname)s in %(name)s: %(message)s')
info_fmt = logging.Formatter('%(message)s')
def format(self, record):
if record.levelno == logging.INFO:
return self.info_fmt.format(record)
else:
return self.default_fmt.format(record)
</code></pre>
<p>But you could make it more generic:</p>
<pre><code>class VarFormatter(logging.Formatter):
default_formatter = logging.Formatter('%(levelname)s in %(name)s: %(message)s')
def __init__(self, formats):
""" formats is a dict { loglevel : logformat } """
self.formatters = {}
for loglevel in formats:
self.formatters[loglevel] = logging.Formatter(formats[loglevel])
def format(self, record):
formatter = self.formatters.get(record.levelno, self.default_formatter)
return formatter.format(record)
</code></pre>
<p>I used a dict as input here, but obviously you could also use tuples, **kwargs, whatever floats your boat. This would then be used like:</p>
<pre><code>formatter = VarFormatter({logging.INFO: '[%(message)s]',
logging.WARNING: 'warning: %(message)s'})
<... attach formatter to logger ...>
</code></pre>
| 3 | 2015-01-08T07:51:54Z | [
"python",
"logging"
] |
How to find Title case phrases from a passage or bunch of paragraphs | 1,343,479 | <p>How do I parse sentence case phrases from a passage.</p>
<p>For example from this passage</p>
<p>Conan Doyle said that the character of Holmes was inspired by Dr. Joseph Bell, for whom Doyle had worked as a clerk at the Edinburgh Royal Infirmary. Like Holmes, Bell was noted for drawing large conclusions from the smallest observations.[1] Michael Harrison argued in a 1971 article in Ellery Queen's Mystery Magazine that the character was inspired by Wendell Scherer, a "consulting detective" in a murder case that allegedly received a great deal of newspaper attention in England in 1882.</p>
<p>We need to generate stuff like Conan Doyle, Holmes, Dr Joseph Bell, Wendell Scherr etc.</p>
<p>I would prefer a Pythonic Solution if possible</p>
| 1 | 2009-08-27T20:04:07Z | 1,343,568 | <p>This kind of processing can be very tricky. This simple code does almost the right thing:</p>
<pre><code>for s in re.finditer(r"([A-Z][a-z]+[. ]+)+([A-Z][a-z]+)?", text):
print s.group(0)
</code></pre>
<p>produces:</p>
<pre><code>Conan Doyle
Holmes
Dr. Joseph Bell
Doyle
Edinburgh Royal Infirmary. Like Holmes
Bell
Michael Harrison
Ellery Queen
Mystery Magazine
Wendell Scherer
England
</code></pre>
<p>To include "Dr. Joseph Bell", you need to be ok with the period in the string, which allows in "Edinburgh Royal Infirmary. Like Holmes".</p>
<p>I had a similar problem: <a href="http://nedbatchelder.com/blog/200804/separating%5Fsentences.html">Separating Sentences</a>.</p>
| 5 | 2009-08-27T20:25:25Z | [
"python",
"parsing",
"nlp",
"text-parsing"
] |
How to find Title case phrases from a passage or bunch of paragraphs | 1,343,479 | <p>How do I parse sentence case phrases from a passage.</p>
<p>For example from this passage</p>
<p>Conan Doyle said that the character of Holmes was inspired by Dr. Joseph Bell, for whom Doyle had worked as a clerk at the Edinburgh Royal Infirmary. Like Holmes, Bell was noted for drawing large conclusions from the smallest observations.[1] Michael Harrison argued in a 1971 article in Ellery Queen's Mystery Magazine that the character was inspired by Wendell Scherer, a "consulting detective" in a murder case that allegedly received a great deal of newspaper attention in England in 1882.</p>
<p>We need to generate stuff like Conan Doyle, Holmes, Dr Joseph Bell, Wendell Scherr etc.</p>
<p>I would prefer a Pythonic Solution if possible</p>
| 1 | 2009-08-27T20:04:07Z | 1,344,498 | <p>The "re" approach runs out of steam very quickly. Named entity recognition is a very complicated topic, way beyond the scope of an SO answer. If you think you have a good approach to this problem, please point it at Flann O'Brien a.k.a. Myles na cGopaleen, Sukarno, Harry S. Truman, J. Edgar Hoover, J. K. Rowling, the mathematician L'Hopital, Joe di Maggio, Algernon Douglas-Montagu-Scott, and Hugo Max Graf von und zu Lerchenfeld auf Köfering und Schönberg.</p>
<p><strong>Update</strong> Following is an "re"-based approach that finds a lot more valid cases. I still don't think that this is a good approach, though. N.B. I've asciified the Bavarian count's name in my text sample. If anyone really wants to use something like this, they should work in Unicode, and normalise whitespace at some stage (either on input or on output).</p>
<pre><code>import re
text1 = """Conan Doyle said that the character of Holmes was inspired by Dr. Joseph Bell, for whom Doyle had worked as a clerk at the Edinburgh Royal Infirmary. Like Holmes, Bell was noted for drawing large conclusions from the smallest observations.[1] Michael Harrison argued in a 1971 article in Ellery Queen's Mystery Magazine that the character was inspired by Wendell Scherer, a "consulting detective" in a murder case that allegedly received a great deal of newspaper attention in England in 1882."""
text2 = """Flann O'Brien a.k.a. Myles na cGopaleen, I Zingari, Sukarno and Suharto, Harry S. Truman, J. Edgar Hoover, J. K. Rowling, the mathematician L'Hopital, Joe di Maggio, Algernon Douglas-Montagu-Scott, and Hugo Max Graf von und zu Lerchenfeld auf Koefering und Schoenberg."""
pattern1 = r"(?:[A-Z][a-z]+[. ]+)+(?:[A-Z][a-z]+)?"
joiners = r"' - de la du von und zu auf van der na di il el bin binte abu etcetera".split()
pattern2 = r"""(?x)
(?:
(?:[ .]|\b%s\b)*
(?:\b[a-z]*[A-Z][a-z]*\b)?
)+
""" % r'\b|\b'.join(joiners)
def get_names(pattern, text):
for m in re.finditer(pattern, text):
s = m.group(0).strip(" .'-")
if s:
yield s
for t in (text1, text2):
print "*** text: ", t[:20], "..."
print "=== Ned B"
for s in re.finditer(pattern1):
print repr(s.group(0))
print "=== John M =="
for name in get_names(pattern2, t):
print repr(name)
</code></pre>
<p>Output:</p>
<pre><code>C:\junk\so>\python26\python extract_names.py
*** text: Conan Doyle said tha ...
=== Ned B
'Conan Doyle '
'Holmes '
'Dr. Joseph Bell'
'Doyle '
'Edinburgh Royal Infirmary. Like Holmes'
'Bell '
'Michael Harrison '
'Ellery Queen'
'Mystery Magazine '
'Wendell Scherer'
'England '
=== John M ==
'Conan Doyle'
'Holmes'
'Dr. Joseph Bell'
'Doyle'
'Edinburgh Royal Infirmary. Like Holmes'
'Bell'
'Michael Harrison'
'Ellery Queen'
'Mystery Magazine'
'Wendell Scherer'
'England'
*** text: Flann O'Brien a.k.a. ...
=== Ned B
'Flann '
'Brien '
'Myles '
'Sukarno '
'Harry '
'Edgar Hoover'
'Joe '
'Algernon Douglas'
'Hugo Max Graf '
'Lerchenfeld '
'Koefering '
'Schoenberg.'
=== John M ==
"Flann O'Brien"
'Myles na cGopaleen'
'I Zingari'
'Sukarno'
'Suharto'
'Harry S. Truman'
'J. Edgar Hoover'
'J. K. Rowling'
"L'Hopital"
'Joe di Maggio'
'Algernon Douglas-Montagu-Scott'
'Hugo Max Graf von und zu Lerchenfeld auf Koefering und Schoenberg'
</code></pre>
| 2 | 2009-08-28T00:53:20Z | [
"python",
"parsing",
"nlp",
"text-parsing"
] |
Nice exception handling when re-trying code | 1,343,541 | <p>I have some test cases. The test cases rely on data which takes time to compute. To speed up testing, I've cached the data so that it doesn't have to be recomputed.</p>
<p>I now have <code>foo()</code>, which looks at the cached data. I can't tell ahead of time what it will look at, as that depends a lot on the test case.</p>
<p>If a test case fails cause it doesn't find the right cached data, I don't want it to fail - I want it to compute the data and then try again. I also don't know what exception in particular it will throw cause of missing data. </p>
<p>My code right now looks like this:</p>
<pre><code>if cacheExists:
loadCache()
dataComputed = False
else:
calculateData()
dataComputed = True
try:
foo()
except:
if not dataComputed:
calculateData()
dataComputed = True
try:
foo()
except:
#error handling code
else:
#the same error handling code
</code></pre>
<p>What's the best way to re-structure this code?</p>
| 3 | 2009-08-27T20:19:49Z | 1,343,567 | <p>Is there a way to tell if you want to do foobetter() before making the call? If you get an exception it should be because something unexpected (exceptional!) happened. Don't use exceptions for flow control.</p>
| 0 | 2009-08-27T20:25:24Z | [
"python",
"exception",
"exception-handling",
"code-formatting"
] |
Nice exception handling when re-trying code | 1,343,541 | <p>I have some test cases. The test cases rely on data which takes time to compute. To speed up testing, I've cached the data so that it doesn't have to be recomputed.</p>
<p>I now have <code>foo()</code>, which looks at the cached data. I can't tell ahead of time what it will look at, as that depends a lot on the test case.</p>
<p>If a test case fails cause it doesn't find the right cached data, I don't want it to fail - I want it to compute the data and then try again. I also don't know what exception in particular it will throw cause of missing data. </p>
<p>My code right now looks like this:</p>
<pre><code>if cacheExists:
loadCache()
dataComputed = False
else:
calculateData()
dataComputed = True
try:
foo()
except:
if not dataComputed:
calculateData()
dataComputed = True
try:
foo()
except:
#error handling code
else:
#the same error handling code
</code></pre>
<p>What's the best way to re-structure this code?</p>
| 3 | 2009-08-27T20:19:49Z | 1,343,588 | <p>Using blanket exceptions isn't usually a great idea. What kind of Exception are you expecting there? Is it a KeyError, AttributeError, TypeError...</p>
<p>Once you've identified what type of error you're looking for you can use something like <code>hasattr()</code> or the <code>in</code> operator or many other things that will test for your condition before you have to deal with exceptions.</p>
<p>That way you can clean up your logic flow and save your exception handling for things that are really broken!</p>
| 1 | 2009-08-27T20:29:44Z | [
"python",
"exception",
"exception-handling",
"code-formatting"
] |
Nice exception handling when re-trying code | 1,343,541 | <p>I have some test cases. The test cases rely on data which takes time to compute. To speed up testing, I've cached the data so that it doesn't have to be recomputed.</p>
<p>I now have <code>foo()</code>, which looks at the cached data. I can't tell ahead of time what it will look at, as that depends a lot on the test case.</p>
<p>If a test case fails cause it doesn't find the right cached data, I don't want it to fail - I want it to compute the data and then try again. I also don't know what exception in particular it will throw cause of missing data. </p>
<p>My code right now looks like this:</p>
<pre><code>if cacheExists:
loadCache()
dataComputed = False
else:
calculateData()
dataComputed = True
try:
foo()
except:
if not dataComputed:
calculateData()
dataComputed = True
try:
foo()
except:
#error handling code
else:
#the same error handling code
</code></pre>
<p>What's the best way to re-structure this code?</p>
| 3 | 2009-08-27T20:19:49Z | 1,343,823 | <p>I disagree with the key suggestion in the existing answers, which basically boils down to treating exceptions in Python as you would in, say, C++ or Java -- that's NOT the preferred style in Python, where often the good old idea that "it's better to ask forgiveness than permission" (attempt an operation and deal with the exception, if any, rather than obscuring your code's main flow and incurring overhead by thorough preliminary checks). I do agree with Gabriel that a bare <code>except</code> is hardly ever a good idea (unless all it does is some form of logging followed by a <code>raise</code> to let the exception propagate). So, say you have a tuple with all the exception types that you do expect and want to handle the same way, say:</p>
<pre><code>expected_exceptions = KeyError, AttributeError, TypeError
</code></pre>
<p>and always use <code>except expected_exceptions:</code> rather than bare <code>except:</code>.</p>
<p>So, with that out of the way, one slightly less-repetitious approach to your needs is:</p>
<pre><code>try:
foo1()
except expected_exceptions:
try:
if condition:
foobetter()
else:
raise
except expected_exceptions:
handleError()
</code></pre>
<p>A different approach is to use an auxiliary function to wrap the try/except logic:</p>
<pre><code>def may_raise(expected_exceptions, somefunction, *a, **k):
try:
return False, somefunction(*a, **k)
except expected_exceptions:
return True, None
</code></pre>
<p>Such a helper may often come in useful in several different situations, so it's pretty common to have something like this somewhere in a project's "utilities" modules. Now, for your case (no arguments, no results) you could use:</p>
<pre><code>failed, _ = may_raise(expected_exceptions, foo1)
if failed and condition:
failed, _ = may_raise(expected_exceptions, foobetter)
if failed:
handleError()
</code></pre>
<p>which I would argue is more linear and therefore simpler. The only issue with this general approach is that an auxiliary function such as <code>may_raise</code> does not FORCE you to deal in some way or other with exceptions, so you <em>might</em> just forget to do so (just like the use of return codes, instead of exceptions, to indicate errors, is prone to those return values mistakenly being ignored); so, use it sparingly...!-)</p>
| 4 | 2009-08-27T21:26:26Z | [
"python",
"exception",
"exception-handling",
"code-formatting"
] |
Nice exception handling when re-trying code | 1,343,541 | <p>I have some test cases. The test cases rely on data which takes time to compute. To speed up testing, I've cached the data so that it doesn't have to be recomputed.</p>
<p>I now have <code>foo()</code>, which looks at the cached data. I can't tell ahead of time what it will look at, as that depends a lot on the test case.</p>
<p>If a test case fails cause it doesn't find the right cached data, I don't want it to fail - I want it to compute the data and then try again. I also don't know what exception in particular it will throw cause of missing data. </p>
<p>My code right now looks like this:</p>
<pre><code>if cacheExists:
loadCache()
dataComputed = False
else:
calculateData()
dataComputed = True
try:
foo()
except:
if not dataComputed:
calculateData()
dataComputed = True
try:
foo()
except:
#error handling code
else:
#the same error handling code
</code></pre>
<p>What's the best way to re-structure this code?</p>
| 3 | 2009-08-27T20:19:49Z | 1,344,513 | <p>Sometimes there's no nice way to express a flow, it's just complicated. But here's a way to call foo() in only one place, and have the error handling in only one place:</p>
<pre><code>if cacheExists:
loadCache()
dataComputed = False
else:
calculateData()
dataComputed = True
while True:
try:
foo()
break
except:
if not dataComputed:
calculateData()
dataComputed = True
continue
else:
#the error handling code
break
</code></pre>
<p>You may not like the loop, YMMV...</p>
<p>Or:</p>
<pre><code>if cacheExists:
loadCache()
dataComputed = False
else:
calculateData()
dataComputed = True
done = False
while !done:
try:
foo()
done = True
except:
if not dataComputed:
calculateData()
dataComputed = True
continue
else:
#the error handling code
done = True
</code></pre>
| 1 | 2009-08-28T01:00:47Z | [
"python",
"exception",
"exception-handling",
"code-formatting"
] |
Nice exception handling when re-trying code | 1,343,541 | <p>I have some test cases. The test cases rely on data which takes time to compute. To speed up testing, I've cached the data so that it doesn't have to be recomputed.</p>
<p>I now have <code>foo()</code>, which looks at the cached data. I can't tell ahead of time what it will look at, as that depends a lot on the test case.</p>
<p>If a test case fails cause it doesn't find the right cached data, I don't want it to fail - I want it to compute the data and then try again. I also don't know what exception in particular it will throw cause of missing data. </p>
<p>My code right now looks like this:</p>
<pre><code>if cacheExists:
loadCache()
dataComputed = False
else:
calculateData()
dataComputed = True
try:
foo()
except:
if not dataComputed:
calculateData()
dataComputed = True
try:
foo()
except:
#error handling code
else:
#the same error handling code
</code></pre>
<p>What's the best way to re-structure this code?</p>
| 3 | 2009-08-27T20:19:49Z | 1,346,770 | <p>I like the alternative approach proposed by Alex Martelli.</p>
<p>What do you think about using a list of functions as argument of the may_raise. The functions would be executed until one succeed!</p>
<p>Here is the code</p>
<pre>
def foo(x):
raise Exception("Arrrgh!")
return 0
def foobetter(x):
print "Hello", x
return 1
def try_many(functions, expected_exceptions, *a, **k):
ret = None
for f in functions:
try:
ret = f(*a, **k)
except expected_exceptions, e:
print e
else:
break
return ret
print try_many((foo, foobetter), Exception, "World")
</pre>
<p>result is </p>
<pre>
Arrrgh!
Hello World
1
</pre>
| 1 | 2009-08-28T12:40:01Z | [
"python",
"exception",
"exception-handling",
"code-formatting"
] |
Is there a FileIO in Python? | 1,343,666 | <p>I know there is a StringIO stream in Python, but is there such a thing as a file stream in Python? Also is there a better way for me to look up these things? Documentation, etc...</p>
<p>I am trying to pass a "stream" to a "writer" object I made. I was hoping that I could pass a file handle/stream to this writer object.</p>
| 1 | 2009-08-27T20:48:47Z | 1,343,676 | <p>There is a builtin file() which works much the same way. Here are the docs: <a href="http://docs.python.org/library/functions.html#file" rel="nofollow">http://docs.python.org/library/functions.html#file</a> and <a href="http://python.org/doc/2.5.2/lib/bltin-file-objects.html" rel="nofollow">http://python.org/doc/2.5.2/lib/bltin-file-objects.html</a>.</p>
<p>If you want to print all the lines of the file do:</p>
<pre><code>for line in file('yourfile.txt'):
print line
</code></pre>
<p>Of course there is more, like .seek(), .close(), .read(), .readlines(), ... basically the same protocol as for StringIO.</p>
<p>Edit: You should use open() instead of file(), which has the same API - file() goes in Python 3.</p>
| 5 | 2009-08-27T20:50:36Z | [
"python",
"file-io",
"stream"
] |
Is there a FileIO in Python? | 1,343,666 | <p>I know there is a StringIO stream in Python, but is there such a thing as a file stream in Python? Also is there a better way for me to look up these things? Documentation, etc...</p>
<p>I am trying to pass a "stream" to a "writer" object I made. I was hoping that I could pass a file handle/stream to this writer object.</p>
| 1 | 2009-08-27T20:48:47Z | 1,343,682 | <p>I am guessing you are looking for open(). <a href="http://docs.python.org/library/functions.html#open">http://docs.python.org/library/functions.html#open</a></p>
<pre><code>outfile = open("/path/to/file", "w")
[...]
outfile.write([...])
</code></pre>
<p>Documentation on all the things you can do with streams (these are called "file objects" or "file-like objects" in Python): <a href="http://docs.python.org/library/stdtypes.html#file-objects">http://docs.python.org/library/stdtypes.html#file-objects</a></p>
| 8 | 2009-08-27T20:52:36Z | [
"python",
"file-io",
"stream"
] |
Is there a FileIO in Python? | 1,343,666 | <p>I know there is a StringIO stream in Python, but is there such a thing as a file stream in Python? Also is there a better way for me to look up these things? Documentation, etc...</p>
<p>I am trying to pass a "stream" to a "writer" object I made. I was hoping that I could pass a file handle/stream to this writer object.</p>
| 1 | 2009-08-27T20:48:47Z | 1,346,880 | <p>In Python, all the I/O operations are wrapped in a hight level API : the file likes objects.</p>
<p>It means that any file likes object will behave the same, and can be used in a function expecting them. This is called duck typing, and for file like objects you can expect the following behavior :</p>
<ul>
<li>open / close / IO Exceptions</li>
<li>iteration</li>
<li>buffering</li>
<li>reading / writing / seeking</li>
</ul>
<p>StringIO, File, and all the file like objects can really be replaced with each others, and you don't have to care about managing the I/O yourself.</p>
<p>As a little demo, let's see what you can do with stdout, the standard output, which is a file like object :</p>
<pre><code>import sys
# replace the standar ouput by a real opened file
sys.stdout = open("out.txt", "w")
# printing won't print anything, it will write in the file
print "test"
</code></pre>
<p>All the file like objects behave the same, and you should use them the same way :</p>
<pre><code># try to open it
# do not bother with checking wheter stream is available or not
try :
stream = open("file.txt", "w")
except IOError :
# if it doesn't work, too bad !
# this error is the same for stringIO, file, etc
# use it and your code get hightly flexible !
pass
else :
stream.write("yeah !")
stream.close()
# in python 3, you'd do the same using context :
with open("file2.txt", "w") as stream :
stream.write("yeah !")
# the rest is taken care automatically
</code></pre>
<p>Note that a the file like objects methods share a common behavior, but the way to create a file like object is not standard :</p>
<pre><code>import urllib
# urllib doesn't use "open" and doesn't raises only IOError exceptions
stream = urllib.urlopen("www.google.com")
# but this is a file like object and you can rely on that :
for line in steam :
print line
</code></pre>
<p>Un last world, it's not because it works the same way that the underlying behavior is the same. It's important to understand what you are working with. In the last example, using the "for" loop on an Internet resource is very dangerous. Indeed, you know is you won't end up with a infinite stream of data.</p>
<p>In that case, using :</p>
<pre><code>print steam.read(10000) # another file like object method
</code></pre>
<p>is safer. Hight abstractions are powerful, but doesn't save you the need to know how the stuff works.</p>
| 1 | 2009-08-28T13:08:09Z | [
"python",
"file-io",
"stream"
] |
Basic tree in Python with a Django QuerySet | 1,343,845 | <p>Here's where I'm exposed as the fraud of a programmer I am. </p>
<p>I've never created a data tree.</p>
<p>Basically, I have a table with four fields: A, B, C, and D. I need to create a tree of unordered lists based on these fields. Ultimately, it would look something like this:</p>
<ul>
<li>A1
<ul>
<li>B1
<ul>
<li>C1
<ul>
<li>D1</li>
<li>D2</li>
</ul></li>
<li>C2
<ul>
<li>D3</li>
<li>D4</li>
</ul></li>
</ul></li>
<li>B2
<ul>
<li>C2
<ul>
<li>D5</li>
<li>D6</li>
</ul></li>
<li>C3
<ul>
<li>D7</li>
<li>D8</li>
</ul></li>
</ul></li>
</ul></li>
<li>A2
<ul>
<li>B2
<ul>
<li>C1
<ul>
<li>D9</li>
<li>D10</li>
</ul></li>
<li>C4
<ul>
<li>D11</li>
<li>D12</li>
</ul></li>
</ul></li>
<li>B3
<ul>
<li>C3
<ul>
<li>D13</li>
<li>D14</li>
</ul></li>
<li>C4
<ul>
<li>D15</li>
<li>D16</li>
</ul></li>
</ul></li>
</ul></li>
</ul>
<p>It's a pretty basic, 4-level tree...I think. It is much larger and complex than I'm representing here, but that's enough to get the point across.</p>
<p>I'm hoping to keep it to one database call, but I'm not sure if that's possible.</p>
<p>I'll be fetching the data with a Django QuerySet. I have Python at my disposal.</p>
<p>I don't even know where to start with the programming logic to keep it from becoming unwieldy.</p>
<p>I'd appreciate any pointers, guidance, links...just about anything!</p>
| 0 | 2009-08-27T21:30:27Z | 1,344,181 | <p>I am not sure of your question, is there something specific you are asking?</p>
<p>Here are a few reusable applications for storing hierarchical data:</p>
<ul>
<li><a href="http://code.google.com/p/django-mptt/" rel="nofollow">django-mptt</a></li>
<li><a href="http://code.google.com/p/django-treebeard/" rel="nofollow">django-treebeard</a></li>
</ul>
<p>What's your reasoning behind using the 4 separate fields?</p>
| 4 | 2009-08-27T22:52:16Z | [
"python",
"django",
"tree",
"iteration",
"django-queryset"
] |
Django hitting MySQL even after select_related()? | 1,344,016 | <p>I'm trying to optimize the database calls coming from a fairly small Django app. At current I have a couple of models, <code>Inquiry</code> and <code>InquiryStatus</code>. When selecting all of the records from MySQL, I get a nice <code>JOIN</code> statement on the two tables, followed by many requests to the InquiryStatus table. Why is Django still making individual requests if I've already done a <code>select_related()</code>?</p>
<p><strong>The models look like so:</strong></p>
<pre><code>class InquiryStatus(models.Model):
status = models.CharField(max_length=25)
status_short = models.CharField(max_length=5)
class Meta:
ordering = ["-default_status", "status", "status_short"]
class Inquiry(models.Model):
ts = models.DateTimeField(auto_now_add=True)
type = models.CharField(max_length=50)
status = models.ForeignKey(InquiryStatus)
class Meta:
ordering = ["-ts"]
</code></pre>
<p><strong>The view I threw together for debugging looks like so:</strong></p>
<pre><code>def inquiries_list(request, template_name="inquiries/list_inquiries.js"):
## Notice the "print" on the following line. Forces evaluation.
print models.Inquiry.objects.select_related('status').all()
return HttpResponse("CRAPSTICKS")
</code></pre>
<p>I've tried using <code>select_related(depth=1)</code>, with no change. Each of the extraneous requests to the database are selecting one specific <code>id</code> in the <code>WHERE</code> clause. </p>
<h2>Update:</h2>
<p>So there was one bit of very important code which should have been put in with the models:</p>
<pre><code>from fullhistory import register_model
register_model(Inquiry)
register_model(InquiryStatus)
</code></pre>
<p>As a result, <code>fullhistory</code> was (for reasons I cannot fathom) pulling each individual result and parsing it.</p>
| 1 | 2009-08-27T22:10:02Z | 1,344,421 | <p>I believe this has to do with lazy evaluation. Django only hits the DB if and when necessary, not when you invoke models.Inquiry.objects.select_related('status').all()</p>
<p><a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#id3" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/db/queries/#id3</a></p>
| 0 | 2009-08-28T00:20:01Z | [
"python",
"django",
"django-models",
"django-select-related"
] |
Django hitting MySQL even after select_related()? | 1,344,016 | <p>I'm trying to optimize the database calls coming from a fairly small Django app. At current I have a couple of models, <code>Inquiry</code> and <code>InquiryStatus</code>. When selecting all of the records from MySQL, I get a nice <code>JOIN</code> statement on the two tables, followed by many requests to the InquiryStatus table. Why is Django still making individual requests if I've already done a <code>select_related()</code>?</p>
<p><strong>The models look like so:</strong></p>
<pre><code>class InquiryStatus(models.Model):
status = models.CharField(max_length=25)
status_short = models.CharField(max_length=5)
class Meta:
ordering = ["-default_status", "status", "status_short"]
class Inquiry(models.Model):
ts = models.DateTimeField(auto_now_add=True)
type = models.CharField(max_length=50)
status = models.ForeignKey(InquiryStatus)
class Meta:
ordering = ["-ts"]
</code></pre>
<p><strong>The view I threw together for debugging looks like so:</strong></p>
<pre><code>def inquiries_list(request, template_name="inquiries/list_inquiries.js"):
## Notice the "print" on the following line. Forces evaluation.
print models.Inquiry.objects.select_related('status').all()
return HttpResponse("CRAPSTICKS")
</code></pre>
<p>I've tried using <code>select_related(depth=1)</code>, with no change. Each of the extraneous requests to the database are selecting one specific <code>id</code> in the <code>WHERE</code> clause. </p>
<h2>Update:</h2>
<p>So there was one bit of very important code which should have been put in with the models:</p>
<pre><code>from fullhistory import register_model
register_model(Inquiry)
register_model(InquiryStatus)
</code></pre>
<p>As a result, <code>fullhistory</code> was (for reasons I cannot fathom) pulling each individual result and parsing it.</p>
| 1 | 2009-08-27T22:10:02Z | 1,345,360 | <p>The code you've shown shouldn't actually generate any queries at all - QuerySets are only evaluated when necessary, not when they're defined, and you don't use the value anywhere so the execution won't be done.</p>
<p>Please show us a template or some other code that actually evaluates the qs - slices it, iterates, prints, or anything.</p>
| 0 | 2009-08-28T06:36:26Z | [
"python",
"django",
"django-models",
"django-select-related"
] |
Django hitting MySQL even after select_related()? | 1,344,016 | <p>I'm trying to optimize the database calls coming from a fairly small Django app. At current I have a couple of models, <code>Inquiry</code> and <code>InquiryStatus</code>. When selecting all of the records from MySQL, I get a nice <code>JOIN</code> statement on the two tables, followed by many requests to the InquiryStatus table. Why is Django still making individual requests if I've already done a <code>select_related()</code>?</p>
<p><strong>The models look like so:</strong></p>
<pre><code>class InquiryStatus(models.Model):
status = models.CharField(max_length=25)
status_short = models.CharField(max_length=5)
class Meta:
ordering = ["-default_status", "status", "status_short"]
class Inquiry(models.Model):
ts = models.DateTimeField(auto_now_add=True)
type = models.CharField(max_length=50)
status = models.ForeignKey(InquiryStatus)
class Meta:
ordering = ["-ts"]
</code></pre>
<p><strong>The view I threw together for debugging looks like so:</strong></p>
<pre><code>def inquiries_list(request, template_name="inquiries/list_inquiries.js"):
## Notice the "print" on the following line. Forces evaluation.
print models.Inquiry.objects.select_related('status').all()
return HttpResponse("CRAPSTICKS")
</code></pre>
<p>I've tried using <code>select_related(depth=1)</code>, with no change. Each of the extraneous requests to the database are selecting one specific <code>id</code> in the <code>WHERE</code> clause. </p>
<h2>Update:</h2>
<p>So there was one bit of very important code which should have been put in with the models:</p>
<pre><code>from fullhistory import register_model
register_model(Inquiry)
register_model(InquiryStatus)
</code></pre>
<p>As a result, <code>fullhistory</code> was (for reasons I cannot fathom) pulling each individual result and parsing it.</p>
| 1 | 2009-08-27T22:10:02Z | 1,347,456 | <p>It seems that <a href="http://code.google.com/p/fullhistory/" rel="nofollow">fullhistory</a> ends up serializing the object, which evaluates each field in the instance to give it a base to compare to.</p>
<p>Take a look at the <code>get_all_data</code> function:</p>
<p><a href="http://code.google.com/p/fullhistory/source/browse/trunk/fullhistory/fullhistory.py" rel="nofollow">http://code.google.com/p/fullhistory/source/browse/trunk/fullhistory/fullhistory.py</a></p>
<p>If anybody wants to write up a detailed reason why this happens, I'll gladly mark that answer correct.</p>
| 0 | 2009-08-28T14:43:58Z | [
"python",
"django",
"django-models",
"django-select-related"
] |
How to explicitly specify a path to Firefox for Selenium? | 1,344,026 | <p>I got Selenium IDE, followed <a href="http://jimmyg.org/blog/2009/getting-started-with-selenium-and-python.html">this post</a>, got to</p>
<pre><code>python test_default_server.py
</code></pre>
<p>and it complains Firefox is not in my path:</p>
<pre><code>Please add the directory containing ''firefox.exe'' to your PATH environment
variable, or explicitly specify a path to Firefox 3 like this:
*firefox3c:\blah\firefox.exe
</code></pre>
<p>I could change my PATH environment variable, but I'd rather pursue the local config option they are mentioning ("explicitly specify a path"). How do I do that? What does the "*firefox3c" refer to?</p>
<p>Selenium 1.0.1, Python 2.5, Windows XP.</p>
| 8 | 2009-08-27T22:12:11Z | 1,345,097 | <p>You have to use the following string when you instantiate selenium instead of just "*firefox":</p>
<pre><code>"*firefox C:\\Program Files\\Mozilla Firefox\\firefox.exe"
</code></pre>
<p>Notice: I'm not sure that path is correct, but it should be a similar one.</p>
<p>Update: Where do you instantiate your browser?
By the tags in the question I suppose you're a python guy:</p>
<pre><code>def setUp(self):
self.verificationErrors = []
self.selenium = selenium("localhost", 4444, "*firefox C:\\Program Files\\Mozilla Firefox\\firefox.exe", "http://change-this-to-the-site-you-are-testing/")
self.selenium.start()
</code></pre>
| 14 | 2009-08-28T05:00:00Z | [
"python",
"windows",
"firefox",
"testing",
"selenium"
] |
How to explicitly specify a path to Firefox for Selenium? | 1,344,026 | <p>I got Selenium IDE, followed <a href="http://jimmyg.org/blog/2009/getting-started-with-selenium-and-python.html">this post</a>, got to</p>
<pre><code>python test_default_server.py
</code></pre>
<p>and it complains Firefox is not in my path:</p>
<pre><code>Please add the directory containing ''firefox.exe'' to your PATH environment
variable, or explicitly specify a path to Firefox 3 like this:
*firefox3c:\blah\firefox.exe
</code></pre>
<p>I could change my PATH environment variable, but I'd rather pursue the local config option they are mentioning ("explicitly specify a path"). How do I do that? What does the "*firefox3c" refer to?</p>
<p>Selenium 1.0.1, Python 2.5, Windows XP.</p>
| 8 | 2009-08-27T22:12:11Z | 1,346,616 | <p>The *firefox etc are the keys for which browser to use to run the tests. </p>
<p>There is a long list of them at <a href="http://stackoverflow.com/questions/1317055/how-to-run-google-chrome-with-selenium-rc/1317131#1317131">http://stackoverflow.com/questions/1317055/how-to-run-google-chrome-with-selenium-rc/1317131#1317131</a> - so you can target Firefox v2 (<em>firefox2), Firefox v3 (</em>firefox3), Google Chrome (*googlechrome) etc</p>
| 0 | 2009-08-28T12:10:25Z | [
"python",
"windows",
"firefox",
"testing",
"selenium"
] |
How to explicitly specify a path to Firefox for Selenium? | 1,344,026 | <p>I got Selenium IDE, followed <a href="http://jimmyg.org/blog/2009/getting-started-with-selenium-and-python.html">this post</a>, got to</p>
<pre><code>python test_default_server.py
</code></pre>
<p>and it complains Firefox is not in my path:</p>
<pre><code>Please add the directory containing ''firefox.exe'' to your PATH environment
variable, or explicitly specify a path to Firefox 3 like this:
*firefox3c:\blah\firefox.exe
</code></pre>
<p>I could change my PATH environment variable, but I'd rather pursue the local config option they are mentioning ("explicitly specify a path"). How do I do that? What does the "*firefox3c" refer to?</p>
<p>Selenium 1.0.1, Python 2.5, Windows XP.</p>
| 8 | 2009-08-27T22:12:11Z | 4,083,009 | <p>If on C# editor, use the following string:</p>
<pre><code>selenium = new DefaultSelenium("localhost", 4444, "*firefox C:\\Program Files\\firefox.exe", "http://www.google.com/");
</code></pre>
<p>Note: use an extra back slash before Program Files and firefox.exe, since a single backslash becomes an unrecognized escape sequence.</p>
| 2 | 2010-11-02T23:28:51Z | [
"python",
"windows",
"firefox",
"testing",
"selenium"
] |
How to explicitly specify a path to Firefox for Selenium? | 1,344,026 | <p>I got Selenium IDE, followed <a href="http://jimmyg.org/blog/2009/getting-started-with-selenium-and-python.html">this post</a>, got to</p>
<pre><code>python test_default_server.py
</code></pre>
<p>and it complains Firefox is not in my path:</p>
<pre><code>Please add the directory containing ''firefox.exe'' to your PATH environment
variable, or explicitly specify a path to Firefox 3 like this:
*firefox3c:\blah\firefox.exe
</code></pre>
<p>I could change my PATH environment variable, but I'd rather pursue the local config option they are mentioning ("explicitly specify a path"). How do I do that? What does the "*firefox3c" refer to?</p>
<p>Selenium 1.0.1, Python 2.5, Windows XP.</p>
| 8 | 2009-08-27T22:12:11Z | 4,806,380 | <pre><code>selenium("localhost", 4444, "*firefox C:\Program Files\Mozilla Firefox\firefox.exe", "http://change-this-to-the-site-you-are-testing/")
</code></pre>
<p>Worked in Java.</p>
| 1 | 2011-01-26T15:32:24Z | [
"python",
"windows",
"firefox",
"testing",
"selenium"
] |
How to explicitly specify a path to Firefox for Selenium? | 1,344,026 | <p>I got Selenium IDE, followed <a href="http://jimmyg.org/blog/2009/getting-started-with-selenium-and-python.html">this post</a>, got to</p>
<pre><code>python test_default_server.py
</code></pre>
<p>and it complains Firefox is not in my path:</p>
<pre><code>Please add the directory containing ''firefox.exe'' to your PATH environment
variable, or explicitly specify a path to Firefox 3 like this:
*firefox3c:\blah\firefox.exe
</code></pre>
<p>I could change my PATH environment variable, but I'd rather pursue the local config option they are mentioning ("explicitly specify a path"). How do I do that? What does the "*firefox3c" refer to?</p>
<p>Selenium 1.0.1, Python 2.5, Windows XP.</p>
| 8 | 2009-08-27T22:12:11Z | 5,539,835 | <p>This helps very much. </p>
<pre><code>setUp("http://localhost:8080/BingDemo/BingDriver.html", "*firefox C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
</code></pre>
| 0 | 2011-04-04T14:21:11Z | [
"python",
"windows",
"firefox",
"testing",
"selenium"
] |
How to explicitly specify a path to Firefox for Selenium? | 1,344,026 | <p>I got Selenium IDE, followed <a href="http://jimmyg.org/blog/2009/getting-started-with-selenium-and-python.html">this post</a>, got to</p>
<pre><code>python test_default_server.py
</code></pre>
<p>and it complains Firefox is not in my path:</p>
<pre><code>Please add the directory containing ''firefox.exe'' to your PATH environment
variable, or explicitly specify a path to Firefox 3 like this:
*firefox3c:\blah\firefox.exe
</code></pre>
<p>I could change my PATH environment variable, but I'd rather pursue the local config option they are mentioning ("explicitly specify a path"). How do I do that? What does the "*firefox3c" refer to?</p>
<p>Selenium 1.0.1, Python 2.5, Windows XP.</p>
| 8 | 2009-08-27T22:12:11Z | 5,539,946 | <p>This helps very much. <code>setUp("http://localhost:8080/BingDemo/BingDriver.html", "*firefox C:\Program Files (x86)\Mozilla Firefox\firefox.exe");</code></p>
<p>However, replace all occurrences of <code>\</code> with <code>\\</code> in *firefox <code>C:\Program Files (x86)\Mozilla Firefox\firefox.exe</code></p>
<p>Additionally, you could point your PATH to in environmental variables to <code>mozilla.exe</code></p>
| 1 | 2011-04-04T14:27:02Z | [
"python",
"windows",
"firefox",
"testing",
"selenium"
] |
How to explicitly specify a path to Firefox for Selenium? | 1,344,026 | <p>I got Selenium IDE, followed <a href="http://jimmyg.org/blog/2009/getting-started-with-selenium-and-python.html">this post</a>, got to</p>
<pre><code>python test_default_server.py
</code></pre>
<p>and it complains Firefox is not in my path:</p>
<pre><code>Please add the directory containing ''firefox.exe'' to your PATH environment
variable, or explicitly specify a path to Firefox 3 like this:
*firefox3c:\blah\firefox.exe
</code></pre>
<p>I could change my PATH environment variable, but I'd rather pursue the local config option they are mentioning ("explicitly specify a path"). How do I do that? What does the "*firefox3c" refer to?</p>
<p>Selenium 1.0.1, Python 2.5, Windows XP.</p>
| 8 | 2009-08-27T22:12:11Z | 28,178,020 | <p>I found it worth useful...</p>
<pre><code>Selenium selenium = new DefaultSelenium("localhost", 4444, "*firefox C:\Program Files (x86)\Mozilla Firefox\firefox.exe", "http://gmail.com");
</code></pre>
| 0 | 2015-01-27T19:03:03Z | [
"python",
"windows",
"firefox",
"testing",
"selenium"
] |
How to explicitly specify a path to Firefox for Selenium? | 1,344,026 | <p>I got Selenium IDE, followed <a href="http://jimmyg.org/blog/2009/getting-started-with-selenium-and-python.html">this post</a>, got to</p>
<pre><code>python test_default_server.py
</code></pre>
<p>and it complains Firefox is not in my path:</p>
<pre><code>Please add the directory containing ''firefox.exe'' to your PATH environment
variable, or explicitly specify a path to Firefox 3 like this:
*firefox3c:\blah\firefox.exe
</code></pre>
<p>I could change my PATH environment variable, but I'd rather pursue the local config option they are mentioning ("explicitly specify a path"). How do I do that? What does the "*firefox3c" refer to?</p>
<p>Selenium 1.0.1, Python 2.5, Windows XP.</p>
| 8 | 2009-08-27T22:12:11Z | 28,340,046 | <p>For Java Solution using Selenium Webdriver, you can import the below class:</p>
<pre><code>import org.openqa.selenium.firefox.FirefoxBinary;
</code></pre>
<p>and use the code snippet below to instantiate a new driver by explicitly specifying the path to the firefox.exe in your local system.</p>
<pre><code>DesiredCapabilities browserCapabilities = DesiredCapabilities.firefox();
FirefoxBinary ffbinary = new FirefoxBinary(new File("C:\Program Files (x86)\Mozilla Firefox\firefox.exe"));
FirefoxProfile ffprofile = new FirefoxProfile();
WebDriver driver = new FirefoxDriver(ffbinary, ffprofile, browserCapabilities);
</code></pre>
<p>Note: You may need to replace "<em>C:\Program Files (x86)\Mozilla Firefox\firefox.exe</em>" with the path that points to firefox.exe on your local machine.</p>
| 0 | 2015-02-05T09:12:12Z | [
"python",
"windows",
"firefox",
"testing",
"selenium"
] |
Condensing code in Python with Mappings | 1,344,208 | <p>I seem to be using this block of code alot in Python.</p>
<pre><code>if Y is not None:
obj[X][0]=Y
</code></pre>
<p>How do I establish a mapping from X=>Y and then iterate through this entire mapping while calling that block of code on X and Y</p>
| 1 | 2009-08-27T23:02:44Z | 1,344,228 | <p>If Y is None, you can do something like:</p>
<pre><code>default_value = 0
obj[X][0] = Y if not None else default_value
</code></pre>
| 0 | 2009-08-27T23:09:31Z | [
"python"
] |
Condensing code in Python with Mappings | 1,344,208 | <p>I seem to be using this block of code alot in Python.</p>
<pre><code>if Y is not None:
obj[X][0]=Y
</code></pre>
<p>How do I establish a mapping from X=>Y and then iterate through this entire mapping while calling that block of code on X and Y</p>
| 1 | 2009-08-27T23:02:44Z | 1,344,229 | <pre><code>mapping = {X1: Y1, X2: Y2, X3: Y3}
mapping[X4] = Y4
mapping[X5] = Y5
for X,Y in mapping.items():
if Y is not None:
obj[X][0] = Y
</code></pre>
| 5 | 2009-08-27T23:10:00Z | [
"python"
] |
In Python, find item in list of dicts, using bisect | 1,344,308 | <p>I have a list of dicts, something like this:</p>
<pre><code>test_data = [
{ 'offset':0, 'data':1500 },
{ 'offset':1270, 'data':120 },
{ 'offset':2117, 'data':30 },
{ 'offset':4055, 'data':30000 },
]
</code></pre>
<p>The dict items are sorted in the list according to the <code>'offset'</code> data. The real data could be much longer.</p>
<p>What I want to do is lookup an item in the list given a particular offset value, which is <strong>not</strong> exactly one of those values, but in that range. So, a binary search is what I want to do.</p>
<p>I am now aware of the Python <a href="http://docs.python.org/library/bisect.html"><code>bisect</code></a> module, which is a ready-made binary searchâgreat, but not directly usable for this case. I'm just wondering what is the easiest way to adapt <a href="http://docs.python.org/library/bisect.html"><code>bisect</code></a> to my needs. Here is what I came up with:</p>
<pre><code>import bisect
class dict_list_index_get_member(object):
def __init__(self, dict_list, member):
self.dict_list = dict_list
self.member = member
def __getitem__(self, index):
return self.dict_list[index][self.member]
def __len__(self):
return self.dict_list.__len__()
test_data_index_get_offset = dict_list_index_get_member(test_data, 'offset')
print bisect.bisect(test_data_index_get_offset, 1900)
</code></pre>
<p>It prints:</p>
<pre><code>2
</code></pre>
<p>My question is, is this the best way to do what I want, or is there some other simpler, better way?</p>
| 7 | 2009-08-27T23:43:19Z | 1,344,347 | <p>The usual pattern here is similar to sorting by an attribute, decorate, operate, and undecorate. So in this case you'd just need to decorate and then call. However you'd want to avoid doing this since decorate would be O(n) whereas you want this to be O(logn). Therefore I'd consider your method best.</p>
| 3 | 2009-08-27T23:56:26Z | [
"python",
"dictionary",
"binary-search"
] |
In Python, find item in list of dicts, using bisect | 1,344,308 | <p>I have a list of dicts, something like this:</p>
<pre><code>test_data = [
{ 'offset':0, 'data':1500 },
{ 'offset':1270, 'data':120 },
{ 'offset':2117, 'data':30 },
{ 'offset':4055, 'data':30000 },
]
</code></pre>
<p>The dict items are sorted in the list according to the <code>'offset'</code> data. The real data could be much longer.</p>
<p>What I want to do is lookup an item in the list given a particular offset value, which is <strong>not</strong> exactly one of those values, but in that range. So, a binary search is what I want to do.</p>
<p>I am now aware of the Python <a href="http://docs.python.org/library/bisect.html"><code>bisect</code></a> module, which is a ready-made binary searchâgreat, but not directly usable for this case. I'm just wondering what is the easiest way to adapt <a href="http://docs.python.org/library/bisect.html"><code>bisect</code></a> to my needs. Here is what I came up with:</p>
<pre><code>import bisect
class dict_list_index_get_member(object):
def __init__(self, dict_list, member):
self.dict_list = dict_list
self.member = member
def __getitem__(self, index):
return self.dict_list[index][self.member]
def __len__(self):
return self.dict_list.__len__()
test_data_index_get_offset = dict_list_index_get_member(test_data, 'offset')
print bisect.bisect(test_data_index_get_offset, 1900)
</code></pre>
<p>It prints:</p>
<pre><code>2
</code></pre>
<p>My question is, is this the best way to do what I want, or is there some other simpler, better way?</p>
| 7 | 2009-08-27T23:43:19Z | 1,344,355 | <p>When you say the real data could be much longer, does that prevent you from keeping a list of offset values on hand?</p>
<pre><code>offset_values = [i['offset'] for i in test_data]
bisect.bisect(offset_values, 1900)
</code></pre>
<p>Your method seems fine to me though.</p>
| 4 | 2009-08-27T23:58:14Z | [
"python",
"dictionary",
"binary-search"
] |
In Python, find item in list of dicts, using bisect | 1,344,308 | <p>I have a list of dicts, something like this:</p>
<pre><code>test_data = [
{ 'offset':0, 'data':1500 },
{ 'offset':1270, 'data':120 },
{ 'offset':2117, 'data':30 },
{ 'offset':4055, 'data':30000 },
]
</code></pre>
<p>The dict items are sorted in the list according to the <code>'offset'</code> data. The real data could be much longer.</p>
<p>What I want to do is lookup an item in the list given a particular offset value, which is <strong>not</strong> exactly one of those values, but in that range. So, a binary search is what I want to do.</p>
<p>I am now aware of the Python <a href="http://docs.python.org/library/bisect.html"><code>bisect</code></a> module, which is a ready-made binary searchâgreat, but not directly usable for this case. I'm just wondering what is the easiest way to adapt <a href="http://docs.python.org/library/bisect.html"><code>bisect</code></a> to my needs. Here is what I came up with:</p>
<pre><code>import bisect
class dict_list_index_get_member(object):
def __init__(self, dict_list, member):
self.dict_list = dict_list
self.member = member
def __getitem__(self, index):
return self.dict_list[index][self.member]
def __len__(self):
return self.dict_list.__len__()
test_data_index_get_offset = dict_list_index_get_member(test_data, 'offset')
print bisect.bisect(test_data_index_get_offset, 1900)
</code></pre>
<p>It prints:</p>
<pre><code>2
</code></pre>
<p>My question is, is this the best way to do what I want, or is there some other simpler, better way?</p>
| 7 | 2009-08-27T23:43:19Z | 1,344,501 | <p>What you can do is this</p>
<pre><code>class OffsetWithAttributes( object ):
def __init__( self, offset, **kw ):
self.offset= offset
self.attributes= kw
def __eq__( self, other ):
return self.offset == other.offset
def __lt__( self, other ):
return self.offset < other.offset
def __le__( self, other ):
return self.offset <= other.offset
def __gt__( self, other ):
return self.offset > other.offset
def __ge__( self, other ):
return self.offset >= other.offset
def __ne__( self, other ):
return self.offset != other.offset
</code></pre>
<p>This should allow you to create a simple <code>list</code> of <code>OffsetWithAttributes</code> instances. The <code>bisect</code> algorithm should be perfectly happy to use the defined operators.</p>
<p>You can use your <code>someOWA.attributes['data']</code>.</p>
<p>Or</p>
<pre><code> def __getattr__( self, key ):
return self.attributes[key]
</code></pre>
<p>That should make the <code>OffsetWithAttributes</code> more like a <code>dict</code>.</p>
| 3 | 2009-08-28T00:55:35Z | [
"python",
"dictionary",
"binary-search"
] |
In Python, find item in list of dicts, using bisect | 1,344,308 | <p>I have a list of dicts, something like this:</p>
<pre><code>test_data = [
{ 'offset':0, 'data':1500 },
{ 'offset':1270, 'data':120 },
{ 'offset':2117, 'data':30 },
{ 'offset':4055, 'data':30000 },
]
</code></pre>
<p>The dict items are sorted in the list according to the <code>'offset'</code> data. The real data could be much longer.</p>
<p>What I want to do is lookup an item in the list given a particular offset value, which is <strong>not</strong> exactly one of those values, but in that range. So, a binary search is what I want to do.</p>
<p>I am now aware of the Python <a href="http://docs.python.org/library/bisect.html"><code>bisect</code></a> module, which is a ready-made binary searchâgreat, but not directly usable for this case. I'm just wondering what is the easiest way to adapt <a href="http://docs.python.org/library/bisect.html"><code>bisect</code></a> to my needs. Here is what I came up with:</p>
<pre><code>import bisect
class dict_list_index_get_member(object):
def __init__(self, dict_list, member):
self.dict_list = dict_list
self.member = member
def __getitem__(self, index):
return self.dict_list[index][self.member]
def __len__(self):
return self.dict_list.__len__()
test_data_index_get_offset = dict_list_index_get_member(test_data, 'offset')
print bisect.bisect(test_data_index_get_offset, 1900)
</code></pre>
<p>It prints:</p>
<pre><code>2
</code></pre>
<p>My question is, is this the best way to do what I want, or is there some other simpler, better way?</p>
| 7 | 2009-08-27T23:43:19Z | 22,946,210 | <p>You could also use one of Python's many SortedDict implementations to manage your test_data. A sorted dict sorts the elements by key and maintains a mapping to a value. Some implementations also support a bisect operation on the keys. For example, the <a href="http://www.grantjenks.com/docs/sortedcontainers/">Python sortedcontainers module</a> has a <a href="http://www.grantjenks.com/docs/sortedcontainers/sorteddict.html">SortedDict</a> that meets your requirements.</p>
<p>In your case it would look something like:</p>
<pre><code>from sortedcontainers import SortedDict
offset_map = SortedDict((item['offset'], item['data']) for item in test_data)
index = offset_map.bisect(1275)
key = offset_map.iloc[index]
print offset_map[key]
# 120
</code></pre>
<p>The SortedDict type has a bisect function which returns the bisected index of the desired key. With that index, you can lookup the actual key. And with that key you can get the value.</p>
<p>All of these operations are very fast in sortedcontainers which is also conveniently implemented in pure-Python. There's a <a href="http://www.grantjenks.com/docs/sortedcontainers/performance.html">performance comparison</a> too which discusses other choices and has benchmark data.</p>
| 5 | 2014-04-08T19:14:32Z | [
"python",
"dictionary",
"binary-search"
] |
Django vs. Pylons | 1,344,824 | <p>I've recently become a little frustrated with Django as a whole. It seems like I can't get full control over anything. I love Python to death, but I want to be able (and free) to do something as simple as adding a css class to an auto-generated form. </p>
<p>One MVC framework that I have really been enjoying working with is Grails (groovy). It has a FANTASTIC templating system and it lets you really have full control as you'd like. </p>
<p>However, I am beyond obsessed with Python. So I'd like to find something decent and powerful written in it for my web application development. </p>
<p>Any suggestions?</p>
<p>Pylons maybe?</p>
| 16 | 2009-08-28T03:03:37Z | 1,344,842 | <p>I'm using Pylons right now. The flexibility is great. It's all about best-of-breed rather than The Django Way. It's more oriented toward custom application development, as opposed to content-based web sites. You can certainly do content sites in it; it's just not specifically designed for them.</p>
<p>On the other hand, you do end up needing to read a lot of different documentation, in different places, of different quality, to grok all the components. Whereas one of the nice things about Django is that for all the core components, you just read "the" documentation.</p>
<p>The Mako (templates) + SQLAlchemy (DB & ORM) combo is really nice, though. Back when I used Django, I replaced its templating and DB system with them (giving up some of its integration features in the process) and they are standard with Pylons. Mako lets you use Python expressions, which is nice because even though you should separate business logic from design, dynamic sites do require significant display logic, and Django's template tags are clumsy to work with. SQLAlchemy lets you work with the same data model anywhere from the raw SQL level to the object-oriented ORM level.</p>
<p>I think it's worth the time to at least go through the <a href="http://pylonshq.com/docs/en/0.9.7/">docs</a> and do the QuickWiki tutorial.</p>
| 19 | 2009-08-28T03:11:29Z | [
"python",
"django",
"grails",
"pylons"
] |
Django vs. Pylons | 1,344,824 | <p>I've recently become a little frustrated with Django as a whole. It seems like I can't get full control over anything. I love Python to death, but I want to be able (and free) to do something as simple as adding a css class to an auto-generated form. </p>
<p>One MVC framework that I have really been enjoying working with is Grails (groovy). It has a FANTASTIC templating system and it lets you really have full control as you'd like. </p>
<p>However, I am beyond obsessed with Python. So I'd like to find something decent and powerful written in it for my web application development. </p>
<p>Any suggestions?</p>
<p>Pylons maybe?</p>
| 16 | 2009-08-28T03:03:37Z | 1,344,869 | <p>Pylons is not that much simpler than Django and it doesn't seem to have the same community. For lightweight apps I would recommend <a href="http://webpy.org/">web.py</a>. Even though there is a little magic, it doesn't feel like it. You see everything you do. For lots of other ideas see this very current list of <a href="http://vermeulen.ca/python-web-platforms.html">web resources on python</a>.</p>
| 5 | 2009-08-28T03:21:56Z | [
"python",
"django",
"grails",
"pylons"
] |
Django vs. Pylons | 1,344,824 | <p>I've recently become a little frustrated with Django as a whole. It seems like I can't get full control over anything. I love Python to death, but I want to be able (and free) to do something as simple as adding a css class to an auto-generated form. </p>
<p>One MVC framework that I have really been enjoying working with is Grails (groovy). It has a FANTASTIC templating system and it lets you really have full control as you'd like. </p>
<p>However, I am beyond obsessed with Python. So I'd like to find something decent and powerful written in it for my web application development. </p>
<p>Any suggestions?</p>
<p>Pylons maybe?</p>
| 16 | 2009-08-28T03:03:37Z | 1,344,897 | <p>Something as simple as adding CSS classes to Django form fields <b>IS</b> <a href="http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs" rel="nofollow">possible</a>.</p>
| 1 | 2009-08-28T03:33:16Z | [
"python",
"django",
"grails",
"pylons"
] |
Django vs. Pylons | 1,344,824 | <p>I've recently become a little frustrated with Django as a whole. It seems like I can't get full control over anything. I love Python to death, but I want to be able (and free) to do something as simple as adding a css class to an auto-generated form. </p>
<p>One MVC framework that I have really been enjoying working with is Grails (groovy). It has a FANTASTIC templating system and it lets you really have full control as you'd like. </p>
<p>However, I am beyond obsessed with Python. So I'd like to find something decent and powerful written in it for my web application development. </p>
<p>Any suggestions?</p>
<p>Pylons maybe?</p>
| 16 | 2009-08-28T03:03:37Z | 2,607,291 | <p>With the risk of going a bit off-topic here, "I want to be able (and free) to do something as simple as adding a css class to an auto-generated form" might not be the best indicator of the power (or lack of power) of a framework. Form generation is notoriously hard to do in a flexible way (cf. <a href="http://blog.ianbicking.org/on-form-libraries.html" rel="nofollow">http://blog.ianbicking.org/on-form-libraries.html</a>), and frameworks will always need to weigh ease-of-use versus supporting advanced use-cases. I've used form generation in Pylons before, and didn't find it to be particularly better or easier than how things work in Django (but not harder either).</p>
| 1 | 2010-04-09T12:20:35Z | [
"python",
"django",
"grails",
"pylons"
] |
Programming a Self Learning Music Maker | 1,344,884 | <p>I want to learn how to program a music application that will analyze songs.</p>
<p>How would I get started in this and is there a library for analyzing soundwaves?</p>
<p>I know C, C++, Java, Python, some assembly, and some Perl.</p>
<p><strong>Related question:</strong> <a href="http://stackoverflow.com/questions/1178479/algorithm-for-music-imitation">Algorithm for music imitation</a></p>
| 6 | 2009-08-28T03:28:03Z | 1,344,890 | <p>You may like to start by looking at the MIDI format, it's reasonable simple compared to the compressed formats, and you can generate some nice things in it.</p>
<p>Depends what you want to do really.</p>
| 0 | 2009-08-28T03:30:04Z | [
"python",
"perl",
"music",
"waveform"
] |
Programming a Self Learning Music Maker | 1,344,884 | <p>I want to learn how to program a music application that will analyze songs.</p>
<p>How would I get started in this and is there a library for analyzing soundwaves?</p>
<p>I know C, C++, Java, Python, some assembly, and some Perl.</p>
<p><strong>Related question:</strong> <a href="http://stackoverflow.com/questions/1178479/algorithm-for-music-imitation">Algorithm for music imitation</a></p>
| 6 | 2009-08-28T03:28:03Z | 1,345,133 | <p>To analyze soundwaves you need some sort of fourier transformation (fft), so you can split the song up into it's frequencies and how they change over time. There exists fft support in numpy, I haven't used it, so I don't know if it's any good. But it would be a great place to start.</p>
<p>After that you then need to make some sort of statistical analysis on frequencies and patterns, and then I no longer have any clue what I'm talking about.</p>
<p>Cool stuff though, go for it!</p>
| 3 | 2009-08-28T05:12:37Z | [
"python",
"perl",
"music",
"waveform"
] |
Programming a Self Learning Music Maker | 1,344,884 | <p>I want to learn how to program a music application that will analyze songs.</p>
<p>How would I get started in this and is there a library for analyzing soundwaves?</p>
<p>I know C, C++, Java, Python, some assembly, and some Perl.</p>
<p><strong>Related question:</strong> <a href="http://stackoverflow.com/questions/1178479/algorithm-for-music-imitation">Algorithm for music imitation</a></p>
| 6 | 2009-08-28T03:28:03Z | 1,345,313 | <p>Once you get past the FFT stuff that Lennart mentioned, you might want to have a look at Markov chains for analyzing intervals between notes, and aggregated patterns. </p>
<p>This is kind of treaded ground, but Markov chains have been used in the past to build a kind of statistical model of melodies from various songs which can be used to generate new melodies. Markov chains can do the same with written english sentences. For an example of how that looks, have a play with the megahal chatterbot to see how markov chains can produce mangled output that statistically looks like its input (in megahal's case, it looks like english sentences)</p>
<p>You could concievably mash up the top 100, and have a markov chain generator blast out the next big hit.</p>
<p>On the other hand, you may want to consider the possibility that it is not any quality of the music itself that makes a song popular. Or perhaps it is a quality of music issue combined with marketing.</p>
| 6 | 2009-08-28T06:22:35Z | [
"python",
"perl",
"music",
"waveform"
] |
Programming a Self Learning Music Maker | 1,344,884 | <p>I want to learn how to program a music application that will analyze songs.</p>
<p>How would I get started in this and is there a library for analyzing soundwaves?</p>
<p>I know C, C++, Java, Python, some assembly, and some Perl.</p>
<p><strong>Related question:</strong> <a href="http://stackoverflow.com/questions/1178479/algorithm-for-music-imitation">Algorithm for music imitation</a></p>
| 6 | 2009-08-28T03:28:03Z | 1,346,272 | <p>Composition and analysis of music by computer is a huge field. There are two basic areas in this type of work, which overlap somewhat. </p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Algorithmic%5Fcomposition"><strong>Algorithmic composition</strong></a> is concerned with the <em>generation</em> of music. This can be based on statistical approaches such as <a href="http://www.complexity.org.au/ci/vol03/mccorm/mccorm.html">Markov chaining</a>, mathematical models employing <a href="http://www.unc.edu/~jimlee/JohnObrienFractalMusic.htm">fractal</a> or <a href="http://www-ccrma.stanford.edu/~blackrse/chaos.html">chaotic</a> processes, or leveraging techniques from AI such as <a href="https://www.areditions.com/cmdas/DAS13/cmdas013.html">expert systems</a>, <a href="http://www.cs.colorado.edu/~mozer/papers/music.html">neural networks</a> and <a href="http://www.springerlink.com/content/caxnx9gn5ghb7rtd/">genetic algorithms</a>. </li>
<li><a href="http://en.wikipedia.org/wiki/Music%5Finformation%5Fretrieval"><strong>Music information retrieval</strong></a> is concerned with identifying common grammars, commonalities and similarity metrics between pieces of music, and identifying uniqueness (sometimes called <a href="http://en.wikipedia.org/wiki/Acoustic%5Ffingerprinting">acoustic fingerprinting</a>).</li>
</ul>
<p>Many, many <a href="http://www.music-ir.org/evaluation/tools.html">libraries, tools</a> and specialised <a href="http://www.nosuch.com/plum/cgi/showlist.cgi?sort=name&concise=yes">programming languages</a> exist which can help with different parts of these problems. Here's a list of music-related <a href="http://wiki.python.org/moin/PythonInMusic">programs and libraries for Python</a>. There is a lot of technology available; you should be able to find something that will do the brunt of the work for you. Reimplementing a 'musical parser' through very low-level frequency analysis tools such as <a href="http://en.wikipedia.org/wiki/Fourier%5Ftransform">Fourier Transforms</a>, as other answers have suggested, while possible, will be quite difficult and is almost certainly unnecessary.</p>
<p>For further advice and specific questions, the <a href="http://www.ismir.net/">International Society for Music Information Retrieval</a> has a mailing list which you would probably find very helpful.</p>
| 9 | 2009-08-28T10:50:37Z | [
"python",
"perl",
"music",
"waveform"
] |
Programming a Self Learning Music Maker | 1,344,884 | <p>I want to learn how to program a music application that will analyze songs.</p>
<p>How would I get started in this and is there a library for analyzing soundwaves?</p>
<p>I know C, C++, Java, Python, some assembly, and some Perl.</p>
<p><strong>Related question:</strong> <a href="http://stackoverflow.com/questions/1178479/algorithm-for-music-imitation">Algorithm for music imitation</a></p>
| 6 | 2009-08-28T03:28:03Z | 1,349,807 | <p>There's the <a href="http://code.google.com/p/echo-nest-remix/" rel="nofollow">Echo Nest remix API</a> that lets you analyze and manipulate music in Python. Some examples here: <a href="http://musicmachinery.com/2009/06/21/wheres-the-pow/" rel="nofollow">Where's the pow</a> and here: <a href="http://musicmachinery.com/2009/07/05/you-make-me-quantized-miss-lizzy/" rel="nofollow">You make me quantized miss lizzie</a>. There's a nifty tutorial here: <a href="http://lindsay.at/work/remix/overview.html" rel="nofollow">An overview of the Echo Nest API</a></p>
| 0 | 2009-08-28T23:03:28Z | [
"python",
"perl",
"music",
"waveform"
] |
Replacing leading and trailing hyphens with spaces? | 1,345,025 | <p>What is the best way to replace each occurrence of a leading or trailing hyphen with a space?</p>
<p>For example, I want</p>
<p>---ab---c-def--</p>
<p>to become</p>
<p>000ab---c-def00
(where the zeros are spaces)</p>
<p>I'm trying to do this in Python, but I can't seem to come up with a regex that will do the substitution. I'm wondering if there is another, better way to do this?</p>
| 2 | 2009-08-28T04:31:41Z | 1,345,050 | <pre><code>re.sub(r'^-+|-+$', lambda m: ' '*len(m.group()), '---ab---c-def--')
</code></pre>
<p>Explanation: the pattern matches 1 or more leading or trailing dashes; the substitution is best performed by a callable, which receives each match object -- so m.group() is the matched substring -- and returns the string that must replace it (as many spaces as there were characters in said substring, in this case).</p>
| 5 | 2009-08-28T04:40:08Z | [
"python",
"regex"
] |
Replacing leading and trailing hyphens with spaces? | 1,345,025 | <p>What is the best way to replace each occurrence of a leading or trailing hyphen with a space?</p>
<p>For example, I want</p>
<p>---ab---c-def--</p>
<p>to become</p>
<p>000ab---c-def00
(where the zeros are spaces)</p>
<p>I'm trying to do this in Python, but I can't seem to come up with a regex that will do the substitution. I'm wondering if there is another, better way to do this?</p>
| 2 | 2009-08-28T04:31:41Z | 1,345,051 | <p>Use a callable as the substitution target:</p>
<pre><code>s = re.sub("^(-+)", lambda m: " " * (m.end() - m.start()), s)
s = re.sub("(-+)$", lambda m: " " * (m.end() - m.start()), s)
</code></pre>
| 3 | 2009-08-28T04:40:39Z | [
"python",
"regex"
] |
Replacing leading and trailing hyphens with spaces? | 1,345,025 | <p>What is the best way to replace each occurrence of a leading or trailing hyphen with a space?</p>
<p>For example, I want</p>
<p>---ab---c-def--</p>
<p>to become</p>
<p>000ab---c-def00
(where the zeros are spaces)</p>
<p>I'm trying to do this in Python, but I can't seem to come up with a regex that will do the substitution. I'm wondering if there is another, better way to do this?</p>
| 2 | 2009-08-28T04:31:41Z | 1,345,083 | <p>Whenever you want to match at the end of a string, always consider carefully whether you need <code>$</code> or <code>\Z</code>. Examples, using '0' instead of ' ' for clarity:</p>
<pre><code>>>> re.sub(r"^-+|-+\Z", lambda m: '0'*len(m.group()), "--ab--c-def--")
'00ab--c-def00'
>>> re.sub(r"^-+|-+\Z", lambda m: '0'*len(m.group()), "--ab--c-def--\n")
'00ab--c-def--\n'
>>> re.sub(r"^-+|-+$", lambda m: '0'*len(m.group()), "--ab--c-def--\n")
'00ab--c-def00\n'
>>>
</code></pre>
| 0 | 2009-08-28T04:54:44Z | [
"python",
"regex"
] |
Simple recursive descent in PyParsing | 1,345,039 | <p>I've tried taking <a href="http://stackoverflow.com/questions/634432/need-help-on-making-the-recursive-parser-using-pyparsing/634725#634725">this code</a> and converting it to something for a project I'm working on for programming language processing, but I'm running into an issue with a simplified version:</p>
<pre><code>op = oneOf( '+ - / *')
lparen, rparen = Literal('('), Literal(')')
expr = Forward()
expr << ( Word(nums) | ( expr + op + expr ) | ( lparen + expr + rparen) )
</code></pre>
<p>I've played around with a number of different modifications of this simple setup. Usually, trying something like:</p>
<pre><code>print(expr.parseString('1+2'))
</code></pre>
<p>Will return <code>['1']</code>. While I get caught in deep recursion with something like:</p>
<pre><code>print(expr.parseString('(1+2)'))
</code></pre>
<p>What am I missing with respect to simple recursion that I can't parse arbitrarily arithmetic expressions, such as <code>1+(2 * 3-(4*(5+6)-(7))...</code>?</p>
| 17 | 2009-08-28T04:38:13Z | 1,345,151 | <p>A grammar like:</p>
<pre><code>expr :: expr op expr
</code></pre>
<p>is hard to work with because the recursion just keeps diving into the left.</p>
<p>A normal arithmetic grammar would look something like:</p>
<pre><code>expr :: mulxp | mulxp '+' expr
mulxp :: atom | atom '*' expr
atom :: Word(nums) | '(' + expr + ')'
</code></pre>
<p>Basically, you never get <code>S :: S</code>; any time a nonterminal appears on the left and right hand sides of a line in the grammar, there must be some literal in the middle for the parser to consume.</p>
| 4 | 2009-08-28T05:19:10Z | [
"python",
"pyparsing",
"recursive-descent"
] |
Simple recursive descent in PyParsing | 1,345,039 | <p>I've tried taking <a href="http://stackoverflow.com/questions/634432/need-help-on-making-the-recursive-parser-using-pyparsing/634725#634725">this code</a> and converting it to something for a project I'm working on for programming language processing, but I'm running into an issue with a simplified version:</p>
<pre><code>op = oneOf( '+ - / *')
lparen, rparen = Literal('('), Literal(')')
expr = Forward()
expr << ( Word(nums) | ( expr + op + expr ) | ( lparen + expr + rparen) )
</code></pre>
<p>I've played around with a number of different modifications of this simple setup. Usually, trying something like:</p>
<pre><code>print(expr.parseString('1+2'))
</code></pre>
<p>Will return <code>['1']</code>. While I get caught in deep recursion with something like:</p>
<pre><code>print(expr.parseString('(1+2)'))
</code></pre>
<p>What am I missing with respect to simple recursion that I can't parse arbitrarily arithmetic expressions, such as <code>1+(2 * 3-(4*(5+6)-(7))...</code>?</p>
| 17 | 2009-08-28T04:38:13Z | 1,345,155 | <p>Is this more or less what you want...?</p>
<pre><code>from pyparsing import Literal,Word,ZeroOrMore,Forward,nums,oneOf
def Syntax():
op = oneOf( '+ - / *')
lpar = Literal( '(' )
rpar = Literal( ')' )
num = Word(nums)
expr = Forward()
atom = num | ( lpar + expr + rpar )
expr << atom + ZeroOrMore( op + expr )
return expr
if __name__ == "__main__":
expr = Syntax()
def test(s):
results = expr.parseString( s )
print s,'->', results
test( "(9 + 3)" )
test( "(9 + 3) * (4 / 5)" )
</code></pre>
<p>emitting</p>
<pre><code>(9 + 3) -> ['(', '9', '+', '3', ')']
(9 + 3) * (4 / 5) -> ['(', '9', '+', '3', ')', '*', '(', '4', '/', '5', ')']
</code></pre>
<p>? This "anchors" the recursion by separating an "atom" (number or parenthesized expression) from an "expression" (one or more "atoms" with operators in-between).</p>
| 9 | 2009-08-28T05:19:59Z | [
"python",
"pyparsing",
"recursive-descent"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.