lrh9 95 Posting Whiz in Training

Well. According to the inductive reasoning involving the first law of thermodynamics, we can be fairly confident that the universe has existed in some form or another for eternity. It just may have been in a form we cannot currently learn about or understand.

lrh9 95 Posting Whiz in Training

A picture or multiple pictures are just extremely small slices of a person's life. It doesn't represent the whole of person's life. There will be times when a manic person will be placid, or an agoraphobic person will go out in public.

As long as someone is going to an accredited physician, I'm going to wait for the doctor's word - the expert - instead of the opinions of bean counters.

lrh9 95 Posting Whiz in Training

I just looked at the links at the bottom of that wiki page. They're very informative.

lrh9 95 Posting Whiz in Training

Autopython is almost right. Correct me if I'm wrong: no matter how long the code is the value is always the same length. If so this is called signing and it uses a hash function to shorten the code and then uses a public key cipher signing method to encrypt that which is the unique value. Or it may simply just hash the code but I assume not

Basically it's just a fixed length hash of the code, and maybe a developer's private key. The most common hashing algorithms used to hash the code are MD5, SHA1, and SHA2.

The primary use is a user or utility can examine the hash value of the code, and check it against a hash value on a site. If the hash values are the same, the user can be highly certain that the code came from that source and that the code hasn't been modified.

However, there are some other features.

http://en.wikipedia.org/wiki/Code_signing

lrh9 95 Posting Whiz in Training

Isn't it the join() method of the thread?

lrh9 95 Posting Whiz in Training

No. That's not it. The code isn't encrypted. A value is created from the code, and if it doesn't match your certificate, the code has been altered.

lrh9 95 Posting Whiz in Training

According to your code, you are replacing all periods with spaces. If you want to replace the dots with absolutely nothing, then use two quotes side by side. ""

However, as for the script itself. Seems to me if you moved the outfile.write() outside of the loop, and changed it to outfile.write(infile), it would work.

Try that.

lrh9 95 Posting Whiz in Training

There is a security technique known as code signing. It basically generates a certificate for your code. This certificate first certifies the author of the code. Second, it has a value generated from the code. This value is unique to that code. If any changes are made to the code, then the certificate is invalidated.

I'm just not sure how to go about doing it. I'd like to do my own. There have a paid certificate authority services, but I don't have the money to pay. There are free certificate authority services, but I'm not sure exactly which service I'd need, so I need to learn more about it.

lrh9 95 Posting Whiz in Training

Sounds like your agents are plugins with no pre-defined interface. To load such modules, you can use this snippet.

I just wanted to see if it could be done. I haven't thought of how someone would interface with it yet.

lrh9 95 Posting Whiz in Training

Is this what you mean ?

class Agent:
    def __init__(self):
        exec "import random" in self.__dict__


ag = Agent()

print ag.random.randrange(100) # this works

print random.randrange(100) # this doesn't work (random not in global namespace)

Oh. "__dict__" is the object's dictionary. Thank you for telling me that.

That was the same idea I had at first, but I couldn't find it. However, I think my solution is slightly more flexible because I can create a new agent with the modules of a previous agent. In your solution, I couldn't copy the object's dictionary because each agent is supposed to have at least one unique value. Thank you for trying, and you did help.

lrh9 95 Posting Whiz in Training

Sorry about all that code. I was in a rush. Next time I'll post only the relevant sections of the source.

lrh9 95 Posting Whiz in Training

Looks good. It looks better than what I wrote. I'll have to give it all a look over though.

Here's what I did.

#!/usr/bin/env python

from uuid import uuid4 as _uuid4
from importlib import import_module as _import

class Agent:

    def __init__(self, name = None):
        self._uuid = _uuid4()   # Universally unique identifier.
        if name is None:
            name = self.uuid
        self.name = name
        self._modules = {}      # Agent's modules dictionary.


    def _get_uuid(self):
        return self._uuid

    uuid = property(_get_uuid)  # help(property)


    def _get_name(self):
        return self._name

    def _set_name(self, name):
        self._name = name

    def _del_name(self):
        self._name = self.uuid

    name = property(_get_name, _set_name, _del_name)


    def add_module(self, name, package = None):
        self._modules[name] = _import(name, package)

    def _get_modules(self):
        return self._modules

    def _set_modules(self, modules):
        self._modules = modules

    def _del_modules(self):
        self._modules = {}

    modules = property(_get_modules, _set_modules, _del_modules)

