How to use the schema.Optional function in schema

To help you get started, we’ve selected a few schema examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github choderalab / yank / Yank / experiment.py View on Github external
if isinstance(yaml_content['experiments'], list):
                combinatorial_trees = [(exp_name, utils.CombinatorialTree(yaml_content[exp_name]))
                                       for exp_name in yaml_content['experiments']]
            else:
                combinatorial_trees = [('experiments', utils.CombinatorialTree(yaml_content['experiments']))]
            self._experiments = collections.OrderedDict(combinatorial_trees)
        except KeyError:
            self._experiments = collections.OrderedDict()
            return

        # Restraint schema contains type and optional parameters.
        restraint_schema = {'type': Or(str, None), Optional(str): object}

        # Define experiment Schema
        experiment_schema = Schema({'system': is_known_system, 'protocol': is_known_protocol,
                                    Optional('options'): Use(validate_experiment_options),
                                    Optional('restraint'): restraint_schema})

        # Schema validation
        for experiment_path, experiment_descr in self._expand_experiments():
            try:
                experiment_schema.validate(experiment_descr)
            except SchemaError as e:
                raise YamlParseError('Experiment {}: {}'.format(experiment_path, e.autos[-1]))
github carsdotcom / skelebot / skelebot / components / registry.py View on Github external
from ..systems.execution import docker

class Registry(Component):
    """
    Registry Class

    Provides the ability to define the registry that will be used when publishing the Docker image
    for the project, and provides the capability to publish by logging into the registry through
    the CLI.
    """

    activation = Activation.PROJECT
    commands = ["publish"]

    schema = Schema({
        Optional('host'): And(str, error='Registry \'host\' must be a String'),
        Optional('port'): And(int, error='Registry \'port\' must be an Integer'),
        Optional('user'): And(str, error='Registry \'user\' must be a String'),
    }, ignore_extra_keys=True)

    host = None
    port = None
    user = None

    def __init__(self, host=None, port=None, user=None):
        """Instantiate the Registry Class Object based on the provided parameters"""
        self.host = host
        self.port = port
        self.user = user

    def addParsers(self, subparsers):
        """
github amplify-education / amplium / amplium / config.py View on Github external
lambda n: 1 <= n <= 65535,
                error="Port must be an integer between 1 and 65535"
            ),
            "selenium_grid_zookeeper_path": Use(str),
        },
        Optional("consul"): {
            "host": Use(str),
            "port": And(
                Use(int),
                lambda n: 1 <= n <= 65535,
                error="Port must be an integer between 1 and 65535"
            ),
            "selenium_grid_service_name": Use(str),
        },
        "logging": {
            Optional("version", default=1): Use(int),
            Optional("disable_existing_loggers", default=True): bool,
            Optional("loggers"): {
                str: {
                    Optional("level"): Use(str),
                    Optional("handlers"): [Use(str)],
                    Optional("filters"): [Use(str)],
                    Optional("propagate"): Use(bool)
                }
            },
            Optional("handlers"): {
                str: {
                    "class": Use(str),
                    Optional("level"): Use(str),
                    Optional("formatter"): Use(str),
                    Optional("filters"): [Use(str)],
                    Optional(Use(str)): object
github sustrik / libdill / doc / generate.py View on Github external
Optional("boilerplate", default=True): bool,
}

tschema = {
    # short name of the protocol; typically the function prefix
    "name": str,
    # title of the topic as it appears in the ToC
    "title": str,
    # topic with smaller order numbers will appear first in the ToC
    Optional("order", default=None): int,
    # if the topic is about a protocol, the type of the protocol
    Optional("protocol", default=None): Or("bytestream", "message", "application"),
    # this string will be added to the man page of each function in the topic
    Optional("info", default=None): str,
    # this example will be used for the functions that don't have example of their own
    Optional("example", default=None): str,
    # all functions in the topic
    "functions": {str: fschema},
    # constand values (will be rendered as #defines)
    Optional("consts", default={}): {str: str},
    # option types associated with this topic
    Optional("opts", default={}): {str: [{
        # name of the option
        "name": str,
        # type of the option
        "type": str,
        # set to true for dill-specific types
        Optional("dill", default=False): bool,
        # type suffix
        Optional("suffix", default=""): str,
        # default value of the option
        "default": str,
github AfricasTalkingLtd / africastalking-python / africastalking / Payment.py View on Github external
def bank_transfer(self, product_name, recipients, callback=None):

        bank_account_schema = Schema({
            'accountNumber': And(str, len),
            'bankCode': And(int, lambda i: i in PaymentService.BANK.values()),
            Optional('accountName'): And(str, len),
        })
        schema = Schema([{
            'bankAccount': And(dict, lambda s: bank_account_schema.validate(s)),
            'currencyCode': And(str, lambda s: len(s) == 3),
            'amount': And(lambda f: float(f) > 0),
            'narration': And(str, len),
            Optional('metadata'): And(dict)
        }])
        recipients = schema.validate(recipients)
        url = self._make_url('/bank/transfer')
        headers = dict(self._headers)
        headers['Content-Type'] = 'application/json'
        data = {
            'username': self._username,
            'productName': product_name,
            'recipients': recipients,
github carsdotcom / skelebot / skelebot / objects / config.py View on Github external
"""

    schema = Schema({
        'name': And(str, error='\'name\' must be a String'),
        Optional('env'): And(str, error='\'env\' must be a String'),
        Optional('description'): And(str, error='\'description\' must be a String'),
        Optional('maintainer'): And(str, error='\'maintainer\' must be a String'),
        Optional('contact'): And(str, error='\'contact\' must be a String'),
        'language': And(str, error='\'language\' must be a String'),
        Optional('baseImage'): And(str, error='\'baseImage\' must be a String'),
        Optional('primaryJob'): And(str, error='\'primaryJob\' must be a String'),
        Optional('primaryExe'): And(str, Use(str.upper), lambda s: s in ('CMD', 'ENTRYPOINT'), error='\'primaryExe\' must be CMD or ENTRYPOINT'),
        Optional('ephemeral'): And(bool, error='\'ephemeral\' must be a Boolean'),
        Optional('dependencies'): Or(dict, list, error='\'dependencies\' must be a Dict or List'),
        Optional('ignores'): And(list, error='\'ignores\' must be a List'),
        Optional('jobs'): And(list, error='\'jobs\' must be a List'),
        Optional('ports'): And(list, error='\'ports\' must be a List'),
        Optional('components'): And(dict, error='\'components\' must be a Dictionary'),
        Optional('params'): And(list, error='\'params\' must be a List'),
        Optional('commands'): And(list, error='\'commands\' must be a List')
    }, ignore_extra_keys=True)

    name = None
    env = None
    description = None
    version = None
    maintainer = None
    contact = None
    language = None
    baseImage = None
    primaryJob = None
    primaryExe = None
