Ejemplo n.º 1
0
class DatasetForm(Form):
    """
    A form used to create an image processing dataset
    """
    def validate_folder_path(form, field):
        if not field.data:
            pass
        else:
            # make sure the filesystem path exists
            if not os.path.exists(field.data) or not os.path.isdir(field.data):
                raise validators.ValidationError(
                    'Folder does not exist or is not reachable')
            else:
                return True

    def validate_file_path(form, field):
        if not field.data:
            pass
        else:
            # make sure the filesystem path exists
            if not os.path.exists(field.data) and not os.path.isdir(
                    field.data):
                raise validators.ValidationError(
                    'File does not exist or is not reachable')
            else:
                return True

    feature_folder = utils.forms.StringField(
        'Feature image folder',
        validators=[
            validators.DataRequired(),
            validate_folder_path,
        ],
        tooltip="Indicate a folder full of images.")

    label_folder = utils.forms.StringField(
        'Label image folder',
        validators=[
            validators.DataRequired(),
            validate_folder_path,
        ],
        tooltip="Indicate a folder full of images. For each image in the feature"
        " image folder there must be one corresponding image in the label"
        " image folder. The label image must have the same filename except"
        " for the extension, which may differ. Label images are expected"
        " to be single-channel images (paletted or grayscale), or RGB"
        " images, in which case the color/class mappings need to be"
        " specified through a separate text file.")

    folder_pct_val = utils.forms.IntegerField(
        '% for validation',
        default=10,
        validators=[validators.NumberRange(min=0, max=100)],
        tooltip="You can choose to set apart a certain percentage of images "
        "from the training images for the validation set.")

    has_val_folder = utils.forms.BooleanField(
        'Separate validation images',
        default=False,
    )

    validation_feature_folder = utils.forms.StringField(
        'Validation feature image folder',
        validators=[
            validate_required_iff(has_val_folder=True),
            validate_folder_path,
        ],
        tooltip="Indicate a folder full of images.")

    validation_label_folder = utils.forms.StringField(
        'Validation label image folder',
        validators=[
            validate_required_iff(has_val_folder=True),
            validate_folder_path,
        ],
        tooltip="Indicate a folder full of images. For each image in the feature"
        " image folder there must be one corresponding image in the label"
        " image folder. The label image must have the same filename except"
        " for the extension, which may differ. Label images are expected"
        " to be single-channel images (paletted or grayscale), or RGB"
        " images, in which case the color/class mappings need to be"
        " specified through a separate text file.")

    channel_conversion = utils.forms.SelectField(
        'Channel conversion',
        choices=[
            ('RGB', 'RGB'),
            ('L', 'Grayscale'),
            ('none', 'None'),
        ],
        default='none',
        tooltip="Perform selected channel conversion on feature images. Label"
        " images are single channel and not affected by this parameter.")

    class_labels_file = utils.forms.StringField(
        'Class labels (optional)',
        validators=[
            validate_file_path,
        ],
        tooltip="The 'i'th line of the file should give the string label "
        "associated with the '(i-1)'th numeric label. (E.g. the "
        "string label for the numeric label 0 is supposed to be "
        "on line 1.)")

    colormap_method = utils.forms.SelectField(
        'Color map specification',
        choices=[
            ('label', 'From label image'),
            ('textfile', 'From text file'),
        ],
        default='label',
        tooltip="Specify how to map class IDs to colors. Select 'From label "
        "image' to use palette or grayscale from label images. For "
        "RGB image labels, select 'From text file' and provide "
        "color map in separate text file.")

    colormap_text_file = utils.forms.StringField(
        'Color map file',
        validators=[
            validate_required_iff(colormap_method="textfile"),
            validate_file_path,
        ],
        tooltip="Specify color/class mappings through a text file. "
        "Each line in the file should contain three space-separated "
        "integer values, one for each of the Red, Green, Blue "
        "channels. The 'i'th line of the file should give the color "
        "associated with the '(i-1)'th class. (E.g. the "
        "color for class #0 is supposed to be on line 1.)")
Ejemplo n.º 2
0
class ValidateUserStatus(Form):
    user_id = IntegerField(
        'Usuario',
        [validators.required(),
         validators.NumberRange(min=1, max=None)])
    activo = IntegerField('Activo', [validators.required()])
Ejemplo n.º 3
0
 def _number_common(cls, model, field, kwargs):
     if field.max_value or field.min_value:
         kwargs['validators'].append(
             validators.NumberRange(max=field.max_value,
                                    min=field.min_value))
Ejemplo n.º 4
0
class IndexForm(Form):
    target_temp = IntegerField('Target Temp', validators=[validators.NumberRange(min=0, max=99), validators.InputRequired()])
    current_temp = TextAreaField('Current Temp', validators=[validators.Optional()], render_kw={'readonly': True})
Ejemplo n.º 5
0
class DatasetForm(Form):
    """
    A form used to create an image processing dataset
    """
    def validate_folder_path(form, field):
        if not field.data:
            pass
        else:
            # make sure the filesystem path exists
            if not os.path.exists(field.data) or not os.path.isdir(field.data):
                raise validators.ValidationError(
                    'Folder does not exist or is not reachable')
            else:
                return True

    feature_folder = utils.forms.StringField(
        'Feature image folder',
        validators=[
            validators.DataRequired(),
            validate_folder_path,
        ],
        tooltip="Indicate a folder full of images.")

    label_folder = utils.forms.StringField(
        'Label image folder',
        validators=[
            validators.DataRequired(),
            validate_folder_path,
        ],
        tooltip="Indicate a folder full of images. For each image in the feature"
        " image folder there must be one corresponding image in the label"
        " image folder. The label image must have the same filename except"
        " for the extension, which may differ.")

    folder_pct_val = utils.forms.IntegerField(
        '% for validation',
        default=10,
        validators=[validators.NumberRange(min=0, max=100)],
        tooltip="You can choose to set apart a certain percentage of images "
        "from the training images for the validation set.")

    has_val_folder = utils.forms.BooleanField(
        'Separate validation images',
        default=False,
    )

    validation_feature_folder = utils.forms.StringField(
        'Validation feature image folder',
        validators=[
            validate_required_iff(has_val_folder=True),
            validate_folder_path,
        ],
        tooltip="Indicate a folder full of images.")

    validation_label_folder = utils.forms.StringField(
        'Validation label image folder',
        validators=[
            validate_required_iff(has_val_folder=True),
            validate_folder_path,
        ],
        tooltip="Indicate a folder full of images. For each image in the feature"
        " image folder there must be one corresponding image in the label"
        " image folder. The label image must have the same filename except"
        " for the extension, which may differ.")

    channel_conversion = utils.forms.SelectField(
        'Channel conversion',
        choices=[
            ('RGB', 'RGB'),
            ('L', 'Grayscale'),
            ('none', 'None'),
        ],
        default='none',
        tooltip="Perform selected channel conversion.")
Ejemplo n.º 6
0
 def handle_integer_types(self, column, field_args, **extra):
     unsigned = getattr(column.type, 'unsigned', False)
     if unsigned:
         field_args['validators'].append(validators.NumberRange(min=0))
     return fields.IntegerField(**field_args)