def main():
    try:
        bond = Agent()  # Software agents, not secret agents.
        print(bond.name)
        bond.name = "James Bond"
        print(bond.name)
        print(bond.uuid)
        print(bond.modules)
        bond.add_module('random')
        print(bond.modules['random'].random())
        trevelyan = Agent("Alec Trevelyan")
        print(trevelyan.name)
        print(trevelyan.uuid)
        trevelyan.modules = bond.modules
        print(trevelyan.modules)
        print(trevelyan.modules['random'].random())
        del trevelyan.modules
        print(trevelyan.modules)
    finally:
        pass

if __name__ == "__main__":
    main()
lrh9 95 Posting Whiz in Training

To access functions in a module in the module dictionary, you simply use:

In an object's method:

self.modules[module_name].function(arguments)

Externally:

x = Agent()
x.modules[module_name].function(arguments)

Where "module_name" is a string or variable containing a string that is the module's name, or the name the module was assigned on import. "function" is the name of the function in the module, and "arguments" are the arguments to the function. I just posted this to let everyone know it can be done. I'll refine my code and post it so everyone can have a clearer and more complete picture of how it works.

lrh9 95 Posting Whiz in Training

I'm just wondering if it is possible to import a module as an object attribute.

The basic description of what I want to accomplish is that I'm creating a software agent object. This agent will have a set of abilities (functions), but I don't know what these are ahead of time. Logically, it is simplest to encapsulate these abilities in a module, and then have the agent import it. Then it would have access to these abilities. This would also allow it to use the standard modules or any other previously developed modules. Another benefit is that each object has its own namespace for modules. If all modules were in the global namespace of the program, every agent would have access to it. This is something I do not want.

Now I obviously don't know how things work, so I resorted to perhaps one of the worse ways to code something: experimentation. The first thing I tried was to simply attempt to import a module as an object attribute. That failed. Then I checked to ensure that a module could indeed be imported to a local namespace. So I defined a class method that imported the random module, printed the local dictionary, and printed a random number. Then to ensure that the module was only accessible by that function, and not globally, I tried to print a random number in the main function. random was in the local dictionary for the test function, and it printed a random …

lrh9 95 Posting Whiz in Training

I do this:
link = soup.find(attrs={'class' : re.compile("util2$")})
print dir(link)

what appear is:


OMG

You can import the module pprint, and using the function pprint, you can display each function and variable on its own line.

from pprint import pprint

link = soup.find(attrs={'class':re.compile("util2$")})
pprint(dir(link))
lrh9 95 Posting Whiz in Training

A truly empty value is None.

mylist = [None] * 5

Creates a list with five empty elements.

pythopian commented: Read posts carefully and think twice before attacking somebody's reputation! +0
lrh9 95 Posting Whiz in Training
lrh9 95 Posting Whiz in Training

I'd like to give a dissenting opinion.

All though functional design and code can be smaller than object oriented design and code for small programs, I still think it is better to always use object oriented programming techniques.

Why do I think this?

1) Object oriented design and code aids program clarity, helping software developers understand the purpose and function of a program. Writing a small program using object oriented programming - though it takes more time and forethought on the developer's part - can reduce the time it takes other developers to learn the program. It may even help the original developer after he or she is no longer familiar with the code.

2) Object oriented code is relocatable, reusable, and flexible. Using object oriented programming in Python, you can quickly place your most often used classes in modules and import them in all future programs you write. Object oriented programming provides the benefit of encapsulating and abstracting functionality, allowing developers to focus on interfacing code instead of rewriting the internal mechanics.

lrh9 95 Posting Whiz in Training

It's more object oriented than most code posted here, but there are more ways to use object oriented design and code in this program.

For instance, there could be a general class for a menu.

lrh9 95 Posting Whiz in Training

Does anyone have a good synonym for exclude or include. This post could certainly use one.

Permit and deny might be good synonyms for include and exclude in this instance.

This will allow for the later use of duck typing for example, and it is best to treat fellow programmers as competent.

- Paddy.

Duck typing. If it looks like a duck and quacks like a duck, it's a duck. When validating data using duck typing, you perform a set of actions to test whether the data acts a certain way. Unlike checking whether the data is an instance of a certain object, this allows developer and user created objects to work so long as they operate like the a certain object.

