Esempio n. 1
0
def test_chain_validations(request_example):
    trip = TripValidator()
    trip.set_next(VanValidator())
    validator = Validator(trip)
    assert validator.validate(request_example) is True
    request_example["van"]["id"] = None
    assert validator.validate(request_example) is False
Esempio n. 2
0
class Todo(object):
    def __init__(self):
        self.validator = Validator()
        self.db = Database()

        self.collection_name = 'todo'

        self.fields = {
            "title": "string",
            "body": "string",
        }

        self.create_required_fields = ["title", "body"]

        # Fields optional for CREATE
        self.create_optional_fields = []

        # Fields required for UPDATE
        self.update_required_fields = []

        # Fields optional for UPDATE
        self.update_optional_fields = []

    def create(self, todo):
        # Validator will throw error if invalid
        self.validator.validate(todo, self.fields, self.create_required_fields,
                                self.create_optional_fields)
        res = self.db.insert(todo, self.collection_name)
        return "Inserted Id " + res
Esempio n. 3
0
    def test_when_all_query_params_are_set(self):
        limit = 5
        offset = "30"
        filters = "distance_learning,honours_award,-foundation_year,sandwich_year,-year_abroad,full_time"
        length_of_course = "3,4"
        countries = "england,wales"
        subjects = "CAH09-01-01,CAH09-01-02"
        language = "en"

        validator = Validator(
            countries, filters, length_of_course, subjects, limit, 100, offset, language
        )

        expected_result = {
            "countries": ["XF", "XI"],
            "distance_learning": True,
            "foundation_year": False,
            "full_time": True,
            "honours_award": True,
            "language": "en",
            "length_of_course": ["3", "4"],
            "limit": 5,
            "offset": 30,
            "sandwich_year": True,
            "subjects": ["CAH09-01-01", "CAH09-01-02"],
            "year_abroad": False,
        }
        output_result, output_error_object = validator.validate()

        self.assertEqual(expected_result, output_result)
        self.assertEqual([], output_error_object)
Esempio n. 4
0
    def test_when_all_query_params_are_bad(self):
        limit = 200
        offset = "-30"
        filters = "illusion,Part_Time,full_time,-full_time"
        length_of_course = "-2,8,twenty"
        countries = "bolivia,-england,england"
        subjects = 32
        language = "bad"

        validator = Validator(
            countries, filters, length_of_course, subjects, limit, 100, offset, language
        )

        expected_result = {}
        output_result, output_error_object = validator.validate()
        expected_error_object = [
            {
                "error": "limit cannot exceed maximum value of 100",
                "error_values": [{"limit": 200}],
            },
            {
                "error": "offset needs to be a positive number, offset cannot be lower than 0",
                "error_values": [{"offset": "-30"}],
            },
            {
                "error": "use of the same filter option more than once",
                "error_values": [{"filters": "full_time"}],
            },
            {
                "error": "invalid filters",
                "error_values": [{"filters": "illusion,Part_Time"}],
            },
            {
                "error": "use of the same countries more than once",
                "error_values": [{"countries": "england"}],
            },
            {"error": "invalid countries", "error_values": [{"countries": "bolivia"}]},
            {
                "error": "length_of_course values needs to be a number",
                "error_values": [{"length_of_course": "twenty"}],
            },
            {
                "error": "length_of_course values needs to be numbers between the range of 1 and 7",
                "error_values": [{"length_of_course": "-2,8"}],
            },
            {
                'error': 'value of language is not supported',
                'error_values': [{'language': 'bad'}],
            }
        ]

        print(f"output: {output_error_object}")

        self.assertEqual(expected_result, output_result)
        self.assertEqual(expected_error_object, output_error_object)
Esempio n. 5
0
def create_item():
    if not is_user():
        return redirect(url_for("login"))
    # for form validation get an instance
    validate = Validator()
    if request.method == "POST":
        # get form fields values in variables
        name, description, category_id = \
            request.form.get('name').strip(), \
            request.form.get('description').strip(), \
            request.form.get('category_id')

        # validate form fields
        validate.validate(name, 'Name')
        validate.validate(description, 'Description')
        validate.validate(description, 'Category Name')
        # if form is valid create this item and send flash message
        if validate.valid_form():
            model.create_item(name=name,
                              description=description,
                              category_id=category_id,
                              user_id=login_session['id'])
            flash("Item Created Successfully")
            return redirect(url_for("home"))

    categories = model.all_categories()
    return render_template("create_item.html",
                           categories=categories,
                           form_errors=validate.get_form_errors(),
                           is_user=is_user(),
                           login_session=login_session)