Ejemplo n.º 7
0
class AdminProfileForm(ProfileForm):
    username = TextField('Username', [validators.Length(max=40)])
    level    = IntegerField('User Level', [validators.NumberRange(min=0, max=10)])
Ejemplo n.º 8
0
    def get_form(cls, group):
        """Returns a Form for all settings found in :class:`SettingsGroup`.

        :param group: The settingsgroup name. It is used to get the settings
                      which are in the specified group.
        """

        class SettingsForm(Form):
            pass

        # now parse the settings in this group
        for setting in group.settings:
            field_validators = []

            # generate the validators
            if "min" in setting.extra:
                # Min number validator
                if setting.value_type in ("integer", "float"):
                    field_validators.append(
                        validators.NumberRange(min=setting.extra["min"])
                    )

                # Min text length validator
                elif setting.value_type in ("string"):
                    field_validators.append(
                        validators.Length(min=setting.extra["min"])
                    )

            if "max" in setting.extra:
                # Max number validator
                if setting.value_type in ("integer", "float"):
                    field_validators.append(
                        validators.NumberRange(max=setting.extra["max"])
                    )

                # Max text length validator
                elif setting.value_type in ("string"):
                    field_validators.append(
                        validators.Length(max=setting.extra["max"])
                    )

            # Generate the fields based on value_type
            # IntegerField
            if setting.value_type == "integer":
                setattr(
                    SettingsForm, setting.key,
                    IntegerField(setting.name, validators=field_validators,
                                 description=setting.description)
                )
            # FloatField
            elif setting.value_type == "float":
                setattr(
                    SettingsForm, setting.key,
                    FloatField(setting.name, validators=field_validators,
                               description=setting.description)
                )

            # TextField
            if setting.value_type == "string":
                setattr(
                    SettingsForm, setting.key,
                    TextField(setting.name, validators=field_validators,
                              description=setting.description)
                )

            # SelectMultipleField
            if setting.value_type == "selectmultiple":
                # if no coerce is found, it will fallback to unicode
                if "coerce" in setting.extra:
                    coerce_to = setting.extra['coerce']
                else:
                    coerce_to = unicode

                setattr(
                    SettingsForm, setting.key,
                    SelectMultipleField(
                        setting.name,
                        choices=setting.extra['choices'](),
                        coerce=coerce_to,
                        description=setting.description
                    )
                )

            # SelectField
            if setting.value_type == "select":
                # if no coerce is found, it will fallback to unicode
                if "coerce" in setting.extra:
                    coerce_to = setting.extra['coerce']
                else:
                    coerce_to = unicode

                setattr(
                    SettingsForm, setting.key,
                    SelectField(
                        setting.name,
                        coerce=coerce_to,
                        choices=setting.extra['choices'](),
                        description=setting.description)
                )

            # BooleanField
            if setting.value_type == "boolean":
                setattr(
                    SettingsForm, setting.key,
                    BooleanField(setting.name, description=setting.description)
                )

        return SettingsForm
Ejemplo n.º 9
0
class ImageClassificationDatasetForm(ImageDatasetForm):
    """
    Defines the form used to create a new ImageClassificationDatasetJob
    """

    # Use a SelectField instead of a HiddenField so that the default value
    # is used when nothing is provided (through the REST API)
    method = wtforms.SelectField(
        u'Dataset type',
        choices=[
            ('folder', 'Folder'),
            ('textfile', 'Textfiles'),
        ],
        default='folder',
    )

    def validate_folder_path(form, field):
        if not field.data:
            pass
        elif utils.is_url(field.data):
            # make sure the URL exists
            try:
                r = requests.get(field.data,
                                 allow_redirects=False,
                                 timeout=utils.HTTP_TIMEOUT)
                if r.status_code not in [
                        requests.codes.ok, requests.codes.moved,
                        requests.codes.found
                ]:
                    raise validators.ValidationError('URL not found')
            except Exception as e:
                raise validators.ValidationError(
                    'Caught %s while checking URL: %s' % (type(e).__name__, e))
            else:
                return True
        else:
            # make sure the filesystem path exists
            if not os.path.exists(field.data) or not os.path.isdir(field.data):
                raise validators.ValidationError('Folder does not exist')
            else:
                return True

    ### Method - folder

    folder_train = wtforms.StringField(
        u'Training Images',
        validators=[
            validate_required_iff(method='folder'),
            validate_folder_path,
        ])

    folder_pct_val = wtforms.IntegerField(
        u'% for validation',
        default=25,
        validators=[
            validate_required_iff(method='folder'),
            validators.NumberRange(min=0, max=100)
        ])

    folder_pct_test = wtforms.IntegerField(
        u'% for testing',
        default=0,
        validators=[
            validate_required_iff(method='folder'),
            validators.NumberRange(min=0, max=100)
        ])

    has_val_folder = wtforms.BooleanField(
        'Separate validation images folder',
        default=False,
        validators=[validate_required_iff(method='folder')])

    folder_val = wtforms.StringField(u'Validation Images',
                                     validators=[
                                         validate_required_iff(
                                             method='folder',
                                             has_val_folder=True),
                                         validate_folder_path,
                                     ])

    has_test_folder = wtforms.BooleanField(
        'Separate test images folder',
        default=False,
        validators=[validate_required_iff(method='folder')])

    folder_test = wtforms.StringField(u'Test Images',
                                      validators=[
                                          validate_required_iff(
                                              method='folder',
                                              has_test_folder=True),
                                          validate_folder_path,
                                      ])

    ### Method - textfile

    textfile_train_images = wtforms.FileField(
        u'Training images',
        validators=[validate_required_iff(method='textfile')])
    textfile_train_folder = wtforms.StringField(u'Training images folder')

    def validate_textfile_train_folder(form, field):
        if form.method.data != 'textfile':
            field.errors[:] = []
            raise validators.StopValidation()
        if not field.data.strip():
            # allow null
            return True
        if not os.path.exists(field.data) or not os.path.isdir(field.data):
            raise validators.ValidationError('folder does not exist')
        return True

    textfile_use_val = wtforms.BooleanField(
        u'Validation set',
        default=True,
        validators=[validate_required_iff(method='textfile')])
    textfile_val_images = wtforms.FileField(u'Validation images',
                                            validators=[
                                                validate_required_iff(
                                                    method='textfile',
                                                    textfile_use_val=True)
                                            ])
    textfile_val_folder = wtforms.StringField(u'Validation images folder')

    def validate_textfile_val_folder(form, field):
        if form.method.data != 'textfile' or not form.textfile_use_val.data:
            field.errors[:] = []
            raise validators.StopValidation()
        if not field.data.strip():
            # allow null
            return True
        if not os.path.exists(field.data) or not os.path.isdir(field.data):
            raise validators.ValidationError('folder does not exist')
        return True

    textfile_use_test = wtforms.BooleanField(
        u'Test set',
        default=False,
        validators=[validate_required_iff(method='textfile')])
    textfile_test_images = wtforms.FileField(u'Test images',
                                             validators=[
                                                 validate_required_iff(
                                                     method='textfile',
                                                     textfile_use_test=True)
                                             ])
    textfile_test_folder = wtforms.StringField(u'Test images folder')

    def validate_textfile_test_folder(form, field):
        if form.method.data != 'textfile' or not form.textfile_use_test.data:
            field.errors[:] = []
            raise validators.StopValidation()
        if not field.data.strip():
            # allow null
            return True
        if not os.path.exists(field.data) or not os.path.isdir(field.data):
            raise validators.ValidationError('folder does not exist')
        return True

    # Can't use a BooleanField here because HTML doesn't submit anything
    # for an unchecked checkbox. Since we want to use a REST API and have
    # this default to True when nothing is supplied, we have to use a
    # SelectField
    textfile_shuffle = wtforms.SelectField(
        'Shuffle lines',
        choices=[
            (1, 'Yes'),
            (0, 'No'),
        ],
        coerce=int,
        default=1,
    )

    textfile_labels_file = wtforms.FileField(
        u'Labels', validators=[validate_required_iff(method='textfile')])