lrh9 95 Posting Whiz in Training

EDIT: I think I understand now. You're saying the real program that you made didn't work but this test script did? If that's the case disregard my above questions

That's what I meant. I'm sorry I wasn't clear.

It easier to help if you post some code and explain what the problem is.

Basically I'm trying to show these individuals a little object oriented design and code.

http://www.daniweb.com/forums/thread232741.html

http://www.daniweb.com/forums/thread232184.html

I was working on writing something similar to the first one, nothing complex but just a player class, a monster class, and a small battle, when I wanted to write a few methods. I wrote a method for a player to select among battle options, but only coded one option. The "attack" option. Then the player would need to select his or her target. So instead of taking time to code a way to display the monsters in the current battle and select from one, I just hard coded a target. Then I'd call the actual attack method to trigger the target's on hit method. That's where it failed. I'll probably go back and write the test battle with just one opponent.

I haven't worked on the second one yet.

lrh9 95 Posting Whiz in Training

That works fine if the second class builds on the function of the first. I'm talking about messaging between two conceptually different objects.

lrh9 95 Posting Whiz in Training

OK. I tested calling one object's methods from another object like so.

class Test:

    def Call_Test2_Method(self, target):
        target.Test2_Method()


class Test2:

    def Test2_Method(self):
        print("This is Test2's method.")


x = Test()
y = Test2()

x.Call_Test2_Method(y)

def nested_test():
    c = Test()
    d = Test2()

    c.Call_Test2_Method(d)

def test():
    a = Test()
    b = Test2()

    a.Call_Test2_Method(b)

    nested_test()

test()

I obtained:

This is Test2's method.
This is Test2's method.
This is Test2's method.

Must be a bug in my actual program.

lrh9 95 Posting Whiz in Training

I want to call another object's methods from another object, and I have no idea how.

Can someone please help me? Thank you.

lrh9 95 Posting Whiz in Training

Graphical user interfaces and object oriented program are not the same thing.

Object oriented programming is designing and coding programs based on objects and their interactions.

Object oriented programming would allow you to code more in less time and greatly improve the structure and function of your programs. Only requiring a little forethought.

lrh9 95 Posting Whiz in Training

Jesus Christ. Get some object oriented design and code in that program ASAP!

lrh9 95 Posting Whiz in Training

So I'm interested in learning about data validation. Especially in Python.

Python all ready has several common idioms for data validation.

There are several statements that evaluate data. For instance, isinstance(object, classinfo) will check that the given object is an instance of the class or type in classinfo.

One idiom is that it is better to ask forgiveness than permission, which basically means it is better to try something and catch the errors instead of trying to force the data to be valid. The main language feature that supports this idiom is the try statement and its associated statements.

It can be very bulky to write. I wonder if it would be possible to write a function wrapper to simplify the writing of such a check or if such wrapper would be worth it or appropriate.

In addition, it can only catch general errors. Sometimes what is technically valid input is invalid input according to design specifications. Now I've read that there is a way for a user to create their own errors and exceptions. Now I don't know if this is true or not, but if it is that would seem the most natural thing to do.

However, another option might be to create custom data validation functions. I'm not talking about the poorly coded "if x != 1 and x != 2 and x != 3", but powerful yet general functions to ensure that data is valid.

Here's the Wikipedia entry …

lrh9 95 Posting Whiz in Training

Here are some RSS related Python libraries that might help you.

http://wiki.python.org/moin/RssLibraries

lrh9 95 Posting Whiz in Training

Is it a good idea to help people with object oriented software design and code?

I'm asking this because most of the code here is written using the functional programming, and all could probably improve a little or a lot with object oriented design and coding.

My first doubt about offering this type of assistance stems from the large amount of homework questions. Courses don't allow you to put advanced techniques in assignments and tests designed to understand the basic material. If you turn in a program written with classes while you're just beginning to learn about defining functions, you'll probably get a big fat F.

That would be good for people who simply copy pasta (copy and paste) code. They're cheaters and deserve to fail. However, for people who actually learn the material, understand it, and adopt it in their normal use, this is unfair. They wouldn't be able to turn in the code they built despite being legitimate. However, they might learn from it and make use of it in future class work and their personal code.