github dimagi / commcare-hq / corehq / motech / dhis2 / entities_helpers.py View on Github external
Returns the schema of a tracked entity instance.
    """
    event_schema = get_event_schema()
    return {
        SchemaOptional("trackedEntityInstance"): DHIS2_ID_SCHEMA,
        "trackedEntityType": DHIS2_ID_SCHEMA,
        "orgUnit": DHIS2_ID_SCHEMA,
        SchemaOptional("geometry"): {
            "type": str,
            "coordinates": [float],
        },
        SchemaOptional("attributes"): [{
            "attribute": DHIS2_ID_SCHEMA,
            "value": object,
        }],
        SchemaOptional("enrollments"): [{
            "program": DHIS2_ID_SCHEMA,
            SchemaOptional("orgUnit"): DHIS2_ID_SCHEMA,
            SchemaOptional("enrollmentDate"): DHIS2_DATE_SCHEMA,
            SchemaOptional("incidentDate"): DHIS2_DATE_SCHEMA,
            SchemaOptional("events"): [event_schema],
        }],
github microsoft / nni / tools / nni_cmd / config_schema.py View on Github external
def setNumberRange(key, keyType, start, end):
    '''check number range'''
    return And(
        And(keyType, error=SCHEMA_TYPE_ERROR % (key, keyType.__name__)),
        And(lambda n: start <= n <= end, error=SCHEMA_RANGE_ERROR % (key, '(%s,%s)' % (start, end))),
    )

def setPathCheck(key):
    '''check if path exist'''
    return And(os.path.exists, error=SCHEMA_PATH_ERROR % key)

common_schema = {
    'authorName': setType('authorName', str),
    'experimentName': setType('experimentName', str),
    Optional('description'): setType('description', str),
    'trialConcurrency': setNumberRange('trialConcurrency', int, 1, 99999),
    Optional('maxExecDuration'): And(Regex(r'^[1-9][0-9]*[s|m|h|d]$', error='ERROR: maxExecDuration format is [digit]{s,m,h,d}')),
    Optional('maxTrialNum'): setNumberRange('maxTrialNum', int, 1, 99999),
    'trainingServicePlatform': setChoice('trainingServicePlatform', 'remote', 'local', 'pai', 'kubeflow', 'frameworkcontroller', 'paiYarn'),
    Optional('searchSpacePath'): And(os.path.exists, error=SCHEMA_PATH_ERROR % 'searchSpacePath'),
    Optional('multiPhase'): setType('multiPhase', bool),
    Optional('multiThread'): setType('multiThread', bool),
    Optional('nniManagerIp'): setType('nniManagerIp', str),
    Optional('logDir'): And(os.path.isdir, error=SCHEMA_PATH_ERROR % 'logDir'),
    Optional('debug'): setType('debug', bool),
    Optional('versionCheck'): setType('versionCheck', bool),
    Optional('logLevel'): setChoice('logLevel', 'trace', 'debug', 'info', 'warning', 'error', 'fatal'),
    Optional('logCollection'): setChoice('logCollection', 'http', 'none'),
    'useAnnotation': setType('useAnnotation', bool),
    Optional('tuner'): dict,
    Optional('advisor'): dict,
github AlexandreDecan / sismic / sismic / io / yaml.py View on Github external
from .datadict import export_to_dict, import_from_dict

__all__ = ['import_from_yaml', 'export_to_yaml']


class SCHEMA:
    contract = {schema.Or('before', 'after', 'always'): schema.Use(str)}

    transition = {
        schema.Optional('target'): schema.Use(str),
        schema.Optional('event'): schema.Use(str),
        schema.Optional('guard'): schema.Use(str),
        schema.Optional('action'): schema.Use(str),
        schema.Optional('contract'): [contract],
        schema.Optional('priority'): schema.Or(schema.Use(int), 'high', 'low'),
    }

    state = dict()  # type: ignore
    state.update({
        'name': schema.Use(str),
        schema.Optional('type'): schema.Or('final', 'shallow history', 'deep history'),
        schema.Optional('on entry'): schema.Use(str),
        schema.Optional('on exit'): schema.Use(str),
        schema.Optional('transitions'): [transition],
        schema.Optional('contract'): [contract],
        schema.Optional('initial'): schema.Use(str),
        schema.Optional('parallel states'): [state],
        schema.Optional('states'): [state],
        schema.Optional('memory'): schema.Use(str),
    })
github dimagi / commcare-hq / corehq / motech / dhis2 / entities_helpers.py View on Github external
def get_tracked_entity_schema() -> dict:
    """
    Returns the schema of a tracked entity instance.
    """
    event_schema = get_event_schema()
    return {
        SchemaOptional("trackedEntityInstance"): DHIS2_ID_SCHEMA,
        "trackedEntityType": DHIS2_ID_SCHEMA,
        "orgUnit": DHIS2_ID_SCHEMA,
        SchemaOptional("geometry"): {
            "type": str,
            "coordinates": [float],
        },
        SchemaOptional("attributes"): [{
            "attribute": DHIS2_ID_SCHEMA,
            "value": object,
        }],
        SchemaOptional("enrollments"): [{
            "program": DHIS2_ID_SCHEMA,
            SchemaOptional("orgUnit"): DHIS2_ID_SCHEMA,
            SchemaOptional("enrollmentDate"): DHIS2_DATE_SCHEMA,
            SchemaOptional("incidentDate"): DHIS2_DATE_SCHEMA,
            SchemaOptional("events"): [event_schema],
        }],