Ejemplo n.º 10
0
class RoomForm(Form):

    state_choices = [('0', '- Escolha o estado -'), ('sp', 'SP'), ('rj', 'RJ')]
    building_choices = [('apto', 'Apartamento'), ('house', 'Casa'), ('hostel', 'Pousada/Pensionato'), ('hotel', 'Hotel')]
    room_choices = [('single', 'Solteiro'), ('singlec', 'Solteiro Coletivo'), ('couple', 'Casal')]
    bathroom_choices = [('single', 'Individual'), ('public', 'Coletivo'), ('half', 'Compartilhado para dois quartos')]

    title = StringField('Titulo'.decode('utf-8'), [validators.Length(max=50)])
    description = TextAreaField('Descrição'.decode('utf-8'), [validators.Length(max=400)])
    address = StringField('Endereço'.decode('utf-8'), [validators.Length(max=50)])
    number = StringField('Número'.decode('utf-8'), [validators.Length(max=7)])
    region = StringField('Bairro'.decode('utf-8'), [validators.Length(max=50)])
    state = SelectField('Estado', choices=state_choices, default=0, validators=[validators.NoneOf(values=['0'], message='Selecione um Estado')])
    city = SelectField('Cidade', coerce=int, default=1, validators=[validators.NumberRange(min=2, message='Selecione uma Cidade')])
    cep = StringField('CEP'.decode('utf-8'), [validators.Length(max=15)])
    building = SelectField('Tipo de Construção'.decode('utf-8'), choices=building_choices)
    type = SelectField('Tipo de Quarto'.decode('utf-8'), choices=room_choices)
    bathroom = SelectField('Tipo de Banheiro'.decode('utf-8'), choices=bathroom_choices)
    price = IntegerField("Mensalidade em R$".decode('utf-8'), [validators.InputRequired()])
    minRent = IntegerField("Tempo mínimo (meses)".decode('utf-8'), [validators.InputRequired()])
    gender = SelectField('Quarto somente para', choices=[('M', 'Homem'), ('F', 'Mulher'), ('B', 'Homem/Mulher')])
    furniture = BooleanField('Mobiliado')
    include_bills = BooleanField('Contas inclusas')
    smoking = BooleanField('Aceita Fumantes')
    pet = BooleanField('Aceita animais')
    visits = BooleanField('Permite receber visitas')
    aircond = BooleanField('Tem arcondicionado')
    internet = BooleanField('Tem internet')
    parking = BooleanField('Tem estacionamento')
    elevator = BooleanField('Tem elevador')

    def getObj(self, room):
        room.title = self.title.data
        room.description = self.description.data
        room.address = self.address.data
        room.number = self.number.data
        room.region = self.region.data
        room.city_id = self.city.data
        room.cep = self.cep.data
        room.building = self.building.data
        room.type = self.type.data
        room.bathroom = self.bathroom.data
        room.minRent = self.minRent.data
        room.price = self.price.data
        room.gender = self.gender.data
        room.furniture = self.furniture.data
        room.include_bills = self.include_bills.data
        room.smoking = self.smoking.data
        room.pet = self.pet.data
        room.visits = self.visits.data
        room.internet = self.internet.data
        room.parking = self.parking.data
        room.elevator = self.elevator.data
        return room

    def populateForm(self, room):
        self.title.data = room.title
        self.description.data = room.description
        self.address.data = room.address
        self.number.data = room.number
        self.region.data = room.region
        city_temp = db.session.query(City).filter(City.id == room.city_id).one()
        self.state.data = city_temp.state
        self.city.data = room.city_id
        self.cep.data = room.cep
        self.building.data = room.building
        self.bathroom.data = room.bathroom
        self.minRent.data = room.minRent
        self.price.data = room.price
        self.gender.data = room.gender
        self.furniture.data = room.furniture
        self.include_bills.data = room.include_bills
        self.smoking.data = room.smoking
        self.pet.data = room.pet
        self.visits.data = room.visits
        self.internet.data = room.internet
        self.parking.data = room.parking
        self.elevator.data = room.elevator
Ejemplo n.º 11
0
class LCDAdd(FlaskForm):
    quantity = IntegerField(lazy_gettext('Quantity'),
                            validators=[validators.NumberRange(min=1, max=20)])
    add = SubmitField(lazy_gettext('Add LCDs'))
Ejemplo n.º 12
0
class ModelFormTest(TestCase):
    F = model_form(test_models.User,
                   exclude=['id'],
                   field_args={
                       'posts': {
                           'validators':
                           [validators.NumberRange(min=4, max=7)],
                           'description': 'Test'
                       }
                   })
    form = F()
    form_with_pk = model_form(test_models.User)()
    form_with_only = model_form(test_models.User,
                                only=['nullbool', 'birthday'])()

    def test_form_sanity(self):
        self.assertEqual(self.F.__name__, 'UserForm')
        self.assertEqual(len([x for x in self.form]), 14)
        self.assertEqual(len([x for x in self.form_with_pk]), 15)
        self.assertEqual(len([x for x in self.form_with_only]), 2)

    def test_label(self):
        self.assertEqual(self.form.reg_ip.label.text, 'IP Addy')
        self.assertEqual(self.form.posts.label.text, 'posts')

    def test_description(self):
        self.assertEqual(self.form.birthday.description, 'Teh Birthday')

    def test_max_length(self):
        self.assertTrue(
            contains_validator(self.form.username, validators.Length))
        self.assertFalse(contains_validator(self.form.posts,
                                            validators.Length))

    def test_optional(self):
        self.assertTrue(
            contains_validator(self.form.email, validators.Optional))

    def test_simple_fields(self):
        self.assertEqual(type(self.form.file), fields.FileField)
        self.assertEqual(type(self.form.file2), fields.FileField)
        self.assertEqual(type(self.form_with_pk.id), fields.IntegerField)
        self.assertEqual(type(self.form.slug), fields.TextField)
        self.assertEqual(type(self.form.birthday), fields.DateField)

    def test_custom_converters(self):
        self.assertEqual(type(self.form.email), fields.TextField)
        self.assertTrue(contains_validator(self.form.email, validators.Email))
        self.assertEqual(type(self.form.reg_ip), fields.TextField)
        self.assertTrue(
            contains_validator(self.form.reg_ip, validators.IPAddress))
        self.assertEqual(type(self.form.group_id), ModelSelectField)

    def test_us_states(self):
        self.assertTrue(len(self.form.state.choices) >= 50)

    def test_field_args(self):
        self.assertTrue(
            contains_validator(self.form.posts, validators.NumberRange))
        self.assertEqual(self.form.posts.description, 'Test')

    def test_nullbool(self):
        field = self.form.nullbool
        assert isinstance(field, fields.SelectField)
        self.assertEqual(len(field.choices), 3)
        pairs = (('True', True), ('False', False), ('None', None), ('2', True),
                 ('0', False))
        for input_val, expected in pairs:
            form = self.F(DummyPostData(nullbool=[input_val]))
            assert form.nullbool.data is expected
