Copying attributes

2005-07-20 Thread red
Hi,

I'm writing a script for Blender and need to build a face array. My 
engine needs that all faces must be triangles, so I convert quads to 
triangles by dividing them into two triangles. Here is the function:

def build_face_table(mesh):
face_table = {}
i = 0
for f in mesh.faces:
if len(f.v) == 3:   # triangle
face_table[i] = f
i += 1
elif len(f.v) == 4: # quad
f1 = NMesh.Face()
f2 = NMesh.Face()

f1.mat = f.mat
##  f1.normal = copy.deepcopy(f.normal)
f1.normal = NMesh.Vert(f.normal[0], f.normal[1], 
f.normal[2])
f1.v.append(f.v[0])
f1.v.append(f.v[1])
f1.v.append(f.v[2])

f2.mat = f.mat
f2.v.append(f.v[2])
f2.v.append(f.v[3])
f2.v.append(f.v[0])

face_table[i] = f1
i += 1
face_table[i] = f2
i += 1
else:
message = "Can't build face from 2 vertices."
Draw.PupMenu("Face Table Error%t|"+message)
return
return face_table

Everything seems be ok, but i'm getting:

Traceback (most recent call last):
File "", line 169, in write
File "", line 102, in build_face_table
AttributeError: normal

I was wondering why? Though the face has an attribute called "normal"! 
Just simply test:

nv = f.normal

and it works! But why my new faces (f1 and f2) no?

Greetings.

-- 
_red  _   __ _
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Copying attributes

2005-07-21 Thread red
Terry Hancock wrote:
> I'm not sure either, yet, but can you indicate which line in your
> listing is 102 in the source file?  That might be helpful.

101: ## f1.normal = copy.deepcopy(f.normal)
102:f1.normal = NMesh.Vert(f.normal[0], f.normal[1], f.normal[2])

I've tried with deepcopy, but the result is exactly same.

-- 
_red  _   __ _
-- 
http://mail.python.org/mailman/listinfo/python-list


Difficulty w/json keys

2010-04-23 Thread Red
My apologies for what is probably a simple question to most on this
group. However, I am new to python and very new to json.

I am trying to read in a json file from a twitter download. There are,
generally, two types of lines: those lines with "text" and the other
lines.  I am only interested in the lines with "text".  I am also only
interested in lines with "lang":"en", but I haven't gotten far enough
to implement that condition in the code snippets below.

I have gotten Option 2 below to sort of work.  It works fine for
'text', but doesn't work for 'lang'.

FWIW I am using Python 2.6.4

Can someone tell me what I'm doing wrong with the following code
snippets and/or point me toward an example of an implementation?

Many thanks for your patience.

-

import sys
import json

f = open(sys.argv[1])

#option 1

for line in f:
j = json.loads(line)
try:
'text' in j
print "TEXT:  ", j
except:
print "EXCEPTION:   ", j
continue
else:
text=j['text']
snip 




#option 2   does basically the same thing as option 1 , but also looks
for 'lang'

for line in f:
j = json.loads(line)
if 'text' in j:
if 'lang' in j:
lang = j['lang']
print "language", lang
text = j['text']
snip 

-- Two Sample Twitter lines -

{"text":"tech managers what size for your teams? better to have 10-20
ppl per manager or 2-5 and have the managers be more hands
on?","in_reply_to_user_id":null,"coordinates":null,"geo":null,"created_at":"Thu
Apr 22 17:35:42 + 2010","contributors":null,"source":"http://twitterfeed.com\"; rel=\"nofollow\">twitterfeed","in_reply_to_status_id":null,"place":null,"truncated":false,"in_reply_to_screen_name":null,"user":
{"favourites_count":
0,"profile_text_color":"00","time_zone":"Eastern Time (US &
Canada)","created_at":"Tue Oct 27 19:50:51 +
2009","statuses_count":
286,"notifications":null,"profile_link_color":"ff","description":"I
write code and talk to people.
","lang":"en","profile_background_image_url":"http://s.twimg.com/a/
1271891196/images/themes/theme1/bg.png","profile_image_url":"http://
s.twimg.com/a/1271891196/images/
default_profile_0_normal.png","location":"Near the
water.","contributors_enabled":false,"following":null,"geo_enabled":false,"profile_sidebar_fill_color":"e0ff92","profile_background_tile":false,"screen_name":"sstatik","profile_sidebar_border_color":"87bc44","followers_count":
40,"protected":false,"verified":false,"url":"http://
elliotmurphy.com/","name":"statik","friends_count":18,"id":
85646316,"utc_offset":-18000,"profile_background_color":"9ae4e8"},"id":
12651537502,"favorited":false}
{"delete":{"status":{"id":12650137902,"user_id":128090723}}}
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Difficulty w/json keys