Esempio n. 6
0
def update_item(cid, iid):
    # from validation instance
    validate = Validator()
    selected_category, item, category_has_item = \
        model.category_item(iid=iid, cid=cid)
    # boolean checks if user is authorized to access this page
    authorized = category_has_item and is_user()\
                 and item.user_id == login_session['id']
    if not authorized:
        return redirect(url_for('login'))
    categories = model.all_categories()
    if request.method == 'POST':
        # get fields into variables
        iid, name, description, category_id = \
            request.form.get('id'), \
            request.form.get('name').strip(), \
            request.form.get('description').strip(), \
            request.form.get('category_id')
        # validate form
        validate.validate(field=name, field_name='Name')
        validate.validate(description, 'Description')
        validate.validate(category_id, "Category Name")
        # if form valid update
        if validate.valid_form():
            item = model.update_item(item,
                                     name=name,
                                     description=description,
                                     cid=category_id)
            # set message shows updated done successfully
            msg = "%s Item Updated Successfully" % name
            flash(msg)
            return redirect(
                url_for("update_item", iid=item.id, cid=item.category_id))

    return render_template("update_item.html",
                           categories=categories,
                           selected_category=selected_category,
                           item=item,
                           form_errors=validate.get_form_errors(),
                           category_has_item=category_has_item,
                           is_user=is_user(),
                           login_session=login_session)
Esempio n. 7
0
class Enigma:
    """
        This class simulates the Enigma machine

        As models M3 and M4 of the Enigma machine, it supports 3 or 4 rotors configuration.

        The order of reflector and rotors definition respect the physical order (left-to-right).

        :param reflector: The reflector associated to the Enigma machine
        :type reflector: Reflector
        :param *rotors:  The rotors associated to the Enigma machine
        :type *rotors: Variable length rotor list
        :raises: :class:`TypeError, ValueError`: If one of the provided parameter is invalid

        Example::
            enigma = Enigma(ReflectorB(), RotorI(), RotorII(), RotorIII("V"))
            enigma.encode("HELLOWORLDHELLOWORLDHELLOWORLD")

            enigma = Enigma(ReflectorA(), RotorIV("E", 18), RotorV("Z", 24), RotorBeta("G", 3), RotorI("P", 5))
            enigma.plugboard.set("PC XZ FM QA ST NB HY OR EV IU")
            enigma.encode("BUPXWJCDPFASXBDHLBBIBSRNWCSZXQOLBNXYAXVHOGCUUIBCVMPUZYUUKHI")
    """
    def __init__(self, reflector, *rotors):
        self._rotor_chain = RotorChain(reflector, *rotors)
        self.plugboard = Plugboard()
        self.__alpha_string_validator = Validator(
            TypeValidator(str), LengthValidator(1, lambda x, y: x >= y),
            AlphaValidator())

    def encode(self, string):
        """
        Perform the whole encoding of a string on the Enigma machine

        Each character of the string is first encoded by the plug board then the character is encoded through the
        rotor chain and finally the character is encoded by the plug board again.

        :param char: The string to encode
        :type char: str
        :return: The encoded string
        :rtype: str
        """
        self.__alpha_string_validator.validate(string)
        encoded_string = ""
        for letter in string:
            encoded_string += self.plugboard.encode(
                self._rotor_chain.encode(self.plugboard.encode(letter)))
        return encoded_string

    def reset(self):
        """
        Reset all rotors of the machine to position to "A" and the ring setting to 1
        """
        self._rotor_chain.reset()

    @property
    def plugboard(self):
        """
        The plug board associated to the Enigma machine

        :getter: Returns the plug board
        :setter: Sets the plug board
        :type: Plugboard
        """
        return self.__plugboard

    @plugboard.setter
    def plugboard(self, plugboard):
        self.__plugboard = plugboard

    @property
    def reflector(self):
        """
        The reflector associated to the Enigma machine

        :getter: Returns the reflector
        :setter: Sets the reflector
        :type: Reflector
        """
        return self._rotor_chain.reflector

    @reflector.setter
    def reflector(self, reflector):
        self._rotor_chain.reflector = reflector

    @property
    def rotors(self):
        """
        The rotors associated to the Enigma machine

        :getter: Returns the list of rotors
        :setter: Sets the list of rotors
        :type: Rotors list
        """
        return self._rotor_chain.rotors

    @rotors.setter
    def rotors(self, rotors):
        self._rotor_chain.rotors = rotors