Ejemplo n.º 13
0
class ResistorValuesForm(Form):
    """
    A class for the form to update the PMTIC resistors.
    """
    crate = IntegerField('crate', [validators.NumberRange(min=0, max=19)])
    slot = IntegerField('slot', [validators.NumberRange(min=0, max=15)])
    r252 = SelectField('R252',
                       coerce=int,
                       choices=[(20000, '20k'), (4000, '4k')])
    r151 = SelectField('R151',
                       coerce=int,
                       choices=[(3600, '3.6k'), (5100, '5.1k'), (6200, '6.2k'),
                                (7500, '7.5k'), (12000, '12k'),
                                (19600, '19.6k'), (20000, '20k'),
                                (21100, '21.1k'), (22200, '22.2k'),
                                (23500, '23.5k'), (28000, '28k'),
                                (55000, '55k')])
    r386 = IntegerField('R386', [validators.NumberRange(min=0)])
    r419 = IntegerField('R419', [validators.NumberRange(min=0)])
    r421 = IntegerField('R421', [validators.NumberRange(min=0)])
    r420 = IntegerField('R420', [validators.NumberRange(min=0)])
    r387 = IntegerField('R387', [validators.NumberRange(min=0)])
    r388 = IntegerField('R388', [validators.NumberRange(min=0)])
    r389 = IntegerField('R389', [validators.NumberRange(min=0)])
    r390 = IntegerField('R390', [validators.NumberRange(min=0)])
    r391 = IntegerField('R391', [validators.NumberRange(min=0)])
    r392 = IntegerField('R392', [validators.NumberRange(min=0)])
    r393 = IntegerField('R393', [validators.NumberRange(min=0)])
    r394 = IntegerField('R394', [validators.NumberRange(min=0)])
    r395 = IntegerField('R395', [validators.NumberRange(min=0)])
    r396 = IntegerField('R396', [validators.NumberRange(min=0)])
    r397 = IntegerField('R397', [validators.NumberRange(min=0)])
    r398 = IntegerField('R398', [validators.NumberRange(min=0)])
    r399 = IntegerField('R399', [validators.NumberRange(min=0)])
    r400 = IntegerField('R400', [validators.NumberRange(min=0)])
    r401 = IntegerField('R401', [validators.NumberRange(min=0)])
    r402 = IntegerField('R402', [validators.NumberRange(min=0)])
    r403 = IntegerField('R403', [validators.NumberRange(min=0)])
    r404 = IntegerField('R404', [validators.NumberRange(min=0)])
    r405 = IntegerField('R405', [validators.NumberRange(min=0)])
    r406 = IntegerField('R406', [validators.NumberRange(min=0)])
    r407 = IntegerField('R407', [validators.NumberRange(min=0)])
    r408 = IntegerField('R408', [validators.NumberRange(min=0)])
    r409 = IntegerField('R409', [validators.NumberRange(min=0)])
    r410 = IntegerField('R410', [validators.NumberRange(min=0)])
    r411 = DecimalField('R412', [validators.NumberRange(min=0)], places=2)
    r412 = DecimalField('R412', [validators.NumberRange(min=0)], places=2)
    r413 = DecimalField('R413', [validators.NumberRange(min=0)], places=2)
    r414 = DecimalField('R414', [validators.NumberRange(min=0)], places=2)
    r415 = DecimalField('R415', [validators.NumberRange(min=0)], places=2)
    r416 = DecimalField('R416', [validators.NumberRange(min=0)], places=2)
    r417 = DecimalField('R417', [validators.NumberRange(min=0)], places=2)
    r418 = DecimalField('R418', [validators.NumberRange(min=0)], places=2)
    password = PasswordField('Password')
Ejemplo n.º 14
0
class InferenceForm(Form):
    """
    A form used to perform inference on a text classification dataset
    """
    def __init__(self, attributes, editable_attribute_ids, **kwargs):
        super(InferenceForm, self).__init__(**kwargs)
        self.attributes = attributes
        self.editable_attribute_ids = editable_attribute_ids

    def validate_file_path(form, field):
        if not field.data:
            pass
        else:
            # make sure the filesystem path exists
            if not os.path.exists(field.data) and not os.path.isdir(
                    field.data):
                raise validators.ValidationError(
                    'File does not exist or is not reachable')
            else:
                return True

    def validate_folder_path(form, field):
        if not field.data:
            pass
        else:
            # make sure the filesystem path exists
            if not os.path.exists(field.data) or not os.path.isdir(field.data):
                raise validators.ValidationError(
                    'Folder does not exist or is not reachable')
            else:
                return True

    row_count = utils.forms.IntegerField(
        u'Rows',
        default=10,
        validators=[validators.NumberRange(min=1)],
        tooltip="Rows to generate in output grid.")

    dataset_type = utils.forms.SelectField('Dataset',
                                           choices=[
                                               ('mnist', 'MNIST'),
                                               ('celeba', 'CelebA'),
                                           ],
                                           default='celeba',
                                           tooltip="Select a dataset.")

    task_id = utils.forms.SelectField('Task ID',
                                      choices=[
                                          ('class', 'MNIST - Class sweep'),
                                          ('style', 'MNIST - Style sweep'),
                                          ('genimg', 'Generate single image'),
                                          ('attributes',
                                           'CelebA - add/remove attributes'),
                                          ('enclist',
                                           'CelebA - Encode list of images'),
                                          ('analogy', 'CelebA - Analogy'),
                                          ('animation', 'CelebA - Animation'),
                                      ],
                                      default='class',
                                      tooltip="Select a task to execute.")

    class_z_vector = utils.forms.StringField(
        u'Z vector (leave blank for random)', )

    style_z1_vector = utils.forms.StringField(
        u'Z1 vector (leave blank for random)', )

    style_z2_vector = utils.forms.StringField(
        u'Z2 vector (leave blank for random)', )

    genimg_z_vector = utils.forms.StringField(
        u'Z vector (leave blank for random)', )

    genimg_class_id = utils.forms.IntegerField(
        u'Class ID',
        default=0,
        validators=[validators.NumberRange(min=0, max=9)],
        tooltip="Class of image to generate (leave blank for CelebA).")

    attributes_z_vector = utils.forms.StringField(
        u'Z vector (leave blank for random)', )

    attributes_file = utils.forms.StringField(
        u'Attributes vector file',
        validators=[
            validate_file_path,
        ],
        tooltip="Specify the path to a file that contains attributes vectors.")

    attributes_params = HiddenField()

    enc_file_list = utils.forms.StringField(
        u'File list',
        validators=[
            validate_file_path,
        ],
        tooltip="Specify the path to a file that contains a list of files.")

    enc_image_folder = utils.forms.StringField(
        u'Image folder',
        validators=[
            validate_folder_path,
        ],
        tooltip="Specify the path to a folder of images.")

    enc_num_images = utils.forms.IntegerField(
        u'Number of images to encode',
        default=100,
        validators=[validators.NumberRange(min=0)],
        tooltip="Max number of images to encode.")

    attributes_z1_vector = utils.forms.StringField(
        u'Source Z vector (leave blank for random)', )

    attributes_z2_vector = utils.forms.StringField(
        u'First Sink Z vector (leave blank for random)', )

    attributes_z3_vector = utils.forms.StringField(
        u'Second Sink Z vector (leave blank for random)', )

    animation_num_transitions = utils.forms.IntegerField(
        u'Number of transitions per image',
        default=10,
        validators=[validators.NumberRange(min=1, max=100)],
        tooltip="Number of transitions between each of the specified images")

    animation_z_vectors = TextAreaField(u'z vectors (one per line)', )