2010-04-23 Thread Red
Thanks to Cliff and Rolando who saw where my real problem was.
Terry,Jim: I had not seen the tutorial before, so I'll have to dig
into that as well.  So little time.

Cheers


On Apr 23, 10:06 am, "J. Cliff Dyer"  wrote:
> You need to know what your input data actually looks like, and the best
> thing for that is a little bit of formatting.  I bet you can figure out
> the problem yourself, once you see the structure of your data more
> clearly.  I've reformatted the JSON for you to help out.
>
> On Fri, 2010-04-23 at 07:20 -0700, Red wrote:
> > -- Two Sample Twitter lines -
>
> {
>   "text":"tech managers what size for your teams? better to have 10-20
> ppl per manager or 2-5 and have the managers be more hands
> on?",
>   "in_reply_to_user_id":null,
>   "coordinates":null,
>   "geo":null,
>   "created_at":"Thu Apr 22 17:35:42 + 2010",
>   "contributors":null,
>   "source":"http://twitterfeed.com\"; rel=\"nofollow
> \">twitterfeed",
>   "in_reply_to_status_id":null,
>   "place":null,
>   "truncated":false,
>   "in_reply_to_screen_name":null,
>   "user": {
>     "favourites_count":0,
>     "profile_text_color":"00",
>     "time_zone":"Eastern Time (US & Canada)",
>     "created_at":"Tue Oct 27 19:50:51 + 2009",
>     "statuses_count": 286,
>     "notifications":null,
>     "profile_link_color":"ff",
>     "description":"I write code and talk to people.",
>     "lang":"en",
>     "profile_background_image_url":"http://s.twimg.com/a/
> 1271891196/images/themes/theme1/bg.png",
>     "profile_image_url":"http://s.twimg.com/a/1271891196/images/
> default_profile_0_normal.png",
>     "location":"Near the water.",
>     "contributors_enabled":false,
>     "following":null,
>     "geo_enabled":false,
>     "profile_sidebar_fill_color":"e0ff92",
>     "profile_background_tile":false,
>     "screen_name":"sstatik",
>     "profile_sidebar_border_color":"87bc44",
>     "followers_count": 40,
>     "protected":false,
>     "verified":false,
>     "url":"http://elliotmurphy.com/";,
>     "name":"statik",
>     "friends_count":18,
>     "id":85646316,
>     "utc_offset":-18000,
>     "profile_background_color":"9ae4e8"
>   },
>   "id": 12651537502,
>   "favorited":false}
>
> {
>   "delete": {
>     "status":{
>       "id":12650137902,
>       "user_id":128090723
>     }
>   }
>
> }
>
>

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Difficulty w/json keys