So basically what I'm asking is is this type of assistance worth the time and effort of rendering?

lrh9 95 Posting Whiz in Training

I don't know. I'd probably just check that the user's input was in a tuple containing the appropriate input values.

lrh9 95 Posting Whiz in Training

Popitem is not meant to be a random generator.

What does it do then? How is it used?

lrh9 95 Posting Whiz in Training

You can use str.count(sub, [, start [, end]]) to count the instances of a substring in a string.

lrh9 95 Posting Whiz in Training

Actually, dictionaries have a popitem method that returns an arbitrary key and value.

I don't know how much a difference there is to using my method or a dictionary though.

lrh9 95 Posting Whiz in Training

I wonder how list slicing or struct.unpack() would work.

lrh9 95 Posting Whiz in Training

So what you basically want is to fill the list with a sequence of numbers? Why?

lrh9 95 Posting Whiz in Training

Object oriented programming is designing and coding software based on objects. Classes are a conceptual abstraction (a way of representing a complex idea with a simpler idea) that have properties. Classes serve as blueprints for the creation of objects. Objects are the actual items in a program. A object's properties are its attributes, which are characteristics of the object, and its methods, which represent things the object can do or how it can interact with other objects. Objects have the ability to message other objects. This is the way an objects methods are invoked or data is sent to the object.

Another object oriented programming feature is inheritance. Classes can inherit properties and methods from other classes. This allows for specialized objects that have their own attributes as well as general attributes that they share with other objects.

Object oriented programming supports hiding the complexity of a method or object with abstraction and encapsulation. Using abstraction, a programmer can focus on interfacing working components instead of focusing on the internal workings of each component, and using encapsulation, a programmer can use encapsulation to ensure that only the appropriate objects can message an object.

The final major feature of object oriented programming is polymorphism. Polymorphism is the ability of an object to respond to method calls using its own appropriate method.

I'll answer questions now.

lrh9 95 Posting Whiz in Training

Here's what I came up with.

#!/usr/bin/env python

import random

class pool(list):
    
    def rand_index(self):
        length = len(self)
        return random.randint(0, length - 1)

    def unique_rand(self):
        return self.pop(self.rand_index())

def main():
    print("""Prints each element in a sequence at random once and only once.""")
    my_pool = pool("AaBbCcDd")
    print(my_pool.unique_rand())
    print(my_pool.unique_rand())
    print(my_pool.unique_rand())
    print(my_pool.unique_rand())
    print(my_pool.unique_rand())
    print(my_pool.unique_rand())
    print(my_pool.unique_rand())
    print(my_pool.unique_rand())
    try:
        print(my_pool.unique_rand())
    except:
        print("The ninth attempt failed because it attempted to remove a ninth element from a sequence of eight elements that had eight previous removals.")
    
    
if __name__ == "__main__":
    main()
lrh9 95 Posting Whiz in Training

It confuses me. I've never had to understand random number generation and pseudo random number generation before. I might be wrong and you might be right. There might be nothing mathematically wrong with shuffle.

However, I do think it is a fair idea that given two options for accomplishing something, it is probably better to use the option that is conceptually simpler if you have trouble understanding the more complex one or if you have trouble understanding both.

Of course, after reviewing the list object, I think the point might be moot. If your goal is to obtain a random element from a list and then remove it, then it would be simplest to use the list.pop(index) method where index is a randomly generated number.

*Smacks forehead.*

lrh9 95 Posting Whiz in Training

I still don't agree. It's very easy to write a shuffle function

from random import randrange

def my_shuffle(the_list):
    n = len(the_list)
    while n > 1:
        i = randrange(n)
        the_list[i], the_list[n-1] = the_list[n-1], the_list[i]
        n -= 1

L = range(10)
my_shuffle(L)
print(L)

Shuffle generates only one permutation. Now since each permutation of n objects is the product of at most n transpositions, you only need to generate at most n random transpositions in a set of order O(n^2) possible transpositions.

So what you're saying is that as the number of permutations exceeds the period of Python's random number generator, each index has an equally probable chance of being relocated to the beginning? Can you prove this?

lrh9 95 Posting Whiz in Training

I don't understand the argument. If you succeed in writing your random generator differently, it will be an alternative to shuffle. Can you explain more precisely the probabilistic argument ? I think that with shuffle, each item has the same probability to be at a given position in the generated sequence.