Ejemplo n.º 15
0
class AddToppingForm(FlaskForm):
    name = StringField('Name:', [validators.data_required(), validators.length(min=3)])
    price = DecimalField('Price:', [validators.data_required(), validators.NumberRange(min=0.1, max=10,
                                                                                       message="Field must be between $3.00 to $50.00")],
                         places=2, default=0.5)
    thumbnail = FileField('Thumbnail:')
Ejemplo n.º 16
0
class AddEquipForm(Form):
    name = StringField('Name', [validators.Length(min=1, max=100)])
    count = IntegerField('Count', [validators.NumberRange(min=1, max=25)])
Ejemplo n.º 17
0
class DatasetForm(Form):
    """
    A form used to create an image processing dataset
    """
    def validate_folder_path(form, field):
        if not field.data:
            pass
        else:
            # make sure the filesystem path exists
            if not os.path.exists(field.data) or not os.path.isdir(field.data):
                raise validators.ValidationError(
                    'Folder does not exist or is not reachable')
            else:
                return True

    train_image_folder = utils.forms.StringField(
        u'Training image folder',
        validators=[
            validators.DataRequired(),
            validate_folder_path,
        ],
        tooltip="Indicate a folder of images to use for training")

    train_label_folder = utils.forms.StringField(
        u'Training label folder',
        validators=[
            validators.DataRequired(),
            validate_folder_path,
        ],
        tooltip="Indicate a folder of training labels")

    val_image_folder = utils.forms.StringField(
        u'Validation image folder',
        validators=[
            validate_required_if_set('val_label_folder'),
            validate_folder_path,
        ],
        tooltip="Indicate a folder of images to use for training")

    val_label_folder = utils.forms.StringField(
        u'Validation label folder',
        validators=[
            validate_required_if_set('val_image_folder'),
            validate_folder_path,
        ],
        tooltip="Indicate a folder of validation labels")

    resize_image_width = utils.forms.IntegerField(
        u'Resize Image Width',
        validators=[
            validate_required_if_set('resize_image_height'),
            validators.NumberRange(min=1),
        ],
        tooltip=
        "If specified, images will be resized to that dimension after padding")

    resize_image_height = utils.forms.IntegerField(
        u'Resize Image Height',
        validators=[
            validate_required_if_set('resize_image_width'),
            validators.NumberRange(min=1),
        ],
        tooltip=
        "If specified, images will be resized to that dimension after padding")

    padding_image_width = utils.forms.IntegerField(
        u'Padding Image Width',
        default=1248,
        validators=[
            validate_required_if_set('padding_image_height'),
            validators.NumberRange(min=1),
        ],
        tooltip="If specified, images will be padded to that dimension")

    padding_image_height = utils.forms.IntegerField(
        u'Padding Image Height',
        default=384,
        validators=[
            validate_required_if_set('padding_image_width'),
            validators.NumberRange(min=1),
        ],
        tooltip="If specified, images will be padded to that dimension")

    channel_conversion = utils.forms.SelectField(
        u'Channel conversion',
        choices=[
            ('RGB', 'RGB'),
            ('L', 'Grayscale'),
            ('none', 'None'),
        ],
        default='RGB',
        tooltip="Perform selected channel conversion.")

    val_min_box_size = utils.forms.IntegerField(
        u'Minimum box size (in pixels) for validation set',
        default='25',
        validators=[
            validators.InputRequired(),
            validators.NumberRange(min=0),
        ],
        tooltip="Retain only the boxes that are larger than the specified "
        "value in both dimensions. This only affects objects in "
        "the validation set. Enter 0 to disable this threshold.")

    custom_classes = utils.forms.StringField(
        u'Custom classes',
        validators=[
            validators.Optional(),
        ],
        tooltip="Enter a comma-separated list of class names. "
        "Class IDs are assigned sequentially, starting from 0. "
        "Unmapped class names automatically map to 0. "
        "Leave this field blank to use default class mappings. "
        "See object detection extension documentation for more "
        "information.")
Ejemplo n.º 18
0
class UpdatePlanForm(Form):
    name = StringField('Plan Name', [validators.Length(min=1, max=50)])
    exercise = StringField('Exercise', [validators.Length(min=1, max=100)])
    reps = IntegerField('Reps', [validators.NumberRange(min=1, max=20)])
    sets = IntegerField('Sets', [validators.NumberRange(min=1, max=20)])
Ejemplo n.º 19
0
 def conv_MSYear(self, field_args, **extra):
     field_args['validators'].append(validators.NumberRange(min=1901, max=2155))
     return fields.TextField(**field_args)
Ejemplo n.º 20
0
class GenericDatasetForm(DatasetForm):
    """
    Defines the form used to create a new GenericDatasetJob
    """
    # Generic dataset options
    dsopts_feature_encoding = utils.forms.SelectField(
        'Feature Encoding',
        default='png',
        choices=[
            ('none', 'None'),
            ('png', 'PNG (lossless)'),
            ('jpg', 'JPEG (lossy, 90% quality)'),
        ],
        tooltip="Using either of these compression formats can save disk"
        " space, but can also require marginally more time for"
        " training.")

    dsopts_label_encoding = utils.forms.SelectField(
        'Label Encoding',
        default='none',
        choices=[
            ('none', 'None'),
            ('png', 'PNG (lossless)'),
            ('jpg', 'JPEG (lossy, 90% quality)'),
        ],
        tooltip="Using either of these compression formats can save disk"
        " space, but can also require marginally more time for"
        " training.")

    dsopts_batch_size = utils.forms.IntegerField(
        'Encoder batch size',
        validators=[
            validators.DataRequired(),
            validators.NumberRange(min=1),
        ],
        default=32,
        tooltip="Encode data in batches of specified number of entries")

    dsopts_num_threads = utils.forms.IntegerField(
        'Number of encoder threads',
        validators=[
            validators.DataRequired(),
            validators.NumberRange(min=1),
        ],
        default=4,
        tooltip="Use specified number of encoder threads")

    dsopts_backend = wtforms.SelectField(
        'DB backend',
        choices=[
            ('lmdb', 'LMDB'),
        ],
        default='lmdb',
    )

    dsopts_force_same_shape = utils.forms.SelectField(
        'Enforce same shape',
        choices=[
            (1, 'Yes'),
            (0, 'No'),
        ],
        coerce=int,
        default=1,
        tooltip="Check that each entry in the database has the same shape."
        "Disabling this will also disable mean image computation.")