2010-04-23 Thread Red
On Apr 23, 1:17 pm, Terry Reedy  wrote:
> On 4/23/2010 10:20 AM, Red wrote:
>
> > My apologies for what is probably a simple question to most on this
> > group. However, I am new to python and very new to json.
>
> > I am trying to read in a json file from a twitter download. There are,
> > generally, two types of lines: those lines with "text" and the other
> > lines.  I am only interested in the lines with "text".  I am also only
> > interested in lines with "lang":"en", but I haven't gotten far enough
> > to implement that condition in the code snippets below.
>
> > I have gotten Option 2 below to sort of work.  It works fine for
> > 'text', but doesn't work for 'lang'.
>
> You do not define 'work', 'sort of work', and "doesn't work".
>
>
>
> > FWIW I am using Python 2.6.4
>
> > Can someone tell me what I'm doing wrong with the following code
> > snippets and/or point me toward an example of an implementation?
>
> > Many thanks for your patience.
>
> > -
>
> > import sys
> > import json
>
> > f = open(sys.argv[1])
>
> > #option 1
>
> > for line in f:
> >    j = json.loads(line)
> >    try:
> >            'text' in j
>
> This does not raise an exception when false
>
> >            print "TEXT:  ", j
>
> so this should always print.
> Forget this option.
>
> >    except:
> >            print "EXCEPTION:   ", j
> >            continue
> >    else:
> >            text=j['text']
> > snip 
>
> > #option 2  does basically the same thing as option 1 ,
>
> Not at all when 'text' in not in j.
>
>   but also looks
>
> > for 'lang'
>
> > for line in f:
> >    j = json.loads(line)
> >    if 'text' in j:
> >            if 'lang' in j:
> >                    lang = j['lang']
> >                    print "language", lang
> >            text = j['text']
> > snip 
>
> tjr

I need to think about the logic here again and see what I'm missing
beyond my original question.  Thanks for taking the time to explain.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pipe in the "return" statement

2011-07-25 Thread red floyd
On Jul 25, 5:52 am, TonyO  wrote:
> > Still I dont get how I am supposed to understand the pipe and its task/
> > idea/influece on control flow, of:
> > return  | 
>
> In the words of René Magritte,
>
> return  | 
>                    ^
> Ceci n'est pas une pipe.

We have a WINNER!!

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is there any principle when writing python function

2011-08-24 Thread Red John
> "We must constantly strive to remove multiplicity from our systems;
> lest it consumes us!"
>
> s/multiplicity/rantingrick/ and I'm in full agreement.

QFT
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Free Software University - Python Certificate

2011-03-23 Thread Red John
> To me all this does not look professional for somebody who want to
> attract students / instructors

I'm a big fan of the Menu containing a (useless) link to First Menu
Item

-- 
http://mail.python.org/mailman/listinfo/python-list


No overflow in variables?

2014-01-22 Thread Philip Red
Hi everyone. First of all sorry if my english is not good.
I have a question about something in Python I can not explain:
in every programming language I know (e.g. C#) if you exceed the max-value of a 
certain type (e.g. a long-integer) you get an overflow. Here is a simple 
example in C#:

static void Main(string[] args)
{
Int64 x = Int64.MaxValue;
Console.WriteLine(x);   // output: 9223372036854775807
x = x * 2;
Console.WriteLine(x);   // output: -2 (overflow)
Console.ReadKey();
}

Now I do the same with Python:

x = 9223372036854775807
print(type(x)) #   
x = x * 2  #   18446744073709551614
print(x)   #   
print(type(x))

and I get the right output without overflow and the type is always a 'int'.
How does Python manages internally the types and their values? Where are they 
stored?

Thank you for your help :)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: No overflow in variables?

2014-01-22 Thread Philip Red
Thank you for your answers!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: No overflow in variables?

2014-01-22 Thread Philip Red
Thank you ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


ctypes & strings

2008-12-24 Thread Red Rackham
Hi friends;
 
I would like to pass a string into a dll function.  I notice that to pass using 
ctypes, it has to be a ctypes type.  Looking at the ctypes doc page I don't see 
a c_string class.  
 
I tried to pass in byref("name of string") and got back "TypeError: byref() 
argument must be a ctypes instance, not 'str'"
 
If I use astr = create_string_buffer( "name of string" ), and try to pass that 
in, I get "ValueError: Procedure probably called with too many arguments (4 
bytes in excess)".
 
If I use astr = (c_char*255)("name of string"), I get "TypeError: one character 
string expected" (on this line).
 
Could some benevolet expert please clue me in on how to accomplish this?
 
Thanks
 