Because the number of permutations exceeds the period of the random number generator, some sequences will never be returned by the function.

lrh9 95 Posting Whiz in Training

Why don't you just use shuffle ?

from random import shuffle

def random_unique(sequence):
    L = list(sequence)
    shuffle(L)
    return iter(L)

for x in random_unique(range(10)):
    print(x)

There are more permutations for a sequence than there are indexes in a sequence. The total number of permutations for even a small sequence can exceed the period of most random number generators. While this probably has little impact for a person merely seeking to rearrange a sequence in place, when you want to obtain only one value each value in the sequence would not have an equally probable chance of being at the point which you sample the resulting permutation.

lrh9 95 Posting Whiz in Training

Actually, it would probably be better to create a new class that inherits another sequence. This might allow this new object to use all of the old methods of the inherited object and have a new method for returning and removing a element of the sequence.

lrh9 95 Posting Whiz in Training

I always wondered how a programmer could efficiently generate a random number from a set* of numbers once and only once.

I quickly realized the inefficient solution. Simply generate the number and if it equals one you have all ready generated then regenerate the number.

Regenerating the number is a poor method. Especially in a small set or if you are going to exhaust the elements in the set.

Today I realized a smarter solution. Instead of using random to generate a number that is in the set, use random to generate the index of a element in the set and then return that value and remove the element from the set.

Now I'm just wondering what the best way to implement this is.

It would be relatively simple to implement it in a function, but part of the procedure is modifying the list in question. Python documentation labels modifying lists within a function as a bad practice. I just don't understand why. I also can't understand how to get around this either at the moment.

* By set, I don't necessarily mean Python's built in set object. This would probably be implemented using a mutable sequence.

lrh9 95 Posting Whiz in Training

Is anyone else besides me thinking Python sets might be a good tool to use to solve this?

Edit: Actually this probably won't work. According to Python documentation on sets, sets are containers for unique objects.

lrh9 95 Posting Whiz in Training

Strange how I missed that even after looking at the Python documentation for strings.

lrh9 95 Posting Whiz in Training

Out of curiosity, how would you reverse a string's case in Python? Make uppercase characters lowercase and lowercase characters uppercase.

Here's the function for the naive implementation.

#!/usr/bin/env python

def flip_case(input_string):
    temp_list = list(input_string)
    for index, character in enumerate(temp_list):
        if character.islower():
            temp_list[index] = character.upper()
        else:
            temp_list[index] = character.lower()
    output_string = ''.join(temp_list)
    return output_string

my_string = "AaBbCc"

my_string = flip_case(my_string)

print(my_string)

The output is:

aAbBcC

I'm thinking a smarter implementation would be to use a string's translate method. What do you think?

lrh9 95 Posting Whiz in Training

I'm wondering why is there a requirement that the code be written using a while loop?

Is it a requirement as part of an assignment?

Is it just to learn the while loop better?

Is it a personal belief that the while loop is a better or the best method to use? It may well be. I'm just curious.

lrh9 95 Posting Whiz in Training

To answer the coding problem, I think that the word "init" has to be wrapped in double underscores.

lrh9 95 Posting Whiz in Training

Hello. I'm lrh9, a new user. This is my first time visiting these forums. I've posted on www.programmingforums.org under the same user name.

I'm a hobbyist and amateur computer programmer. My primary languages are C++, a custom scripting language for Windows named AutoHotkey, and Python which I've just started out learning but am determined to learn. I learned some Visual Basic 6 - my first programming language -in high school, but I've forgotten most of it. I've also used programming features of graphing calculators to a small extent.

I think I'm naturally inclined to computer programming. When I was a child, I'd often assemble and disassemble objects to learn how they worked. Legos were one of my favorite toys for instance. It was a relatively easy transition from assembling and disassembling physical components to assembling and disassembling virtual components.

I was introduced to computing technologies when my mother bought me my first video gaming system, the Sega Genesis. It was only natural that when I encountered computer games, I wanted a computer. My grandmother purchased my first computer in the late 1990s, my second around 2005, and I assembled a computer using parts purchased with my own money this year.

My current interest in software development is general purpose artificial intelligence. I am an amateur a.i. researcher, with a focus in computer learning. After surveying approaches to artificial intelligence last year, I decided that I'd pursue the child machine hypothesis as it made the …