Ejemplo n.º 21
0
class CreateExpenseForm(FlaskForm):

    client_name = StringField('Client Name', validators=[DataRequired()])

    client_project = StringField('Client Project', validators=[DataRequired()])

    client_or_saggezza = SelectField('Client or Saggezza:',
                                     choices=[('Saggezza UK', 'Saggezza UK'),
                                              ('Saggezza US', 'Saggezza US'),
                                              ('Client', 'Client')])

    expenses_date = DateField('Choose date of the appointment:',
                              format='%Y-%m-%d',
                              validators=[DataRequired()])

    billable_to = SelectField('Billable to client ?',
                              choices=[('Yes', 'Yes'), ('No', 'No')])

    payment = SelectField('Payment Method',
                          choices=[('Own Payment', 'Own Payment'),
                                   ('Corporate Card', 'Corporate Card')])

    receipt = SelectField('Receipt',
                          choices=[('Yes-Soft Copy', 'Yes-Soft Copy'),
                                   ('Yes-Hard Copy', 'Yes-Hard Copy'),
                                   ('No-Receipt', 'No-Receipt')])

    description = TextAreaField('Description', validators=[DataRequired()])

    expense_category = SelectField(
        'Category',
        choices=[
            ('Employee Rewards', 'Employee Rewards'),
            ('Consumables', 'Consumables'),
            ('General Office Expenses', 'General Office Expenses'),
            ('General Travel: Accommodation', 'General Travel: Accommodation'),
            ('General Travel: Travel', 'General Travel: Travel'),
            ('General Travel: Subsistence', 'General Travel: Subsistence'),
            ('Sales Entertaining', 'Sales Entertaining'),
            ('Staff Entertaining', 'Staff Entertaining'),
            ('Recruitment fees', 'Recruitment fees'),
            ('Visa & Immigration', 'Visa & Immigration'),
            ('Software & IT', 'Software & IT'),
            ('Staff Training', 'Staff Training'),
            ('Stationery & Office Supplies', 'Stationery & Office Supplies'),
            ('Telephone & Conference', 'Telephone & Conference'),
            ('Other', 'Other')
        ])

    GBP = FloatField('Cost in GBP:  Required *',
                     validators=[validators.NumberRange(min=0)])
    EUR = FloatField('Cost in EUR: (optional)',
                     validators=[validators.NumberRange(min=0)])
    USD = FloatField('Cost in USD: (optional)',
                     validators=[validators.NumberRange(min=0)])

    picture_expense = FileField(
        'Upload Receipt Image',
        validators=[FileAllowed(['jpg', 'png', 'tiff'])])

    submit = SubmitField('Add Expense')
Ejemplo n.º 22
0
class uploadForm(Form):
    appName = StringField("Enter app name", validators=[validators.Length(min=4, max=25)])
    ageRestriction = IntegerField("Enter age limit",validators=[validators.NumberRange(min=0, max=99)])
    size = IntegerField("Enter size in Mb", validators=[validators.NumberRange(min=0, max=99)])
    osVersion = IntegerField("Enter android version", validators=[validators.NumberRange(min=4, max=9)])
    category = StringField("Enter category", validators=[validators.Length(min=4, max=25)])
Ejemplo n.º 23
0
class TransactionForm(Form):
    sender = IntegerField('sender', [validators.NumberRange(min=1)])
    receiver = IntegerField('receiver', [validators.NumberRange(min=1)])
    amount = FloatField('amount', [validators.NumberRange(min=0)])
Ejemplo n.º 24
0
class applyFilterForm(Form):
    ageRestriction = IntegerField("Enter age limit",validators=[validators.NumberRange(min=0, max=99),validators.DataRequired("This area cannot be blank")])
    size = IntegerField("Enter size in Mb", validators=[validators.NumberRange(min=0, max=99),validators.DataRequired("This area cannot be blank")])
    osVersion = IntegerField("Enter android version", validators=[validators.NumberRange(min=4, max=9),validators.DataRequired("This area cannot be blank")])
    category = StringField("Enter category", validators=[validators.Length(min=4, max=25),validators.DataRequired("This area cannot be blank")])
Ejemplo n.º 25
0
class ChangePagination(Form):
    paginacion = IntegerField(
        'Paginacion',
        [validators.required(),
         validators.NumberRange(min=1, max=20)])