Mark
 
 
 


  --
http://mail.python.org/mailman/listinfo/python-list


defaultdict's bug or feature?

2009-05-21 Thread Red Forks
from collections import defaultdict

d = defaultdict(set)
assert isinstance(d['a'], set)
assert isinstance(d.get('b'), set)

d['a'] is ok, and a new set object is insert to d, but d.get('b') won't.

It's a bug, or just a feature?

I think dict.get() method is just a *safe* version of dict[key], maybe it
should be:

def get(self, key, default = None):
  try:
return self[key]
  except KeyError:
return default
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: defaultdict's bug or feature?

2009-05-21 Thread Red Forks
You mean 'get' method should not alter the dict, does 'dict[key]' should not
alter the dict either?

d = defaultdict(set)
assert len(d) == 0
print d[1]
assert len(d) == 1

auto insert value to dict, when value is not in dict, is what defaultdict
try to do.

On Fri, May 22, 2009 at 7:46 AM, Rhodri James
wrote:

> On Thu, 21 May 2009 13:07:50 +0100, Red Forks  wrote:
>
>  from collections import defaultdict
>>
>> d = defaultdict(set)
>> assert isinstance(d['a'], set)
>> assert isinstance(d.get('b'), set)
>>
>> d['a'] is ok, and a new set object is insert to d, but d.get('b') won't.
>>
>> It's a bug, or just a feature?
>>
>
> Feature.  You're blaming 'get' for doing exactly what it said it would,
> both in returning None and not gratuitously altering the dictionary.
>
> --
> Rhodri James *-* Wildebeeste Herder to the Masses
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: defaultdict's bug or feature?

2009-05-22 Thread Red Forks
Yes, you maybe right. When use defaultdict, should not rely get() method
anymore, d[] is just enough. When a function return a defaultdict, but
people don't know it, so:

