コード例 #1
0
ファイル: appcnt.py プロジェクト: Kasumiiii/WebAppPrac
    def update_data(self):
        validator = Validator()
        err = validator.check(self._answer)

        if not err:
            db_cnt = DBcnt()
            update_data = db_cnt.update_data(self._answer)
            return update_data, True
        else:
            return err, False
コード例 #2
0
ファイル: appcnt.py プロジェクト: Kasumiiii/WebAppPrac
    def val(self):
        # print(self._answer)

        validator = Validator()
        err = validator.check(self._answer)

        if not err:
            val_data = self._answer
            db_cnt = DBcnt()
            db_cnt.add_data(val_data)
            return val_data, True
        else:
            return err, False
コード例 #3
0
ファイル: api_views.py プロジェクト: jaredwy/taskoverflow
def apigen_validate(param_container, instructions, errors):
    # define the validated field values
    validated_fieldvalues = {}
    
    # create the validator 
    vinst = Validator({ 'datetime': is_datetime })
    
    # iterate through the instructions and check to see if everything stacks up
    for fname, finst in instructions.iteritems():
        logging.info("checking validity of field: %s\n" % fname)
        
        # get the field value
        field_value = None
        if param_container.__contains__(fname):
            field_value = param_container[fname]
            
        # save the field data to the dict
        validated_fieldvalues[fname] = field_value

        # if the field is required and no data is supplied then add a validation error
        if finst['required'] and (not field_value):
            errors.append(create_error("validation", message = "Field is required", target = fname))
        
        # TODO: run sql injection attack checks
        
        # if we get past the requiredness check, let run the specified validators
        elif finst.__contains__('checks') and finst['checks']:
            # iterate through the validators and dynamically run
            for check_name in finst['checks']:
                logging.info("running check %s\n" % check_name)
                
                # ask the validator to run the required check
                try:
                    # print >> sys.stderr, "attempting to call module function %s" % dir(validators),
                    validated_fieldvalues[fname] = vinst.check(check_name, field_value)
                except ValidateError, err:
                    logging.info("Caught validation error %s" % err.message)
                    errors.append(create_error("validation", message = err.message, target = fname))
コード例 #4
0
ファイル: CandidateAI.py プロジェクト: elixxx/Method-of-AI
class CandidateAI:
    """ Implement the Candidate and the Function used by the genetic Algorithm
    """
    _fitness = None

    def __init__(self, assignments):
        """ Create an Candidate


        :param assignments:List of Lists. Possible assignments of Lectures of Instructors of rooms to time and day.
        EXAMPLE:
                <<instructor_idx,room_idx,time_idx,day_idx>
                 <instructor_idx,room_idx,time_idx,day_idx>
                                .....
                 <instructor_idx,room_idx,time_idx,day_idx>>
        """
        self.assignments = assignments

        # Initialize the Constraint Validator
        self._validator = Validator()
    def print(self):
        for lecture_idx, lecture in enumerate(self.assignments):
            lecture_ = "Lecture"+str(lecture_idx+1)
            instructor = "Instructor"+str(lecture[0])
            room = "Room"+str(lecture[1])
            time_dict = ['8-10','10-12','12-14']
            time = time_dict[lecture[2]-1]
            day_dict = ['Monday', 'Tuesday', 'wednesday','Thursday', 'Friday']
            day = day_dict[lecture[3]-1]
            print(lecture_+":"+instructor+":"+room+":"+time+":"+day)

    def crossover(self, other_candidate, strategy="onePointSwap"):
        """Exchange of Properties of two Candidates

        :param other_candidate: Object of the other Candidate, given by the genetic Algorithm.
        :param strategy: Crossover Strategy that should be used.
        :return: empty
        """
        self._fitness = None
        if (strategy == "onePointSwap"):
            self._crossing_one_point_swap(other_candidate)
        elif strategy == "twoPointSwap":
            self._crossing_two_point_swap(other_candidate)

    def mutation(self, mutation_rate):
        """ Check which Property should changed and change it

        :param mutation_rate: Probability (from 0.0 ... 1.0) of mutation for each Property
        :return: empty
        """
        # Reset Fitness score
        self._fitness = None

        # Get index Property
        for lecture_idx, lecture in enumerate(self.assignments):
            for element_idx, element in enumerate(self.assignments[lecture_idx]):
                # Check whether property classifies for mutation
                if (random.random() < mutation_rate):
                    if element_idx == 2:  # Days only 1 to 3
                        self.assignments[lecture_idx][element_idx] = randTo(3)
                    else:  # Else 1 to 5
                        self.assignments[lecture_idx][element_idx] = randTo(5)

    def get_diversity(self, other_candidate):
        """ Compare the error between two Candidates

        :param other_candidate:
        :return: difference between Candidates in percent
        """
        div = 0
        all_elements = 0
        for lecture_idx in range(len(self.assignments)):
            for idx_inner in range(len(self.assignments[lecture_idx])):
                all_elements += 1
                if self.assignments[lecture_idx][idx_inner] != other_candidate.assignments[lecture_idx][idx_inner]:
                    div += 1

        return div/ all_elements

    def get_fitness(self):
        """ Evaluate Candidate

        :return: Fitness from 0 to 1 and 1.5 if it is a valid Solution
        """
        if (self._fitness is None):
            constraint_errors = self._validator.check(self.assignments)
            if constraint_errors == 0:
                self._fitness = 1.5
            else:
                self._fitness = 1 / constraint_errors
        return self._fitness

    def _crossing_one_point_swap(self, other_candidate):
        """ One Point crossing

        :param other_candidate:
        :return:
        """
        cut_idx = randTo(4*19+3)  # 19 times 4 cut points + 3 in the end
        swap_idx = None
        if 0.5 < random.random():
            swap_idx = range(cut_idx, 4*20-1)  # Forward from idx
        else:
            swap_idx = range(0, cut_idx)# Backward from idx
        for idx in swap_idx:
            # Split long index in Lecture and field index
            lecture_idx = int( idx /4 )
            field_idx = idx % 4
            tmp = other_candidate.assignments[lecture_idx][field_idx]
            other_candidate.assignments[lecture_idx][field_idx] = self.assignments[lecture_idx][field_idx]
            self.assignments[lecture_idx][field_idx] = tmp

    def _crossing_two_point_swap(self, other_candidate):
        """ Two Point Crossing

        :param other_candidate:
        :return:
        """
        cut_from = random.randint(0, 4*19+3)
        cut_to = random.randint(0, 4*19+3)

        if cut_from < cut_to:
            swap_idx = range(cut_from, cut_to)
        else:
            swap_idx = range(cut_to, cut_from)

        for idx in swap_idx:
            # Split long index in Lecture and field index
            lecture_idx = int( idx /4 )
            field_idx = idx % 4
            tmp = other_candidate.assignments[lecture_idx][field_idx]
            other_candidate.assignments[lecture_idx][field_idx] = self.assignments[lecture_idx][field_idx]
            self.assignments[lecture_idx][field_idx] = tmp