Esempio n. 8
0
                           BaseTransform(300, dataset_mean),
                           AnnotationTransform())
    data_loader = data.DataLoader(dataset,
                                  32,
                                  num_workers=2,
                                  shuffle=False,
                                  collate_fn=detection_collate,
                                  pin_memory=True)
    from layers.modules import MultiBoxLoss
    criterion = MultiBoxLoss(num_classes, 0.5, True, 0, True, 3, 0.5, False,
                             args.cuda)

    from validation import Validator
    v = Validator(data_loader, net, num_classes, criterion=criterion)

    AP, mAP, losses = v.validate()
    for idx, a in enumerate(AP):
        print("{0:20}  AP: {1:.4f}".format(VOC_CLASSES[idx], a))
    print("mAP", mAP)
    print(
        "total loss: {0:.4f},  class loss: {1:.4f}, loc loss: {2:.4f}".format(
            losses[0], losses[1], losses[2]))

    exit()

    net.eval()

    if args.cuda:
        net = net.cuda()
        cudnn.benchmark = True
    # evaluation
Esempio n. 9
0
class CustomerDatabase:
    '''
    data structure:

    db{customer_id:{logs:[234,34565,234,234], deposit_records:{'2019-07-01':{'1':[123.45], '2':[400.33]}}}}

    logs contain an array of ids
    deposit records contain a dictionary of beginning mondays, follwoed by weekday offsets,
    followed by an array of deposits for that day

    '''
    def __init__(self):
        logger.info('inititlizing db')
        self.db = dict()
        self.validator = Validator()

    def __init_customer_data(self, customer_id):
        if customer_id not in self.db:

            logger.debug("creating new customer")
            default_customer = {"logs": [], "deposit_records": {}}
            self.db[customer_id] = default_customer

        return self.db[customer_id]

    # multiple customer_id / transaction ids not permitted.
    def __is_duplicate_transaction(self, logs, txn_id):
        in_logs = txn_id in logs
        return in_logs

    #add the transaction id to the customer log
    def __update_transaction_history(self, customer_id, txn_id):
        logs = self.db[customer_id]["logs"]

        logs.append(txn_id)
        self.db[customer_id]["logs"] = logs

    # add the load amount to the weekly/daily bucket
    def __update_db(self, customer_id, deposits):
        try:
            self.db[customer_id]["deposit_records"] = deposits

        except Exception as e:
            logger.exception(e, exc_info=True)

    # deposit is the only public class here - use this to load your card.

    def deposit(self, customer_id, txn_id, time, amount):
        try:

            amount = sanitize_currency(amount)
            customer_data = self.__init_customer_data(customer_id)

            if self.__is_duplicate_transaction(customer_data["logs"], txn_id):
                return False, 403

            deposits = customer_data["deposit_records"]
            monday, date_index = breakdown_date(convert_to_utc(time))
            valid_transaction = self.validator.validate(
                deposits, monday, date_index, amount)

            self.__update_transaction_history(customer_id, txn_id)

            if valid_transaction:
                if monday not in deposits:
                    deposits[monday] = {date_index: []}
                if date_index not in deposits[monday]:
                    deposits[monday][date_index] = []
                deposits[monday][date_index].append(amount)

                self.__update_db(customer_id, deposits)

                return True, 200
            else:
                return False, 406
        except Exception as e:
            logging.exception("Could not process data", exc_info=True)
            sys.exit(0)