d = load_map()
# if she call d['a'], everything is OK but
# when call d.get('a'), she is always get None.
# Why she call d.get('a'), not d['a'], because she don't want to provider
default value herself (she didn't know it is a defaultdict)
It is just wield, call d[''a'] Ok, not get('a').

Sorry my poor english. Maybe somebody don't catch my mind, or maybe a little
rude.
I'm using and learning python about 2 weeks ago, spent me three hrs to find
the problem, almost drive me mad.
Maybe other like me, find some inconvience on this.

--

Actually, I steal defaultdict to do other things:

class OnloadDict(defaultdict):
def __init__(self, onload):
self.__onload = onload

def __missing__(self, key):
result = self.__onload(key)
if not result:
raise KeyError

self[key] = result
return result

def get(self, key, default = None):
''' defaultdict.get() won't call __missing__, so override '''
try:
return self[key]
except KeyError:
return default

OnloadDict, is like a cache. When the value is not in dict, using 'onload'
function to load the value by the key.
When no value correspond to a key, a KeyError will raised. So I need a
*safer* version 'get()' method.

On Fri, May 22, 2009 at 12:35 PM, Rhodri James
wrote:

> Please don't top-post, it makes the thread of argument hard to follow.
>
> On Fri, 22 May 2009 01:44:37 +0100, Red Forks  wrote:
>
>  You mean 'get' method should not alter the dict, does 'dict[key]' should
>> not
>> alter the dict either?
>>
>> d = defaultdict(set)
>> assert len(d) == 0
>> print d[1]
>> assert len(d) == 1
>>
>> auto insert value to dict, when value is not in dict, is what defaultdict
>> try to do.
>>
>
> Behaviour you are deliberately avoiding by calling `get`, since that
> explicitly behaves the same way that it does for dicts.  You're doing
> two different things through two different interfaces with two different
> specs.  Why are you expecting them to have the same effect?
>
>
> --
> Rhodri James *-* Wildebeeste Herder to the Masses
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: defaultdict's bug or feature?

2009-05-22 Thread Red Forks
On Sat, May 23, 2009 at 2:03 AM, Rhodri James
wrote:

> I asked you not to top-post.  Please put your replies *below* the
> messages you're quoting, not above.  It's much easier to understand
> the conversation that we're having if you do that, and much more
> aggravating if you don't.
>
I misunderstand you last email, thanks.

>
> On Fri, 22 May 2009 09:53:04 +0100, Red Forks  wrote:
>
>  Yes, you maybe right. When use defaultdict, should not rely get() method
>> anymore, d[] is just enough.
>>
>
> Almost.  You should rely on get() to do what it says, not what you think
> it should do.  That's generally true, by the way; when the Fine Manual
> says that a class, function or method will do one thing, expecting it to
> do something else is unreasonable.
>
>  Actually, I steal defaultdict to do other things:
>>
>> class OnloadDict(defaultdict):
>>def __init__(self, onload):
>>self.__onload = onload
>>
>>def __missing__(self, key):
>>result = self.__onload(key)
>>if not result:
>>raise KeyError
>>
>>self[key] = result
>>return result
>>
>>def get(self, key, default = None):
>>''' defaultdict.get() won't call __missing__, so override '''
>>try:
>>return self[key]
>>except KeyError:
>>return default
>>
>> OnloadDict, is like a cache. When the value is not in dict, using 'onload'
>> function to load the value by the key.
>> When no value correspond to a key, a KeyError will raised. So I need a
>> *safer* version 'get()' method.
>>
>
> Why are you so determined to (ab)use get() on your class?  You should
> only be calling OnloadDict.get() if you really mean "get me the value
> associated with this key, or the default I'm telling you about *right*
> *now* if there isn't one."

The key point is: "what key/value pairs should in defaultdict". I think any
key/default pair(they'll add to dict when you ask for it), maybe you think
only manual added pairs.
defaultdict break dict rules, that a query method (d[key]) should not modify
dict, so another query method (the get() method) break default rule is not a
big deal.
Never mind, my "get()" method hack works OK.

>
>
> Aside from that, this is neat.  Strictly you should call
> defaultdict.__init__(self) in your __init__() function just in case
> defaultdict needs any setup that you aren't doing (which it does, but
> you override __missing__() so it never notices that it doesn't have
> a default_factory).  You get away with it here, but it's not a good
> habit to get into.
>
I'm new to python, adding  'defaultdict.__init__()' call would be nice. In
other languages, base class's default constructor is automaticlly called.

>
> --
> Rhodri James *-* Wildebeeste Herder to the Masses
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: multi-core software

2009-06-05 Thread Red Forks
Single - thread programming is great! clean, safe!!!
I'm trying schedual task to several work process (not thread).
On Fri, Jun 5, 2009 at 4:49 AM, MRAB  wrote:

> Kaz Kylheku wrote:
>
>> ["Followup-To:" header set to comp.lang.lisp.]
>> On 2009-06-04, Roedy Green  wrote:
>>
>>> On Thu, 4 Jun 2009 09:46:44 -0700 (PDT), Xah Lee 
>>> wrote, quoted or indirectly quoted someone who said :
>>>
>>>  • Why Must Software Be Rewritten For Multi-Core Processors?

>>> Threads have been part of Java since Day 1.
>>>
>>
>> Unfortunately, not sane threads designed by people who actually understand
>> multithreading.
>>
>>  The nice thing about Java is whether you are on a single core
>>> processor or a 256 CPU machine (We got to run our Athena Integer Java
>>> spreadsheet engine on such a beast), does not concern your code.
>>>
>>
>> You are dreaming if you think that there are any circumstances (other than
>> circumstances in which performance doesn't matter) in which you don't have
>> to
>> concern yourself about the difference between a uniprocessor and a 256 CPU
>> machine.
>>
>
> If you're interested in parallel programming, have a look at Flow-Based
> Programming:
>
> http://www.jpaulmorrison.com/fbp/
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PYTHONPATH and multiple python versions

2009-06-05 Thread Red Forks
maybe a shell script to switch PYTHONPATH, like:
start-python-2.5
start-python-2.4 ...
On Fri, Jun 5, 2009 at 4:56 PM, David Cournapeau  wrote:

> Hi,
>
> As I don't have admin privileges on my main dev machine, I install a
> good deal of python modules somewhere in my $HOME, using PYTHONPATH to
> point my python intepreter to the right location. I think PEP370
> (per-user site-packages) does exactly what I need, but it works only
> for python 2.6 and above. Am I out of luck for versions below ?
>
> David
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Interesting things of 'getattr' and 'setattr'

2009-12-15 Thread Red Forks
I don't know it is a feature, or implement detail:

>>> class C(object): pass
...
>>> c = C()
>>> setattr(c, ' ', 3)
>>> getattr(c, ' ')
3
>>> setattr(c, 'with blank', 4)
>>> getattr(c, 'with blank')
4

getattr / setattr seems treat any string as attribute name.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Google AI challenge: planet war. Lisp won.

2010-12-04 Thread Red John
>
> Yeah, riiight.  So it's a crime to have any fun in life, right?  Go get
> a life.
>
> -- Benjamin L. Russell

+1
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IDLE: A cornicopia of mediocrity and obfuscation.

2011-02-01 Thread Red John
On Feb 1, 10:26 am, rantingrick  wrote:
> On Feb 1, 10:29 am, "Littlefield, Tyler"  wrote:
>
> > I hope everyone will
> > excuse me now, I must dash off to slit  my wrists in a tub of warm water
> > and listen to Free Bird,
>
> Free Bird! hmm, I would have chosen Chopin's nocturne 48-1 or 72-1 if
> i was feeling rather melancholy at the moment. Then there is always
> the funeral march if you really want to lay it on thick. However the
> march does have a rather lengthy "hopeful" section that may make you
> give second thoughts. Or perhaps the Berceuse in D-flat Major as a
> final glorious celebration of life as one journeys beyond the edge of
> transcendence. If there is a heaven it must sound like this...
>
>    http://il.youtube.com/watch?v=8TQ-AXJZqtg
>
> ...only a man who suffered so greatly can know what true beauty is.
> RIP Chopin.
>
> If you're going to met your end it should be at least to a piece that
> is truly timeless -- not some reefer+jack induced rockabilly ballad!

Go away. You are easily one of the worst (and definitely most
annoying) person I've encountered in person or online, which is saying
something because I used to frequent 4chan.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IDLE: A cornicopia of mediocrity and obfuscation.

2011-02-02 Thread Red John
On Feb 1, 11:23 am, rantingrick  wrote:

> Hmm, that coming from someone who has two posts in this group. And the
> last he posted was a year ago! Alright, let me add you to the proper
> category...
>
> py> troll_group.append("Red John")

I realize that not agreeing with you is enough to be labeled a troll -
which is fine with me, a lot of my favorite posters were in that
group :) - but I fail to see how it's relevant that I prefer reading
others' ideas.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IDLE: A cornicopia of mediocrity and obfuscation.

2011-02-03 Thread Red John
On Feb 2, 9:03 pm, alex23  wrote:
> rantingrick  wrote:
> > Hmm, that coming from someone who has two posts in this group. And the
> > last he posted was a year ago!
>
> Wait, I thought you had the approval of the silent majority?
>
> So once anyone actually posts, they lost the right to be counted,
> because only when they shut up can you consider them allies?

Lulz, +1 internetz for you
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dynamically modify help text

2010-06-27 Thread Red Forks
Read you doc file and set the __doc__ attr of the object you want to change.

On Monday, June 28, 2010, Brian Blais  wrote:
> Hello,
>
> I know that the help text for an object will give a description of every 
> method based on the doc string.  Is there a way to add something to this 
> text, specific to an object, but generated at run-time?  I have an object 
> that reads a file, and I would like part of that file to be shown if one 
> does:  help(myobject)
>
>
>                         thanks,
>
>                                 Brian Blais
>
> --
> Brian Blais
> bbl...@bryant.edu
> http://web.bryant.edu/~bblais
> http://bblais.blogspot.com/
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: string.Template issue

2009-08-01 Thread Red Forks
On Thu, Jul 30, 2009 at 4:17 PM, Javier Collado wrote:

> Hello,
>
> In the string.Template documentation
> (http://docs.python.org/library/string.html) it's explained that if a
> custom regular expression for pattern substitution is needed, it's
> possible to override idpattern class attribute (whose default value is
> [_a-z][_a-z0-9]*).
>
> However, if the custom pattern that is needed is just uppercase
> letters something like [A-Z]+ won't work because of the following line
> in the _TemplateMetaclass class __init__ method:
> cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)

derive a new class, and replace __init__ method, or
replace _TemplateMetaclass.__init__() method.

>


>
> I would say that this is an error (IGNORECASE just shouldn't be there)
> and that the line above should be:
> cls.pattern = _re.compile(pattern, _re.VERBOSE)
> and the default value for idpattern:
> [_a-zA-Z][_a-zA-Z0-9]*
>
> Do you agree on this? Is there any reason for the IGNORECASE option to
> be passed to re.compile?
>
> Best regards,
>Javier
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Custom namespaces

2009-08-01 Thread Red Forks
On Sun, Aug 2, 2009 at 9:06 AM, Steven D'Aprano <
st...@remove-this-cybersource.com.au> wrote:

> I was playing around with a custom mapping type, and I wanted to use it
> as a namespace, so I tried to use it as my module __dict__:
>
> >>> import __main__
> >>> __main__.__dict__ = MyNamespace()
> Traceback (most recent call last):
>  File "", line 1, in 
> TypeError: readonly attribute
>
> Why is __dict__ made read-only?

to protect module type? Use .update() method:
__main.__.__dict__.update(MyNamespace())
You can create your own Module instance:
from types import ModuleType
m = ModuleType('modulename')
and make a sub class of ModuleType is also OK

>
>
> I next thought I could change the type of the namespace to my class:
>
> >>> __main__.__dict__.__class__ = MyNamespace
> Traceback (most recent call last):
>  File "", line 1, in 
> TypeError: __class__ assignment: only for heap types
>
> Drat, foiled again!!!
>
> Okay, if I can't do this at the module level, can I at least install a
> custom namespace at the class level?
>
> >>> class MyNamespace(dict):
> ... def __getitem__(self, key):
> ... print "Looking up key '%s'" % key
> ... return super(MyNamespace, self).__getitem__(key)
> ...
> >>> namespace = MyNamespace(x=1, y=2, z=3)
> >>> namespace['x']
> Looking up key 'x'
> 1
> >>> C = new.classobj("C", (object,), namespace)
> >>> C.x
> 1
>
> Apparently not. It looks like the namespace provided to the class
> constructor gets copied when the class is made.
>
> Interestingly enough, the namespace argument gets modified *before* it
> gets copied, which has an unwanted side-effect:
>
> >>> namespace
> {'y': 2, 'x': 1, '__module__': '__main__', 'z': 3, '__doc__': None}
>
>
> Is there any way to install a custom type as a namespace?
>
>
>
> --
> Steven
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


red bull hats, monster energy hats, red bull t shirts, monster energy t shirts, snapback hats on www.theworldhats.com

2011-09-29 Thread red bull hats red bull hats
 www.theworldhats.com are promoting

the products:

red bull hats:http://www.theworldhats.com/category-130-b0-Red-Bull-
Hats.html

snapback hats: http://www.theworldhats.com/category-230-b0-Snapback-Hats.html

monster energy hats: 
http://www.theworldhats.com/category-128-b0-Monster-Energy-Hats.html

red bull t shirts:http://www.theworldhats.com/category-227-b0-Red-Bull-
T-shirts.html

monster energy t shirts:http://www.theworldhats.com/category-203-b0-
Monster-Energy-T-shirts.html

website: www.theworldhats.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Euclid's Algorithm in Python?

2005-08-04 Thread Erik the Red
In Fundamental Algorithms (The Art of Computer Programming), the first
algorithm discussed is Euclid's Algorithm.

The only idea I have of writing this in python is that it must involve
usage of the modulo % sign.

How do I write this in python?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Euclid's Algorithm in Python?

2005-08-07 Thread Erik the Red
So, I did the following:
---
a=input("Give me an integer")
b=input("Give me another integer")

def gcd(a,b):

if a < b:
 a, b = b, a
while b != 0:
 a, b = b, a % b
return a
---
But, in the xterm, it terminates after "Give me another integer."

Is Euclid's Algorithm supposed to be implemented in such a way as to be
used as a tool to find the GCD of two integers, or have I
misinterpreted the intent of the algorithm?

-- 
http://mail.python.org/mailman/listinfo/python-list


Fwd: Re: Logging question

2009-12-16 Thread Vinay Sajip at Red Dove


 Original Message 
Subject:Re: Logging question
Date:   Tue, 15 Dec 2009 18:28:54 +
From:   Vinay Sajip at Red Dove 
To: Yaroslav Molochko 



On 15/12/2009 14:29, Yaroslav Molochko wrote:
> Hello Vinay Sajip,
>
> my name is Yaroslav, I'm trying to use your logging module, and it's
> working quite good. There is one issue I've figure out:
>
> logging.basicConfig(filename=c_logfile,
> level=logging_level, # By default logging is
> in INFO mode. You can change it to DEBUG by -v variable
> format="gert
> :%(asctime)-10s%(msecs)d:%(levelname)s: %(message)s",
> datefmt='%d%m %H%M%S.',)
>
> if I use it, and delete the logfile it will not create the logfile
> again. Only restart of the application will do. Is there any
> workaround for this?
>

Hello Yaroslav,

Once you create a FileHandler, the file "belongs" to the logging package
which assumes it has exclusive access to the file. If the file is
deleted, in order to log to it again, you need to remove the existing
handler, close it, open a new handler, and attach it to the root logger.
For this you will have to use the other logging API functions.

Please post questions like this on comp.lang.python so that others can
join in the discussion.

Regards,

Vinay Sajip


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question to logging

2009-12-16 Thread Vinay Sajip at Red Dove
On 16/12/2009 12:49, stefan.messerl...@postfinance.ch wrote:
> I have the following error and no clue, how to solve that. Up to python 
> version 2.5 the following script worked without an error, but since python 
> 2.6. I get the following error:
>
> #!/usr/bin/env python
> # -*- coding: ISO-8859-1 -*-
> import logging
> logging.getLogger().addHandler( logging.StreamHandler() )
> log = logging.getLogger()
> t = "äöü"
> print "this is printed   : " + t
> log.error( "this is log.error : " + t )
>
>
>
> # running the above script with Python 2.5
> $ ./x.py
> this is printed   : äöü
> this is log.error : äöü
>
>
> # running the above script with Python 2.6
> $ ./x.py
> this is printed   : äöü
> Traceback (most recent call last):
>   File 
> "/var/tmp/pf-python-2.6-2.6.1-root/appl_local/python-2.6/lib/python2.6/logging/__init__.py",
>  line 765, in emit
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 20: 
> ordinal not in range(128)
>
>
> I found your answer of issue6991 in bugs.python.org, where somebody had a 
> similar problem, but to be honest, I have no idea how to solve my problem.
>
> Can you please give me a tip what I have to change or where I can find more 
> information ?
>   

Hello Stefan,

You should pass a stream to StreamHandler which has an encoding
attribute set to the appropriate encoding (presumably iso-8859-1) and
ensure that your stream will encode any Unicode sent to it with that
encoding. For example,

import codecs
ENCODING = 'iso-8859-1' # or whatever
writer = codecs.getwriter(ENCODING)
w = writer(sys.stderr)
w.encoding = ENCODING
...
handler = logging.StreamHandler(w)
...

In future, please ask questions like this on comp.lang.python
(python-list@python.org) to give others the chance to participate in any
discussion.

Regards,

Vinay Sajip


-- 
http://mail.python.org/mailman/listinfo/python-list