title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
FIFO (named pipe) messaging obstacles | 927,233 | <p>I plan to use Unix named pipes (mkfifo) for simple multi-process messaging.
A message would be just a single line of text.</p>
<p>Would you discourage me from that? What obstacles should I expect?</p>
<p>I have noticed these limitations:</p>
<ol>
<li>A sender cannot continue until the message is received.</li>
<li>A receiver is blocked until there are some data. Nonblocking IO would be needed
when we need to stop the reading. For example, another thread could ask for that.</li>
<li>The receiver could obtain many messages in a single read. These have to be processed
before quiting.</li>
<li>The max length of an atomic message is limited by 4096 bytes. That is the PIPE_BUF limit on Linux (see man 7 pipe).</li>
</ol>
<p>I will implement the messaging in Python. But the obstacles hold in general.</p>
| 1 | 2009-05-29T17:35:45Z | 927,371 | <p>The blocking, both on the sender side and the receiver side, can be worked around via non-blocking I/O.</p>
<p>Further limitations of FIFOs:</p>
<ul>
<li>Only one client at a time.</li>
<li>After the client closes the FIFO, the server need to re-open its endpoint.</li>
<li>Unidirectional.</li>
</ul>
<p>I would use <a href="http://en.wikipedia.org/wiki/Unix%5Fdomain%5Fsocket" rel="nofollow">UNIX domain sockets</a> instead, which have none of the above limitations.</p>
<p>As an added benefit, if you want to scale it to communicate between multiple machines, it's barely any change at all. For example, just take the Python documentation page on <a href="http://docs.python.org/library/socket.html#socket-example" rel="nofollow">socket</a> and replace <code>socket.AF_INET</code> with <code>socket.AF_UNIX</code>, <code>(HOST, PORT)</code> with <code>filename</code>, and it <em>just works</em>.</p>
<p><code>SOCK_STREAM</code> will give you stream-like behavior; that is, two sends may be merged into one receive or vice versa. <code>AF_UNIX</code> also supports <code>SOCK_DGRAM</code>: datagrams are guaranteed to be sent and read all as one unit or not at all. (Analogously, <code>AF_INET</code>+<code>SOCK_STREAM</code>=TCP, <code>AF_INET</code>+<code>SOCK_DGRAM</code>=UDP.)</p>
| 3 | 2009-05-29T18:11:45Z | [
"python",
"linux",
"unix",
"pipe",
"named-pipes"
] |
how to parse windows inf files for python? | 927,279 | <p>please help me.
example inf file : </p>
<pre><code>;=============================================================================
;
; Copyright (c) Intel Corporation (2002).
;
; INTEL MAKES NO WARRANTY OF ANY KIND REGARDING THE CODE. THIS CODE IS
; LICENSED ON AN "AS IS" BASIS AND INTEL WILL NOT PROVIDE ANY SUPPORT,
; ASSISTANCE, INSTALLATION, TRAINING OR OTHER SERVICES. INTEL DOES NOT
; PROVIDE ANY UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY
; DISCLAIMS ANY WARRANTY OF MERCHANTABILITY, NONINFRINGEMENT, FITNESS FOR ANY
; PARTICULAR PURPOSE, OR ANY OTHER WARRANTY. Intel disclaims all liability,
; including liability for infringement of any proprietary rights, relating to
; use of the code. No license, express or implied, by estoppel or otherwise,
; to any intellectual property rights is granted herein.
;
;=============================================================================
; Installation inf for the Intel Corporation graphics adapter.
[Version]
Signature="$WINDOWS NT$"
Provider=%Intel%
ClassGUID={4D36E968-E325-11CE-BFC1-08002BE10318}
Class=Display
CatalogFile=i830mnt5.cat
DriverVer=08/20/2004,6.14.10.3889
[DestinationDirs]
DefaultDestDir = 11
ialm.Miniport = 12 ; drivers
ialm.Display = 11 ; system32
Help.Copy = 11
CUI.Copy = 11
Uninstall_Copy = 11
OpenGL.Copy = 11 ; OpenGL Drivers in System32
;
; Driver information
;
[Manufacturer]
%Intel% = Intel.Mfg
[Intel.Mfg]
;830
;%i830M% = i830M, PCI\VEN_8086&DEV_3577
%i830M% = i830M, PCI\VEN_8086&DEV_3577&SUBSYS_00C81028
%i830M% = i830M, PCI\VEN_8086&DEV_3577&SUBSYS_01221028
%i830M% = i830M, PCI\VEN_8086&DEV_3577&SUBSYS_00B81028
%i830M% = i830M, PCI\VEN_8086&DEV_3577&SUBSYS_00B91028
%i830M% = i830M, PCI\VEN_8086&DEV_3577&SUBSYS_00F51028
;845
;%iBKDG% = i845G, PCI\VEN_8086&DEV_2562
%iBKDG% = i845G, PCI\VEN_8086&DEV_2562&SUBSYS_013D1028
%iBKDG% = i845G, PCI\VEN_8086&DEV_2562&SUBSYS_01471028
%iBKDG% = i845G, PCI\VEN_8086&DEV_2562&SUBSYS_03011028
%iBKDG% = i845G, PCI\VEN_8086&DEV_2562&SUBSYS_013A1028
%iBKDG% = i845G, PCI\VEN_8086&DEV_2562&SUBSYS_01481028
%iBKDG% = i845G, PCI\VEN_8086&DEV_2562&SUBSYS_01381028
%iBKDG% = i845G, PCI\VEN_8086&DEV_2562&SUBSYS_01261028
%iBKDG% = i845G, PCI\VEN_8086&DEV_2562&SUBSYS_01271028
%iBKDG% = i845G, PCI\VEN_8086&DEV_2562&SUBSYS_01331028
%iBKDG% = i845G, PCI\VEN_8086&DEV_2562&SUBSYS_014B1028
%iBKDG% = i845G, PCI\VEN_8086&DEV_2562&SUBSYS_01601028
%iBKDG% = i845G, PCI\VEN_8086&DEV_2562&SUBSYS_01611028
%iBKDG% = i845G, PCI\VEN_8086&DEV_2562&SUBSYS_01291028
%iBKDG% = i845G, PCI\VEN_8086&DEV_2562&SUBSYS_01461028
%iBKDG% = i845G, PCI\VEN_8086&DEV_2562&SUBSYS_03031028
;845GM
%iBKDGM% = i845GM, PCI\VEN_8086&DEV_2562&SUBSYS_01491028
</code></pre>
<p>how to parse and formated "%iBKDGM% = i845GM, PCI\VEN_8086&DEV_2562&SUBSYS_01491028" this line ? </p>
| 3 | 2009-05-29T17:52:31Z | 927,306 | <p>You may try the built-in ConfigParser</p>
<p><a href="http://docs.python.org/library/configparser.html">http://docs.python.org/library/configparser.html</a></p>
<p>As well as ConfigObj</p>
<p><a href="http://code.google.com/p/configobj/">http://code.google.com/p/configobj/</a></p>
<p>Both claim to be able to handle Windows INI files.</p>
| 10 | 2009-05-29T17:57:35Z | [
"python",
"windows",
"parsing",
"file",
"drivers"
] |
Parsing HTTP User-Agent string | 927,552 | <p>What is the best method to parse a User-Agent string in Python to reliably detect</p>
<ol>
<li>Browser</li>
<li>Browser version</li>
<li>OS</li>
</ol>
<p>Or perhaps any helper library that does it</p>
| 45 | 2009-05-29T18:53:46Z | 927,710 | <p>However if you wish to parse all this on the Python side you can use the XML/INI files provided at <a href="http://browsers.garykeith.com/downloads.asp" rel="nofollow">http://browsers.garykeith.com/downloads.asp</a> to do lookups on the user agent. This is the same file that is used in php's get_browser() function.</p>
| 2 | 2009-05-29T19:25:27Z | [
"python",
"http",
"http-headers",
"user-agent"
] |
Parsing HTTP User-Agent string | 927,552 | <p>What is the best method to parse a User-Agent string in Python to reliably detect</p>
<ol>
<li>Browser</li>
<li>Browser version</li>
<li>OS</li>
</ol>
<p>Or perhaps any helper library that does it</p>
| 45 | 2009-05-29T18:53:46Z | 929,077 | <p>Th <a href="http://www.djangosnippets.org/snippets/267/" rel="nofollow">Browser Cap Parser</a> should work. It may be a bit slow though..</p>
| 3 | 2009-05-30T05:28:49Z | [
"python",
"http",
"http-headers",
"user-agent"
] |
Parsing HTTP User-Agent string | 927,552 | <p>What is the best method to parse a User-Agent string in Python to reliably detect</p>
<ol>
<li>Browser</li>
<li>Browser version</li>
<li>OS</li>
</ol>
<p>Or perhaps any helper library that does it</p>
| 45 | 2009-05-29T18:53:46Z | 1,151,956 | <p>Answering my own question ;)</p>
<p>Finally I decided to go by suggestion#1 i.e. write your own. And I am happy with the outcome. Please feel free to use/modify/send me patch etc.</p>
<p>It's here -> <a href="http://pypi.python.org/pypi/httpagentparser">http://pypi.python.org/pypi/httpagentparser</a></p>
| 63 | 2009-07-20T06:24:40Z | [
"python",
"http",
"http-headers",
"user-agent"
] |
Parsing HTTP User-Agent string | 927,552 | <p>What is the best method to parse a User-Agent string in Python to reliably detect</p>
<ol>
<li>Browser</li>
<li>Browser version</li>
<li>OS</li>
</ol>
<p>Or perhaps any helper library that does it</p>
| 45 | 2009-05-29T18:53:46Z | 1,339,838 | <p><a href="http://user-agent-string.info/download/UASparser-for-Python">UASparser for Python</a>
by Hicro Kee. Auto updated datafile and cache from remote server with version checking.</p>
| 10 | 2009-08-27T09:10:50Z | [
"python",
"http",
"http-headers",
"user-agent"
] |
Parsing HTTP User-Agent string | 927,552 | <p>What is the best method to parse a User-Agent string in Python to reliably detect</p>
<ol>
<li>Browser</li>
<li>Browser version</li>
<li>OS</li>
</ol>
<p>Or perhaps any helper library that does it</p>
| 45 | 2009-05-29T18:53:46Z | 10,109,978 | <p>Having run these suggestions against <a href="http://www.useragentstring.com/pages/Firefox/">the full corpus of Firefox User Agents</a>, I've found that the version-number parsing for comparison is quite poor. </p>
<p>If that's what you need, I suggest that you take a look at <a href="https://github.com/dinomite/uaParser">UAparser</a>, which used to be part of the <a href="http://code.google.com/p/browserscope/">browserscope</a> project. <a href="http://code.google.com/p/browserscope/wiki/UserAgentParsing">Documentation here.</a></p>
| 6 | 2012-04-11T16:25:00Z | [
"python",
"http",
"http-headers",
"user-agent"
] |
Parsing HTTP User-Agent string | 927,552 | <p>What is the best method to parse a User-Agent string in Python to reliably detect</p>
<ol>
<li>Browser</li>
<li>Browser version</li>
<li>OS</li>
</ol>
<p>Or perhaps any helper library that does it</p>
| 45 | 2009-05-29T18:53:46Z | 11,148,234 | <p>Werkzeug has user-agent parsing built-in.</p>
<p><a href="http://werkzeug.pocoo.org/docs/0.10/utils/#module-werkzeug.useragents">http://werkzeug.pocoo.org/docs/0.10/utils/#module-werkzeug.useragents</a></p>
| 8 | 2012-06-21T23:25:03Z | [
"python",
"http",
"http-headers",
"user-agent"
] |
Parsing HTTP User-Agent string | 927,552 | <p>What is the best method to parse a User-Agent string in Python to reliably detect</p>
<ol>
<li>Browser</li>
<li>Browser version</li>
<li>OS</li>
</ol>
<p>Or perhaps any helper library that does it</p>
| 45 | 2009-05-29T18:53:46Z | 27,642,188 | <p>The other responses to this question are rather old now. I believe the new standard in Browser User Agent parsing is Browserscope's <a href="https://github.com/ua-parser/uap-python/">user agent parser</a>. </p>
<ul>
<li><a href="https://pypi.python.org/pypi/ua-parser">UA Parser pypi package</a> </li>
<li><a href="https://github.com/ua-parser/uap-python">UA Parser on github</a></li>
</ul>
<p>Also conveniently available with the <em>exact same matching patterns</em> in <a href="https://github.com/ua-parser">many other languages</a>. Someday you might want to also parse some UA strings in JavaScript and you don't need to worry about inconsistent parsing.</p>
| 5 | 2014-12-24T21:08:03Z | [
"python",
"http",
"http-headers",
"user-agent"
] |
str.startswith() not working as I intended | 927,584 | <p>I'm trying to test for a /t or a space character and I can't understand why this bit of code won't work. What I am doing is reading in a file, counting the loc for the file, and then recording the names of each function present within the file along with their individual lines of code. The bit of code below is where I attempt to count the loc for the functions.</p>
<pre><code>import re
...
else:
loc += 1
for line in infile:
line_t = line.lstrip()
if len(line_t) > 0 \
and not line_t.startswith('#') \
and not line_t.startswith('"""'):
if not line.startswith('\s'):
print ('line = ' + repr(line))
loc += 1
return (loc, name)
else:
loc += 1
elif line_t.startswith('"""'):
while True:
if line_t.rstrip().endswith('"""'):
break
line_t = infile.readline().rstrip()
return(loc,name)
</code></pre>
<p>Output:</p>
<pre><code>Enter the file name: test.txt
line = '\tloc = 0\n'
There were 19 lines of code in "test.txt"
Function names:
count_loc -- 2 lines of code
</code></pre>
<p>As you can see, my test print for the line shows a /t, but the if statement explicitly says (or so I thought) that it should only execute with no whitespace characters present.</p>
<p>Here is my full test file I have been using:</p>
<pre><code>def count_loc(infile):
""" Receives a file and then returns the amount
of actual lines of code by not counting commented
or blank lines """
loc = 0
for line in infile:
line = line.strip()
if len(line) > 0 \
and not line.startswith('//') \
and not line.startswith('/*'):
loc += 1
func_loc, func_name = checkForFunction(line);
elif line.startswith('/*'):
while True:
if line.endswith('*/'):
break
line = infile.readline().rstrip()
return loc
if __name__ == "__main__":
print ("Hi")
Function LOC = 15
File LOC = 19
</code></pre>
| 1 | 2009-05-29T19:00:37Z | 927,599 | <p><code>\s</code> is only whitespace to the <code>re</code> package when doing pattern matching.</p>
<p>For <code>startswith</code>, an ordinary method of ordinary strings, <code>\s</code> is nothing special. Not a pattern, just characters.</p>
| 8 | 2009-05-29T19:03:30Z | [
"python",
"string",
"python-3.x"
] |
str.startswith() not working as I intended | 927,584 | <p>I'm trying to test for a /t or a space character and I can't understand why this bit of code won't work. What I am doing is reading in a file, counting the loc for the file, and then recording the names of each function present within the file along with their individual lines of code. The bit of code below is where I attempt to count the loc for the functions.</p>
<pre><code>import re
...
else:
loc += 1
for line in infile:
line_t = line.lstrip()
if len(line_t) > 0 \
and not line_t.startswith('#') \
and not line_t.startswith('"""'):
if not line.startswith('\s'):
print ('line = ' + repr(line))
loc += 1
return (loc, name)
else:
loc += 1
elif line_t.startswith('"""'):
while True:
if line_t.rstrip().endswith('"""'):
break
line_t = infile.readline().rstrip()
return(loc,name)
</code></pre>
<p>Output:</p>
<pre><code>Enter the file name: test.txt
line = '\tloc = 0\n'
There were 19 lines of code in "test.txt"
Function names:
count_loc -- 2 lines of code
</code></pre>
<p>As you can see, my test print for the line shows a /t, but the if statement explicitly says (or so I thought) that it should only execute with no whitespace characters present.</p>
<p>Here is my full test file I have been using:</p>
<pre><code>def count_loc(infile):
""" Receives a file and then returns the amount
of actual lines of code by not counting commented
or blank lines """
loc = 0
for line in infile:
line = line.strip()
if len(line) > 0 \
and not line.startswith('//') \
and not line.startswith('/*'):
loc += 1
func_loc, func_name = checkForFunction(line);
elif line.startswith('/*'):
while True:
if line.endswith('*/'):
break
line = infile.readline().rstrip()
return loc
if __name__ == "__main__":
print ("Hi")
Function LOC = 15
File LOC = 19
</code></pre>
| 1 | 2009-05-29T19:00:37Z | 927,606 | <p>You string literals aren't what you think they are.
You can specify a space or TAB like so:</p>
<pre><code>space = ' '
tab = '\t'
</code></pre>
| 2 | 2009-05-29T19:05:08Z | [
"python",
"string",
"python-3.x"
] |
str.startswith() not working as I intended | 927,584 | <p>I'm trying to test for a /t or a space character and I can't understand why this bit of code won't work. What I am doing is reading in a file, counting the loc for the file, and then recording the names of each function present within the file along with their individual lines of code. The bit of code below is where I attempt to count the loc for the functions.</p>
<pre><code>import re
...
else:
loc += 1
for line in infile:
line_t = line.lstrip()
if len(line_t) > 0 \
and not line_t.startswith('#') \
and not line_t.startswith('"""'):
if not line.startswith('\s'):
print ('line = ' + repr(line))
loc += 1
return (loc, name)
else:
loc += 1
elif line_t.startswith('"""'):
while True:
if line_t.rstrip().endswith('"""'):
break
line_t = infile.readline().rstrip()
return(loc,name)
</code></pre>
<p>Output:</p>
<pre><code>Enter the file name: test.txt
line = '\tloc = 0\n'
There were 19 lines of code in "test.txt"
Function names:
count_loc -- 2 lines of code
</code></pre>
<p>As you can see, my test print for the line shows a /t, but the if statement explicitly says (or so I thought) that it should only execute with no whitespace characters present.</p>
<p>Here is my full test file I have been using:</p>
<pre><code>def count_loc(infile):
""" Receives a file and then returns the amount
of actual lines of code by not counting commented
or blank lines """
loc = 0
for line in infile:
line = line.strip()
if len(line) > 0 \
and not line.startswith('//') \
and not line.startswith('/*'):
loc += 1
func_loc, func_name = checkForFunction(line);
elif line.startswith('/*'):
while True:
if line.endswith('*/'):
break
line = infile.readline().rstrip()
return loc
if __name__ == "__main__":
print ("Hi")
Function LOC = 15
File LOC = 19
</code></pre>
| 1 | 2009-05-29T19:00:37Z | 928,150 | <p>Your question has already been answered and this is slightly off-topic, but...</p>
<p>If you want to parse code, it is often easier and less error-prone to use a parser. If your code is Python code, Python comes with a couple of parsers (<a href="http://docs.python.org/library/tokenize.html" rel="nofollow">tokenize</a>, <a href="http://docs.python.org/library/ast.html" rel="nofollow">ast</a>, <a href="http://docs.python.org/library/parser.html#module-parser" rel="nofollow">parser</a>). For other languages, you can find a lot of parsers on the internet. <a href="http://www.antlr.org/" rel="nofollow">ANTRL</a> is a well-known one with Python <a href="http://www.antlr.org/wiki/display/ANTLR3/Example" rel="nofollow">bindings</a>.</p>
<p>As an example, the following couple of lines of code print all lines of a Python module that are not comments and not doc-strings:</p>
<pre><code>import tokenize
ignored_tokens = [tokenize.NEWLINE,tokenize.COMMENT,tokenize.N_TOKENS
,tokenize.STRING,tokenize.ENDMARKER,tokenize.INDENT
,tokenize.DEDENT,tokenize.NL]
with open('test.py', 'r') as f:
g = tokenize.generate_tokens(f.readline)
line_num = 0
for a_token in g:
if a_token[2][0] != line_num and a_token[0] not in ignored_tokens:
line_num = a_token[2][0]
print(a_token)
</code></pre>
<p>As <code>a_token</code> above is already parsed, you can easily check for function definition, too. You can also keep track where the function ends by looking at the current column start <code>a_token[2][1]</code>. If you want to do more complex things, you should use ast.</p>
| 3 | 2009-05-29T21:04:44Z | [
"python",
"string",
"python-3.x"
] |
how to override the verbose name of a superclass model field in django | 927,729 | <p>Let's say that I have a model Foo that inherits from SuperFoo:</p>
<pre><code>class SuperFoo(models.Model):
name = models.CharField('name of SuperFoo instance', max_length=50)
...
class Foo(SuperFoo):
... # do something that changes verbose_name of name field of SuperFoo
</code></pre>
<p>In class Foo, I'd like to override the verbose_name of the name field of SuperFoo. Can I? If not, is the best option setting a label inside the model form definition to get it displayed in a template?</p>
| 23 | 2009-05-29T19:30:57Z | 928,030 | <p>Your best bet would be setting/changing the label in the form itself. Referring to the <code>name</code> field of the <code>Foo</code> model (eg. by looking it up in <code>Foo._meta.fields</code>) will actually give you a reference to the <code>name</code> field of <code>SuperFoo</code>, so changing its <code>verbose_name</code> will change it in both models.</p>
<p>Also, adding a <code>name</code> field to the <code>Foo</code> class won't work either, <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#field-name-hiding-is-not-permitted" rel="nofollow">because</a>...</p>
<blockquote>
<p>Overriding fields in a parent model
leads to difficulties in areas such as
initialising new instances (specifying
which field is being intialised in
<code>Model.__init__</code>) and serialization.
These are features which normal Python
class inheritance doesn't have to deal
with in quite the same way, so the
difference between Django model
inheritance and Python class
inheritance isn't merely arbitrary.</p>
</blockquote>
| 4 | 2009-05-29T20:39:38Z | [
"python",
"django",
"inheritance",
"django-models"
] |
how to override the verbose name of a superclass model field in django | 927,729 | <p>Let's say that I have a model Foo that inherits from SuperFoo:</p>
<pre><code>class SuperFoo(models.Model):
name = models.CharField('name of SuperFoo instance', max_length=50)
...
class Foo(SuperFoo):
... # do something that changes verbose_name of name field of SuperFoo
</code></pre>
<p>In class Foo, I'd like to override the verbose_name of the name field of SuperFoo. Can I? If not, is the best option setting a label inside the model form definition to get it displayed in a template?</p>
| 23 | 2009-05-29T19:30:57Z | 928,774 | <p>A simple hack I have used is:</p>
<pre><code>class SuperFoo(models.Model):
name = models.CharField('name of SuperFoo instance', max_length=50)
...
class Foo(SuperFoo):
... # do something that changes verbose_name of name field of SuperFoo
Foo._meta.get_field('name').verbose_name = 'Whatever'
</code></pre>
| 45 | 2009-05-30T02:02:46Z | [
"python",
"django",
"inheritance",
"django-models"
] |
how to override the verbose name of a superclass model field in django | 927,729 | <p>Let's say that I have a model Foo that inherits from SuperFoo:</p>
<pre><code>class SuperFoo(models.Model):
name = models.CharField('name of SuperFoo instance', max_length=50)
...
class Foo(SuperFoo):
... # do something that changes verbose_name of name field of SuperFoo
</code></pre>
<p>In class Foo, I'd like to override the verbose_name of the name field of SuperFoo. Can I? If not, is the best option setting a label inside the model form definition to get it displayed in a template?</p>
| 23 | 2009-05-29T19:30:57Z | 6,426,278 | <p>Have a look at how Django-CMS does this, they override the <code>db_table</code> field in the models inheriting from <code>CMSPlugin</code>. The basics (which I also use for my own stuff) boil down to:</p>
<pre><code>class SuperFooMetaClass(ModelBase):
def __new__(cls, name, bases, attrs):
new_class = super(SuperFooMetaClass, cls).__new__(cls, name, bases, attrs)
new_class._meta.verbose_name = "...." # perhaps only if not customized
return new_class
class SuperFoo(models.Model):
__metaclass__ = SuperFooMetaClass
....
</code></pre>
<p>You can add some checks, e.g. only update for subclasses (not the direct type), or only update if the value is not customized.</p>
| 5 | 2011-06-21T13:43:24Z | [
"python",
"django",
"inheritance",
"django-models"
] |
how to override the verbose name of a superclass model field in django | 927,729 | <p>Let's say that I have a model Foo that inherits from SuperFoo:</p>
<pre><code>class SuperFoo(models.Model):
name = models.CharField('name of SuperFoo instance', max_length=50)
...
class Foo(SuperFoo):
... # do something that changes verbose_name of name field of SuperFoo
</code></pre>
<p>In class Foo, I'd like to override the verbose_name of the name field of SuperFoo. Can I? If not, is the best option setting a label inside the model form definition to get it displayed in a template?</p>
| 23 | 2009-05-29T19:30:57Z | 24,475,838 | <p>Bearing in mind the caveat that modifying Foo._meta.fields will affect the superclass too - and therefore is only really useful if the superclass is abstract, I've wrapped the answer @Gerry gave up as a reusable class decorator:</p>
<pre><code>def modify_fields(**kwargs):
def wrap(cls):
for field, prop_dict in kwargs.items():
for prop, val in prop_dict.items():
setattr(cls._meta.get_field(field), prop, val)
return cls
return wrap
</code></pre>
<p>Use it like this:</p>
<pre><code>@modify_fields(timestamp={
'verbose_name': 'Available From',
'help_text': 'Earliest date you can book this'})
class Purchase(BaseOrderItem):
pass
</code></pre>
<p>The example above changes the verbose_name and help_text for the inherited field 'timestamp'. You can pass in as many keyword args as there are fields you want to modify.</p>
| 5 | 2014-06-29T11:54:04Z | [
"python",
"django",
"inheritance",
"django-models"
] |
Really odd (mod)_python problem | 927,759 | <p>this one is hard to explain!</p>
<p>I am writing a python application to be ran through mod_python. At each request, the returned output differs, even though the logic is 'fixed'.</p>
<p>I have two classes, <code>classA</code> and <code>classB</code>. Such that:</p>
<pre><code>class ClassA:
def page(self, req):
req.write("In classA page")
objB = ClassB()
objB.methodB(req)
req.write("End of page")
class ClassB:
def methodB(self, req):
req.write("In methodB")
return None
</code></pre>
<p>Which is a <strong>heavily</strong> snipped version of what I have. But the stuff I have snipped doesn't change the control flow. There is only <strong>one</strong> place where <code>MethodB()</code> is called. That is from <code>__init__()</code> in <code>classA</code>.</p>
<p>You would expect the following output:</p>
<pre><code>In classA __init__
In methodB
End of __init__
</code></pre>
<p>However, seemingly randomly either get the above correct output or:</p>
<pre><code>In classA __init__
In methodB
End of __init__
In methodB
</code></pre>
<p>The stacktrace shows that <code>methodB</code> is being called the second time from <code>__init__</code>. <code>methodB</code> should only be called once. If it is called a second time, you would expect that the other logic in <code>__init__</code> be done twice too. But nothing before or after <code>methodB</code> executes and there is no recursion.</p>
<p>I wouldn't usually resort to using SO for my debugging, but I have been scratching my head for a while on this.</p>
<p>Version: 2.5.2 r252:60911</p>
<p><strong>thanks in advance</strong></p>
<p><strong>Edit</strong>
Some clues that the problem might be elsewhere .... The above changes to the snippet result in the weird output 1 in every 250 or so hits. Which is odd.</p>
<p>The more output prior to printing "In methodB", the more it is printed subsequently incorrectly ... on average, not in direct ratio. It even does it in Lynx.</p>
<p>Im going back to the drawing board.</p>
<p>:(</p>
<h1>In response to answer</h1>
<p>It seems mod_python and Apache are having marital problems. A restart and things are fine for a few requests. Then it all goes increasingly pear-shaped. When issuing</p>
<pre><code>/etc/rc.d/init.d/httpd stop
</code></pre>
<p>It takes a weirdly long amount of time. Also RAM is getting eaten up with requests. I am not that familiar with Apache's internals but it <em>feels</em> like (thanks to Nadia) that threads are staying alive and <strong>randomly butting in</strong> on requests. Which is plain bonkers.</p>
<p><strong>Moving to mod_wsgi as S.Lott and Nadia suggested</strong></p>
<p><strong>thanks again!!</strong></p>
| 2 | 2009-05-29T19:38:24Z | 927,769 | <p>I don't really know, but constructors aren't supposed to return anything, so remove the <code>return None</code>. Even if they could return stuff, <code>None</code> is automatically returned if a function doesn't return anything by itself.</p>
<p>And I think you need a <code>self</code> argument in MethodB.</p>
<p><b>EDIT:</b> Could you show more code? This is working fine.</p>
| 1 | 2009-05-29T19:41:07Z | [
"python",
"debugging",
"mod-python"
] |
Really odd (mod)_python problem | 927,759 | <p>this one is hard to explain!</p>
<p>I am writing a python application to be ran through mod_python. At each request, the returned output differs, even though the logic is 'fixed'.</p>
<p>I have two classes, <code>classA</code> and <code>classB</code>. Such that:</p>
<pre><code>class ClassA:
def page(self, req):
req.write("In classA page")
objB = ClassB()
objB.methodB(req)
req.write("End of page")
class ClassB:
def methodB(self, req):
req.write("In methodB")
return None
</code></pre>
<p>Which is a <strong>heavily</strong> snipped version of what I have. But the stuff I have snipped doesn't change the control flow. There is only <strong>one</strong> place where <code>MethodB()</code> is called. That is from <code>__init__()</code> in <code>classA</code>.</p>
<p>You would expect the following output:</p>
<pre><code>In classA __init__
In methodB
End of __init__
</code></pre>
<p>However, seemingly randomly either get the above correct output or:</p>
<pre><code>In classA __init__
In methodB
End of __init__
In methodB
</code></pre>
<p>The stacktrace shows that <code>methodB</code> is being called the second time from <code>__init__</code>. <code>methodB</code> should only be called once. If it is called a second time, you would expect that the other logic in <code>__init__</code> be done twice too. But nothing before or after <code>methodB</code> executes and there is no recursion.</p>
<p>I wouldn't usually resort to using SO for my debugging, but I have been scratching my head for a while on this.</p>
<p>Version: 2.5.2 r252:60911</p>
<p><strong>thanks in advance</strong></p>
<p><strong>Edit</strong>
Some clues that the problem might be elsewhere .... The above changes to the snippet result in the weird output 1 in every 250 or so hits. Which is odd.</p>
<p>The more output prior to printing "In methodB", the more it is printed subsequently incorrectly ... on average, not in direct ratio. It even does it in Lynx.</p>
<p>Im going back to the drawing board.</p>
<p>:(</p>
<h1>In response to answer</h1>
<p>It seems mod_python and Apache are having marital problems. A restart and things are fine for a few requests. Then it all goes increasingly pear-shaped. When issuing</p>
<pre><code>/etc/rc.d/init.d/httpd stop
</code></pre>
<p>It takes a weirdly long amount of time. Also RAM is getting eaten up with requests. I am not that familiar with Apache's internals but it <em>feels</em> like (thanks to Nadia) that threads are staying alive and <strong>randomly butting in</strong> on requests. Which is plain bonkers.</p>
<p><strong>Moving to mod_wsgi as S.Lott and Nadia suggested</strong></p>
<p><strong>thanks again!!</strong></p>
| 2 | 2009-05-29T19:38:24Z | 927,925 | <p>I've seen similar behaviour with mod_python before. Usually it is because apache is running multiple threads and one of them is running an older version of the code. When you refresh the page chances are the thread with the older code is serving the page. I usually fix this by stoping apache and then restarting it again</p>
<pre><code>sudo /etc/init.d/apache stop
sudo /etc/init.d/apache restart
</code></pre>
<p>Restart on its own doesn't always work. Sometimes even that doesn't work! That might sound strange but my last resort in those rare cases where nothing is working is to add a <code>raise Exception()</code> statement on the first line in the handler, refresh the page, restart apache and then refresh the page again. That works every time. There must be a better solution. But that what worked for me. mod_python can drive one crazy for sure!</p>
<p>I hope this might help.</p>
| 4 | 2009-05-29T20:16:55Z | [
"python",
"debugging",
"mod-python"
] |
How to get the owner and group of a folder with Python on a Linux machine? | 927,866 | <p>How can I get the owner and group IDs of a directory using Python under Linux?</p>
| 6 | 2009-05-29T20:04:54Z | 927,886 | <p>I tend to use <a href="http://docs.python.org/library/os.html#files-and-directories" rel="nofollow">os.stat</a>:</p>
<blockquote>
<p>Perform a stat system call on the given path. The return value is an object whose attributes correspond to the members of the stat structure, namely: st_mode (protection bits), <code>st_ino</code> (inode number), <code>st_dev</code> (device), <code>st_nlink</code> (number of hard links), <strong><code>st_uid</code> (user id of owner), <code>st_gid</code> (group id of owner)</strong>, <code>st_size</code> (size of file, in bytes), <code>st_atime</code> (time of most recent access), <code>st_mtime</code> (time of most recent content modification), <code>st_ctime</code> (platform dependent; time of most recent metadata change on Unix, or the time of creation on Windows)</p>
</blockquote>
<p>There's an example at the link to <code>os.stat</code> above.</p>
| 0 | 2009-05-29T20:09:52Z | [
"python",
"linux",
"folder",
"group",
"owner"
] |
How to get the owner and group of a folder with Python on a Linux machine? | 927,866 | <p>How can I get the owner and group IDs of a directory using Python under Linux?</p>
| 6 | 2009-05-29T20:04:54Z | 927,888 | <p>Use the <code>os.stat</code> function.</p>
| 0 | 2009-05-29T20:10:30Z | [
"python",
"linux",
"folder",
"group",
"owner"
] |
How to get the owner and group of a folder with Python on a Linux machine? | 927,866 | <p>How can I get the owner and group IDs of a directory using Python under Linux?</p>
| 6 | 2009-05-29T20:04:54Z | 927,890 | <p>Use <a href="http://docs.python.org/library/os.html#os.stat"><code>os.stat()</code></a> to get the uid and gid of the file. Then, use <a href="http://docs.python.org/library/pwd.html#pwd.getpwuid"><code>pwd.getpwuid()</code></a> and <a href="http://docs.python.org/library/grp.html#grp.getgrgid"><code>grp.getgrgid()</code></a> to get the user and group names respectively.</p>
<pre><code>import grp
import pwd
import os
stat_info = os.stat('/path')
uid = stat_info.st_uid
gid = stat_info.st_gid
print uid, gid
user = pwd.getpwuid(uid)[0]
group = grp.getgrgid(gid)[0]
print user, group
</code></pre>
| 22 | 2009-05-29T20:10:40Z | [
"python",
"linux",
"folder",
"group",
"owner"
] |
How to get the owner and group of a folder with Python on a Linux machine? | 927,866 | <p>How can I get the owner and group IDs of a directory using Python under Linux?</p>
| 6 | 2009-05-29T20:04:54Z | 927,902 | <p>Use <a href="http://docs.python.org/3.0/library/os.html#os.stat" rel="nofollow">os.stat</a>:</p>
<pre><code>>>> s = os.stat('.')
>>> s.st_uid
1000
>>> s.st_gid
1000
</code></pre>
<p><code>st_uid</code> is the user id of the owner, <code>st_gid</code> is the group id. See the linked documentation for other information that can be acuired through <code>stat</code>.</p>
| 0 | 2009-05-29T20:13:19Z | [
"python",
"linux",
"folder",
"group",
"owner"
] |
How to get the owner and group of a folder with Python on a Linux machine? | 927,866 | <p>How can I get the owner and group IDs of a directory using Python under Linux?</p>
| 6 | 2009-05-29T20:04:54Z | 36,546,321 | <p>Since Python 3.4.4, the <code>Path</code> class of <code>pathlib</code> module provides a nice syntax for this:</p>
<pre><code>from pathlib import Path
whatever = Path("relative/or/absolute/path/to_whatever")
if whatever.exists():
print("Owner: %s" % whatever.owner())
print("Group: %s" % whatever.group())
</code></pre>
| 1 | 2016-04-11T10:38:07Z | [
"python",
"linux",
"folder",
"group",
"owner"
] |
Python Class Inheritance issue | 927,985 | <p>I'm playing with Python Class inheritance and ran into a problem where the inherited <code>__init__</code> is not being executed if called from the sub-class (code below) the result I get from Active Python is:</p>
<p><hr /></p>
<pre><code>>>> start
Tom Sneed
Sue Ann
Traceback (most recent call last):
File "C:\Python26\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 312, <br>in RunScript
exec codeObject in __main__.__dict__
File "C:\temp\classtest.py", line 22, in <module>
print y.get_emp()
File "C:\temp\classtest.py", line 16, in get_emp
return self.FirstName + ' ' + 'abc'
AttributeError: Employee instance has no attribute 'FirstName'
</code></pre>
<p><hr /></p>
<h2>Here's the code</h2>
<pre><code>class Person():
AnotherName = 'Sue Ann'
def __init__(self):
self.FirstName = 'Tom'
self.LastName = 'Sneed'
def get_name(self):
return self.FirstName + ' ' + self.LastName
class Employee(Person):
def __init__(self):
self.empnum = 'abc123'
def get_emp(self):
print self.AnotherName
return self.FirstName + ' ' + 'abc'
x = Person()
y = Employee()
print 'start'
print x.get_name()
print y.get_emp()
</code></pre>
| 16 | 2009-05-29T20:28:23Z | 927,996 | <p>Employee has to explicitly invoke the parent's __init__ (not init):</p>
<pre><code> class Employee(Person):
def __init__(self):
Person.__init__(self)
self.empnum = 'abc123'
</code></pre>
| 5 | 2009-05-29T20:31:04Z | [
"python",
"class",
"inheritance"
] |
Python Class Inheritance issue | 927,985 | <p>I'm playing with Python Class inheritance and ran into a problem where the inherited <code>__init__</code> is not being executed if called from the sub-class (code below) the result I get from Active Python is:</p>
<p><hr /></p>
<pre><code>>>> start
Tom Sneed
Sue Ann
Traceback (most recent call last):
File "C:\Python26\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 312, <br>in RunScript
exec codeObject in __main__.__dict__
File "C:\temp\classtest.py", line 22, in <module>
print y.get_emp()
File "C:\temp\classtest.py", line 16, in get_emp
return self.FirstName + ' ' + 'abc'
AttributeError: Employee instance has no attribute 'FirstName'
</code></pre>
<p><hr /></p>
<h2>Here's the code</h2>
<pre><code>class Person():
AnotherName = 'Sue Ann'
def __init__(self):
self.FirstName = 'Tom'
self.LastName = 'Sneed'
def get_name(self):
return self.FirstName + ' ' + self.LastName
class Employee(Person):
def __init__(self):
self.empnum = 'abc123'
def get_emp(self):
print self.AnotherName
return self.FirstName + ' ' + 'abc'
x = Person()
y = Employee()
print 'start'
print x.get_name()
print y.get_emp()
</code></pre>
| 16 | 2009-05-29T20:28:23Z | 928,004 | <p>You should explicitely call the superclass' init function:</p>
<pre><code>class Employee(Person):
def __init__(self):
Person.__init__(self)
self.empnum = "abc123"
</code></pre>
| 9 | 2009-05-29T20:32:36Z | [
"python",
"class",
"inheritance"
] |
Python Class Inheritance issue | 927,985 | <p>I'm playing with Python Class inheritance and ran into a problem where the inherited <code>__init__</code> is not being executed if called from the sub-class (code below) the result I get from Active Python is:</p>
<p><hr /></p>
<pre><code>>>> start
Tom Sneed
Sue Ann
Traceback (most recent call last):
File "C:\Python26\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 312, <br>in RunScript
exec codeObject in __main__.__dict__
File "C:\temp\classtest.py", line 22, in <module>
print y.get_emp()
File "C:\temp\classtest.py", line 16, in get_emp
return self.FirstName + ' ' + 'abc'
AttributeError: Employee instance has no attribute 'FirstName'
</code></pre>
<p><hr /></p>
<h2>Here's the code</h2>
<pre><code>class Person():
AnotherName = 'Sue Ann'
def __init__(self):
self.FirstName = 'Tom'
self.LastName = 'Sneed'
def get_name(self):
return self.FirstName + ' ' + self.LastName
class Employee(Person):
def __init__(self):
self.empnum = 'abc123'
def get_emp(self):
print self.AnotherName
return self.FirstName + ' ' + 'abc'
x = Person()
y = Employee()
print 'start'
print x.get_name()
print y.get_emp()
</code></pre>
| 16 | 2009-05-29T20:28:23Z | 928,013 | <p>Three things:</p>
<ol>
<li>You need to explicitly call the constructor. It isn't called for you automatically like in C++</li>
<li>Use a new-style class inherited from object</li>
<li>With a new-style class, use the super() method available</li>
</ol>
<p>This will look like:</p>
<pre><code>class Person(object):
AnotherName = 'Sue Ann'
def __init__(self):
super(Person, self).__init__()
self.FirstName = 'Tom'
self.LastName = 'Sneed'
def get_name(self):
return self.FirstName + ' ' + self.LastName
class Employee(Person):
def __init__(self):
super(Employee, self).__init__()
self.empnum = 'abc123'
def get_emp(self):
print self.AnotherName
return self.FirstName + ' ' + 'abc'
</code></pre>
<p>Using super is recommended as it will also deal correctly with calling constructors only once in multiple inheritance cases (as long as each class in the inheritance graph also uses super). It's also one less place you need to change code if/when you change what a class is inherited from (for example, you factor out a base-class and change the derivation and don't need to worry about your classes calling the wrong parent constructors). Also on the MI front, you only need one super call to correctly call all the base-class constructors.</p>
| 25 | 2009-05-29T20:34:37Z | [
"python",
"class",
"inheritance"
] |
Python Class Inheritance issue | 927,985 | <p>I'm playing with Python Class inheritance and ran into a problem where the inherited <code>__init__</code> is not being executed if called from the sub-class (code below) the result I get from Active Python is:</p>
<p><hr /></p>
<pre><code>>>> start
Tom Sneed
Sue Ann
Traceback (most recent call last):
File "C:\Python26\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 312, <br>in RunScript
exec codeObject in __main__.__dict__
File "C:\temp\classtest.py", line 22, in <module>
print y.get_emp()
File "C:\temp\classtest.py", line 16, in get_emp
return self.FirstName + ' ' + 'abc'
AttributeError: Employee instance has no attribute 'FirstName'
</code></pre>
<p><hr /></p>
<h2>Here's the code</h2>
<pre><code>class Person():
AnotherName = 'Sue Ann'
def __init__(self):
self.FirstName = 'Tom'
self.LastName = 'Sneed'
def get_name(self):
return self.FirstName + ' ' + self.LastName
class Employee(Person):
def __init__(self):
self.empnum = 'abc123'
def get_emp(self):
print self.AnotherName
return self.FirstName + ' ' + 'abc'
x = Person()
y = Employee()
print 'start'
print x.get_name()
print y.get_emp()
</code></pre>
| 16 | 2009-05-29T20:28:23Z | 4,147,739 | <p>Instead of <code>super(class, instance)</code> pattern why not just use <code>super(instance)</code> as the class is always <code>instance.__class__</code>?</p>
<p>Are there specific cases where it would not be <code>instance.__class__</code>?</p>
| 2 | 2010-11-10T18:25:50Z | [
"python",
"class",
"inheritance"
] |
Formatting the output of a key from a dictionary | 928,330 | <p>I have a dictionary which store a string as the key, and an integer as the value. In my output I would like to have the key displayed as a string without parenthesis or commas. How would I do this?</p>
<pre><code>for f_name,f_loc in dict_func.items():
print ('Function names:\n\n\t{0} -- {1} lines of code\n'.format(f_name, f_loc))
</code></pre>
<p>output:</p>
<pre><code>Enter the file name: test.txt
line = 'def count_loc(infile):'
There were 19 lines of code in "test.txt"
Function names:
('count_loc(infile)',) -- 15 lines of code
</code></pre>
<p>Just incase it wasn't clear, I would like the last line of the output to be displayed as:</p>
<pre><code>count_loc(infile) -- 15 lines of code
</code></pre>
<p>EDIT </p>
<pre><code>name = re.search(func_pattern, line).groups()
name = str(name)
</code></pre>
<p>Using type() before my output, I verified it remains a string, but the output is as it was when name was a tuple</p>
| 1 | 2009-05-29T21:55:29Z | 928,340 | <p>I expect you have a problem with your parsing code. The lines as written should work as expected.</p>
| 2 | 2009-05-29T21:58:06Z | [
"python",
"string",
"dictionary",
"python-3.x"
] |
Formatting the output of a key from a dictionary | 928,330 | <p>I have a dictionary which store a string as the key, and an integer as the value. In my output I would like to have the key displayed as a string without parenthesis or commas. How would I do this?</p>
<pre><code>for f_name,f_loc in dict_func.items():
print ('Function names:\n\n\t{0} -- {1} lines of code\n'.format(f_name, f_loc))
</code></pre>
<p>output:</p>
<pre><code>Enter the file name: test.txt
line = 'def count_loc(infile):'
There were 19 lines of code in "test.txt"
Function names:
('count_loc(infile)',) -- 15 lines of code
</code></pre>
<p>Just incase it wasn't clear, I would like the last line of the output to be displayed as:</p>
<pre><code>count_loc(infile) -- 15 lines of code
</code></pre>
<p>EDIT </p>
<pre><code>name = re.search(func_pattern, line).groups()
name = str(name)
</code></pre>
<p>Using type() before my output, I verified it remains a string, but the output is as it was when name was a tuple</p>
| 1 | 2009-05-29T21:55:29Z | 928,342 | <p>I don't have Python 3 so I can't test this, but the output of f_name makes it look like it is a tuple with one element in it. So you would change <code>.format(f_name, f_loc)</code> to <code>.format(f_name[0], f_loc)</code></p>
<p><strong>EDIT</strong>:</p>
<p>In response to your edit, try using <a href="http://docs.python.org/library/re.html#re.MatchObject.group" rel="nofollow"><code>.group()</code></a> instead of <code>.groups()</code></p>
| 4 | 2009-05-29T21:58:14Z | [
"python",
"string",
"dictionary",
"python-3.x"
] |
Formatting the output of a key from a dictionary | 928,330 | <p>I have a dictionary which store a string as the key, and an integer as the value. In my output I would like to have the key displayed as a string without parenthesis or commas. How would I do this?</p>
<pre><code>for f_name,f_loc in dict_func.items():
print ('Function names:\n\n\t{0} -- {1} lines of code\n'.format(f_name, f_loc))
</code></pre>
<p>output:</p>
<pre><code>Enter the file name: test.txt
line = 'def count_loc(infile):'
There were 19 lines of code in "test.txt"
Function names:
('count_loc(infile)',) -- 15 lines of code
</code></pre>
<p>Just incase it wasn't clear, I would like the last line of the output to be displayed as:</p>
<pre><code>count_loc(infile) -- 15 lines of code
</code></pre>
<p>EDIT </p>
<pre><code>name = re.search(func_pattern, line).groups()
name = str(name)
</code></pre>
<p>Using type() before my output, I verified it remains a string, but the output is as it was when name was a tuple</p>
| 1 | 2009-05-29T21:55:29Z | 928,352 | <p>To elaborate on <a href="http://stackoverflow.com/questions/928330/formatting-the-output-of-a-key-from-a-dictionary/928340#928340">Peter's answer</a>, It looks to me like you're assigning a one-item <a href="http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange" rel="nofollow">tuple</a> as the key of your dictionary. If you're evaluating an expression in parentheses somewhere and using that as the key, be sure you don't have a stray comma in there.</p>
<p>Looking at your further edited answer, it's indeed because you're using the groups() method of your regex match. That returns a tuple of <code>(the entire matched section + all the matched groups)</code>, and since you have no groups, you want the entire thing. <code>group()</code> with no parameters will give you that.</p>
| 3 | 2009-05-29T22:00:23Z | [
"python",
"string",
"dictionary",
"python-3.x"
] |
Formatting the output of a key from a dictionary | 928,330 | <p>I have a dictionary which store a string as the key, and an integer as the value. In my output I would like to have the key displayed as a string without parenthesis or commas. How would I do this?</p>
<pre><code>for f_name,f_loc in dict_func.items():
print ('Function names:\n\n\t{0} -- {1} lines of code\n'.format(f_name, f_loc))
</code></pre>
<p>output:</p>
<pre><code>Enter the file name: test.txt
line = 'def count_loc(infile):'
There were 19 lines of code in "test.txt"
Function names:
('count_loc(infile)',) -- 15 lines of code
</code></pre>
<p>Just incase it wasn't clear, I would like the last line of the output to be displayed as:</p>
<pre><code>count_loc(infile) -- 15 lines of code
</code></pre>
<p>EDIT </p>
<pre><code>name = re.search(func_pattern, line).groups()
name = str(name)
</code></pre>
<p>Using type() before my output, I verified it remains a string, but the output is as it was when name was a tuple</p>
| 1 | 2009-05-29T21:55:29Z | 928,391 | <p>Since the key is some type of tuple, you may want to join the different elements before printing. We can't really tell what the significance of the key is from the snippet shown.</p>
<p>So you could do something like such:</p>
<pre><code>.format(", ".join(f_name), f_loc)
</code></pre>
| 1 | 2009-05-29T22:17:34Z | [
"python",
"string",
"dictionary",
"python-3.x"
] |
Tkinter: Changing a variable within a function | 928,520 | <p>I know this kind of question gets asked all the time but either i've been unable to come across the answer i need, or i've been unable to understand it when i did.</p>
<p>I want to be able to do something like:</p>
<pre><code>spam = StringVar()
spam.set(aValue)
class MyScale(Scale):
def __init__(self,var,*args,**kwargs):
Scale.__init__(self,*args,**kwargs)
self.bind("<ButtonRelease-1>",self.getValue)
self.set(var.get())
def getValue(self,event):
## spam gets changed to the new value set
## by the user manipulating the scale
var.set(self.get)
eggs = MyScale(spam,*args,**kwargs)
eggs.pack()
</code></pre>
<p>Of course, i get back "NameError: global name 'var' is not defined."</p>
<p>How do i get around the inability to pass arguments to getValue? I've been warned against using global variables but is that my only option? Is it setting up a separate scale class for each variable i want to change? I get the feeling i'm missing something thats right under my nose...</p>
<p>edit:
is this what you mean?</p>
<pre><code>Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python26\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "C:\...\interface.py", line 70, in getValue
var.set(self.get)
NameError: global name 'var' is not defined
</code></pre>
<p>Sorry, I've only been programming a month and some of the jargon still escapes me.</p>
| 1 | 2009-05-29T23:17:34Z | 928,554 | <p>Let's look at this method function</p>
<pre><code> def getValue(self,event):
## spam gets changed to the new value set
## by the user manipulating the scale
var.set(self.get)
</code></pre>
<p>The <code>var.set(self.get)</code> line has exactly two local variables available:</p>
<ul>
<li><code>self</code></li>
<li><code>event</code></li>
</ul>
<p>The variable <code>var</code> is not local to this method function. Perhaps it was used elsewhere in the class or script, but it's not local here.</p>
<p>It may, possibly, be global, but that's a bad practice.</p>
<p>I'm not sure why you'd think the variable <code>var</code> would be known in this context.</p>
| 1 | 2009-05-29T23:37:13Z | [
"python",
"tkinter"
] |
Tkinter: Changing a variable within a function | 928,520 | <p>I know this kind of question gets asked all the time but either i've been unable to come across the answer i need, or i've been unable to understand it when i did.</p>
<p>I want to be able to do something like:</p>
<pre><code>spam = StringVar()
spam.set(aValue)
class MyScale(Scale):
def __init__(self,var,*args,**kwargs):
Scale.__init__(self,*args,**kwargs)
self.bind("<ButtonRelease-1>",self.getValue)
self.set(var.get())
def getValue(self,event):
## spam gets changed to the new value set
## by the user manipulating the scale
var.set(self.get)
eggs = MyScale(spam,*args,**kwargs)
eggs.pack()
</code></pre>
<p>Of course, i get back "NameError: global name 'var' is not defined."</p>
<p>How do i get around the inability to pass arguments to getValue? I've been warned against using global variables but is that my only option? Is it setting up a separate scale class for each variable i want to change? I get the feeling i'm missing something thats right under my nose...</p>
<p>edit:
is this what you mean?</p>
<pre><code>Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python26\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "C:\...\interface.py", line 70, in getValue
var.set(self.get)
NameError: global name 'var' is not defined
</code></pre>
<p>Sorry, I've only been programming a month and some of the jargon still escapes me.</p>
| 1 | 2009-05-29T23:17:34Z | 929,100 | <p>Please give this a shot.</p>
<p>Lots of example code out there generously uses globals, like your "var" variable.</p>
<p>I have used your var argument to act as a pointer back to the original spam object; assigned to self.var_pointer within the MyScale class.</p>
<p>The code below will change the value of 'spam' (and 'eggs') on the scale's ButtonRelease.</p>
<p>You can check out the value by typing eggs.get() or spam.get() to see the changed value.</p>
<pre><code>from Tkinter import *
root = Tk()
aValue = "5"
spam = StringVar()
spam.set(aValue)
class MyScale(Scale):
def __init__(self,var,*args,**kwargs):
self.var_pointer = var
Scale.__init__(self,*args,**kwargs)
self.bind("<ButtonRelease-1>",self.getValue)
self.set(var.get())
def getValue(self,event):
## spam gets changed to the new value set
## by the user manipulating the scale
self.var_pointer.set(self.get())
eggs = MyScale(spam)
eggs.pack(anchor=CENTER)
</code></pre>
| 2 | 2009-05-30T05:45:14Z | [
"python",
"tkinter"
] |
How do I access the name of the class of an Object in Python? | 928,806 | <p>The title says it mostly.</p>
<p>If I have an object in Python and want to access the name of the class it is instantiated from is there a standard way to do this?</p>
| 1 | 2009-05-30T02:21:11Z | 928,810 | <pre><code>obj.__class__.__name__
</code></pre>
| 19 | 2009-05-30T02:23:00Z | [
"python"
] |
Python File Read + Write | 928,918 | <p>I am working on porting over a database from a custom MSSQL CMS to MYSQL - Wordpress. I am using Python to read a txt file with <code>\t</code> delineated columns and one row per line.</p>
<p>I am trying to write a Python script that will read this file (fread) and [eventually] create a MYSSQL ready .sql file with insert statements.</p>
<p>A line in the file I'm reading looks something like:</p>
<pre><code>1 John Smith Developer http://twiiter.com/johns Chicago, IL
</code></pre>
<p>My Python script so far:</p>
<pre><code>import sys
fwrite = open('d:/icm_db/wp_sql/wp.users.sql','w')
fread = open('d:/icm_db/users.txt','r')
for line in fread:
print line;
fread.close()
fwrite.close()
</code></pre>
<p>How can I "implode" each line so I can access each column and do business on it?</p>
<p>I need to generate multiple MYSQL insert statements per line I read. So... for each line read, I'd generate something like:</p>
<pre><code>INSERT INTO `wp_users` (`ID`, `user_login`, `user_name`)
VALUES (line[0], 'line[2]', 'line[3]');
</code></pre>
| 4 | 2009-05-30T03:21:24Z | 928,927 | <p>What you probably want is something like this:
<code>data=line.split("\t")</code><br/>It'll give you a nice sequence object to work with.<br/>
(By the way, no need for semicolons in Python. There's one here: <code>print line;</code>)<br/><br/>As Dave pointed out, this might leave a newline in there. Call strip() on line before splitting, like so: <code>line.strip().split("\t")</code></p>
| 0 | 2009-05-30T03:25:16Z | [
"python",
"file"
] |
Python File Read + Write | 928,918 | <p>I am working on porting over a database from a custom MSSQL CMS to MYSQL - Wordpress. I am using Python to read a txt file with <code>\t</code> delineated columns and one row per line.</p>
<p>I am trying to write a Python script that will read this file (fread) and [eventually] create a MYSSQL ready .sql file with insert statements.</p>
<p>A line in the file I'm reading looks something like:</p>
<pre><code>1 John Smith Developer http://twiiter.com/johns Chicago, IL
</code></pre>
<p>My Python script so far:</p>
<pre><code>import sys
fwrite = open('d:/icm_db/wp_sql/wp.users.sql','w')
fread = open('d:/icm_db/users.txt','r')
for line in fread:
print line;
fread.close()
fwrite.close()
</code></pre>
<p>How can I "implode" each line so I can access each column and do business on it?</p>
<p>I need to generate multiple MYSQL insert statements per line I read. So... for each line read, I'd generate something like:</p>
<pre><code>INSERT INTO `wp_users` (`ID`, `user_login`, `user_name`)
VALUES (line[0], 'line[2]', 'line[3]');
</code></pre>
| 4 | 2009-05-30T03:21:24Z | 928,937 | <p>The Python Standard Library has a module for <a href="http://docs.python.org/library/csv.html" rel="nofollow">CSV (comma separated value) file reading and writing</a> that can be made to work on tab separated files like your one. It's probably overkill for this task.</p>
| 0 | 2009-05-30T03:32:11Z | [
"python",
"file"
] |
Python File Read + Write | 928,918 | <p>I am working on porting over a database from a custom MSSQL CMS to MYSQL - Wordpress. I am using Python to read a txt file with <code>\t</code> delineated columns and one row per line.</p>
<p>I am trying to write a Python script that will read this file (fread) and [eventually] create a MYSSQL ready .sql file with insert statements.</p>
<p>A line in the file I'm reading looks something like:</p>
<pre><code>1 John Smith Developer http://twiiter.com/johns Chicago, IL
</code></pre>
<p>My Python script so far:</p>
<pre><code>import sys
fwrite = open('d:/icm_db/wp_sql/wp.users.sql','w')
fread = open('d:/icm_db/users.txt','r')
for line in fread:
print line;
fread.close()
fwrite.close()
</code></pre>
<p>How can I "implode" each line so I can access each column and do business on it?</p>
<p>I need to generate multiple MYSQL insert statements per line I read. So... for each line read, I'd generate something like:</p>
<pre><code>INSERT INTO `wp_users` (`ID`, `user_login`, `user_name`)
VALUES (line[0], 'line[2]', 'line[3]');
</code></pre>
| 4 | 2009-05-30T03:21:24Z | 928,943 | <p>Although this is easily doable, it does become easier with the <a href="http://docs.python.org/library/csv.html">csv</a> module.</p>
<pre><code>>>> import csv
>>> reader = csv.reader(open('C:/www/stackoverflow.txt'), delimiter='\t')
>>> for row in reader:
... print row
...
['1', 'John Smith', 'Developer', 'http://twiiter.com/johns', 'Chicago, IL']
['2', 'John Doe', 'Developer', 'http://whatever.com', 'Tallahassee, FL']
</code></pre>
<p>Also, as pointed out, semicolons are not needed in Python. Try to kick that habit :)</p>
| 9 | 2009-05-30T03:38:16Z | [
"python",
"file"
] |
Python File Read + Write | 928,918 | <p>I am working on porting over a database from a custom MSSQL CMS to MYSQL - Wordpress. I am using Python to read a txt file with <code>\t</code> delineated columns and one row per line.</p>
<p>I am trying to write a Python script that will read this file (fread) and [eventually] create a MYSSQL ready .sql file with insert statements.</p>
<p>A line in the file I'm reading looks something like:</p>
<pre><code>1 John Smith Developer http://twiiter.com/johns Chicago, IL
</code></pre>
<p>My Python script so far:</p>
<pre><code>import sys
fwrite = open('d:/icm_db/wp_sql/wp.users.sql','w')
fread = open('d:/icm_db/users.txt','r')
for line in fread:
print line;
fread.close()
fwrite.close()
</code></pre>
<p>How can I "implode" each line so I can access each column and do business on it?</p>
<p>I need to generate multiple MYSQL insert statements per line I read. So... for each line read, I'd generate something like:</p>
<pre><code>INSERT INTO `wp_users` (`ID`, `user_login`, `user_name`)
VALUES (line[0], 'line[2]', 'line[3]');
</code></pre>
| 4 | 2009-05-30T03:21:24Z | 928,953 | <p>Knowing the exact number of columns helps self document your code:</p>
<pre><code>fwrite = open("d:/icm_db/wp_sql/wp.users.sql","w")
for line in open("d:/icm_db/users.txt"):
name, title, login, location = line.strip().split("\t")
# Double up on those single quotes to avoid nasty SQL!
safe_name = name.replace("'","''")
safe_login = name.replace("'","''")
# ID field is primary key and will auto-increment
fwrite.write( "INSERT INTO `wp_users` (`user_login`, `user_name`) " )
fwrite.write( "VALUES ('%s','%s');\n" % (safe_name,safe_login) )
</code></pre>
| 1 | 2009-05-30T03:48:39Z | [
"python",
"file"
] |
Python File Read + Write | 928,918 | <p>I am working on porting over a database from a custom MSSQL CMS to MYSQL - Wordpress. I am using Python to read a txt file with <code>\t</code> delineated columns and one row per line.</p>
<p>I am trying to write a Python script that will read this file (fread) and [eventually] create a MYSSQL ready .sql file with insert statements.</p>
<p>A line in the file I'm reading looks something like:</p>
<pre><code>1 John Smith Developer http://twiiter.com/johns Chicago, IL
</code></pre>
<p>My Python script so far:</p>
<pre><code>import sys
fwrite = open('d:/icm_db/wp_sql/wp.users.sql','w')
fread = open('d:/icm_db/users.txt','r')
for line in fread:
print line;
fread.close()
fwrite.close()
</code></pre>
<p>How can I "implode" each line so I can access each column and do business on it?</p>
<p>I need to generate multiple MYSQL insert statements per line I read. So... for each line read, I'd generate something like:</p>
<pre><code>INSERT INTO `wp_users` (`ID`, `user_login`, `user_name`)
VALUES (line[0], 'line[2]', 'line[3]');
</code></pre>
| 4 | 2009-05-30T03:21:24Z | 928,973 | <pre><code>fwrite = open('/home/lyrae/Desktop/E/wp.users.sql','a')
fread = open('/home/lyrae/Desktop/E/users.txt','r')
for line in fread:
line = line.split("\t")
fwrite.write("insert into wp_users ( ID, user_login, user_name ) values (%s, '%s', '%s')\n" % (line[0], line[1], line[2]))
fread.close()
fwrite.close()
</code></pre>
<p>Assuming users.txt is:</p>
<pre><code>1 John Smith Developer http://twiiter.com/johns Chicago, IL
2 Billy bob Developer http://twiiter.com/johns Chicago, IL
3 John Smith Developer http://twiiter.com/johns Chicago, IL
</code></pre>
<p>wp.users.sql will look like:</p>
<pre><code>insert into wp_users ( ID, user_login, user_name ) values (1, 'John Smith', 'Developer')
insert into wp_users ( ID, user_login, user_name ) values (2, 'Billy bob', 'Developer')
insert into wp_users ( ID, user_login, user_name ) values (3, 'John Smith', 'Developer')
</code></pre>
<p>Assuming only 1 tab separates the id, name, position</p>
| 0 | 2009-05-30T04:08:45Z | [
"python",
"file"
] |
Looping over a Python / IronPython Object Methods | 928,990 | <p>What is the proper way to loop over a Python object's methods and call them?</p>
<p>Given the object:</p>
<pre><code>class SomeTest():
def something1(self):
print "something 1"
def something2(self):
print "something 2"
</code></pre>
| 3 | 2009-05-30T04:24:46Z | 928,997 | <h3>Edit</h3>
<p>Daniel, you are wrong.</p>
<p><a href="http://docs.python.org/reference/datamodel.html" rel="nofollow">http://docs.python.org/reference/datamodel.html</a></p>
<blockquote>
<p>User-defined methods</p>
<p>A user-defined <strong>method</strong> object <strong>combines a class, a class instance</strong> (or
None) and <strong>any callable object</strong> (normally a user-defined function).</p>
</blockquote>
<p>Therefore, anything that defines __call__ and is attached to an object is a method.</p>
<h3>Answer</h3>
<p>The proper way to see what elements an object has is to use the dir() function.</p>
<p>Obviously this example only works for functions that take no arguments.</p>
<pre><code>a=SomeTest()
for varname in dir(a):
var = getattr(a, varname)
if hasattr(var, "__call__"):
var()
</code></pre>
| -1 | 2009-05-30T04:30:56Z | [
"python",
"reflection",
"ironpython",
"introspection",
"python-datamodel"
] |
Looping over a Python / IronPython Object Methods | 928,990 | <p>What is the proper way to loop over a Python object's methods and call them?</p>
<p>Given the object:</p>
<pre><code>class SomeTest():
def something1(self):
print "something 1"
def something2(self):
print "something 2"
</code></pre>
| 3 | 2009-05-30T04:24:46Z | 1,191,333 | <p>Methods vs. functions and other types of callables...</p>
<p>(To address the issue in the comments in Unknown's post.)</p>
<p>First, it should be noted that, in addition to user-defined methods, there are built-in methods, and a built-in method is, as the doc at <a href="http://docs.python.org/reference/datamodel.html" rel="nofollow">http://docs.python.org/reference/datamodel.html</a> says, "really a different disguise of a built-in function" (which is a wrapper around a C function.)</p>
<p>As for user-defined methods, as Unknown's cited quote says:</p>
<blockquote>
<p>A user-defined method object combines
a class, a class instance (or None)
and any callable object (normally a
user-defined function).</p>
</blockquote>
<p>But this does not mean that "anything that defines <code>__call__</code> and is attached to an object is a method." A method is a callable, but a callable is not necessarily a method. User-defined methods are wrappers around what the quote says.</p>
<p>Hopefully this output (from Python 2.5.2 which I have handy) will show the distinction:</p>
<pre><code>IDLE 1.2.2
>>> class A(object):
x = 7
>>> A # show the class object
<class '__main__.A'>
>>> a = A()
>>> a # show the instance
<__main__.A object at 0x021AFBF0>
>>> def test_func(self):
print self.x
>>> type(test_func) # what type is it?
<type 'function'>
>>> dir(test_func) # what does it have?
['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__',
'__getattribute__', '__hash__', '__init__', '__module__', '__name__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict',
'func_doc', 'func_globals', 'func_name']
>>> # But now let's put test_func on the class...
>>> A.test = test_func
>>> type(A.test) # What type does this show?
<type 'instancemethod'>
>>> dir(A.test) # And what does it have?
['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__get__',
'__getattribute__', '__hash__', '__init__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__str__', 'im_class',
'im_func', 'im_self']
>>> # See, we just got a wrapper, and the function is in 'im_func'...
>>> getattr(A.test, 'im_func')
<function test_func at 0x0219F4B0>
>>> # Now to show bound vs. unbound methods...
>>> getattr(a.test, 'im_self') # Accessing it via the instance
<__main__.A object at 0x021AFBF0>
>>> # The instance is itself 'im_self'
>>> a.test()
7
>>> getattr(A.test, 'im_self') # Accessing it via the class returns None...
>>> print getattr(A.test, 'im_self')
None
>>> # It's unbound when accessed that way, so there's no instance in there
>>> # Which is why the following fails...
>>> A.test()
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
A.test()
TypeError: unbound method test_func() must be called with A instance as
first argument (got nothing instead)
>>>
</code></pre>
<p>And - editing to add the following additional output, which is also relevant...</p>
<pre><code>>>> class B(object):
pass
>>> b = B()
>>> b.test = test_func # Putting the function on the instance, not class
>>> type(b.test)
<type 'function'>
>>>
</code></pre>
<p>I wont add more output, but you could also make a class an attribute of another class or instance, and, even though classes are callable, you would not get a method. Methods are implemented using non-data descriptors, so look up descriptors if you want more info on how they work.</p>
| 3 | 2009-07-28T00:21:36Z | [
"python",
"reflection",
"ironpython",
"introspection",
"python-datamodel"
] |
Looping over a Python / IronPython Object Methods | 928,990 | <p>What is the proper way to loop over a Python object's methods and call them?</p>
<p>Given the object:</p>
<pre><code>class SomeTest():
def something1(self):
print "something 1"
def something2(self):
print "something 2"
</code></pre>
| 3 | 2009-05-30T04:24:46Z | 1,447,529 | <p>You can use the inspect module to get class (or instance) members:</p>
<pre><code>>>> class C(object):
... a = 'blah'
... def b(self):
... pass
...
...
>>> c = C()
>>> inspect.getmembers(c, inspect.ismethod)
[('b', <bound method C.b of <__main__.C object at 0x100498250>>)]
</code></pre>
<p>getmembers() returns a list of tuples, where each tuple is (name, member). The second argument to getmembers() is the predicate, which filters the return list (in this case, returning only method objects)</p>
| 7 | 2009-09-19T02:17:33Z | [
"python",
"reflection",
"ironpython",
"introspection",
"python-datamodel"
] |
Looping over a Python / IronPython Object Methods | 928,990 | <p>What is the proper way to loop over a Python object's methods and call them?</p>
<p>Given the object:</p>
<pre><code>class SomeTest():
def something1(self):
print "something 1"
def something2(self):
print "something 2"
</code></pre>
| 3 | 2009-05-30T04:24:46Z | 3,911,435 | <p>This code snippet will call anything it will find in <code>obj</code> and store results in mapping, where key is attribute name â <code>dict((k, v()) for (k, v) in obj.__dict__.iteritems() if k.startswith('something'))</code></p>
| 0 | 2010-10-12T03:13:23Z | [
"python",
"reflection",
"ironpython",
"introspection",
"python-datamodel"
] |
How do I access the child classes of an object in django without knowing the name of the child class? | 929,029 | <p>In Django, when you have a parent class and multiple child classes that inherit from it you would normally access a child through parentclass.childclass1_set or parentclass.childclass2_set, but what if I don't know the name of the specific child class I want?</p>
<p>Is there a way to get the related objects in the parent->child direction without knowing the child class name?</p>
| 63 | 2009-05-30T04:52:56Z | 929,073 | <p>You can achieve this looking for all the fields in the parent that are an instance of django.db.models.fields.related.RelatedManager. From your example it seems that the child classes you are talking about are not subclasses. Right?</p>
| 0 | 2009-05-30T05:23:19Z | [
"python",
"django",
"many-to-many"
] |
How do I access the child classes of an object in django without knowing the name of the child class? | 929,029 | <p>In Django, when you have a parent class and multiple child classes that inherit from it you would normally access a child through parentclass.childclass1_set or parentclass.childclass2_set, but what if I don't know the name of the specific child class I want?</p>
<p>Is there a way to get the related objects in the parent->child direction without knowing the child class name?</p>
| 63 | 2009-05-30T04:52:56Z | 929,128 | <p>In Python, given a ("new-style") class X, you can get its (direct) subclasses with <code>X.__subclasses__()</code>, which returns a list of class objects. (If you want "further descendants", you'll also have to call <code>__subclasses__</code> on each of the direct subclasses, etc etc -- if you need help on how to do that effectively in Python, just ask!).</p>
<p>Once you have somehow identified a child class of interest (maybe all of them, if you want instances of all child subclasses, etc), <code>getattr(parentclass,'%s_set' % childclass.__name__)</code> should help (if the child class's name is <code>'foo'</code>, this is just like accessing <code>parentclass.foo_set</code> -- no more, no less). Again, if you need clarification or examples, please ask!</p>
| 15 | 2009-05-30T06:02:24Z | [
"python",
"django",
"many-to-many"
] |
How do I access the child classes of an object in django without knowing the name of the child class? | 929,029 | <p>In Django, when you have a parent class and multiple child classes that inherit from it you would normally access a child through parentclass.childclass1_set or parentclass.childclass2_set, but what if I don't know the name of the specific child class I want?</p>
<p>Is there a way to get the related objects in the parent->child direction without knowing the child class name?</p>
| 63 | 2009-05-30T04:52:56Z | 929,982 | <p>(<strong>Update</strong>: For Django 1.2 and newer, which can follow select_related queries across reverse OneToOneField relations (and thus down inheritance hierarchies), there's a better technique available which doesn't require the added <code>real_type</code> field on the parent model. It's available as <a href="https://django-model-utils.readthedocs.org/en/latest/managers.html#inheritancemanager" rel="nofollow">InheritanceManager</a> in the <a href="https://github.com/carljm/django-model-utils/" rel="nofollow">django-model-utils</a> project.)</p>
<p>The usual way to do this is to add a ForeignKey to ContentType on the Parent model which stores the content type of the proper "leaf" class. Without this, you may have to do quite a number of queries on child tables to find the instance, depending how large your inheritance tree is. Here's how I did it in one project:</p>
<pre><code>from django.contrib.contenttypes.models import ContentType
from django.db import models
class InheritanceCastModel(models.Model):
"""
An abstract base class that provides a ``real_type`` FK to ContentType.
For use in trees of inherited models, to be able to downcast
parent instances to their child types.
"""
real_type = models.ForeignKey(ContentType, editable=False)
def save(self, *args, **kwargs):
if not self._state.adding:
self.real_type = self._get_real_type()
super(InheritanceCastModel, self).save(*args, **kwargs)
def _get_real_type(self):
return ContentType.objects.get_for_model(type(self))
def cast(self):
return self.real_type.get_object_for_this_type(pk=self.pk)
class Meta:
abstract = True
</code></pre>
<p>This is implemented as an abstract base class to make it reusable; you could also put these methods and the FK directly onto the parent class in your particular inheritance hierarchy.</p>
<p>This solution won't work if you aren't able to modify the parent model. In that case you're pretty much stuck checking all the subclasses manually.</p>
| 74 | 2009-05-30T15:47:56Z | [
"python",
"django",
"many-to-many"
] |
How do I access the child classes of an object in django without knowing the name of the child class? | 929,029 | <p>In Django, when you have a parent class and multiple child classes that inherit from it you would normally access a child through parentclass.childclass1_set or parentclass.childclass2_set, but what if I don't know the name of the specific child class I want?</p>
<p>Is there a way to get the related objects in the parent->child direction without knowing the child class name?</p>
| 63 | 2009-05-30T04:52:56Z | 930,709 | <p>Carl's solution is a good one, here's one way to do it manually if there are multiple related child classes:</p>
<pre><code>def get_children(self):
rel_objs = self._meta.get_all_related_objects()
return [getattr(self, x.get_accessor_name()) for x in rel_objs if x.model != type(self)]
</code></pre>
<p>It uses a function out of _meta, which is not guaranteed to be stable as django evolves, but it does the trick and can be used on-the-fly if need be.</p>
| 4 | 2009-05-30T22:01:08Z | [
"python",
"django",
"many-to-many"
] |
How do I access the child classes of an object in django without knowing the name of the child class? | 929,029 | <p>In Django, when you have a parent class and multiple child classes that inherit from it you would normally access a child through parentclass.childclass1_set or parentclass.childclass2_set, but what if I don't know the name of the specific child class I want?</p>
<p>Is there a way to get the related objects in the parent->child direction without knowing the child class name?</p>
| 63 | 2009-05-30T04:52:56Z | 972,789 | <p>It turns out that what I really needed was this:</p>
<p><a href="http://www.djangosnippets.org/snippets/1034/">Model inheritance with content type and inheritance-aware manager</a></p>
<p>That has worked perfectly for me. Thanks to everyone else, though. I learned a lot just reading your answers!</p>
| 5 | 2009-06-09T22:20:31Z | [
"python",
"django",
"many-to-many"
] |
How do I access the child classes of an object in django without knowing the name of the child class? | 929,029 | <p>In Django, when you have a parent class and multiple child classes that inherit from it you would normally access a child through parentclass.childclass1_set or parentclass.childclass2_set, but what if I don't know the name of the specific child class I want?</p>
<p>Is there a way to get the related objects in the parent->child direction without knowing the child class name?</p>
| 63 | 2009-05-30T04:52:56Z | 12,425,895 | <p>An alternative approach using proxies can be found in <a href="http://anthony-tresontani.github.com/Python/2012/09/11/django-polymorphism/" rel="nofollow">this blog post</a>. Like the other solutions, it has its benefits and liabilities, which are very well put in the end of the post.</p>
| 0 | 2012-09-14T13:47:42Z | [
"python",
"django",
"many-to-many"
] |
How do I access the child classes of an object in django without knowing the name of the child class? | 929,029 | <p>In Django, when you have a parent class and multiple child classes that inherit from it you would normally access a child through parentclass.childclass1_set or parentclass.childclass2_set, but what if I don't know the name of the specific child class I want?</p>
<p>Is there a way to get the related objects in the parent->child direction without knowing the child class name?</p>
| 63 | 2009-05-30T04:52:56Z | 12,608,181 | <p>Here's my solution, again it uses <code>_meta</code> so isn't guaranteed to be stable.</p>
<pre><code>class Animal(models.model):
name = models.CharField()
number_legs = models.IntegerField()
...
def get_child_animal(self):
child_animal = None
for r in self._meta.get_all_related_objects():
if r.field.name == 'animal_ptr':
child_animal = getattr(self, r.get_accessor_name())
if not child_animal:
raise Exception("No subclass, you shouldn't create Animals directly")
return child_animal
class Dog(Animal):
...
for a in Animal.objects.all():
a.get_child_animal() # returns the dog (or whatever) instance
</code></pre>
| 1 | 2012-09-26T18:32:38Z | [
"python",
"django",
"many-to-many"
] |
How do I access the child classes of an object in django without knowing the name of the child class? | 929,029 | <p>In Django, when you have a parent class and multiple child classes that inherit from it you would normally access a child through parentclass.childclass1_set or parentclass.childclass2_set, but what if I don't know the name of the specific child class I want?</p>
<p>Is there a way to get the related objects in the parent->child direction without knowing the child class name?</p>
| 63 | 2009-05-30T04:52:56Z | 16,658,889 | <p>You can use <a href="https://github.com/chrisglass/django_polymorphic" rel="nofollow">django-polymorphic</a> for that.</p>
| 1 | 2013-05-20T21:43:09Z | [
"python",
"django",
"many-to-many"
] |
Eclipse + AppEngine =? autocomplete | 929,095 | <p>I was doing some beginner AppEngine dev on a Windows box and installed Eclipse for that. I liked the autocompletion I got with the objects and functions.</p>
<p>I moved my dev environment over to my Macbook, and installed Eclipse Ganymede. I installed the AppEngine SDK and Eclipse plug in. However, when I am typing out code now, the autocomplete isn't functioning. Did I miss a step?</p>
<p>UPDATE</p>
<p>Just to add to this:</p>
<p>the line:</p>
<pre><code>import cgi
</code></pre>
<p>appears to give me what I need. When I type "cgi." I get all of the auto complete. However, the lines:</p>
<pre><code>from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
</code></pre>
<p>don't give me any auto complete. If I type "users." there is no auto complete.</p>
| 0 | 2009-05-30T05:41:17Z | 930,606 | <ol>
<li>Do you have any form of 'Java Proposals' checked in Java->Editor->Content Assist->Advanced (see below)?</li>
<li>Do you have any messages in your error log?</li>
</ol>
<p><img src="http://img26.imageshack.us/img26/2663/completionpreferences.png" alt="Preferences" /></p>
| 0 | 2009-05-30T21:00:38Z | [
"python",
"eclipse",
"google-app-engine"
] |
Eclipse + AppEngine =? autocomplete | 929,095 | <p>I was doing some beginner AppEngine dev on a Windows box and installed Eclipse for that. I liked the autocompletion I got with the objects and functions.</p>
<p>I moved my dev environment over to my Macbook, and installed Eclipse Ganymede. I installed the AppEngine SDK and Eclipse plug in. However, when I am typing out code now, the autocomplete isn't functioning. Did I miss a step?</p>
<p>UPDATE</p>
<p>Just to add to this:</p>
<p>the line:</p>
<pre><code>import cgi
</code></pre>
<p>appears to give me what I need. When I type "cgi." I get all of the auto complete. However, the lines:</p>
<pre><code>from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
</code></pre>
<p>don't give me any auto complete. If I type "users." there is no auto complete.</p>
| 0 | 2009-05-30T05:41:17Z | 932,259 | <p>The App Engine plugin for eclipse is for the Java SDK, not for the Python one. I don't know eclipse very well, but I suspect what you're missing is simply the path to the App Engine SDK included in eclipse's pythonpath configuration. Find somewhere to add that, and it'll be able to find the SDK classes and offer autocomplete suggestions for them.</p>
| 2 | 2009-05-31T15:33:55Z | [
"python",
"eclipse",
"google-app-engine"
] |
Eclipse + AppEngine =? autocomplete | 929,095 | <p>I was doing some beginner AppEngine dev on a Windows box and installed Eclipse for that. I liked the autocompletion I got with the objects and functions.</p>
<p>I moved my dev environment over to my Macbook, and installed Eclipse Ganymede. I installed the AppEngine SDK and Eclipse plug in. However, when I am typing out code now, the autocomplete isn't functioning. Did I miss a step?</p>
<p>UPDATE</p>
<p>Just to add to this:</p>
<p>the line:</p>
<pre><code>import cgi
</code></pre>
<p>appears to give me what I need. When I type "cgi." I get all of the auto complete. However, the lines:</p>
<pre><code>from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
</code></pre>
<p>don't give me any auto complete. If I type "users." there is no auto complete.</p>
| 0 | 2009-05-30T05:41:17Z | 945,606 | <p>To have Eclipse auto-complete your Python code you need to install Pydev into Eclipse.</p>
<p>It's a free plug-in and is available here: <a href="http://aptana.com/python" rel="nofollow">http://aptana.com/python</a></p>
<p>The URL to use when updating Eclipse:
<a href="http://pydev.sourceforge.net/updates/" rel="nofollow">http://pydev.sourceforge.net/updates/</a>
(In Eclipse, select 'Help/Software Updates...')</p>
<p>An enhanced version of the plug-in called Pydev Extensions (costs: <a href="http://www.fabioz.com/pydev/buy.html" rel="nofollow">http://www.fabioz.com/pydev/buy.html</a>) that provides more functionality including code-analysis, code completion with auto-import and remote debugging.</p>
| 0 | 2009-06-03T16:09:02Z | [
"python",
"eclipse",
"google-app-engine"
] |
Eclipse + AppEngine =? autocomplete | 929,095 | <p>I was doing some beginner AppEngine dev on a Windows box and installed Eclipse for that. I liked the autocompletion I got with the objects and functions.</p>
<p>I moved my dev environment over to my Macbook, and installed Eclipse Ganymede. I installed the AppEngine SDK and Eclipse plug in. However, when I am typing out code now, the autocomplete isn't functioning. Did I miss a step?</p>
<p>UPDATE</p>
<p>Just to add to this:</p>
<p>the line:</p>
<pre><code>import cgi
</code></pre>
<p>appears to give me what I need. When I type "cgi." I get all of the auto complete. However, the lines:</p>
<pre><code>from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
</code></pre>
<p>don't give me any auto complete. If I type "users." there is no auto complete.</p>
| 0 | 2009-05-30T05:41:17Z | 961,360 | <p>I found the answer from a poster on the Google App Engine forum. I will blog the experience later, but this one gets a FAIL for GOOG. You need to click on the download link for "Linux/Other" to get the ZIP file with the right files. You can then point your PYTHONPATH at the directory on your local machine.</p>
<p>The fail here is that the Mac SDK download gives you the AppEngineLauncher, but not these files. Nowhere on the AppEngine site, or in the directions GOOG publishes, do they suggest that as a Mac developer that you should download these "other" files. Very, very, very annoying.</p>
| 0 | 2009-06-07T06:57:52Z | [
"python",
"eclipse",
"google-app-engine"
] |
Eclipse + AppEngine =? autocomplete | 929,095 | <p>I was doing some beginner AppEngine dev on a Windows box and installed Eclipse for that. I liked the autocompletion I got with the objects and functions.</p>
<p>I moved my dev environment over to my Macbook, and installed Eclipse Ganymede. I installed the AppEngine SDK and Eclipse plug in. However, when I am typing out code now, the autocomplete isn't functioning. Did I miss a step?</p>
<p>UPDATE</p>
<p>Just to add to this:</p>
<p>the line:</p>
<pre><code>import cgi
</code></pre>
<p>appears to give me what I need. When I type "cgi." I get all of the auto complete. However, the lines:</p>
<pre><code>from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
</code></pre>
<p>don't give me any auto complete. If I type "users." there is no auto complete.</p>
| 0 | 2009-05-30T05:41:17Z | 13,116,061 | <ol>
<li>Add library
<a href="http://stackoverflow.com/questions/7756981/pydev-project-for-google-app-engine-not-finding-webapp2">PyDev project for Google App Engine not finding webapp2</a></li>
<li>Create pydev GAE project now
<a href="http://www.mkyong.com/google-app-engine/google-app-engine-python-hello-world-example-using-eclipse/" rel="nofollow">http://www.mkyong.com/google-app-engine/google-app-engine-python-hello-world-example-using-eclipse/</a></li>
</ol>
<p>or add a library similar to this
<a href="https://developers.google.com/appengine/articles/eclipse" rel="nofollow">https://developers.google.com/appengine/articles/eclipse</a></p>
| 1 | 2012-10-29T04:57:51Z | [
"python",
"eclipse",
"google-app-engine"
] |
Convert a number range to another range, maintaining ratio | 929,103 | <p>I'm trying to convert one range of numbers to another, maintaining ratio. Maths is not my strong point.</p>
<p>I have an image file where point values may range from -16000.00 to 16000.00 though the typical range may be much less. What I want to do is compress these values into the integer range 0-100, where 0 is the value of the smallest point, and 100 is the value of the largest. All points in between should keep a relative ratio even though some precision is being lost I'd like to do this in python but even a general algorithm should suffice. I'd prefer an algorithm where the min/max or either range can be adjusted (ie, the second range could be -50 to 800 instead of 0 to 100).</p>
| 135 | 2009-05-30T05:48:22Z | 929,104 | <p>That's a simple linear conversion.</p>
<pre><code>new_value = ( (old_value - old_min) / (old_max - old_min) ) * (new_max - new_min) + new_min
</code></pre>
<p>So converting 10000 on the scale of -16000 to 16000 to a new scale of 0 to 100 yields:</p>
<pre><code>old_value = 10000
old_min = -16000
old_max = 16000
new_min = 0
new_max = 100
new_value = ( ( 10000 - -16000 ) / (16000 - -16000) ) * (100 - 0) + 0
= 81.25
</code></pre>
| 39 | 2009-05-30T05:50:45Z | [
"python",
"math"
] |
Convert a number range to another range, maintaining ratio | 929,103 | <p>I'm trying to convert one range of numbers to another, maintaining ratio. Maths is not my strong point.</p>
<p>I have an image file where point values may range from -16000.00 to 16000.00 though the typical range may be much less. What I want to do is compress these values into the integer range 0-100, where 0 is the value of the smallest point, and 100 is the value of the largest. All points in between should keep a relative ratio even though some precision is being lost I'd like to do this in python but even a general algorithm should suffice. I'd prefer an algorithm where the min/max or either range can be adjusted (ie, the second range could be -50 to 800 instead of 0 to 100).</p>
| 135 | 2009-05-30T05:48:22Z | 929,107 | <pre><code>NewValue = (((OldValue - OldMin) * (NewMax - NewMin)) / (OldMax - OldMin)) + NewMin
</code></pre>
<p>Or a little more readable: </p>
<pre><code>OldRange = (OldMax - OldMin)
NewRange = (NewMax - NewMin)
NewValue = (((OldValue - OldMin) * NewRange) / OldRange) + NewMin
</code></pre>
<p>Or if you want to protect for the case where the old range is 0 (<em>OldMin = OldMax</em>):</p>
<pre><code>OldRange = (OldMax - OldMin)
if (OldRange == 0)
NewValue = NewMin
else
{
NewRange = (NewMax - NewMin)
NewValue = (((OldValue - OldMin) * NewRange) / OldRange) + NewMin
}
</code></pre>
<p>Note that in this case we're forced to pick one of the possible new range values arbitrarily. Depending on context, sensible choices could be: <code>NewMin</code> (<em>see sample</em>), <code>NewMax</code> or <code>(NewMin + NewMax) / 2</code></p>
| 244 | 2009-05-30T05:52:21Z | [
"python",
"math"
] |
Convert a number range to another range, maintaining ratio | 929,103 | <p>I'm trying to convert one range of numbers to another, maintaining ratio. Maths is not my strong point.</p>
<p>I have an image file where point values may range from -16000.00 to 16000.00 though the typical range may be much less. What I want to do is compress these values into the integer range 0-100, where 0 is the value of the smallest point, and 100 is the value of the largest. All points in between should keep a relative ratio even though some precision is being lost I'd like to do this in python but even a general algorithm should suffice. I'd prefer an algorithm where the min/max or either range can be adjusted (ie, the second range could be -50 to 800 instead of 0 to 100).</p>
| 135 | 2009-05-30T05:48:22Z | 11,405,720 | <p>There is a condition, when all of the values that you are checking are the same, where @jerryjvl's code would return NaN.</p>
<pre><code>if (OldMin != OldMax && NewMin != NewMax):
return (((OldValue - OldMin) * (NewMax - NewMin)) / (OldMax - OldMin)) + NewMin
else:
return (NewMax + NewMin) / 2
</code></pre>
| 8 | 2012-07-10T02:11:52Z | [
"python",
"math"
] |
Convert a number range to another range, maintaining ratio | 929,103 | <p>I'm trying to convert one range of numbers to another, maintaining ratio. Maths is not my strong point.</p>
<p>I have an image file where point values may range from -16000.00 to 16000.00 though the typical range may be much less. What I want to do is compress these values into the integer range 0-100, where 0 is the value of the smallest point, and 100 is the value of the largest. All points in between should keep a relative ratio even though some precision is being lost I'd like to do this in python but even a general algorithm should suffice. I'd prefer an algorithm where the min/max or either range can be adjusted (ie, the second range could be -50 to 800 instead of 0 to 100).</p>
| 135 | 2009-05-30T05:48:22Z | 15,537,393 | <p>Actually there are some cases that above answers would break.
Such as wrongly input value, wrongly input range, negative input/output ranges.</p>
<pre><code>def remap( x, oMin, oMax, nMin, nMax ):
#range check
if oMin == oMax:
print "Warning: Zero input range"
return None
if nMin == nMax:
print "Warning: Zero output range"
return None
#check reversed input range
reverseInput = False
oldMin = min( oMin, oMax )
oldMax = max( oMin, oMax )
if not oldMin == oMin:
reverseInput = True
#check reversed output range
reverseOutput = False
newMin = min( nMin, nMax )
newMax = max( nMin, nMax )
if not newMin == nMin :
reverseOutput = True
portion = (x-oldMin)*(newMax-newMin)/(oldMax-oldMin)
if reverseInput:
portion = (oldMax-x)*(newMax-newMin)/(oldMax-oldMin)
result = portion + newMin
if reverseOutput:
result = newMax - portion
return result
#test cases
print remap( 25.0, 0.0, 100.0, 1.0, -1.0 ), "==", 0.5
print remap( 25.0, 100.0, -100.0, -1.0, 1.0 ), "==", -0.25
print remap( -125.0, -100.0, -200.0, 1.0, -1.0 ), "==", 0.5
print remap( -125.0, -200.0, -100.0, -1.0, 1.0 ), "==", 0.5
#even when value is out of bound
print remap( -20.0, 0.0, 100.0, 0.0, 1.0 ), "==", -0.2
</code></pre>
| 13 | 2013-03-21T00:32:53Z | [
"python",
"math"
] |
Convert a number range to another range, maintaining ratio | 929,103 | <p>I'm trying to convert one range of numbers to another, maintaining ratio. Maths is not my strong point.</p>
<p>I have an image file where point values may range from -16000.00 to 16000.00 though the typical range may be much less. What I want to do is compress these values into the integer range 0-100, where 0 is the value of the smallest point, and 100 is the value of the largest. All points in between should keep a relative ratio even though some precision is being lost I'd like to do this in python but even a general algorithm should suffice. I'd prefer an algorithm where the min/max or either range can be adjusted (ie, the second range could be -50 to 800 instead of 0 to 100).</p>
| 135 | 2009-05-30T05:48:22Z | 24,658,800 | <p>I used this solution in a problem I was solving in js, so I thought I would share the translation. Thanks for the explanation and solution.</p>
<pre><code>function remap( x, oMin, oMax, nMin, nMax ){
//range check
if (oMin == oMax){
console.log("Warning: Zero input range");
return None;
};
if (nMin == nMax){
console.log("Warning: Zero output range");
return None
}
//check reversed input range
var reverseInput = false;
oldMin = Math.min( oMin, oMax );
oldMax = Math.max( oMin, oMax );
if (oldMin != oMin){
reverseInput = true;
}
//check reversed output range
var reverseOutput = false;
newMin = Math.min( nMin, nMax )
newMax = Math.max( nMin, nMax )
if (newMin != nMin){
reverseOutput = true;
};
var portion = (x-oldMin)*(newMax-newMin)/(oldMax-oldMin)
if (reverseInput){
portion = (oldMax-x)*(newMax-newMin)/(oldMax-oldMin);
};
var result = portion + newMin
if (reverseOutput){
result = newMax - portion;
}
return result;
}
</code></pre>
| 2 | 2014-07-09T16:14:08Z | [
"python",
"math"
] |
Convert a number range to another range, maintaining ratio | 929,103 | <p>I'm trying to convert one range of numbers to another, maintaining ratio. Maths is not my strong point.</p>
<p>I have an image file where point values may range from -16000.00 to 16000.00 though the typical range may be much less. What I want to do is compress these values into the integer range 0-100, where 0 is the value of the smallest point, and 100 is the value of the largest. All points in between should keep a relative ratio even though some precision is being lost I'd like to do this in python but even a general algorithm should suffice. I'd prefer an algorithm where the min/max or either range can be adjusted (ie, the second range could be -50 to 800 instead of 0 to 100).</p>
| 135 | 2009-05-30T05:48:22Z | 27,137,732 | <p>C++ Variant</p>
<p>I found PenguinTD's Solution usefull, so i ported it to C++ if anyone needs it:</p>
<blockquote>
<p>float remap(float x, float oMin, float oMax, float nMin, float nMax ){</p>
<pre><code>//range check
if( oMin == oMax) {
//std::cout<< "Warning: Zero input range";
return -1; }
if( nMin == nMax){
//std::cout<<"Warning: Zero output range";
return -1; }
//check reversed input range
bool reverseInput = false;
float oldMin = min( oMin, oMax );
float oldMax = max( oMin, oMax );
if (oldMin == oMin)
reverseInput = true;
//check reversed output range
bool reverseOutput = false;
float newMin = min( nMin, nMax );
float newMax = max( nMin, nMax );
if (newMin == nMin)
reverseOutput = true;
float portion = (x-oldMin)*(newMax-newMin)/(oldMax-oldMin);
if (reverseInput)
portion = (oldMax-x)*(newMax-newMin)/(oldMax-oldMin);
float result = portion + newMin;
if (reverseOutput)
result = newMax - portion;
return result; }
</code></pre>
</blockquote>
| 1 | 2014-11-25T22:11:12Z | [
"python",
"math"
] |
Convert a number range to another range, maintaining ratio | 929,103 | <p>I'm trying to convert one range of numbers to another, maintaining ratio. Maths is not my strong point.</p>
<p>I have an image file where point values may range from -16000.00 to 16000.00 though the typical range may be much less. What I want to do is compress these values into the integer range 0-100, where 0 is the value of the smallest point, and 100 is the value of the largest. All points in between should keep a relative ratio even though some precision is being lost I'd like to do this in python but even a general algorithm should suffice. I'd prefer an algorithm where the min/max or either range can be adjusted (ie, the second range could be -50 to 800 instead of 0 to 100).</p>
| 135 | 2009-05-30T05:48:22Z | 27,497,644 | <p>In the listing provided by PenguinTD, I do not understand why the ranges are reversed, it works without having to reverse the ranges. Linear range conversion is based upon the linear equation <code>Y=Xm+n</code>, where <code>m</code> and <code>n</code> are derived from the given ranges. Rather than refer to the ranges as <code>min</code> and <code>max</code>, it would be better to refer to them as 1 and 2. So the formula would be:</p>
<pre><code>Y = (((X - x1) * (y2 - y1)) / (x2 - x1)) + y1
</code></pre>
<p>Where <code>Y=y1</code> when <code>X=x1</code>, and <code>Y=y2</code> when <code>X=x2</code>. <code>x1</code>, <code>x2</code>, <code>y1</code> & <code>y2</code> can be given any <code>positive</code> or <code>negative</code> value. Defining the expression in a macro makes it more useful,it can then be used with any argument names.</p>
<pre><code>#define RangeConv(X, x1, x2, y1, y2) (((float)((X - x1) * (y2 - y1)) / (x2 - x1)) + y1)
</code></pre>
<p>The <code>float</code> cast would ensure floating point division in the case where all the arguments are <code>integer</code> values.
Depending on the application it may not be necessary to check the ranges <code>x1=x2</code> and <code>y1==y2</code>.</p>
| 2 | 2014-12-16T04:40:26Z | [
"python",
"math"
] |
Convert a number range to another range, maintaining ratio | 929,103 | <p>I'm trying to convert one range of numbers to another, maintaining ratio. Maths is not my strong point.</p>
<p>I have an image file where point values may range from -16000.00 to 16000.00 though the typical range may be much less. What I want to do is compress these values into the integer range 0-100, where 0 is the value of the smallest point, and 100 is the value of the largest. All points in between should keep a relative ratio even though some precision is being lost I'd like to do this in python but even a general algorithm should suffice. I'd prefer an algorithm where the min/max or either range can be adjusted (ie, the second range could be -50 to 800 instead of 0 to 100).</p>
| 135 | 2009-05-30T05:48:22Z | 29,505,969 | <p><strong>Short-cut/simplified proposal</strong> </p>
<pre><code> NewRange/OldRange = Handy multiplicand or HM
Convert OldValue in OldRange to NewValue in NewRange =
(OldValue - OldMin x HM) + NewMin
</code></pre>
<p>wayne</p>
| -1 | 2015-04-08T04:30:54Z | [
"python",
"math"
] |
Convert a number range to another range, maintaining ratio | 929,103 | <p>I'm trying to convert one range of numbers to another, maintaining ratio. Maths is not my strong point.</p>
<p>I have an image file where point values may range from -16000.00 to 16000.00 though the typical range may be much less. What I want to do is compress these values into the integer range 0-100, where 0 is the value of the smallest point, and 100 is the value of the largest. All points in between should keep a relative ratio even though some precision is being lost I'd like to do this in python but even a general algorithm should suffice. I'd prefer an algorithm where the min/max or either range can be adjusted (ie, the second range could be -50 to 800 instead of 0 to 100).</p>
| 135 | 2009-05-30T05:48:22Z | 36,244,586 | <p>PHP Port</p>
<p>Found PenguinTD's solution helpful so I ported it to PHP. Help yourself!</p>
<pre><code>/**
* =====================================
* Remap Range
* =====================================
* - Convert one range to another. (including value)
*
* @param int $intValue The value in the old range you wish to convert
* @param int $oMin The minimum of the old range
* @param int $oMax The maximum of the old range
* @param int $nMin The minimum of the new range
* @param int $nMax The maximum of the new range
*
* @return float $fResult The old value converted to the new range
*/
function remapRange($intValue, $oMin, $oMax, $nMin, $nMax) {
// Range check
if ($oMin == $oMax) {
echo 'Warning: Zero input range';
return false;
}
if ($nMin == $nMax) {
echo 'Warning: Zero output range';
return false;
}
// Check reversed input range
$bReverseInput = false;
$intOldMin = min($oMin, $oMax);
$intOldMax = max($oMin, $oMax);
if ($intOldMin != $oMin) {
$bReverseInput = true;
}
// Check reversed output range
$bReverseOutput = false;
$intNewMin = min($nMin, $nMax);
$intNewMax = max($nMin, $nMax);
if ($intNewMin != $nMin) {
$bReverseOutput = true;
}
$fRatio = ($intValue - $intOldMin) * ($intNewMax - $intNewMin) / ($intOldMax - $intOldMin);
if ($bReverseInput) {
$fRatio = ($intOldMax - $intValue) * ($intNewMax - $intNewMin) / ($intOldMax - $intOldMin);
}
$fResult = $fRatio + $intNewMin;
if ($bReverseOutput) {
$fResult = $intNewMax - $fRatio;
}
return $fResult;
}
</code></pre>
| 2 | 2016-03-27T06:37:22Z | [
"python",
"math"
] |
str.startswith() not working as I intended | 929,169 | <p>I can't see why this won't work. I am performing lstrip() on the string being passed to the function, and trying to see if it starts with """. For some reason, it gets caught in an infinite loop</p>
<pre><code>def find_comment(infile, line):
line_t = line.lstrip()
if not line_t.startswith('"""') and not line_t.startswith('#'):
print (line, end = '')
return line
elif line.lstrip().startswith('"""'):
while True:
if line.rstrip().endswith('"""'):
line = infile.readline()
find_comment(infile, line)
else:
line = infile.readline()
else:
line = infile.readline()
find_comment(infile, line)
</code></pre>
<p>And my output:</p>
<pre><code>Enter the file name: test.txt
import re
def count_loc(infile):
</code></pre>
<p>Here is the top of the file i am reading in for reference:</p>
<pre><code> import re
def count_loc(infile):
""" Receives a file and then returns the amount
of actual lines of code by not counting commented
or blank lines """
loc = 0
func_records = {}
for line in infile:
(...)
</code></pre>
| -1 | 2009-05-30T06:27:38Z | 929,177 | <pre><code>not line_t.startswith('"""') or not line_t.startswith('#')
</code></pre>
<p>This expression evaluates to True no matter what string line_t denotes. Do you want 'and' instead of 'or'? Your question isn't clear to me.</p>
| 1 | 2009-05-30T06:32:59Z | [
"python",
"string",
"python-3.x"
] |
str.startswith() not working as I intended | 929,169 | <p>I can't see why this won't work. I am performing lstrip() on the string being passed to the function, and trying to see if it starts with """. For some reason, it gets caught in an infinite loop</p>
<pre><code>def find_comment(infile, line):
line_t = line.lstrip()
if not line_t.startswith('"""') and not line_t.startswith('#'):
print (line, end = '')
return line
elif line.lstrip().startswith('"""'):
while True:
if line.rstrip().endswith('"""'):
line = infile.readline()
find_comment(infile, line)
else:
line = infile.readline()
else:
line = infile.readline()
find_comment(infile, line)
</code></pre>
<p>And my output:</p>
<pre><code>Enter the file name: test.txt
import re
def count_loc(infile):
</code></pre>
<p>Here is the top of the file i am reading in for reference:</p>
<pre><code> import re
def count_loc(infile):
""" Receives a file and then returns the amount
of actual lines of code by not counting commented
or blank lines """
loc = 0
func_records = {}
for line in infile:
(...)
</code></pre>
| -1 | 2009-05-30T06:27:38Z | 929,185 | <pre><code>if not line_t.startswith('"""') or not line_t.startswith('#'):
</code></pre>
<p>This <code>if</code> will always be satisfied -- either the line doesn't start with <code>"""</code>, or it doesn't start with <code>#</code> (or both). You probably meant to use <code>and</code> where you used <code>or</code>.</p>
| 1 | 2009-05-30T06:37:58Z | [
"python",
"string",
"python-3.x"
] |
str.startswith() not working as I intended | 929,169 | <p>I can't see why this won't work. I am performing lstrip() on the string being passed to the function, and trying to see if it starts with """. For some reason, it gets caught in an infinite loop</p>
<pre><code>def find_comment(infile, line):
line_t = line.lstrip()
if not line_t.startswith('"""') and not line_t.startswith('#'):
print (line, end = '')
return line
elif line.lstrip().startswith('"""'):
while True:
if line.rstrip().endswith('"""'):
line = infile.readline()
find_comment(infile, line)
else:
line = infile.readline()
else:
line = infile.readline()
find_comment(infile, line)
</code></pre>
<p>And my output:</p>
<pre><code>Enter the file name: test.txt
import re
def count_loc(infile):
</code></pre>
<p>Here is the top of the file i am reading in for reference:</p>
<pre><code> import re
def count_loc(infile):
""" Receives a file and then returns the amount
of actual lines of code by not counting commented
or blank lines """
loc = 0
func_records = {}
for line in infile:
(...)
</code></pre>
| -1 | 2009-05-30T06:27:38Z | 929,200 | <p><code>while True</code> is an infinite loop. You need to <code>break</code> once you're done.</p>
| 2 | 2009-05-30T06:49:50Z | [
"python",
"string",
"python-3.x"
] |
str.startswith() not working as I intended | 929,169 | <p>I can't see why this won't work. I am performing lstrip() on the string being passed to the function, and trying to see if it starts with """. For some reason, it gets caught in an infinite loop</p>
<pre><code>def find_comment(infile, line):
line_t = line.lstrip()
if not line_t.startswith('"""') and not line_t.startswith('#'):
print (line, end = '')
return line
elif line.lstrip().startswith('"""'):
while True:
if line.rstrip().endswith('"""'):
line = infile.readline()
find_comment(infile, line)
else:
line = infile.readline()
else:
line = infile.readline()
find_comment(infile, line)
</code></pre>
<p>And my output:</p>
<pre><code>Enter the file name: test.txt
import re
def count_loc(infile):
</code></pre>
<p>Here is the top of the file i am reading in for reference:</p>
<pre><code> import re
def count_loc(infile):
""" Receives a file and then returns the amount
of actual lines of code by not counting commented
or blank lines """
loc = 0
func_records = {}
for line in infile:
(...)
</code></pre>
| -1 | 2009-05-30T06:27:38Z | 929,208 | <p>You haven't provided and exit path from the recursive loop. A return statement should do the trick.</p>
<pre><code> (...)
while True:
if line.rstrip().endswith('"""'):
line = infile.readline()
return find_comment(infile, line)
else:
line = infile.readline()
</code></pre>
| 3 | 2009-05-30T06:57:19Z | [
"python",
"string",
"python-3.x"
] |
str.startswith() not working as I intended | 929,169 | <p>I can't see why this won't work. I am performing lstrip() on the string being passed to the function, and trying to see if it starts with """. For some reason, it gets caught in an infinite loop</p>
<pre><code>def find_comment(infile, line):
line_t = line.lstrip()
if not line_t.startswith('"""') and not line_t.startswith('#'):
print (line, end = '')
return line
elif line.lstrip().startswith('"""'):
while True:
if line.rstrip().endswith('"""'):
line = infile.readline()
find_comment(infile, line)
else:
line = infile.readline()
else:
line = infile.readline()
find_comment(infile, line)
</code></pre>
<p>And my output:</p>
<pre><code>Enter the file name: test.txt
import re
def count_loc(infile):
</code></pre>
<p>Here is the top of the file i am reading in for reference:</p>
<pre><code> import re
def count_loc(infile):
""" Receives a file and then returns the amount
of actual lines of code by not counting commented
or blank lines """
loc = 0
func_records = {}
for line in infile:
(...)
</code></pre>
| -1 | 2009-05-30T06:27:38Z | 929,213 | <p>As long as lines start or end with a comment, the code below should work.</p>
<p>However, keep in mind that the docstrings can start or end in the middle of a line of code.</p>
<p>Also, you'll need to code for triple single-quotes as well as docstrings assigned to variables which aren't really comments.</p>
<p>Does this get you closer to an answer?</p>
<pre><code>def count_loc(infile):
skipping_comments = False
loc = 0
for line in infile:
# Skip one-liners
if line.strip().startswith("#"): continue
# Toggle multi-line comment finder: on and off
if line.strip().startswith('"""'):
skipping_comments = not skipping_comments
if line.strip().endswith('"""'):
skipping_comments = not skipping_comments
continue
if skipping_comments: continue
print line,
</code></pre>
| 1 | 2009-05-30T07:01:10Z | [
"python",
"string",
"python-3.x"
] |
Is there a Python module/recipe (not numpy) for 2d arrays for small games | 929,274 | <p>I am writing some small games in Python with Pygame & Pyglet as hobby projects.</p>
<p>A class for 2D array would be very handy. I use py2exe to send the games to relatives/friends and numpy is just too big and most of it's features are unnecessary for my requirements.</p>
<p>Could you suggest a Python module/recipe I could use for this.</p>
<p>-- Chirag</p>
<p>[Edit]:
List of lists would be usable as mentioned below by MatrixFrog and zvoase. But it is pretty primitive. A class with methods to insert/delete rows and columns as well as to rotate/flip the array would make it very easy and reusable too. dicts are good for sparse arrays only.</p>
<p>Thank you for your ideas.</p>
| 1 | 2009-05-30T07:46:36Z | 929,332 | <p>The simplest approach would just be to use nested lists:</p>
<pre><code>>>> matrix = [[0] * num_cols] * num_rows
>>> matrix[i][j] = 'value' # row i, column j, value 'value'
>>> print repr(matrix[i][j])
'value'
</code></pre>
<p>Alternatively, if youâre going to be dealing with sparse matrices (i.e. matrices with a lot of empty or zero values), it might be more efficient to use nested dictionaries. In this case, you could implement setter and getter functions which will operate on a matrix, like so:</p>
<pre><code>def get_element(mat, i, j, default=None):
# This will also set the accessed row to a dictionary.
row = mat.setdefault(i, {})
return row.setdefault(j, default)
def set_element(mat, i, j, value):
row = mat.setdefault(i, {})
row[j] = value
</code></pre>
<p>And then you would use them like this:</p>
<pre><code>>>> matrix = {}
>>> set_element(matrix, 2, 3, 'value') # row 2, column 3, value 'value'
>>> print matrix
{2: {3: 'value'}}
>>> print repr(get_element(matrix, 2, 3))
'value'
</code></pre>
<p>If you wanted, you could implement a <code>Matrix</code> class which implemented these methods, but that might be overkill:</p>
<pre><code>class Matrix(object):
def __init__(self, initmat=None, default=0):
if initmat is None: initmat = {}
self._mat = initmat
self._default = default
def __getitem__(self, pos):
i, j = pos
return self._mat.setdefault(i, {}).setdefault(j, self._default)
def __setitem__(self, pos, value):
i, j = pos
self._mat.setdefault(i, {})[j] = value
def __repr__(self):
return 'Matrix(%r, %r)' % (self._mat, self._default)
>>> m = Matrix()
>>> m[2,3] = 'value'
>>> print m[2,3]
'value'
>>> m
Matrix({2: {3: 'value'}}, 0)
</code></pre>
| 3 | 2009-05-30T08:30:11Z | [
"python",
"arrays",
"multidimensional-array"
] |
Is there a Python module/recipe (not numpy) for 2d arrays for small games | 929,274 | <p>I am writing some small games in Python with Pygame & Pyglet as hobby projects.</p>
<p>A class for 2D array would be very handy. I use py2exe to send the games to relatives/friends and numpy is just too big and most of it's features are unnecessary for my requirements.</p>
<p>Could you suggest a Python module/recipe I could use for this.</p>
<p>-- Chirag</p>
<p>[Edit]:
List of lists would be usable as mentioned below by MatrixFrog and zvoase. But it is pretty primitive. A class with methods to insert/delete rows and columns as well as to rotate/flip the array would make it very easy and reusable too. dicts are good for sparse arrays only.</p>
<p>Thank you for your ideas.</p>
| 1 | 2009-05-30T07:46:36Z | 929,376 | <p>How about using a defaultdict?</p>
<pre><code>>>> import collections
>>> Matrix = lambda: collections.defaultdict(int)
>>> m = Matrix()
>>> m[3,2] = 6
>>> print m[3,4] # deliberate typo :-)
0
>>> m[3,2] += 4
>>> print m[3,2]
10
>>> print m
defaultdict(<type 'int'>, {(3, 2): 10, (3, 4): 0})
</code></pre>
<p>As the underlying dict uses tuples as keys, this supports 1D, 2D, 3D, ... matrices.</p>
| 6 | 2009-05-30T08:48:39Z | [
"python",
"arrays",
"multidimensional-array"
] |
Is there a Python module/recipe (not numpy) for 2d arrays for small games | 929,274 | <p>I am writing some small games in Python with Pygame & Pyglet as hobby projects.</p>
<p>A class for 2D array would be very handy. I use py2exe to send the games to relatives/friends and numpy is just too big and most of it's features are unnecessary for my requirements.</p>
<p>Could you suggest a Python module/recipe I could use for this.</p>
<p>-- Chirag</p>
<p>[Edit]:
List of lists would be usable as mentioned below by MatrixFrog and zvoase. But it is pretty primitive. A class with methods to insert/delete rows and columns as well as to rotate/flip the array would make it very easy and reusable too. dicts are good for sparse arrays only.</p>
<p>Thank you for your ideas.</p>
| 1 | 2009-05-30T07:46:36Z | 930,212 | <p>Maybe <a href="http://code.google.com/p/pyeuclid/" rel="nofollow">pyeuclid</a> matches your needs -- (dated but usable) formatted docs are <a href="http://partiallydisassembled.net/euclid/" rel="nofollow">here</a>, up-to-date docs in ReST format are in <a href="http://code.google.com/p/pyeuclid/source/browse/trunk/euclid.txt" rel="nofollow">this text file</a> in the pyeuclid sources (to do your own formatting of ReST text, use <a href="http://docutils.sourceforge.net/rst.html" rel="nofollow">the docutils</a>).</p>
| 2 | 2009-05-30T17:53:32Z | [
"python",
"arrays",
"multidimensional-array"
] |
Is there a Python module/recipe (not numpy) for 2d arrays for small games | 929,274 | <p>I am writing some small games in Python with Pygame & Pyglet as hobby projects.</p>
<p>A class for 2D array would be very handy. I use py2exe to send the games to relatives/friends and numpy is just too big and most of it's features are unnecessary for my requirements.</p>
<p>Could you suggest a Python module/recipe I could use for this.</p>
<p>-- Chirag</p>
<p>[Edit]:
List of lists would be usable as mentioned below by MatrixFrog and zvoase. But it is pretty primitive. A class with methods to insert/delete rows and columns as well as to rotate/flip the array would make it very easy and reusable too. dicts are good for sparse arrays only.</p>
<p>Thank you for your ideas.</p>
| 1 | 2009-05-30T07:46:36Z | 1,243,930 | <p>I wrote the class. Don't know if it is a good or redundant but... Posted it here <a href="http://bitbucket.org/pieceofpeace/container2d/" rel="nofollow">http://bitbucket.org/pieceofpeace/container2d/</a></p>
| 0 | 2009-08-07T09:56:58Z | [
"python",
"arrays",
"multidimensional-array"
] |
Django ORM Query to limit for the specific key instance | 929,468 | <p>Projectfundingdetail has a foreign key to project.</p>
<p>The following query gives me the list of all projects that have <em>any</em> projectfundingdetail under 1000. How do I limit it to latest projectfundingdetail only.</p>
<pre><code>projects_list.filter(projectfundingdetail__budget__lte=1000).distinct()
</code></pre>
<p>I have defined the following function,</p>
<pre><code>def latest_funding(self):
return self.projectfundingdetail_set.latest(field_name='end_date')
</code></pre>
<p>But I cant use the following as <code>latest_funding</code> is not a database field</p>
<pre><code>projects_list.filter(latest_funding__budget__lte=1000).distinct()
</code></pre>
<p>So what query should I use to get all projects that have only their latest projectfundingdetail under 1000.</p>
| 1 | 2009-05-30T09:59:51Z | 930,180 | <p>This query is harder than it looks at first glance. AFAIK the Django ORM does not provide any way to generate efficient SQL for this query, because the efficient SQL requires a correlated subquery. (I'd love to be corrected on this!) You can generate some ugly SQL with this query:</p>
<pre><code>Projectfundingdetail.objects.annotate(latest=Max('project__projectfundingdetail__end_date')).filter(end_date=F('latest')).filter(budget__lte==1000).select_related()
</code></pre>
<p>But this requires to join from Projectfundingdetail to Project and back again, which is inefficient (though perhaps adequate for your needs).</p>
<p>The other way to do this is to write raw SQL and encapsulate it in a manager method. It looks a little bit scary but works great. If you assign the manager as "objects" attribute on Projectfundingdetail, you can use it like this to get the latest funding details for each project:</p>
<pre><code>>>> Projectfundingdetail.objects.latest_by_project()
</code></pre>
<p>And it returns a normal QuerySet, so you can add on further filters:</p>
<pre><code>>>> Projectfundingdetail.objects.latest_by_project().filter(budget__lte=1000)
</code></pre>
<p>Here's the code:</p>
<pre><code>from django.db import connection, models
qn = connection.ops.quote_name
class ProjectfundingdetailManager(models.Manager):
def latest_by_project(self):
project_model = self.model._meta.get_field('project').rel.to
names = {'project': qn(project_model._meta.db_table),
'pfd': qn(self.model._meta.db_table),
'end_date': qn(self.model._meta.get_field('end_date').column),
'project_id': qn(self.model._meta.get_field('project').column),
'pk': qn(self.model._meta.pk.column),
'p_pk': qn(project_model._meta.pk.column)}
sql = """SELECT pfd.%(pk)s FROM %(project)s AS p
JOIN %(pfd)s AS pfd ON p.%(p_pk)s = pfd.%(project_id)s
WHERE pfd.%(end_date)s =
(SELECT MAX(%(end_date)s) FROM %(pfd)s
WHERE %(project_id)s = p.%(p_pk)s)
""" % names
cursor = connection.cursor()
cursor.execute(sql)
return self.model.objects.filter(id__in=[r[0] for r
in cursor.fetchall()])
</code></pre>
<p>About half of that code (the "names" dictionary) is only necessary to be robust against the possibility of nonstandard database table and column names. You could also just hardcode the table and column names into the SQL if you're confident they won't ever change.</p>
| 2 | 2009-05-30T17:38:58Z | [
"python",
"django",
"orm",
"django-models",
"django-orm"
] |
Why doesn't inspect.getsource return the whole class source? | 929,472 | <p>I have this code in my <code>forms.py</code>:</p>
<pre><code>from django import forms
from formfieldset.forms import FieldsetMixin
class ContactForm(forms.Form, FieldsetMixin):
full_name = forms.CharField(max_length=120)
email = forms.EmailField()
website = forms.URLField()
message = forms.CharField(max_length=500, widget=forms.Textarea)
send_notification = forms.BooleanField(required=False)
fieldsets = ((u'Personal Information',
{'fields': ('full_name', 'email', 'website'),
'description': u'Your personal information will not ' \
u'be shared with 3rd parties.'}),
(None,
{'fields': ('message',),
'description': u'All HTML will be stripped out.'}),
(u'Preferences',
{'fields': ('send_notification',)}))
</code></pre>
<p>When I try to extract the code programmatically with <code>inspect</code> it leaves out <code>fieldsets</code>:</p>
<pre><code>In [1]: import inspect
In [2]: import forms
In [3]: print inspect.getsource(forms)
from django import forms
from formfieldset.forms import FieldsetMixin
class ContactForm(forms.Form, FieldsetMixin):
full_name = forms.CharField(max_length=120)
email = forms.EmailField()
website = forms.URLField()
message = forms.CharField(max_length=500, widget=forms.Textarea)
send_notification = forms.BooleanField(required=False)
fieldsets = ((u'Personal Information',
{'fields': ('full_name', 'email', 'website'),
'description': u'Your personal information will not ' \
u'be shared with 3rd parties.'}),
(None,
{'fields': ('message',),
'description': u'All HTML will be stripped out.'}),
(u'Preferences',
{'fields': ('send_notification',)}))
In [4]: print inspect.getsource(forms.ContactForm)
class ContactForm(forms.Form, FieldsetMixin):
full_name = forms.CharField(max_length=120)
email = forms.EmailField()
website = forms.URLField()
message = forms.CharField(max_length=500, widget=forms.Textarea)
send_notification = forms.BooleanField(required=False)
In [5]:
</code></pre>
<p>This doesn't seem to be an issue with blank lines. I've tested without the blank line in between and I've put additional blank lines in between other attributes. Results don't change.</p>
<p>Any ideas why inspect is returning only the part before <code>fieldsets</code> and not the whole source of the class?</p>
| 0 | 2009-05-30T10:01:19Z | 929,524 | <p><strong>edit: revised based on comments:</strong></p>
<p>Inside <code>inspect.getsource(forms.ContactForm)</code> the method <code>BlockFinder.tokeneater()</code> is used to determine where the <code>ContactForm</code> block stops. Besides others, it checks for <code>tokenize.DEDENT</code>, which it finds right before fieldsets in your version stored at github. The line contains only a line break, so <code>inspect</code> thinks the current block has ended.</p>
<p>If you insert 4 spaces, it works for me again. I cannot argue on the rationale behind this, maybe performance.</p>
<pre><code>class ContactForm(forms.Form):
full_name = forms.CharField(max_length=120)
email = forms.EmailField()
website = forms.URLField()
message = forms.CharField(max_length=500, widget=forms.Textarea)
send_notification = forms.BooleanField(required=False)
# <-- insert 4 spaces here
fieldsets = ((u'Personal Information',
{'fields': ('full_name', 'email', 'website'),
'description': u'Your personal information will not ' \
u'be shared with 3rd parties.'}),
(None,
{'fields': ('message',),
'description': u'All HTML will be stripped out.'}),
(u'Preferences',
{'fields': ('send_notification',)}))
</code></pre>
<p>The reason that <code>inspect.getsource(forms)</code> works differently is because <code>inspect</code> in that case does not have to determine the class definition's start and end. It simply outputs the whole file.</p>
| 1 | 2009-05-30T10:47:17Z | [
"python",
"inspect",
"code-inspection"
] |
Why doesn't inspect.getsource return the whole class source? | 929,472 | <p>I have this code in my <code>forms.py</code>:</p>
<pre><code>from django import forms
from formfieldset.forms import FieldsetMixin
class ContactForm(forms.Form, FieldsetMixin):
full_name = forms.CharField(max_length=120)
email = forms.EmailField()
website = forms.URLField()
message = forms.CharField(max_length=500, widget=forms.Textarea)
send_notification = forms.BooleanField(required=False)
fieldsets = ((u'Personal Information',
{'fields': ('full_name', 'email', 'website'),
'description': u'Your personal information will not ' \
u'be shared with 3rd parties.'}),
(None,
{'fields': ('message',),
'description': u'All HTML will be stripped out.'}),
(u'Preferences',
{'fields': ('send_notification',)}))
</code></pre>
<p>When I try to extract the code programmatically with <code>inspect</code> it leaves out <code>fieldsets</code>:</p>
<pre><code>In [1]: import inspect
In [2]: import forms
In [3]: print inspect.getsource(forms)
from django import forms
from formfieldset.forms import FieldsetMixin
class ContactForm(forms.Form, FieldsetMixin):
full_name = forms.CharField(max_length=120)
email = forms.EmailField()
website = forms.URLField()
message = forms.CharField(max_length=500, widget=forms.Textarea)
send_notification = forms.BooleanField(required=False)
fieldsets = ((u'Personal Information',
{'fields': ('full_name', 'email', 'website'),
'description': u'Your personal information will not ' \
u'be shared with 3rd parties.'}),
(None,
{'fields': ('message',),
'description': u'All HTML will be stripped out.'}),
(u'Preferences',
{'fields': ('send_notification',)}))
In [4]: print inspect.getsource(forms.ContactForm)
class ContactForm(forms.Form, FieldsetMixin):
full_name = forms.CharField(max_length=120)
email = forms.EmailField()
website = forms.URLField()
message = forms.CharField(max_length=500, widget=forms.Textarea)
send_notification = forms.BooleanField(required=False)
In [5]:
</code></pre>
<p>This doesn't seem to be an issue with blank lines. I've tested without the blank line in between and I've put additional blank lines in between other attributes. Results don't change.</p>
<p>Any ideas why inspect is returning only the part before <code>fieldsets</code> and not the whole source of the class?</p>
| 0 | 2009-05-30T10:01:19Z | 929,618 | <p>Works for me. I don't have "from formfieldset.forms import FieldsetMixin" in my code. Maybe that is causing an issue..</p>
| 0 | 2009-05-30T11:54:59Z | [
"python",
"inspect",
"code-inspection"
] |
Why does assigning to my global variables not work in Python? | 929,777 | <p>I'm having terrible trouble trying to understand python scoping rules.</p>
<p>With the following script:</p>
<pre><code>a = 7
def printA():
print "Value of a is %d" % (a)
def setA(value):
a = value
print "Inside setA, a is now %d" %(a)
print "Before setA"
printA()
setA(42)
print "After setA"
printA()
</code></pre>
<p>Gives the unexpected (to me) output of:</p>
<pre>
Before setA
Value of a is 7
Inside setA, a is now 42
After setA
Value of a is 7
</pre>
<p>Where I would expect the last printing of the value of a to be 42, not 7. What am I missing about Python's scope rules for the scoping of global variables?</p>
| 34 | 2009-05-30T14:09:18Z | 929,783 | <p>Global variables are special. If you try to assign to a variable <code>a = value</code> inside of a function, it creates a new local variable inside the function, even if there is a global variable with the same name. To instead access the global variable, add a <a href="http://docs.python.org/reference/simple%5Fstmts.html#the-global-statement"><code>global</code> statement</a> inside the function:</p>
<pre><code>a = 7
def setA(value):
global a # declare a to be a global
a = value # this sets the global value of a
</code></pre>
<p>See also <a href="http://docs.python.org/reference/executionmodel.html#naming-and-binding">Naming and binding</a> for a detailed explanation of Python's naming and binding rules.</p>
| 78 | 2009-05-30T14:12:14Z | [
"python",
"global-variables",
"scope"
] |
Why does assigning to my global variables not work in Python? | 929,777 | <p>I'm having terrible trouble trying to understand python scoping rules.</p>
<p>With the following script:</p>
<pre><code>a = 7
def printA():
print "Value of a is %d" % (a)
def setA(value):
a = value
print "Inside setA, a is now %d" %(a)
print "Before setA"
printA()
setA(42)
print "After setA"
printA()
</code></pre>
<p>Gives the unexpected (to me) output of:</p>
<pre>
Before setA
Value of a is 7
Inside setA, a is now 42
After setA
Value of a is 7
</pre>
<p>Where I would expect the last printing of the value of a to be 42, not 7. What am I missing about Python's scope rules for the scoping of global variables?</p>
| 34 | 2009-05-30T14:09:18Z | 929,793 | <p>The trick to understanding this is that when you assign to a variable, using =, you also declare it as a local variable. So instead of changing the value of the global variable a, setA(value) actually sets a local variable (which happens to be called a) to the value passed in.</p>
<p>This becomes more obvious if you try to print the value of a at the start of setA(value) like so:</p>
<pre><code>def setA(value):
print "Before assignment, a is %d" % (a)
a = value
print "Inside setA, a is now %d" % (a)
</code></pre>
<p>If you try to run this Python will give you a helpful error:</p>
<pre>
Traceback (most recent call last):
File "scopeTest.py", line 14, in
setA(42)
File "scopeTest.py", line 7, in setA
print "Before assignment, a is %d" % (a)
UnboundLocalError: local variable 'a' referenced before assignment
</pre>
<p>This tells us that Python has decided that the setA(value) function has a local variable called a, which is what you alter when you assign to it in the function. If you don't assign to a in the function (as with printA()) then Python uses the global variable A.</p>
<p>To mark a variable as global you need to use the global keyword in Python, <em>in the scope that you want to use the global variable</em>. In this case that is within the setA(value) function. So the script becomes:</p>
<pre><code>a = 7
def printA():
print "Value of a is %d" % (a)
def setA(value):
global a
a = value
print "Inside setA, a is now %d" %(a)
print "Before setA"
printA()
setA(42)
print "After setA"
printA()
</code></pre>
<p>This one line addition tells Python that when you use the variable a in the setA(value) function that you are talking about the global variable, not a local variable.</p>
| 10 | 2009-05-30T14:17:00Z | [
"python",
"global-variables",
"scope"
] |
Why does assigning to my global variables not work in Python? | 929,777 | <p>I'm having terrible trouble trying to understand python scoping rules.</p>
<p>With the following script:</p>
<pre><code>a = 7
def printA():
print "Value of a is %d" % (a)
def setA(value):
a = value
print "Inside setA, a is now %d" %(a)
print "Before setA"
printA()
setA(42)
print "After setA"
printA()
</code></pre>
<p>Gives the unexpected (to me) output of:</p>
<pre>
Before setA
Value of a is 7
Inside setA, a is now 42
After setA
Value of a is 7
</pre>
<p>Where I would expect the last printing of the value of a to be 42, not 7. What am I missing about Python's scope rules for the scoping of global variables?</p>
| 34 | 2009-05-30T14:09:18Z | 930,768 | <p>Python does not have a concept of variables as other languages. You have objects which are "somewhere" and you have references to these objects. = is used to assign these objects to references in the <em>current</em> namespace.</p>
<p>You create a name a in the namespace of the setA function which refers to the object to which value refers.</p>
| 1 | 2009-05-30T22:26:57Z | [
"python",
"global-variables",
"scope"
] |
Why does assigning to my global variables not work in Python? | 929,777 | <p>I'm having terrible trouble trying to understand python scoping rules.</p>
<p>With the following script:</p>
<pre><code>a = 7
def printA():
print "Value of a is %d" % (a)
def setA(value):
a = value
print "Inside setA, a is now %d" %(a)
print "Before setA"
printA()
setA(42)
print "After setA"
printA()
</code></pre>
<p>Gives the unexpected (to me) output of:</p>
<pre>
Before setA
Value of a is 7
Inside setA, a is now 42
After setA
Value of a is 7
</pre>
<p>Where I would expect the last printing of the value of a to be 42, not 7. What am I missing about Python's scope rules for the scoping of global variables?</p>
| 34 | 2009-05-30T14:09:18Z | 2,076,921 | <p>inside the function,<em>a</em> is treated as a local variable,you need to define <br></p>
<blockquote>
<p>global a </p>
</blockquote>
<p>inside the function</p>
| 1 | 2010-01-16T10:03:30Z | [
"python",
"global-variables",
"scope"
] |
Runtime directory of Python | 929,841 | <p>How do I find out the current runtime directory from within a Python script?</p>
| 1 | 2009-05-30T14:45:12Z | 929,849 | <p>Use <a href="http://docs.python.org/library/os.html#os.getcwd" rel="nofollow"><code>os.getcwd</code></a>. This will tell you the <em>current working directory</em>. If you create a new file with</p>
<pre><code>fp = open('a.txt', 'w')
</code></pre>
<p>then <code>a.txt</code> will be created in the current working directory. Use <a href="http://docs.python.org/library/os.html#os.chdir" rel="nofollow"><code>os.chdir</code></a> to change the working directory, if needed.</p>
| 6 | 2009-05-30T14:48:33Z | [
"python",
"working-directory"
] |
Runtime directory of Python | 929,841 | <p>How do I find out the current runtime directory from within a Python script?</p>
| 1 | 2009-05-30T14:45:12Z | 6,064,915 | <p>This is working for me.</p>
<pre><code>os.path.dirname(__file__)
</code></pre>
| 0 | 2011-05-19T21:08:57Z | [
"python",
"working-directory"
] |
Runtime directory of Python | 929,841 | <p>How do I find out the current runtime directory from within a Python script?</p>
| 1 | 2009-05-30T14:45:12Z | 13,082,959 | <p><code>os.getcwd()</code> will change when u use <code>os.chdir</code></p>
<p>If you need a fixed path to your python file, use:</p>
<pre><code>module_path = os.path.dirname(__file__)
</code></pre>
| 0 | 2012-10-26T07:54:12Z | [
"python",
"working-directory"
] |
Two simple questions about python | 929,887 | <p>I have 2 simple questions about python:</p>
<p>1.How to get number of lines of a file in python?</p>
<p>2.How to locate the position in a file object to the
last line easily?</p>
| 2 | 2009-05-30T15:05:14Z | 929,899 | <p>lines are just data delimited by the newline char <code>'\n'</code>.</p>
<p>1) Since lines are variable length, you have to read the entire file to know where the newline chars are, so you can count how many lines:</p>
<pre><code>count = 0
for line in open('myfile'):
count += 1
print count, line # it will be the last line
</code></pre>
<p>2) reading a chunk from the end of the file is the fastest method to find the last newline char.</p>
<pre><code>def seek_newline_backwards(file_obj, eol_char='\n', buffer_size=200):
if not file_obj.tell(): return # already in beginning of file
# All lines end with \n, including the last one, so assuming we are just
# after one end of line char
file_obj.seek(-1, os.SEEK_CUR)
while file_obj.tell():
ammount = min(buffer_size, file_obj.tell())
file_obj.seek(-ammount, os.SEEK_CUR)
data = file_obj.read(ammount)
eol_pos = data.rfind(eol_char)
if eol_pos != -1:
file_obj.seek(eol_pos - len(data) + 1, os.SEEK_CUR)
break
file_obj.seek(-len(data), os.SEEK_CUR)
</code></pre>
<p>You can use that like this:</p>
<pre><code>f = open('some_file.txt')
f.seek(0, os.SEEK_END)
seek_newline_backwards(f)
print f.tell(), repr(f.readline())
</code></pre>
| 8 | 2009-05-30T15:11:00Z | [
"python",
"file"
] |
Two simple questions about python | 929,887 | <p>I have 2 simple questions about python:</p>
<p>1.How to get number of lines of a file in python?</p>
<p>2.How to locate the position in a file object to the
last line easily?</p>
| 2 | 2009-05-30T15:05:14Z | 929,905 | <p>The only way to count lines [that I know of] is to read all lines, like this:</p>
<pre><code>count = 0
for line in open("file.txt"): count = count + 1
</code></pre>
<p>After the loop, <code>count</code> will have the number of lines read.</p>
| 1 | 2009-05-30T15:13:26Z | [
"python",
"file"
] |
Two simple questions about python | 929,887 | <p>I have 2 simple questions about python:</p>
<p>1.How to get number of lines of a file in python?</p>
<p>2.How to locate the position in a file object to the
last line easily?</p>
| 2 | 2009-05-30T15:05:14Z | 929,907 | <p>Answer to the first question (beware of poor performance on large files when using this method):</p>
<pre><code>f = open("myfile.txt").readlines()
print len(f) - 1
</code></pre>
<p>Answer to the second question:</p>
<pre><code>f = open("myfile.txt").read()
print f.rfind("\n")
</code></pre>
<p>P.S. Yes I do understand that this only suits for small files and simple programs. I think I will not delete this answer however useless for real use-cases it may seem.</p>
| 0 | 2009-05-30T15:14:07Z | [
"python",
"file"
] |
Two simple questions about python | 929,887 | <p>I have 2 simple questions about python:</p>
<p>1.How to get number of lines of a file in python?</p>
<p>2.How to locate the position in a file object to the
last line easily?</p>
| 2 | 2009-05-30T15:05:14Z | 929,922 | <p>For small files that fit memory,
how about using <a href="http://docs.python.org/library/string.html#string.count" rel="nofollow"><code>str.count()</code></a> for getting the number of lines of a file:</p>
<pre><code>line_count = open("myfile.txt").read().count('\n')
</code></pre>
| 2 | 2009-05-30T15:20:49Z | [
"python",
"file"
] |
Two simple questions about python | 929,887 | <p>I have 2 simple questions about python:</p>
<p>1.How to get number of lines of a file in python?</p>
<p>2.How to locate the position in a file object to the
last line easily?</p>
| 2 | 2009-05-30T15:05:14Z | 929,924 | <p>Let's not forget</p>
<pre><code>f = open("myfile.txt")
lines = f.readlines()
numlines = len(lines)
lastline = lines[-1]
</code></pre>
<p>NOTE: this reads the whole file in memory as a list. Keep that in mind in the case that the file is very large.</p>
| 7 | 2009-05-30T15:21:11Z | [
"python",
"file"
] |
Two simple questions about python | 929,887 | <p>I have 2 simple questions about python:</p>
<p>1.How to get number of lines of a file in python?</p>
<p>2.How to locate the position in a file object to the
last line easily?</p>
| 2 | 2009-05-30T15:05:14Z | 929,970 | <p>The <em>easiest</em> way is simply to read the file into memory. eg:</p>
<pre><code>f = open('filename.txt')
lines = f.readlines()
num_lines = len(lines)
last_line = lines[-1]
</code></pre>
<p>However for big files, this may use up a lot of memory, as the whole file is loaded into RAM. An alternative is to iterate through the file line by line. eg:</p>
<pre><code>f = open('filename.txt')
num_lines = sum(1 for line in f)
</code></pre>
<p>This is more efficient, since it won't load the entire file into memory, but only look at a line at a time. If you want the last line as well, you can keep track of the lines as you iterate and get both answers by:</p>
<pre><code>f = open('filename.txt')
count=0
last_line = None
for line in f:
num_lines += 1
last_line = line
print "There were %d lines. The last was: %s" % (num_lines, last_line)
</code></pre>
<p>One final possible improvement if you need only the last line, is to start at the end of the file, and seek backwards until you find a newline character. <a href="http://stackoverflow.com/questions/136168/tail-a-file-with-python">Here's</a> a question which has some code doing this. If you need both the linecount as well though, theres no alternative except to iterate through all lines in the file however.</p>
| 5 | 2009-05-30T15:42:56Z | [
"python",
"file"
] |
Two simple questions about python | 929,887 | <p>I have 2 simple questions about python:</p>
<p>1.How to get number of lines of a file in python?</p>
<p>2.How to locate the position in a file object to the
last line easily?</p>
| 2 | 2009-05-30T15:05:14Z | 930,010 | <p>I'd like too add to the other solutions that some of them (those who look for <code>\n</code>) will not work with files with OS 9-style line endings (<code>\r</code> only), and that they may contain an extra blank line at the end because lots of text editors append it for some curious reasons, so you might or might not want to add a check for it.</p>
| 2 | 2009-05-30T15:56:49Z | [
"python",
"file"
] |
Two simple questions about python | 929,887 | <p>I have 2 simple questions about python:</p>
<p>1.How to get number of lines of a file in python?</p>
<p>2.How to locate the position in a file object to the
last line easily?</p>
| 2 | 2009-05-30T15:05:14Z | 930,229 | <p>For the first question there're already a few good ones, I'll suggest @Brian's one as the best (most pythonic, line ending character proof and memory efficient):</p>
<pre><code>f = open('filename.txt')
num_lines = sum(1 for line in f)
</code></pre>
<p>For the second one, I like @nosklo's one, but modified to be more general should be:</p>
<pre><code>import os
f = open('myfile')
to = f.seek(0, os.SEEK_END)
found = -1
while found == -1 and to > 0:
fro = max(0, to-1024)
f.seek(fro)
chunk = f.read(to-fro)
found = chunk.rfind("\n")
to -= 1024
if found != -1:
found += fro
</code></pre>
<p>It seachs in chunks of 1Kb from the end of the file, until it finds a newline character or the file ends. At the end of the code, found is the index of the last newline character.</p>
| 0 | 2009-05-30T18:04:33Z | [
"python",
"file"
] |
Equivalent for Python's lambda functions in Java? | 929,988 | <p>Can someone please tell me if there is an equivalent for Python's lambda functions in Java?</p>
| 21 | 2009-05-30T15:49:17Z | 930,003 | <p>One idea is based on a generic <code>public interface Lambda<T></code> -- see <a href="http://www.javalobby.org/java/forums/t75427.html">http://www.javalobby.org/java/forums/t75427.html</a> .</p>
| 6 | 2009-05-30T15:53:55Z | [
"java",
"python",
"function",
"lambda"
] |
Equivalent for Python's lambda functions in Java? | 929,988 | <p>Can someone please tell me if there is an equivalent for Python's lambda functions in Java?</p>
| 21 | 2009-05-30T15:49:17Z | 930,012 | <p>I don't think there is an exact equivalent, however there are anonymous classes that are about as close as you can get. But still pretty different. Joel Spolsky wrote an article about how the students taught only Java are missing out on these beauties of functional style programming: <a href="http://www.joelonsoftware.com/items/2006/08/01.html" rel="nofollow">Can Your Programming Language Do This?</a>.</p>
| 9 | 2009-05-30T15:57:01Z | [
"java",
"python",
"function",
"lambda"
] |
Equivalent for Python's lambda functions in Java? | 929,988 | <p>Can someone please tell me if there is an equivalent for Python's lambda functions in Java?</p>
| 21 | 2009-05-30T15:49:17Z | 930,019 | <p>Unfortunately, there are no lambdas in Java. However, you can get <em>almost</em> the same effect (in a really ugly way) with anonymous classes:</p>
<pre><code>interface MyLambda {
void theFunc(); // here we define the interface for the function
}
public class Something {
static void execute(MyLambda l) {
l.theFunc(); // this class just wants to use the lambda for something
}
}
public class Test {
static void main(String[] args) {
Something.execute(new MyLambda() { // here we create an anonymous class
void theFunc() { // implementing MyLambda
System.out.println("Hello world!");
}
});
}
}
</code></pre>
<p>Obviously these would have to be in separate files :(</p>
| 28 | 2009-05-30T15:58:12Z | [
"java",
"python",
"function",
"lambda"
] |
Equivalent for Python's lambda functions in Java? | 929,988 | <p>Can someone please tell me if there is an equivalent for Python's lambda functions in Java?</p>
| 21 | 2009-05-30T15:49:17Z | 3,050,232 | <p>Somewhat similarly to Zifre's, you could create an interface thus</p>
<pre><code>public interface myLambda<In, Out> {
Out call(In i);
}
</code></pre>
<p>to enable you to write, say</p>
<pre><code>Function<MyObj, Boolean> func = new Function<MyObj, Boolean>() {
public Boolean callFor(myObj obj) {
return obj.canDoStuff();
};
MyObj thing = getThing;
if (func.callFor(thing)) {
doSomeStuff();
} else {
doOtherStuff();
}
</code></pre>
<p>It's still a bit kludgy, yeah, but it has input/output at least.</p>
| 1 | 2010-06-16T01:52:18Z | [
"java",
"python",
"function",
"lambda"
] |
Equivalent for Python's lambda functions in Java? | 929,988 | <p>Can someone please tell me if there is an equivalent for Python's lambda functions in Java?</p>
| 21 | 2009-05-30T15:49:17Z | 28,942,165 | <p>Yes,</p>
<p>Lambda expressions are introduced in java from java8.</p>
<p>Basic syntax for lambda expressions are:</p>
<pre><code>(parameters)->
{
statements;
}
</code></pre>
<p>Example</p>
<pre><code>(String s)->
{
System.out.println(s);
}
</code></pre>
<p>Check this link:</p>
<p><a href="http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html" rel="nofollow">http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html</a></p>
| 0 | 2015-03-09T12:36:06Z | [
"java",
"python",
"function",
"lambda"
] |
Python String Cleanup + Manipulation (Accented Characters) | 930,303 | <p>I have a database full of names like:</p>
<pre><code>John Smith
Scott J. Holmes
Dr. Kaplan
Ray's Dog
Levi's
Adrian O'Brien
Perry Sean Smyre
Carie Burchfield-Thompson
Björn Ãrnason
</code></pre>
<p>There are a few foreign names with accents in them that need to be converted to strings with non-accented characters.</p>
<p>I'd like to convert the full names (after stripping characters like " ' " , "-") to user logins like:</p>
<pre><code>john.smith
scott.j.holmes
dr.kaplan
rays.dog
levis
adrian.obrien
perry.sean.smyre
carie.burchfieldthompson
bjorn.arnason
</code></pre>
<p>So far I have:</p>
<pre><code>Fullname.strip() # get rid of leading/trailing white space
Fullname.lower() # make everything lower case
... # after bad chars converted/removed
Fullname.replace(' ', '.') # replace spaces with periods
</code></pre>
| 5 | 2009-05-30T18:36:16Z | 930,316 | <p>Take a look at this link [redacted]</p>
<p>Here is the code from the page</p>
<pre><code>def latin1_to_ascii (unicrap):
"""This replaces UNICODE Latin-1 characters with
something equivalent in 7-bit ASCII. All characters in the standard
7-bit ASCII range are preserved. In the 8th bit range all the Latin-1
accented letters are stripped of their accents. Most symbol characters
are converted to something meaningful. Anything not converted is deleted.
"""
xlate = {
0xc0:'A', 0xc1:'A', 0xc2:'A', 0xc3:'A', 0xc4:'A', 0xc5:'A',
0xc6:'Ae', 0xc7:'C',
0xc8:'E', 0xc9:'E', 0xca:'E', 0xcb:'E',
0xcc:'I', 0xcd:'I', 0xce:'I', 0xcf:'I',
0xd0:'Th', 0xd1:'N',
0xd2:'O', 0xd3:'O', 0xd4:'O', 0xd5:'O', 0xd6:'O', 0xd8:'O',
0xd9:'U', 0xda:'U', 0xdb:'U', 0xdc:'U',
0xdd:'Y', 0xde:'th', 0xdf:'ss',
0xe0:'a', 0xe1:'a', 0xe2:'a', 0xe3:'a', 0xe4:'a', 0xe5:'a',
0xe6:'ae', 0xe7:'c',
0xe8:'e', 0xe9:'e', 0xea:'e', 0xeb:'e',
0xec:'i', 0xed:'i', 0xee:'i', 0xef:'i',
0xf0:'th', 0xf1:'n',
0xf2:'o', 0xf3:'o', 0xf4:'o', 0xf5:'o', 0xf6:'o', 0xf8:'o',
0xf9:'u', 0xfa:'u', 0xfb:'u', 0xfc:'u',
0xfd:'y', 0xfe:'th', 0xff:'y',
0xa1:'!', 0xa2:'{cent}', 0xa3:'{pound}', 0xa4:'{currency}',
0xa5:'{yen}', 0xa6:'|', 0xa7:'{section}', 0xa8:'{umlaut}',
0xa9:'{C}', 0xaa:'{^a}', 0xab:'<<', 0xac:'{not}',
0xad:'-', 0xae:'{R}', 0xaf:'_', 0xb0:'{degrees}',
0xb1:'{+/-}', 0xb2:'{^2}', 0xb3:'{^3}', 0xb4:"'",
0xb5:'{micro}', 0xb6:'{paragraph}', 0xb7:'*', 0xb8:'{cedilla}',
0xb9:'{^1}', 0xba:'{^o}', 0xbb:'>>',
0xbc:'{1/4}', 0xbd:'{1/2}', 0xbe:'{3/4}', 0xbf:'?',
0xd7:'*', 0xf7:'/'
}
r = ''
for i in unicrap:
if xlate.has_key(ord(i)):
r += xlate[ord(i)]
elif ord(i) >= 0x80:
pass
else:
r += i
return r
# This gives an example of how to use latin1_to_ascii().
# This creates a string will all the characters in the latin-1 character set
# then it converts the string to plain 7-bit ASCII.
if __name__ == '__main__':
s = unicode('','latin-1')
for c in range(32,256):
if c != 0x7f:
s = s + unicode(chr(c),'latin-1')
print 'INPUT:'
print s.encode('latin-1')
print
print 'OUTPUT:'
print latin1_to_ascii(s)
</code></pre>
| 12 | 2009-05-30T18:47:38Z | [
"python",
"regex",
"unicode",
"string"
] |
Python String Cleanup + Manipulation (Accented Characters) | 930,303 | <p>I have a database full of names like:</p>
<pre><code>John Smith
Scott J. Holmes
Dr. Kaplan
Ray's Dog
Levi's
Adrian O'Brien
Perry Sean Smyre
Carie Burchfield-Thompson
Björn Ãrnason
</code></pre>
<p>There are a few foreign names with accents in them that need to be converted to strings with non-accented characters.</p>
<p>I'd like to convert the full names (after stripping characters like " ' " , "-") to user logins like:</p>
<pre><code>john.smith
scott.j.holmes
dr.kaplan
rays.dog
levis
adrian.obrien
perry.sean.smyre
carie.burchfieldthompson
bjorn.arnason
</code></pre>
<p>So far I have:</p>
<pre><code>Fullname.strip() # get rid of leading/trailing white space
Fullname.lower() # make everything lower case
... # after bad chars converted/removed
Fullname.replace(' ', '.') # replace spaces with periods
</code></pre>
| 5 | 2009-05-30T18:36:16Z | 930,324 | <p>I would do something like this</p>
<pre><code># coding=utf-8
def alnum_dot(name, replace={}):
import re
for k, v in replace.items():
name = name.replace(k, v)
return re.sub("[^a-z.]", "", name.strip().lower())
print alnum_dot(u"Frédrik Holmström", {
u"ö":"o",
" ":"."
})
</code></pre>
<p>Second argument is a dict of the characters you want replaced, all non a-z and . chars that are not replaced will be stripped</p>
| 1 | 2009-05-30T18:51:11Z | [
"python",
"regex",
"unicode",
"string"
] |
Python String Cleanup + Manipulation (Accented Characters) | 930,303 | <p>I have a database full of names like:</p>
<pre><code>John Smith
Scott J. Holmes
Dr. Kaplan
Ray's Dog
Levi's
Adrian O'Brien
Perry Sean Smyre
Carie Burchfield-Thompson
Björn Ãrnason
</code></pre>
<p>There are a few foreign names with accents in them that need to be converted to strings with non-accented characters.</p>
<p>I'd like to convert the full names (after stripping characters like " ' " , "-") to user logins like:</p>
<pre><code>john.smith
scott.j.holmes
dr.kaplan
rays.dog
levis
adrian.obrien
perry.sean.smyre
carie.burchfieldthompson
bjorn.arnason
</code></pre>
<p>So far I have:</p>
<pre><code>Fullname.strip() # get rid of leading/trailing white space
Fullname.lower() # make everything lower case
... # after bad chars converted/removed
Fullname.replace(' ', '.') # replace spaces with periods
</code></pre>
| 5 | 2009-05-30T18:36:16Z | 930,331 | <p>The translate method allows you to delete characters. You can use that to delete arbitrary characters.</p>
<pre><code>Fullname.translate(None,"'-\"")
</code></pre>
<p>If you want to delete whole classes of characters, you might want to use the re module.</p>
<pre><code>re.sub('[^a-z0-9 ]', '', Fullname.strip().lower(),)
</code></pre>
| 1 | 2009-05-30T18:53:34Z | [
"python",
"regex",
"unicode",
"string"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.