Ejemplo n.º 26
0
class ModelForm(Form):

    ### Methods

    def selection_exists_in_choices(form, field):
        found = False
        for choice in field.choices:
            if choice[0] == field.data:
                found = True
        if not found:
            raise validators.ValidationError(
                "Selected job doesn't exist. Maybe it was deleted by another user."
            )

    def validate_NetParameter(form, field):
        fw = frameworks.get_framework_by_id(form['framework'].data)
        try:
            # below function raises a BadNetworkException in case of validation error
            fw.validate_network(field.data)
        except frameworks.errors.BadNetworkError as e:
            raise validators.ValidationError('Bad network: %s' % e.message)

    def validate_file_exists(form, field):
        from_client = bool(form.python_layer_from_client.data)

        filename = ''
        if not from_client and field.type == 'StringField':
            filename = field.data

        if filename == '': return

        if not os.path.isfile(filename):
            raise validators.ValidationError(
                'Server side file, %s, does not exist.' % filename)

    def validate_py_ext(form, field):
        from_client = bool(form.python_layer_from_client.data)

        filename = ''
        if from_client and field.type == 'FileField':
            filename = flask.request.files[field.name].filename
        elif not from_client and field.type == 'StringField':
            filename = field.data

        if filename == '': return

        (root, ext) = os.path.splitext(filename)
        if ext != '.py' and ext != '.pyc':
            raise validators.ValidationError(
                'Python file, %s, needs .py or .pyc extension.' % filename)

    ### Fields

    # The options for this get set in the view (since they are dynamic)
    dataset = utils.forms.SelectField(
        'Select Dataset',
        choices=[],
        tooltip="Choose the dataset to use for this model.")

    python_layer_from_client = utils.forms.BooleanField(
        u'Use client-side file', default=False)

    python_layer_client_file = utils.forms.FileField(
        u'Client-side file',
        validators=[validate_py_ext],
        tooltip=
        "Choose a Python file on the client containing layer definitions.")
    python_layer_server_file = utils.forms.StringField(
        u'Server-side file',
        validators=[validate_file_exists, validate_py_ext],
        tooltip=
        "Choose a Python file on the server containing layer definitions.")

    train_epochs = utils.forms.IntegerField(
        'Training epochs',
        validators=[validators.NumberRange(min=1)],
        default=30,
        tooltip="How many passes through the training data?")

    snapshot_interval = utils.forms.FloatField(
        'Snapshot interval (in epochs)',
        default=1,
        validators=[
            validators.NumberRange(min=0),
        ],
        tooltip="How many epochs of training between taking a snapshot?")

    val_interval = utils.forms.FloatField(
        'Validation interval (in epochs)',
        default=1,
        validators=[validators.NumberRange(min=0)],
        tooltip=
        "How many epochs of training between running through one pass of the validation data?"
    )

    random_seed = utils.forms.IntegerField(
        'Random seed',
        validators=[
            validators.NumberRange(min=0),
            validators.Optional(),
        ],
        tooltip=
        "If you provide a random seed, then back-to-back runs with the same model and dataset should give identical results."
    )

    batch_size = utils.forms.MultiIntegerField(
        'Batch size',
        validators=[
            utils.forms.MultiNumberRange(min=1),
            utils.forms.MultiOptional(),
        ],
        tooltip=
        "How many images to process at once. If blank, values are used from the network definition."
    )

    batch_accumulation = utils.forms.IntegerField(
        'Batch Accumulation',
        validators=[
            validators.NumberRange(min=1),
            validators.Optional(),
        ],
        tooltip=
        "Accumulate gradients over multiple batches (useful when you need a bigger batch size for training but it doesn't fit in memory)."
    )

    ### Solver types

    solver_type = utils.forms.SelectField(
        'Solver type',
        choices=[
            ('SGD', 'Stochastic gradient descent (SGD)'),
            ('NESTEROV', "Nesterov's accelerated gradient (NAG)"),
            ('ADAGRAD', 'Adaptive gradient (AdaGrad)'),
            ('RMSPROP', 'RMSprop'),
            ('ADADELTA', 'AdaDelta'),
            ('ADAM', 'Adam'),
        ],
        default='SGD',
        tooltip="What type of solver will be used?",
    )

    def validate_solver_type(form, field):
        fw = frameworks.get_framework_by_id(form.framework)
        if fw is not None:
            if not fw.supports_solver_type(field.data):
                raise validators.ValidationError(
                    'Solver type not supported by this framework')

    ### Learning rate

    learning_rate = utils.forms.MultiFloatField(
        'Base Learning Rate',
        default=0.01,
        validators=[
            utils.forms.MultiNumberRange(min=0),
        ],
        tooltip=
        "Affects how quickly the network learns. If you are getting NaN for your loss, you probably need to lower this value."
    )

    lr_policy = wtforms.SelectField('Policy',
                                    choices=[
                                        ('fixed', 'Fixed'),
                                        ('step', 'Step Down'),
                                        ('multistep',
                                         'Step Down (arbitrary steps)'),
                                        ('exp', 'Exponential Decay'),
                                        ('inv', 'Inverse Decay'),
                                        ('poly', 'Polynomial Decay'),
                                        ('sigmoid', 'Sigmoid Decay'),
                                    ],
                                    default='step')

    lr_step_size = wtforms.FloatField('Step Size', default=33)
    lr_step_gamma = wtforms.FloatField('Gamma', default=0.1)
    lr_multistep_values = wtforms.StringField('Step Values', default="50,85")

    def validate_lr_multistep_values(form, field):
        if form.lr_policy.data == 'multistep':
            for value in field.data.split(','):
                try:
                    float(value)
                except ValueError:
                    raise validators.ValidationError('invalid value')

    lr_multistep_gamma = wtforms.FloatField('Gamma', default=0.5)
    lr_exp_gamma = wtforms.FloatField('Gamma', default=0.95)
    lr_inv_gamma = wtforms.FloatField('Gamma', default=0.1)
    lr_inv_power = wtforms.FloatField('Power', default=0.5)
    lr_poly_power = wtforms.FloatField('Power', default=3)
    lr_sigmoid_step = wtforms.FloatField('Step', default=50)
    lr_sigmoid_gamma = wtforms.FloatField('Gamma', default=0.1)

    ### Network

    # Use a SelectField instead of a HiddenField so that the default value
    # is used when nothing is provided (through the REST API)
    method = wtforms.SelectField(
        u'Network type',
        choices=[
            ('standard', 'Standard network'),
            ('previous', 'Previous network'),
            ('custom', 'Custom network'),
        ],
        default='standard',
    )

    ## framework - hidden field, set by Javascript to the selected framework ID
    framework = wtforms.HiddenField(
        'framework',
        validators=[
            validators.AnyOf(
                [fw.get_id() for fw in frameworks.get_frameworks()],
                message='The framework you choose is not currently supported.')
        ],
        default=frameworks.get_frameworks()[0].get_id())

    # The options for this get set in the view (since they are dependent on the data type)
    standard_networks = wtforms.RadioField(
        'Standard Networks',
        validators=[
            validate_required_iff(method='standard'),
        ],
    )

    previous_networks = wtforms.RadioField(
        'Previous Networks',
        choices=[],
        validators=[
            validate_required_iff(method='previous'),
            selection_exists_in_choices,
        ],
    )

    custom_network = utils.forms.TextAreaField(
        'Custom Network',
        validators=[
            validate_required_iff(method='custom'),
            validate_NetParameter,
        ],
    )

    custom_network_snapshot = utils.forms.TextField(
        'Pretrained model(s)',
        tooltip=
        "Paths to pretrained model files, separated by '%s'. Only edit this field if you understand how fine-tuning works in caffe or torch."
        % os.path.pathsep)

    def validate_custom_network_snapshot(form, field):
        if form.method.data == 'custom':
            for filename in field.data.strip().split(os.path.pathsep):
                if filename and not os.path.exists(filename):
                    raise validators.ValidationError(
                        'File "%s" does not exist' % filename)

    # Select one of several GPUs
    select_gpu = wtforms.RadioField(
        'Select which GPU you would like to use',
        choices=[('next', 'Next available')] + [(
            index,
            '#%s - %s (%s memory)' %
            (index, get_device(index).name,
             sizeof_fmt(
                 get_nvml_info(index)['memory']['total']
                 if get_nvml_info(index) and 'memory' in get_nvml_info(index)
                 else get_device(index).totalGlobalMem)),
        ) for index in config_value('gpu_list').split(',') if index],
        default='next',
    )

    # Select N of several GPUs
    select_gpus = utils.forms.SelectMultipleField(
        'Select which GPU[s] you would like to use',
        choices=[(
            index,
            '#%s - %s (%s memory)' %
            (index, get_device(index).name,
             sizeof_fmt(
                 get_nvml_info(index)['memory']['total']
                 if get_nvml_info(index) and 'memory' in get_nvml_info(index)
                 else get_device(index).totalGlobalMem)),
        ) for index in config_value('gpu_list').split(',') if index],
        tooltip=
        "The job won't start until all of the chosen GPUs are available.")

    # XXX For testing
    # The Flask test framework can't handle SelectMultipleFields correctly
    select_gpus_list = wtforms.StringField(
        'Select which GPU[s] you would like to use (comma separated)')

    def validate_select_gpus(form, field):
        if form.select_gpus_list.data:
            field.data = form.select_gpus_list.data.split(',')

    # Use next available N GPUs
    select_gpu_count = wtforms.IntegerField(
        'Use this many GPUs (next available)',
        validators=[
            validators.NumberRange(min=1,
                                   max=len(
                                       config_value('gpu_list').split(',')))
        ],
        default=1,
    )

    def validate_select_gpu_count(form, field):
        if field.data is None:
            if form.select_gpus.data:
                # Make this field optional
                field.errors[:] = []
                raise validators.StopValidation()

    model_name = utils.forms.StringField(
        'Model Name',
        validators=[validators.DataRequired()],
        tooltip=
        "An identifier, later used to refer to this model in the Application.")

    # allows shuffling data during training (for frameworks that support this, as indicated by
    # their Framework.can_shuffle_data() method)
    shuffle = utils.forms.BooleanField(
        'Shuffle Train Data',
        default=True,
        tooltip='For every epoch, shuffle the data before training.')
