class SelectActivityForm(Form): checkin_for = wtforms.SelectField()
class CreateELBForm(ELBHealthChecksForm, ELBAccessLogsFormMixin): """Create Elastic Load Balancer form""" ELB_NAME_PATTERN = '^[a-zA-Z0-9-]{1,32}$' name_error_msg = _( 'Name is required, and may only contain alphanumeric characters and/or hyphens. ' 'Length may not exceed 32 characters.') name = wtforms.TextField( label=_(u'Name'), validators=[validators.InputRequired(message=name_error_msg)], ) vpc_network_error_msg = _(u'VPC network is required') vpc_network = wtforms.SelectField( label=_(u'VPC network'), validators=[validators.InputRequired(message=vpc_network_error_msg)], ) vpc_subnet = wtforms.SelectMultipleField(label=_(u'VPC subnets'), ) securitygroup = wtforms.SelectMultipleField(label=_(u'Security groups')) securitygroup_help_text = _( u'If you do not select a security group, the default group will be used.' ) zone = wtforms.SelectMultipleField(label=_(u'Availability zones')) cross_zone_enabled_help_text = _( u'Distribute traffic evenly across all instances in all availability zones' ) cross_zone_enabled = wtforms.BooleanField( label=_(u'Enable cross-zone load balancing')) add_availability_zones_help_text = _( u'Enable this load balancer to route traffic to instances in the selected zones' ) add_vpc_subnets_help_text = _( u'Enable this load balancer to route traffic to instances in the selected subnets' ) add_instances_help_text = _( u'Balance traffic between the selected instances') def __init__(self, request, conn=None, vpc_conn=None, **kwargs): super(CreateELBForm, self).__init__(request, **kwargs) self.conn = conn self.vpc_conn = vpc_conn self.cloud_type = request.session.get('cloud_type', 'euca') self.is_vpc_supported = BaseView.is_vpc_supported(request) self.set_error_messages() self.choices_manager = ChoicesManager(conn=conn) self.vpc_choices_manager = ChoicesManager(conn=vpc_conn) self.set_choices(request) self.securitygroup.help_text = self.securitygroup_help_text self.cross_zone_enabled.help_text = self.cross_zone_enabled_help_text self.bucket_name.help_text = self.bucket_name_help_text self.bucket_prefix.help_text = self.bucket_prefix_help_text def set_choices(self, request): if self.cloud_type == 'euca' and self.is_vpc_supported: self.vpc_network.choices = self.vpc_choices_manager.vpc_networks( add_blank=False) else: self.vpc_network.choices = self.vpc_choices_manager.vpc_networks() self.vpc_subnet.choices = self.vpc_choices_manager.vpc_subnets() self.securitygroup.choices = self.choices_manager.security_groups( securitygroups=None, use_id=True, add_blank=False) self.zone.choices = self.get_availability_zone_choices() self.ping_protocol.choices = self.get_ping_protocol_choices() self.time_between_pings.choices = self.get_time_between_pings_choices() self.failures_until_unhealthy.choices = self.get_failures_until_unhealthy_choices( ) self.passes_until_healthy.choices = self.get_passes_until_healthy_choices( ) self.bucket_name.choices = self.s3_choices_manager.buckets() self.collection_interval.choices = self.get_collection_interval_choices( ) self.cross_zone_enabled.data = True # Set default choices where applicable, defaulting to first non-blank choice if self.cloud_type == 'aws' and len(self.zone.choices) > 1: self.zone.data = self.zone.choices[0] # Set the defailt option to be the first choice if len(self.vpc_network.choices) > 1: self.vpc_network.data = self.vpc_network.choices[0][0] def set_error_messages(self): self.name.error_msg = self.name_error_msg self.bucket_name.error_msg = self.bucket_name_error_msg self.bucket_prefix.error_msg = self.bucket_prefix_error_msg def get_availability_zone_choices(self): return self.choices_manager.availability_zones(self.region, add_blank=False)
class SecurityPolicyForm(BaseSecureForm): """ELB Security Policy form""" predefined_policy_error_msg = _(u'Policy is required') predefined_policy = wtforms.SelectField( label=_(u'Policy name'), validators=[ PredefinedPolicyRequired(message=predefined_policy_error_msg) ], ) ssl_protocols_error_msg = _(u'At least one protocol is required.') ssl_protocols = wtforms.SelectMultipleField( label=_(u'SSL Protocols'), validators=[validators.InputRequired(message=ssl_protocols_error_msg)], ) ssl_ciphers_error_msg = _(u'At least one cipher is required.') ssl_ciphers = wtforms.SelectMultipleField( label=_(u'SSL Ciphers'), validators=[validators.InputRequired(message=ssl_ciphers_error_msg)], ) server_order_preference = wtforms.BooleanField( label=_(u'Server order preference')) # Under SSL Options def __init__(self, request, elb_conn=None, predefined_policy_choices=None, **kwargs): super(SecurityPolicyForm, self).__init__(request, **kwargs) self.elb_conn = elb_conn self.predefined_policy_choices = predefined_policy_choices self.set_error_messages() self.set_choices() self.set_initial_data() def set_error_messages(self): self.predefined_policy.error_msg = self.predefined_policy_error_msg self.ssl_protocols.error_msg = self.ssl_protocols_error_msg self.ssl_ciphers.error_msg = self.ssl_ciphers_error_msg def set_choices(self): self.ssl_protocols.choices = self.get_ssl_protocol_choices() self.ssl_ciphers.choices = self.get_ssl_cipher_choices() self.predefined_policy.choices = self.get_predefined_policy_choices() def set_initial_data(self): # Default to TLS 1, 1.1, and 1.2 for ssl_protocols self.ssl_protocols.data = [ val for val, label in self.get_ssl_protocol_choices() ] def get_predefined_policy_choices(self): if self.predefined_policy_choices: return self.predefined_policy_choices if self.elb_conn is not None: return ChoicesManager( conn=self.elb_conn).predefined_policy_choices(add_blank=False) return [] @staticmethod def get_ssl_protocol_choices(): return [ ('Protocol-TLSv1.2', u'TLSv1.2'), ('Protocol-TLSv1.1', u'TLSv1.1'), ('Protocol-TLSv1', u'TLSv1'), ] @staticmethod def get_ssl_cipher_choices(): return [(val, val) for val in SSL_CIPHERS]
class CardSelectForm(flask_wtf.FlaskForm): atr = wtforms.SelectField(u"ATR") submit = wtforms.SubmitField("Show")
class GenericImageDatasetForm(ImageDatasetForm): """ Defines the form used to create a new GenericImageDatasetJob """ # 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( 'Dataset type', choices=[ ('prebuilt', 'Prebuilt'), ], default='prebuilt', ) def validate_lmdb_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') 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) or not os.path.isfile( field.data): raise validators.ValidationError('File does not exist') # # Method - prebuilt # prebuilt_train_images = wtforms.StringField( 'Training Images', validators=[ validate_required_iff(method='prebuilt'), validate_lmdb_path, ]) prebuilt_train_labels = wtforms.StringField('Training Labels', validators=[ validate_lmdb_path, ]) prebuilt_val_images = wtforms.StringField('Validation Images', validators=[ validate_lmdb_path, ]) prebuilt_val_labels = wtforms.StringField('Validation Labels', validators=[ validate_lmdb_path, ]) # 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 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 (can be time-consuming)' ) prebuilt_mean_file = utils.forms.StringField( 'Mean Image', validators=[ validate_file_path, ], tooltip="Path to a .binaryproto file on the server")
class OrgSearchForm(MyBaseForm): name = wtforms.StringField('Organization Name') city = wtforms.StringField('City') state = wtforms.SelectField('State', choices=states()) zip_code = wtforms.StringField('Zip') submit = wtforms.SubmitField('Search')
class TextMessageForm(MyBaseForm): recipient = wtforms.SelectField('Recipient', choices=[], coerce=str) message = wtforms.TextAreaField( 'Message', [wtforms.validators.DataRequired()]) submit = wtforms.SubmitField('Send Text')
class StatisticFilterForm(wtforms.Form): filter_by = wtforms.SelectField( choices=(('day', 'Day'), ('month', 'Month'), ('year', 'Year')), ) date = wtforms.DateField(validators=[wtforms.validators.DataRequired()])
import json from wtforms import HiddenField from flask_wtf import FlaskForm import wtforms from wtforms.validators import DataRequired cracker_fields = [ wtforms.SelectField( "Cracker", choices=[("John", "John"), ("Hashcat", "Hashcat")], # wtforms 2.2 requires a list of tuples # https://github.com/wtforms/wtforms/pull/526 description={ 'id': 'cracker', 'help': "Choose 'John' or 'Hashcat'", } ), wtforms.StringField( "Binary Path", description={ 'help': "Path to the binary", 'placeholder': "/usr/sbin/john", 'id': 'binary_path', }, validators=[DataRequired("This field is required.")], ), wtforms.StringField( "Additional Arguments", description={
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')])
class UserEditForm(wtf.Form): """ Admin edits freelancer's profile """ start_work_experience_tooltip = u""" Rok rozpoczęcia pracy zawodowej, dzięki czemu będziemy mogli policzyć automatycznie doświadczenie. Jeżeli ktoś pracował przez 4 lata na pół etatu, to należy to potraktować jako 2 lata, czyli dodać dwa do roku rozpoczęcia pracy zawodowej. Bierzemy pod uwagę tylko pracę w branży wynikającej ze stanowiska, czyli jak programista pracował jako kelner to tego mu nie wliczamy. """ employment_contract = wtf.BooleanField( _(u"Employment contract"), validators=[], ) is_active = wtf.BooleanField(_(u"Is active"), validators=[]) avatar = wtf.HiddenField() roles = wtf.SelectMultipleField( _(u'Role'), validators=[], choices=User.ROLES, ) start_work = wtf.DateField( _(u"Start work"), format='%d/%m/%Y', validators=[MinYearValidator()], ) start_full_time_work = wtf.DateField( _(u"Start full time work"), format='%d/%m/%Y', validators=[validators.Optional(), MinYearValidator()], ) stop_work = wtf.DateField( _(u"Stop work"), format='%d/%m/%Y', validators=[validators.Optional(), MinYearValidator()], ) description = wtf.TextField( _(u"Description"), validators=[validators.Optional()], ) date_of_birth = wtf.DateField( _(u"Date of birth"), format='%d/%m/%Y', validators=[validators.Optional(), MinYearValidator()], ) location = wtf.SelectField( _(u"Office location"), choices=[(k, v[0]) for k, v in User.LOCATIONS.items()], ) start_work_experience = wtf.DateField( _(u"Start work experience"), validators=[validators.Optional(), MinYearValidator()], description=start_work_experience_tooltip, format="%Y", ) availability_link = wtf.TextField( _(u"Availability calendar link"), validators=[validators.Optional(), validators.URL()], ) tasks_link = wtf.TextField( _(u"Tasks calendar link"), validators=[validators.Optional(), validators.URL()], ) skype = wtf.TextField(_(u"Skype"), validators=[validators.Optional()]) phone = wtf.TextField(_(u"Phone"), validators=[validators.Optional()]) phone_on_desk = wtf.TextField( _(u"Deskphone"), validators=[validators.Optional()], ) irc = wtf.TextField(_(u"IRC"), validators=[validators.Optional()]) groups = wtf.SelectMultipleField( _(u'Groups'), validators=[], choices=zip(User.GROUPS, User.GROUPS), )
class UserView(ModelView): can_view_details = True column_type_formatters = MY_DEFAULT_FORMATTERS form_extra_fields = { "password1": CustomPasswordField("Contraseña", validators=[validators.InputRequired()]), "password2": CustomPasswordField("Contraseña"), "avatar": form.ImageUploadField( "Avatar", base_path=file_path, namegen=prefix_name, url_relative_path="images/", ), "gender": wtforms.SelectField( validate_choice=False, label="Genero", choices=[(None, "--"), ("Hombre", "Hombre"), ("Mujer", "Mujer")], ), "roles": MultiCheckboxField( label="Roles", choices=[ ("ROLE_USER", "Usuario regular"), ("ROLE_EDITOR", "Editor"), ("ROLE_ADMIN", "Admin"), ], ), } column_list = [ "id", "username", "email", "first_name", "last_name", "location", "gender", "roles", "avatar", ] form_create_rules = [ form.rules.FieldSet([ "username", "password1", "email", "first_name", "last_name", "location", "gender", "information", "roles", "avatar", "avatar_url" ]) ] form_edit_rules = [ form.rules.FieldSet([ "username", "password2", "email", "first_name", "last_name", "location", "gender", "information", "roles", "avatar", "avatar_url" ]) ] form_widget_args = { "username": { "Autocomplete": "off" }, "password1": { "Autocomplete": "off" }, "password2": { "Autocomplete": "off" }, "email": { "Autocomplete": "off" }, } def _list_thumbnail(self, context, model, name): if not model.avatar: return Markup('<img src="%s" height="50">' % url_for("static", filename="images/default.png")) return Markup('<img src="%s" height="50">' % url_for("static", filename="images/" + model.avatar)) column_formatters = {"avatar": _list_thumbnail} form_formatters = {"avatar": _list_thumbnail} def is_accessible(self): return current_user.is_authenticated and 'ROLE_ADMIN' in current_user.roles def inaccessible_callback(self, name, **kwargs): return redirect(url_for("login.admin_login"))
class CloudWatchAlarmCreateForm(BaseSecureForm): """Form for creating a CloudWatch alarm""" name_error_msg = _(u'Name is required') name = wtforms.TextField( label=_(u'Name'), validators=[ validators.InputRequired(message=name_error_msg), ], ) desc_error_msg = _(u'Description is required') description = wtforms.TextAreaField( label=_(u'Description'), validators=[ validators.Length( max=255, message=_(u'Description must be less than 255 characters')) ], ) metric_error_msg = _(u'Metric is required') metric = wtforms.SelectField( label=_(u'Metric'), validators=[ validators.InputRequired(message=metric_error_msg), ], ) comparison_error_msg = _(u'Comparison is required') comparison = wtforms.SelectField( label=_(u'Comparison'), validators=[ validators.InputRequired(message=comparison_error_msg), ], ) statistic_error_msg = _(u'Statistic is required') statistic = wtforms.SelectField( label=_(u'Statistic'), validators=[ validators.InputRequired(message=statistic_error_msg), ], ) threshold_error_msg = _(u'Trigger threshold amount is required') threshold = wtforms.IntegerField( label=_(u'Trigger threshold'), validators=[ validators.InputRequired(message=threshold_error_msg), ], ) period_help_text = _(u'Length of measurement period in minutes.') period_error_msg = _( u'Period length is required and must be a whole number greater than zero' ) period = wtforms.IntegerField( label=_(u'Period length'), validators=[ validators.InputRequired(message=period_error_msg), ], ) evaluation_periods_help_text = _( u'How many consecutive periods the trigger threshold must be breached before the alarm is triggered.' ) evaluation_periods_error_msg = _(u'Measurement periods is required') evaluation_periods = wtforms.IntegerField( label=_(u'Periods'), validators=[ validators.InputRequired(message=evaluation_periods_error_msg), ], ) unit = wtforms.SelectField(label=_(u'Unit')) image_id = wtforms.TextField(label=_(u'Image')) availability_zone = wtforms.SelectField() instance_id = wtforms.SelectField() instance_type = wtforms.SelectField() load_balancer_name = wtforms.SelectField() scaling_group_name = wtforms.SelectField() volume_id = wtforms.SelectField() def __init__(self, request, ec2_conn=None, autoscale_conn=None, elb_conn=None, scaling_group=None, **kwargs): super(CloudWatchAlarmCreateForm, self).__init__(request, **kwargs) self.ec2_conn = ec2_conn self.autoscale_conn = autoscale_conn self.elb_conn = elb_conn self.scaling_group = scaling_group self.cloud_type = request.session.get('cloud_type', 'euca') self.ec2_choices_manager = ChoicesManager(conn=ec2_conn) self.autoscale_choices_manager = ChoicesManager(conn=autoscale_conn) self.elb_choices_manager = ChoicesManager(conn=elb_conn) self.set_initial_data() self.set_error_messages() region = request.session.get('region') self.set_choices(region) self.set_help_text() def set_initial_data(self): self.evaluation_periods.data = 1 self.period.data = 5 if self.scaling_group is not None: self.scaling_group_name.data = self.scaling_group.name self.statistic.data = 'SampleCount' self.metric.data = 'GroupDesiredCapacity' self.unit.data = 'Count' def set_choices(self, region): self.comparison.choices = self.get_comparison_choices() self.statistic.choices = self.get_statistic_choices() self.metric.choices = self.get_metric_choices() self.unit.choices = self.get_unit_choices() self.availability_zone.choices = self.ec2_choices_manager.availability_zones( region) self.instance_id.choices = self.ec2_choices_manager.instances() self.instance_type.choices = self.get_instance_type_choices() self.load_balancer_name.choices = self.elb_choices_manager.load_balancers( ) self.scaling_group_name.choices = self.autoscale_choices_manager.scaling_groups( ) self.volume_id.choices = self.ec2_choices_manager.volumes() def set_help_text(self): self.evaluation_periods.help_text = self.evaluation_periods_help_text self.period.help_text = self.period_help_text def set_error_messages(self): self.name.error_msg = self.name_error_msg self.description.error_msg = self.desc_error_msg self.comparison.error_msg = self.comparison_error_msg self.statistic.error_msg = self.statistic_error_msg self.metric.error_msg = self.metric_error_msg self.threshold.error_msg = self.threshold_error_msg self.period.error_msg = self.period_error_msg self.evaluation_periods.error_msg = self.evaluation_periods_error_msg def get_instance_type_choices(self): return self.ec2_choices_manager.instance_types( cloud_type=self.cloud_type) @staticmethod def get_metric_choices(): choices = [BLANK_CHOICE] for metric in METRIC_TYPES: value = metric.get('name') label = '{0} - {1}'.format(metric.get('namespace'), metric.get('name')) choices.append((value, label)) return sorted(set(choices), key=itemgetter(1)) @staticmethod def get_comparison_choices(): return (('>=', '>='), ('>', '>'), ('<=', '<='), ('<', '<')) @staticmethod def get_statistic_choices(): return sorted([(choice, choice) for choice in Metric.Statistics]) @staticmethod def get_unit_choices(): choices = [BLANK_CHOICE] for choice in Metric.Units: if choice is not None: choices.append((choice, choice)) return choices
class VenueForm(Form): title = wtforms.TextField("Name", description="Name of the venue", validators=[ wtforms.validators.Required(), wtforms.validators.length(max=250) ]) description = RichTextField("Notes", description="Notes about the venue", content_css="/static/css/editor.css") address1 = wtforms.TextField("Address (line 1)", validators=[ wtforms.validators.Required(), wtforms.validators.length(max=80) ]) address2 = wtforms.TextField("Address (line 2)", validators=[ wtforms.validators.Optional(), wtforms.validators.length(max=80) ]) city = wtforms.TextField("City", validators=[ wtforms.validators.Required(), wtforms.validators.length(max=30) ]) state = wtforms.TextField("State", validators=[ wtforms.validators.Optional(), wtforms.validators.length(max=30) ]) postcode = wtforms.TextField("Post code", validators=[ wtforms.validators.Optional(), wtforms.validators.length(max=20) ]) country = wtforms.SelectField("Country", validators=[ wtforms.validators.Required(), wtforms.validators.length(max=2) ], choices=country_codes, default="IN") timezone = wtforms.SelectField('Timezone', validators=[wtforms.validators.Required()], choices=sorted_timezones()) latitude = wtforms.DecimalField("Latitude", places=None, validators=[ wtforms.validators.Optional(), wtforms.validators.NumberRange( -90, 90) ]) longitude = wtforms.DecimalField("Longitude", places=None, validators=[ wtforms.validators.Optional(), wtforms.validators.NumberRange( -180, 180) ]) profile_id = wtforms.SelectField( "Owner", description="The owner of this listing", coerce=int, validators=[wtforms.validators.Required()])
class RoleForm(MyBaseForm): role = wtforms.SelectField('', choices=[], coerce=str) submit = wtforms.SubmitField('Update')
class BeneficiarySignupForm(wtforms.Form): category = wtforms.RadioField(label='Which category best describes you? *', validators=[wtforms.validators.Required()], coerce=int, choices=BENEFICIARY_CATEGORY) title = wtforms.TextField(label='Name of the Organisation/Individual ', validators=[ wtforms.validators.Required(), wtforms.validators.Length(max=160) ]) organization_status = wtforms.RadioField( label='Organisation Status', validators=[wtforms.validators.Required()], coerce=int, choices=ORG_STATUS_CHOICES) address = wtforms.TextField( label='Head Office Address', description= 'In case of an individual, a residence address can be given.', validators=[ wtforms.validators.Required(), wtforms.validators.Length(max=500) ]) contact_number = wtforms.TextField( label='Head Office Phone Number', description= 'In case of an individual, a personal phone number can be given.', validators=[ wtforms.validators.Required(), wtforms.validators.Length(max=15) ]) email = wtforms.TextField(label='Email ID', validators=[ wtforms.validators.Required(), wtforms.validators.Email(), wtforms.validators.Length(max=254) ]) website = wtforms.TextField( label='Website URL', description=u'Website should start with http://', validators=[ wtforms.validators.Optional(), wtforms.validators.URL(), wtforms.validators.Length(max=500) ]) facebook = wtforms.TextField( label='Facebook link', description=u'Facebook link should start with http://', validators=[ wtforms.validators.Optional(), wtforms.validators.URL(), wtforms.validators.Length(max=500) ]) twitter = wtforms.TextField( label='Twitter link', description=u'Twitter link should start with http://', validators=[ wtforms.validators.Optional(), wtforms.validators.URL(), wtforms.validators.Length(max=500) ]) blog = wtforms.TextField( label='Blog link', description=u'Blog link should start with http://', validators=[ wtforms.validators.Optional(), wtforms.validators.URL(), wtforms.validators.Length(max=500) ]) has_80g_certificate = wtforms.RadioField( label='Does your organisation have 80G certification', validators=[wtforms.validators.Required()], coerce=bool, default=True, choices=[(True, 'Yes'), (False, 'No')]) person1_name = wtforms.TextField(label='Name', validators=[ wtforms.validators.Optional(), wtforms.validators.Length(max=160) ]) person1_position = wtforms.TextField(label='Position in the organisation', validators=[ wtforms.validators.Optional(), wtforms.validators.Length(max=160) ]) person1_email = wtforms.TextField(label='Email Id', validators=[ wtforms.validators.Optional(), wtforms.validators.Email(), wtforms.validators.Length(max=254) ]) person1_phone = wtforms.TextField(label='Phone Number', validators=[ wtforms.validators.Optional(), wtforms.validators.Length(max=15) ]) person2_name = wtforms.TextField(label='Your Name', validators=[ wtforms.validators.Optional(), wtforms.validators.Length(max=160) ]) person2_position = wtforms.TextField(label='Position in the organisation', validators=[ wtforms.validators.Optional(), wtforms.validators.Length(max=160) ]) person2_email = wtforms.TextField(label='Your Email Id', validators=[ wtforms.validators.Optional(), wtforms.validators.Email(), wtforms.validators.Length(max=254) ]) person2_phone = wtforms.TextField(label='Your Phone no', validators=[ wtforms.validators.Optional(), wtforms.validators.Length(max=15) ]) language1 = wtforms.SelectField(label='language1', choices=LANGUAGE_CHOICES, validators=[wtforms.validators.Required()]) language2 = wtforms.SelectField(label='language2', choices=LANGUAGE_CHOICES, validators=[wtforms.validators.Optional()]) language3 = wtforms.SelectField(label='language3', choices=LANGUAGE_CHOICES, validators=[wtforms.validators.Optional()]) total_impact_on_children = wtforms.IntegerField( label='Number of children that will be impacted by this campaign', validators=[wtforms.validators.Optional()]) org_work = wtforms.SelectMultipleField( label= 'Do you/your organisation do any work for following (check all that apply)', validators=[wtforms.validators.Required()], coerce=int, choices=ORG_WORK_CHOICES) project_books = wtforms.IntegerField( label='Books', validators=[wtforms.validators.Optional()]) project_lib_in_classroom = wtforms.IntegerField( label='Library-in-a-classroom (LIC)', validators=[wtforms.validators.Optional()]) project_state = wtforms.SelectField( label='Please select any one state in the list', validators=[wtforms.validators.Required()], choices=STATES) project_city = wtforms.TextField(validators=[ wtforms.validators.Required(), wtforms.validators.Length(max=100) ]) project_title = wtforms.TextField( label= 'Please enter a title for your campaign here. This is the first thing a donor will see or search while looking for your campaign.', validators=[ wtforms.validators.Optional(), wtforms.validators.Length(max=500) ]) project_description = wtforms.TextAreaField( label= 'Brief description of the project for which you are raising funds.', validators=[ wtforms.validators.Required(), wtforms.validators.Length(max=1500) ]) project_who_are_you = wtforms.TextAreaField( label='Who are you?', validators=[ wtforms.validators.Required(), wtforms.validators.Length(max=3000) ]) project_impact = wtforms.TextAreaField( label='What work do you do and how does it impact society ?', validators=[ wtforms.validators.Required(), wtforms.validators.Length(max=4000) ]) fund_utilization = wtforms.TextAreaField( label='How will the funds be utilized?', validators=[ wtforms.validators.Required(), wtforms.validators.Length(max=4000) ]) def set_edit_data(self, campaign): self.set_data(campaign.org) self.project_title.data = campaign.title self.project_description.data = campaign.description self.project_who_are_you.data = campaign.who self.project_impact.data = campaign.impact self.total_impact_on_children.data = campaign.total_impact_on_children self.fund_utilization.data = campaign.utilization self.project_books.data = campaign.nbooks self.project_lib_in_classroom.data = campaign.nlic self.project_state.data = campaign.state self.project_city.data = campaign.city for work in campaign.org.works: self.org_work.data.append(work.choice_id) languages = split(campaign.languages, ', ') languages = map(lambda x: x.strip(), languages) if len(languages) > 0: self.language1.data = languages[0] if len(languages) > 1: self.language2.data = languages[1] if len(languages) > 2: self.language3.data = languages[2] def set_data(self, org): self.category.data = org.info.category self.title.data = org.title self.email.data = org.info.email self.organization_status.data = org.info.status self.address.data = org.info.address self.contact_number.data = org.info.contact_number self.website.data = org.info.website self.facebook.data = org.info.facebook self.twitter.data = org.info.twitter self.has_80g_certificate.data = org.info.has_80g_certificate self.person1_name.data = org.info.person1_name self.person1_position.data = org.info.person1_position self.person1_email.data = org.info.person1_email self.person1_phone.data = org.info.person1_phone org_works = org.works org_works_selected = [] for org_work in org_works: org_works_selected.append(org_work.choice_id) self.org_work.data = org_works_selected def validate_language1(self, field): if field.data == 'Select': msg = u'Select at least one language' raise wtforms.ValidationError(msg)
class GroupUserRoleForm(MyBaseForm): role = wtforms.SelectField('', choices=[]) cohost_meeting = wtforms.BooleanField( 'Can Cohost Meetings', validators=[wtforms.validators.Optional()]) submit = wtforms.SubmitField('Update')
class CreateLaunchConfigForm(BaseSecureForm): """Create Launch Configuration form""" image_id = wtforms.HiddenField(label=_(u'Image')) name_error_msg = _( u'Name must be between 1 and 255 characters long, and must not contain \'/\' and \'\\\'' ) name = wtforms.TextField( label=_(u'Name'), validators=[validators.InputRequired(message=name_error_msg)], ) instance_type_error_msg = _(u'Instance type is required') instance_type = wtforms.SelectField( label=_(u'Instance type'), validators=[validators.InputRequired(message=instance_type_error_msg)], ) keypair_error_msg = _(u'Key pair is required') keypair = wtforms.SelectField( label=_(u'Key name'), validators=[validators.InputRequired(message=keypair_error_msg)], ) securitygroup_error_msg = _(u'Security group is required') securitygroup = wtforms.SelectMultipleField( label=_(u'Security group'), validators=[validators.InputRequired(message=securitygroup_error_msg)], ) associate_public_ip_address = wtforms.SelectField( label=_(u'VPC IP assignment')) associate_public_ip_address_helptext = _(u'This setting only applies \ when this launch configuration is used with a scaling group using a VPC network.' ) role = wtforms.SelectField() userdata = wtforms.TextAreaField(label=_(u'User data')) userdata_file_helptext = _(u'User data file may not exceed 16 KB') userdata_file = wtforms.FileField(label='') kernel_id = wtforms.SelectField(label=_(u'Kernel ID')) ramdisk_id = wtforms.SelectField(label=_(u'RAM disk ID (RAMFS)')) monitoring_enabled = wtforms.BooleanField(label=_(u'Enable monitoring')) create_sg_from_lc = wtforms.BooleanField( label=_(u'Create scaling group using this launch configuration')) def __init__(self, request, image=None, securitygroups=None, keyname=None, conn=None, iam_conn=None, **kwargs): super(CreateLaunchConfigForm, self).__init__(request, **kwargs) self.image = image self.keyname = keyname self.securitygroups = securitygroups self.conn = conn self.iam_conn = iam_conn self.cloud_type = request.session.get('cloud_type', 'euca') self.set_error_messages() self.monitoring_enabled.data = True self.create_sg_from_lc.data = True self.choices_manager = ChoicesManager(conn=conn) self.set_help_text() self.set_choices() self.set_monitoring_enabled_field() if image is not None: self.image_id.data = self.image.id if self.keyname is not None: self.keypair.data = self.keyname instance_id = request.params.get('userdata_instanceid') if instance_id is not None: with boto_error_handler(self.request): userdata = self.conn.get_instance_attribute( instance_id, 'userData') userdata = userdata['userData'] self.userdata.data = base64.b64decode( userdata) if userdata is not None else '' def set_monitoring_enabled_field(self): if self.cloud_type == 'euca': self.monitoring_enabled.data = True self.monitoring_enabled.help_text = _( u'Gather CloudWatch metric data for instances that use this launch configuration.' ) elif self.cloud_type == 'aws': self.monitoring_enabled.label.text = _( u'Enable detailed monitoring') self.monitoring_enabled.help_text = _( u'Gather all CloudWatch metric data at a higher frequency, ' u'and enable data aggregation by AMI and instance type. ' u'If left unchecked, data will still be gathered, but less often ' u'and without aggregation. ') def set_help_text(self): self.associate_public_ip_address.help_text = self.associate_public_ip_address_helptext self.userdata_file.help_text = self.userdata_file_helptext def set_choices(self): self.instance_type.choices = self.choices_manager.instance_types( cloud_type=self.cloud_type) empty_key_opt = True if self.keyname is not None: empty_key_opt = False self.keypair.choices = self.choices_manager.keypairs( add_blank=empty_key_opt, no_keypair_option=True) self.securitygroup.choices = self.choices_manager.security_groups( securitygroups=self.securitygroups, use_id=True, add_blank=False) self.role.choices = ChoicesManager(self.iam_conn).roles(add_blank=True) self.kernel_id.choices = self.choices_manager.kernels(image=self.image) self.ramdisk_id.choices = self.choices_manager.ramdisks( image=self.image) self.associate_public_ip_address.choices = self.get_associate_public_ip_address_choices( ) # Set init data for security group if len(self.securitygroup.choices) > 1: self.securitygroup.data = [ value for value, label in self.securitygroup.choices ] @staticmethod def get_associate_public_ip_address_choices(): return [('None', _(u'Only for instances in default VPC & subnet')), ('true', _(u'For all instances')), ('false', _(u'Never'))] def set_error_messages(self): self.name.error_msg = self.name_error_msg self.instance_type.error_msg = self.instance_type_error_msg self.securitygroup.error_msg = self.securitygroup_error_msg
class GroupAddOrgForm(MyBaseForm): orgs = wtforms.SelectField('Organization', choices=[], validators=[ wtforms.validators.DataRequired()]) submit = wtforms.SubmitField('Add Organization')
class SearchForm(wtforms.Form): location = wtforms.StringField( default='', validators=[no_wiki_or_html, geocodable_location]) keywords = wtforms.StringField(default='', validators=[no_wiki_or_html, valid_query]) distance = wtforms.IntegerField(default=50) distance_units = wtforms.SelectField(choices=[('miles', 'Miles'), ('km', 'KM')], default='km') locale = wtforms.StringField(default='') min_attendees = wtforms.IntegerField(default=0) time_period = wtforms.SelectField(choices=[(x, x) for x in TIME_LIST], default=TIME_ALL_FUTURE) deb = wtforms.StringField(default='') # For calendaring datetime-range queries: start = wtforms.DateField() end = wtforms.DateField() def distance_in_km(self): if self.distance_units.data == 'miles': distance_in_km = math.miles_in_km(self.distance.data) else: distance_in_km = self.distance.data return distance_in_km def url_params(self): d = {} if self.deb.data: d['deb'] = self.deb.data if self.keywords.data: d['keywords'] = self.keywords.data if self.min_attendees.data: d['min_attendees'] = self.min_attendees.data d['location'] = self.location.data or '' d['distance'] = self.distance.data d['distance_units'] = self.distance_units.data d['locale'] = self.locale.data return d def validate(self): rv = super(SearchForm, self).validate() if not rv: return False success = True if self.start.data and self.end.data: if self.start.data >= self.end.data: self.start.errors.append('start must be less than end') self.end.errors.append('start must be less than end') success = False return success def get_bounds(self): bounds = None if self.location.data: geocode = gmaps_api.get_geocode(address=self.location.data, language=self.locale.data) bounds = math.expand_bounds(geocode.latlng_bounds(), self.distance_in_km()) return bounds def build_query(self, start_end_query=False): bounds = self.get_bounds() keywords = _get_parsed_keywords(self.keywords.data) common_fields = dict(bounds=bounds, min_attendees=self.min_attendees.data, keywords=keywords) if start_end_query: query = SearchQuery(start_date=self.start.data, end_date=self.end.data, **common_fields) else: query = SearchQuery(time_period=self.time_period.data, **common_fields) return query
class AnalysisResultForm(flask_wtf.FlaskForm): analysis = wtforms.SelectField(u"Run") submit = wtforms.SubmitField("Show")
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." )
class AttackSelectForm(flask_wtf.FlaskForm): attack_name = wtforms.SelectField(u"Attack") submit = wtforms.SubmitField("Show")
class ImagesFiltersForm(BaseSecureForm): """Form class for filters on landing page""" owner_alias = wtforms.SelectField(label=_(u'Images owned by')) platform = wtforms.SelectMultipleField(label=_(u'Platform')) root_device_type = wtforms.SelectMultipleField( label=_(u'Root device type')) architecture = wtforms.SelectMultipleField(label=_(u'Architecture')) tags = TextEscapedField(label=_(u'Tags')) def __init__(self, request, cloud_type='euca', **kwargs): super(ImagesFiltersForm, self).__init__(request, **kwargs) self.request = request self.cloud_type = cloud_type self.owner_alias.choices = self.get_owner_choices() self.platform.choices = self.get_platform_choices() self.root_device_type.choices = self.get_root_device_type_choices() self.architecture.choices = self.get_architecture_choices() if cloud_type == 'aws' and not self.request.params.get('owner_alias'): self.owner_alias.data = 'amazon' # Default to Amazon AMIs on AWS self.facets = [ { 'name': 'owner_alias', 'label': self.owner_alias.label.text, 'options': self.get_owner_choices() }, { 'name': 'platform', 'label': self.platform.label.text, 'options': self.get_platform_choices() }, { 'name': 'architecture', 'label': self.architecture.label.text, 'options': self.get_architecture_choices() }, { 'name': 'root_device_type', 'label': self.root_device_type.label.text, 'options': self.get_root_device_type_choices() }, ] def get_owner_choices(self): owner_choices = EUCA_IMAGE_OWNER_ALIAS_CHOICES if self.cloud_type == 'aws': owner_choices = AWS_IMAGE_OWNER_ALIAS_CHOICES return owner_choices def get_platform_choices(self): if self.cloud_type == 'euca': return [ { 'key': 'linux', 'label': _(u'Linux') }, { 'key': 'windows', 'label': _(u'Windows') }, ] else: return [{'key': 'windows', 'label': _(u'Windows')}] @staticmethod def get_root_device_type_choices(): return [ { 'key': 'ebs', 'label': _(u'EBS') }, { 'key': 'instance-store', 'label': _(u'Instance-store') }, ] @staticmethod def get_architecture_choices(): return [ { 'key': 'x86_64', 'label': _(u'64-bit') }, { 'key': 'i386', 'label': _(u'32-bit') }, ]
class ELBHealthChecksForm(BaseSecureForm): """ELB Health Checks form""" ping_protocol_error_msg = _(u'Ping protocol is required') ping_protocol = wtforms.SelectField( label=_(u'Protocol'), validators=[validators.InputRequired(message=ping_protocol_error_msg)], ) ping_port_error_msg = _( u'Port range value must be whole numbers between 1-65535') ping_port = wtforms.IntegerField( label=_(u'Port'), validators=[ validators.InputRequired(message=ping_port_error_msg), validators.NumberRange(min=1, max=65535), ], ) ping_path_error_msg = _(u'Ping path is required and must start with a /') ping_path = TextEscapedField( id=u'ping-path', label=_(u'Path'), default="/", validators=[PingPathRequired(message=ping_path_error_msg)], ) response_timeout_error_msg = _(u'Response timeout is required') response_timeout = wtforms.IntegerField( label=_(u'Response timeout (secs)'), validators=[ validators.InputRequired(message=response_timeout_error_msg) ], ) time_between_pings_error_msg = _(u'Time between pings is required') time_between_pings = wtforms.SelectField( label=_(u'Time between pings'), validators=[ validators.InputRequired(message=time_between_pings_error_msg) ], ) failures_until_unhealthy_error_msg = _( u'Failures until unhealthy is required') failures_until_unhealthy = wtforms.SelectField( label=_(u'Failures until unhealthy'), validators=[ validators.InputRequired( message=failures_until_unhealthy_error_msg) ], ) passes_until_healthy_error_msg = _(u'Passes until healthy is required') passes_until_healthy = wtforms.SelectField( label=_(u'Passes until healthy'), validators=[ validators.InputRequired(message=passes_until_healthy_error_msg) ], ) def __init__(self, request, s3_conn=None, elb_conn=None, elb=None, **kwargs): super(ELBHealthChecksForm, self).__init__(request, **kwargs) self.s3_conn = s3_conn self.s3_choices_manager = ChoicesManager(conn=s3_conn) self.elb_conn = elb_conn self.elb = elb self.kwargs = kwargs self.set_health_check_initial_data() self.set_health_check_choices() self.set_health_check_error_messages() def set_health_check_initial_data(self): if self.elb is not None: # Set health check initial data hc_data = self.get_health_check_data() self.ping_protocol.data = hc_data.get('ping_protocol') self.ping_port.data = int(hc_data.get('ping_port', 80)) self.ping_path.data = hc_data.get('ping_path') self.time_between_pings.data = str(self.elb.health_check.interval) self.response_timeout.data = self.elb.health_check.timeout self.failures_until_unhealthy.data = str( self.elb.health_check.unhealthy_threshold) self.passes_until_healthy.data = str( self.elb.health_check.healthy_threshold) def set_health_check_error_messages(self): self.ping_path.error_msg = self.ping_path_error_msg def set_health_check_choices(self): self.ping_protocol.choices = self.get_ping_protocol_choices() self.time_between_pings.choices = self.get_time_between_pings_choices() self.failures_until_unhealthy.choices = self.get_failures_until_unhealthy_choices( ) self.passes_until_healthy.choices = self.get_passes_until_healthy_choices( ) def get_health_check_data(self): if self.elb is not None and self.elb.health_check.target is not None: match = re.search('^(\w+):(\d+)(.+)?', self.elb.health_check.target) return dict( ping_protocol=match.group(1), ping_port=match.group(2), ping_path=match.group(3), ) return {} @staticmethod def get_ping_protocol_choices(): return [('HTTP', 'HTTP'), ('HTTPS', 'HTTPS'), ('TCP', 'TCP'), ('SSL', 'SSL')] @staticmethod def get_time_between_pings_choices(): return [('30', _(u'30 seconds')), ('60', _(u'1 minute')), ('300', _(u'5 minutes'))] @staticmethod def get_failures_until_unhealthy_choices(): return [(str(x), str(x)) for x in range(2, 11)] @staticmethod def get_passes_until_healthy_choices(): return [(str(x), str(x)) for x in range(2, 11)]
class ClientAdd(FlaskForm): name = wtforms.StringField( _("Name"), validators=[wtforms.validators.DataRequired()], render_kw={"placeholder": "Client Name"}, ) contact = wtforms.EmailField( _("Contact"), validators=[wtforms.validators.Optional()], render_kw={"placeholder": "*****@*****.**"}, ) uri = wtforms.URLField( _("URI"), validators=[wtforms.validators.DataRequired()], render_kw={"placeholder": "https://mydomain.tld"}, ) redirect_uris = wtforms.URLField( _("Redirect URIs"), validators=[wtforms.validators.DataRequired()], render_kw={"placeholder": "https://mydomain.tld/callback"}, ) grant_type = wtforms.SelectMultipleField( _("Grant types"), validators=[wtforms.validators.DataRequired()], choices=[ ("password", "password"), ("authorization_code", "authorization_code"), ("implicit", "implicit"), ("hybrid", "hybrid"), ("refresh_token", "refresh_token"), ], default=["authorization_code", "refresh_token"], ) scope = wtforms.StringField( _("Scope"), validators=[wtforms.validators.Optional()], default="openid profile email", render_kw={"placeholder": "openid profile"}, ) response_type = wtforms.SelectMultipleField( _("Response types"), validators=[wtforms.validators.DataRequired()], choices=[("code", "code"), ("token", "token"), ("id_token", "id_token")], default=["code"], ) token_endpoint_auth_method = wtforms.SelectField( _("Token Endpoint Auth Method"), validators=[wtforms.validators.DataRequired()], choices=[ ("client_secret_basic", "client_secret_basic"), ("client_secret_post", "client_secret_post"), ("none", "none"), ], default="client_secret_basic", ) audience = wtforms.SelectMultipleField( _("Token audiences"), validators=[wtforms.validators.Optional()], choices=client_audiences, validate_choice=False, ) logo_uri = wtforms.URLField( _("Logo URI"), validators=[wtforms.validators.Optional()], render_kw={"placeholder": "https://mydomain.tld/logo.png"}, ) tos_uri = wtforms.URLField( _("Terms of service URI"), validators=[wtforms.validators.Optional()], render_kw={"placeholder": "https://mydomain.tld/tos.html"}, ) policy_uri = wtforms.URLField( _("Policy URI"), validators=[wtforms.validators.Optional()], render_kw={"placeholder": "https://mydomain.tld/policy.html"}, ) software_id = wtforms.StringField( _("Software ID"), validators=[wtforms.validators.Optional()], render_kw={"placeholder": "xyz"}, ) software_version = wtforms.StringField( _("Software Version"), validators=[wtforms.validators.Optional()], render_kw={"placeholder": "1.0"}, ) jwk = wtforms.StringField( _("JWK"), validators=[wtforms.validators.Optional()], render_kw={"placeholder": ""}, ) jwk_uri = wtforms.URLField( _("JKW URI"), validators=[wtforms.validators.Optional()], render_kw={"placeholder": ""}, ) preconsent = wtforms.BooleanField( _("Pre-consent"), validators=[wtforms.validators.Optional()], default=False, )
class CertificateForm(BaseSecureForm): """ELB Certificate form (used on wizard and detail page)""" certificate_name_error_msg = NAME_WITHOUT_SPACES_NOTICE certificate_name = wtforms.TextField( label=_(u'Certificate name'), validators=[ validators.InputRequired(message=certificate_name_error_msg) ], ) private_key_error_msg = _(u'Private key is required') private_key_help_text = _( u'Enter the contents of your private key file. Begins with Private-Key:' ) private_key = wtforms.TextAreaField( label=_(u'Private key'), validators=[validators.InputRequired(message=private_key_error_msg)], ) public_key_certificate_error_msg = _(u'Public key certificate is required') public_key_help_text = _( u'Enter the contents of your public key certificate file. Begins with -----BEGIN CERTIFICATE-----' ) public_key_certificate = wtforms.TextAreaField( label=_(u'Public key certificate'), validators=[ validators.InputRequired(message=public_key_certificate_error_msg) ], ) certificate_chain = wtforms.TextAreaField(label=_(u'Certificate chain'), ) certificates_error_msg = _(u'Certificate is required') certificate_arn = wtforms.SelectField( label=_(u'Certificate'), validators=[CertificateARNRequired(message=certificates_error_msg)], ) def __init__(self, request, conn=None, iam_conn=None, elb_conn=None, can_list_certificates=True, **kwargs): super(CertificateForm, self).__init__(request, **kwargs) self.conn = conn self.iam_conn = iam_conn self.elb_conn = elb_conn self.can_list_certificates = can_list_certificates self.set_error_messages() self.set_help_text() self.set_certificate_choices() def set_error_messages(self): self.certificate_name.error_msg = self.certificate_name_error_msg self.private_key.error_msg = self.private_key_error_msg self.public_key_certificate.error_msg = self.public_key_certificate_error_msg def set_help_text(self): self.private_key.help_text = self.private_key_help_text self.public_key_certificate.help_text = self.public_key_help_text def set_certificate_choices(self): if self.iam_conn and self.can_list_certificates: self.certificate_arn.choices = self.get_all_server_certs( iam_conn=self.iam_conn) if len(self.certificate_arn.choices) > 1: self.certificate_arn.data = self.certificate_arn.choices[0][0] else: self.certificate_arn.choices = [] def get_all_server_certs(self, iam_conn=None, add_blank=True): choices = [] if iam_conn is not None: certificates = self.iam_conn.get_all_server_certs() for cert in certificates.list_server_certificates_result.server_certificate_metadata_list: choices.append((cert.arn, cert.server_certificate_name)) if len(choices) == 0: choices.append(NO_CERTIFICATES_CHOICE) else: choices.insert(0, BLANK_CHOICE) return sorted(set(choices))
class MassEmailForm(MyBaseForm): recipient = wtforms.SelectField('Recipient', choices=[], coerce=str) subject = wtforms.StringField('Subject', [wtforms.validators.DataRequired()]) message = wtforms.TextAreaField( 'Message', [wtforms.validators.DataRequired()]) submit = wtforms.SubmitField('Send Email')
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.args[0]) 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?" ) traces_interval = utils.forms.IntegerField( 'Tracing Interval (in steps)', validators=[ validators.NumberRange(min=0) ], default=0, tooltip="Generation of a timeline trace every few steps" ) 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', 'SGD (Stochastic Gradient Descent)'), ('MOMENTUM', 'Momentum'), ('NESTEROV', "NAG (Nesterov's accelerated gradient)"), ('ADAGRAD', 'AdaGrad (Adaptive Gradient)'), ('ADAGRADDA', 'AdaGradDA (AdaGrad Dual Averaging)'), ('ADADELTA', 'AdaDelta'), ('ADAM', 'Adam (Adaptive Moment Estimation)'), ('RMSPROP', 'RMSprop'), ('FTRL', 'FTRL (Follow-The-Regularized-Leader)'), ], 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') # Additional settings specific to selected solver rms_decay = utils.forms.FloatField( 'RMS decay value', default=0.99, validators=[ validators.NumberRange(min=0), ], tooltip=("If the gradient updates results in oscillations the gradient is reduced " "by times 1-rms_decay. Otherwise it will be increased by rms_decay.") ) # 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'), ('pretrained', 'Pretrained 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, ], ) pretrained_networks = wtforms.RadioField( 'Pretrained Networks', choices=[], validators=[ validate_required_iff(method='pretrained'), 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): pass # if form.method.data == 'custom': # for filename in field.data.strip().split(os.path.pathsep): # if filename and not os.path.lexists(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." ) group_name = utils.forms.StringField('Group Name', tooltip="An optional group name for organization on the main page." ) # 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.' )
class UpdateIssueForm(PagureForm): """ Form to add a comment to an issue. """ tag = wtforms.StringField( "tag", [ wtforms.validators.Optional(), wtforms.validators.Regexp(TAGS_REGEX, flags=re.IGNORECASE), wtforms.validators.Length(max=255), ], ) depending = wtforms.StringField( "depending issue", [wtforms.validators.Optional()] ) blocking = wtforms.StringField( "blocking issue", [wtforms.validators.Optional()] ) comment = wtforms.TextAreaField("Comment", [wtforms.validators.Optional()]) assignee = wtforms.TextAreaField( "Assigned to", [wtforms.validators.Optional()] ) status = wtforms.SelectField( "Status", [wtforms.validators.Optional()], choices=[] ) priority = wtforms.SelectField( "Priority", [wtforms.validators.Optional()], choices=[] ) milestone = wtforms.SelectField( "Milestone", [wtforms.validators.Optional()], choices=[], coerce=convert_value, ) private = wtforms.BooleanField( "Private", [wtforms.validators.optional()], false_values=FALSE_VALUES ) close_status = wtforms.SelectField( "Closed as", [wtforms.validators.Optional()], choices=[], coerce=convert_value, ) def __init__(self, *args, **kwargs): """ Calls the default constructor with the normal argument but uses the list of collection provided to fill the choices of the drop-down list. """ super(UpdateIssueForm, self).__init__(*args, **kwargs) if "status" in kwargs: self.status.choices = [ (status, status) for status in kwargs["status"] ] self.priority.choices = [] if "priorities" in kwargs: for key in sorted(kwargs["priorities"]): self.priority.choices.append((key, kwargs["priorities"][key])) self.milestone.choices = [] if "milestones" in kwargs and kwargs["milestones"]: for key in kwargs["milestones"]: self.milestone.choices.append((key, key)) self.milestone.choices.insert(0, ("", "")) self.close_status.choices = [] if "close_status" in kwargs: for key in sorted(kwargs["close_status"]): self.close_status.choices.append((key, key)) self.close_status.choices.insert(0, ("", ""))