Ejemplo n.º 27
0
class InputMod(FlaskForm):
    input_id = IntegerField('Input ID', widget=widgets.HiddenInput())
    name = StringField(lazy_gettext('Name'), validators=[DataRequired()])
    i2c_bus = IntegerField(lazy_gettext('I<sup>2</sup>C Bus'))
    location = StringField(lazy_gettext('Location'))
    baud_rate = IntegerField(lazy_gettext('Baud Rate'))
    device_loc = StringField(lazy_gettext('Device Location'))
    calibrate_sensor_measure = StringField(
        lazy_gettext('Calibration Measurement'))
    resolution = IntegerField(lazy_gettext('Resolution'))
    sensitivity = IntegerField(lazy_gettext('Sensitivity'))
    power_relay_id = IntegerField(lazy_gettext('Power Output'))
    multiplexer_address = StringField(lazy_gettext('Multiplexer (MX)'))
    multiplexer_bus = StringField(lazy_gettext('Mx I<sup>2</sup>C Bus'))
    multiplexer_channel = IntegerField(lazy_gettext('Mx Channel'))
    cmd_command = StringField(lazy_gettext('Command'))
    cmd_measurement = StringField(lazy_gettext('Measurement'))
    cmd_measurement_units = StringField(lazy_gettext('Unit'))
    adc_channel = IntegerField(lazy_gettext('Channel'))
    adc_gain = IntegerField(lazy_gettext('Gain'))
    adc_resolution = IntegerField(lazy_gettext('Resolution'))
    adc_measurement = StringField(lazy_gettext('Measurement'))
    adc_measurement_units = StringField(lazy_gettext('Measurement Units'))
    adc_volts_min = DecimalField(lazy_gettext('Volts Min'))
    adc_volts_max = DecimalField(lazy_gettext('Volts Max'))
    adc_units_min = DecimalField(lazy_gettext('Units Min'))
    adc_units_max = DecimalField(lazy_gettext('Units Max'))
    adc_inverse_unit_scale = BooleanField(lazy_gettext('Inverse Unit Scale'))
    switch_edge = StringField(lazy_gettext('Edge'))
    switch_bounce_time = IntegerField(lazy_gettext('Bounce Time (ms)'))
    switch_reset_period = IntegerField(lazy_gettext('Reset Period'))
    pre_relay_id = StringField(lazy_gettext('Pre Output'))
    pre_relay_duration = DecimalField(
        lazy_gettext('Pre Output Duration'),
        validators=[validators.NumberRange(min=0, max=86400)])
    period = DecimalField(lazy_gettext('Period (seconds)'),
                          validators=[
                              DataRequired(),
                              validators.NumberRange(min=5.0, max=86400.0)
                          ])
    weighting = DecimalField(lazy_gettext('Weighting'))
    rpm_pulses_per_rev = DecimalField(lazy_gettext('Pulses Per Rev'))
    sample_time = DecimalField(lazy_gettext('Sample Time (seconds)'))
    sht_clock_pin = IntegerField(
        lazy_gettext('Clock Pin'),
        validators=[
            validators.NumberRange(min=0,
                                   max=100,
                                   message=lazy_gettext(
                                       "If using a SHT sensor, enter the GPIO "
                                       "connected to the clock pin (using BCM "
                                       "numbering)"))
        ])
    sht_voltage = StringField(lazy_gettext('Voltage'))
    host = StringField(lazy_gettext('Host'))
    port = IntegerField(lazy_gettext('Port'))
    times_check = IntegerField(lazy_gettext('Times to Check'))
    deadline = IntegerField(lazy_gettext('Deadline (seconds)'))

    input_mod = SubmitField(lazy_gettext('Save'))
    input_delete = SubmitField(lazy_gettext('Delete'))
    input_activate = SubmitField(lazy_gettext('Activate'))
    input_deactivate = SubmitField(lazy_gettext('Deactivate'))
    input_order_up = SubmitField(lazy_gettext('Up'))
    input_order_down = SubmitField(lazy_gettext('Down'))
Ejemplo n.º 28
0
class ModifyDrinkForm(FlaskForm):
    name = StringField('Name:', [validators.data_required(), validators.length(min=3)])
    price = DecimalField('Price:', [validators.data_required(), validators.NumberRange(min=3, max=50,
                                                                                       message="Field must be between $3.00 to $50.00")],
                         places=2)
    thumbnail = FileField('Thumbnail:')
class CreatureForm(FlaskForm):
    name = StringField("Name", [validators.Length(min=2), validators.Length(max=40), validators.optional()])
    hp = IntegerField("HP", [validators.NumberRange(min=1)])
    formula = StringField("HP formula", [validators.Length(min=2), validators.Length(max=40), validators.optional()])
    ac = IntegerField("AC", [validators.NumberRange(min=0)])
    speed = IntegerField("Speed", [validators.NumberRange(min=0)], default=30)
    flyspeed = IntegerField("Flying speed", [validators.NumberRange(min=0)], default=0)
    swimspeed = IntegerField("Swimming speed", [validators.NumberRange(min=0)], default=0)
    strength = IntegerField("STR", [validators.NumberRange(min=1)])
    dex = IntegerField("DEX", [validators.NumberRange(min=1)])
    con = IntegerField("CON", [validators.NumberRange(min=1)])
    intelligence = IntegerField("INT", [validators.NumberRange(min=1)])
    wis = IntegerField("WIS", [validators.NumberRange(min=1)])
    cha = IntegerField("CHA", [validators.NumberRange(min=1)])
    proficiency = IntegerField("Proficiency", [validators.NumberRange(min=0)])
    cr = DecimalField("CR")
    strsav = BooleanField("STR")
    dexsav = BooleanField("DEX")
    consav = BooleanField("CON")
    intsav = BooleanField("INT")
    wissav = BooleanField("WIS")
    chasav = BooleanField("CHA")

    athletics = BooleanField("Athletics")
    
    acrobatics = BooleanField("Acrobatics")
    soh = BooleanField("Sleight of Hand")
    stealth = BooleanField("Stealth")

    arcana = BooleanField("Arcana")
    history = BooleanField("History")
    investigation = BooleanField("Investigation")
    nature = BooleanField("Nature")
    religion = BooleanField("Religion")

    animal = BooleanField("Animal Handling")
    insight = BooleanField("Insight")
    medicine = BooleanField("Medicine")
    perception = BooleanField("Perception")
    survival = BooleanField("Survival")

    deception = BooleanField("Deception")
    intimidation = BooleanField("Intimidation")
    performance = BooleanField("Performance")
    persuasion = BooleanField("Persuasion")

    class Meta:
        csrf = False
Ejemplo n.º 30
0
class TansikForm(Form):
    tansik = FloatField("tansik", [
        validators.NumberRange(min=205, max=410, message="Enter valid grade"),
        validators.DataRequired()
    ])