Python distutils.util.strtobool() Examples

The following are 30 code examples of distutils.util.strtobool(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module distutils.util , or try the search function .
Example #1
Source File: util.py    From cf-mendix-buildpack with Apache License 2.0 7 votes vote down vote up
def bypass_loggregator():
    env_var = os.getenv("BYPASS_LOGGREGATOR", "False")
    # Throws a useful message if you put in a nonsensical value.
    # Necessary since we store these in cloud portal as strings.
    try:
        bypass = strtobool(env_var)
    except ValueError as _:
        logging.warning(
            "Bypass loggregator has a nonsensical value: %s. "
            "Falling back to old loggregator-based metric reporting.",
            env_var,
        )
        return False

    if bypass:
        if os.getenv("TRENDS_STORAGE_URL"):
            return True
        else:
            logging.warning(
                "BYPASS_LOGGREGATOR is set to true, but no metrics URL is "
                "set. Falling back to old loggregator-based metric reporting."
            )
            return False
    return False 
Example #2
Source File: optionparser.py    From securityheaders with Apache License 2.0 6 votes vote down vote up
def __add_checks__(self, appconfig, result):
        checks = []
        unwanted = []
        for checker in appconfig.sections():
            if "checker" in checker.lower() or "collector" in checker.lower():
                try: 
                    enabled=not strtobool(appconfig.get(checker, 'disabled'))
                except NoOptionError:
                    enabled=True
                try: 
                    enabled=strtobool(appconfig.get(checker, 'enabled'))
                except NoOptionError:
                    enabled=True
                if enabled:
                    checks.append(checker)
                else:
                    unwanted.append(checker)
        result['checks'] = checks
        result['unwanted'] = unwanted 
Example #3
Source File: diskover.py    From diskover with Apache License 2.0 6 votes vote down vote up
def user_prompt(question):
    """ Prompt the yes/no-*question* to the user. """
    from distutils.util import strtobool

    while True:
        try:
            if IS_PY3:
                user_input = input(question + " [y/n]: ").lower()
            else:
                user_input = raw_input(question + " [y/n]: ").lower()
            result = strtobool(user_input)
            return result
        except ValueError:
            print("Please use y/n or yes/no.\n")
        except KeyboardInterrupt:
            print("Ctrl-c keyboard interrupt, shutting down...")
            sys.exit(0) 
Example #4
Source File: neural_networks.py    From pase with MIT License 6 votes vote down vote up
def __init__(self, options,inp_dim):
        super(RNN_cudnn, self).__init__()
        
        self.input_dim=inp_dim
        self.hidden_size=int(options['hidden_size'])
        self.num_layers=int(options['num_layers'])
        self.nonlinearity=options['nonlinearity']
        self.bias=bool(strtobool(options['bias']))
        self.batch_first=bool(strtobool(options['batch_first']))
        self.dropout=float(options['dropout'])
        self.bidirectional=bool(strtobool(options['bidirectional']))
        
        self.rnn = nn.ModuleList([nn.RNN(self.input_dim, self.hidden_size, self.num_layers, 
                            nonlinearity=self.nonlinearity,bias=self.bias,dropout=self.dropout,bidirectional=self.bidirectional)])
         
        self.out_dim=self.hidden_size+self.bidirectional*self.hidden_size 
Example #5
Source File: neural_networks.py    From pase with MIT License 6 votes vote down vote up
def __init__(self, options,inp_dim):
        super(RNN_cudnn, self).__init__()
        
        self.input_dim=inp_dim
        self.hidden_size=int(options['hidden_size'])
        self.num_layers=int(options['num_layers'])
        self.nonlinearity=options['nonlinearity']
        self.bias=bool(strtobool(options['bias']))
        self.batch_first=bool(strtobool(options['batch_first']))
        self.dropout=float(options['dropout'])
        self.bidirectional=bool(strtobool(options['bidirectional']))
        
        self.rnn = nn.ModuleList([nn.RNN(self.input_dim, self.hidden_size, self.num_layers, 
                            nonlinearity=self.nonlinearity,bias=self.bias,dropout=self.dropout,bidirectional=self.bidirectional)])
         
        self.out_dim=self.hidden_size+self.bidirectional*self.hidden_size 
Example #6
Source File: shell.py    From poetry with MIT License 6 votes vote down vote up
def handle(self):
        from poetry.utils.shell import Shell

        # Check if it's already activated or doesn't exist and won't be created
        venv_activated = strtobool(environ.get("POETRY_ACTIVE", "0")) or getattr(
            sys, "real_prefix", sys.prefix
        ) == str(self.env.path)
        if venv_activated:
            self.line(
                "Virtual environment already activated: "
                "<info>{}</>".format(self.env.path)
            )

            return

        self.line("Spawning shell within <info>{}</>".format(self.env.path))

        # Setting this to avoid spawning unnecessary nested shells
        environ["POETRY_ACTIVE"] = "1"
        shell = Shell.get()
        shell.activate(self.env)
        environ.pop("POETRY_ACTIVE") 
Example #7
Source File: neural_networks.py    From pase with MIT License 6 votes vote down vote up
def __init__(self, options,inp_dim):
        super(RNN_cudnn, self).__init__()
        
        self.input_dim=inp_dim
        self.hidden_size=int(options['hidden_size'])
        self.num_layers=int(options['num_layers'])
        self.nonlinearity=options['nonlinearity']
        self.bias=bool(strtobool(options['bias']))
        self.batch_first=bool(strtobool(options['batch_first']))
        self.dropout=float(options['dropout'])
        self.bidirectional=bool(strtobool(options['bidirectional']))
        
        self.rnn = nn.ModuleList([nn.RNN(self.input_dim, self.hidden_size, self.num_layers, 
                            nonlinearity=self.nonlinearity,bias=self.bias,dropout=self.dropout,bidirectional=self.bidirectional)])
         
        self.out_dim=self.hidden_size+self.bidirectional*self.hidden_size 
Example #8
Source File: search.py    From invenio-app-ils with MIT License 6 votes vote down vote up
def search_factory_literature(self, search):
    """Search factory for literature (series and documents)."""
    def filter_periodical_issues(search, query_string=None):
        """Filter periodical issues unless include_all is specified."""
        from distutils.util import strtobool
        from flask import request

        include_all = request.values.get("include_all", "no")
        if include_all == "":
            include_all = "yes"

        if not strtobool(include_all):
            issue_query_string = "NOT document_type:PERIODICAL_ISSUE"
            if query_string:
                query_string = "{} AND {}".format(
                    query_string,
                    issue_query_string
                )
            else:
                query_string = issue_query_string
        return search, query_string

    return _ils_search_factory(self, search, filter_periodical_issues) 
Example #9
Source File: oo_filters.py    From origin-ci-tool with Apache License 2.0 5 votes vote down vote up
def oo_openshift_loadbalancer_backends(api_port, servers_hostvars, use_nuage=False, nuage_rest_port=None):
        loadbalancer_backends = [{'name': 'atomic-openshift-api',
                                  'mode': 'tcp',
                                  'option': 'tcplog',
                                  'balance': 'source',
                                  'servers': FilterModule.oo_haproxy_backend_masters(servers_hostvars, api_port)}]
        if bool(strtobool(str(use_nuage))) and nuage_rest_port is not None:
            loadbalancer_backends.append({'name': 'nuage-monitor',
                                          'mode': 'tcp',
                                          'option': 'tcplog',
                                          'balance': 'source',
                                          'servers': FilterModule.oo_haproxy_backend_masters(servers_hostvars, nuage_rest_port)})
        return loadbalancer_backends 
Example #10
Source File: oo_filters.py    From origin-ci-tool with Apache License 2.0 5 votes vote down vote up
def oo_openshift_loadbalancer_backends(api_port, servers_hostvars, use_nuage=False, nuage_rest_port=None):
        loadbalancer_backends = [{'name': 'atomic-openshift-api',
                                  'mode': 'tcp',
                                  'option': 'tcplog',
                                  'balance': 'source',
                                  'servers': FilterModule.oo_haproxy_backend_masters(servers_hostvars, api_port)}]
        if bool(strtobool(str(use_nuage))) and nuage_rest_port is not None:
            loadbalancer_backends.append({'name': 'nuage-monitor',
                                          'mode': 'tcp',
                                          'option': 'tcplog',
                                          'balance': 'source',
                                          'servers': FilterModule.oo_haproxy_backend_masters(servers_hostvars, nuage_rest_port)})
        return loadbalancer_backends 
Example #11
Source File: oo_filters.py    From origin-ci-tool with Apache License 2.0 5 votes vote down vote up
def oo_openshift_loadbalancer_frontends(api_port, servers_hostvars, use_nuage=False, nuage_rest_port=None):
        loadbalancer_frontends = [{'name': 'atomic-openshift-api',
                                   'mode': 'tcp',
                                   'options': ['tcplog'],
                                   'binds': ["*:{0}".format(api_port)],
                                   'default_backend': 'atomic-openshift-api'}]
        if bool(strtobool(str(use_nuage))) and nuage_rest_port is not None:
            loadbalancer_frontends.append({'name': 'nuage-monitor',
                                           'mode': 'tcp',
                                           'options': ['tcplog'],
                                           'binds': ["*:{0}".format(nuage_rest_port)],
                                           'default_backend': 'nuage-monitor'})
        return loadbalancer_frontends 
Example #12
Source File: baseparser.py    From FuYiSpider with Apache License 2.0 5 votes vote down vote up
def _update_defaults(self, defaults):
        """Updates the given defaults with values from the config files and
        the environ. Does a little special handling for certain types of
        options (lists)."""

        # Accumulate complex default state.
        self.values = optparse.Values(self.defaults)
        late_eval = set()
        # Then set the options with those values
        for key, val in self._get_ordered_configuration_items():
            # '--' because configuration supports only long names
            option = self.get_option('--' + key)

            # Ignore options not present in this parser. E.g. non-globals put
            # in [global] by users that want them to apply to all applicable
            # commands.
            if option is None:
                continue

            if option.action in ('store_true', 'store_false', 'count'):
                val = strtobool(val)
            elif option.action == 'append':
                val = val.split()
                val = [self.check_default(option, key, v) for v in val]
            elif option.action == 'callback':
                late_eval.add(option.dest)
                opt_str = option.get_opt_string()
                val = option.convert_value(opt_str, val)
                # From take_action
                args = option.callback_args or ()
                kwargs = option.callback_kwargs or {}
                option.callback(option, opt_str, val, self, *args, **kwargs)
            else:
                val = self.check_default(option, key, val)

            defaults[option.dest] = val

        for key in late_eval:
            defaults[key] = getattr(self.values, key)
        self.values = None
        return defaults 
Example #13
Source File: openshift_facts.py    From origin-ci-tool with Apache License 2.0 5 votes vote down vote up
def safe_get_bool(fact):
    """ Get a boolean fact safely.

        Args:
            facts: fact to convert
        Returns:
            bool: given fact as a bool
    """
    return bool(strtobool(str(fact))) 
Example #14
Source File: oo_filters.py    From origin-ci-tool with Apache License 2.0 5 votes vote down vote up
def oo_openshift_loadbalancer_frontends(api_port, servers_hostvars, use_nuage=False, nuage_rest_port=None):
        loadbalancer_frontends = [{'name': 'atomic-openshift-api',
                                   'mode': 'tcp',
                                   'options': ['tcplog'],
                                   'binds': ["*:{0}".format(api_port)],
                                   'default_backend': 'atomic-openshift-api'}]
        if bool(strtobool(str(use_nuage))) and nuage_rest_port is not None:
            loadbalancer_frontends.append({'name': 'nuage-monitor',
                                           'mode': 'tcp',
                                           'options': ['tcplog'],
                                           'binds': ["*:{0}".format(nuage_rest_port)],
                                           'default_backend': 'nuage-monitor'})
        return loadbalancer_frontends 
Example #15
Source File: oo_filters.py    From origin-ci-tool with Apache License 2.0 5 votes vote down vote up
def oo_openshift_loadbalancer_backends(api_port, servers_hostvars, use_nuage=False, nuage_rest_port=None):
        loadbalancer_backends = [{'name': 'atomic-openshift-api',
                                  'mode': 'tcp',
                                  'option': 'tcplog',
                                  'balance': 'source',
                                  'servers': FilterModule.oo_haproxy_backend_masters(servers_hostvars, api_port)}]
        if bool(strtobool(str(use_nuage))) and nuage_rest_port is not None:
            loadbalancer_backends.append({'name': 'nuage-monitor',
                                          'mode': 'tcp',
                                          'option': 'tcplog',
                                          'balance': 'source',
                                          'servers': FilterModule.oo_haproxy_backend_masters(servers_hostvars, nuage_rest_port)})
        return loadbalancer_backends 
Example #16
Source File: openshift_facts.py    From origin-ci-tool with Apache License 2.0 5 votes vote down vote up
def safe_get_bool(fact):
    """ Get a boolean fact safely.

        Args:
            facts: fact to convert
        Returns:
            bool: given fact as a bool
    """
    return bool(strtobool(str(fact))) 
Example #17
Source File: oo_filters.py    From origin-ci-tool with Apache License 2.0 5 votes vote down vote up
def oo_openshift_loadbalancer_backends(api_port, servers_hostvars, use_nuage=False, nuage_rest_port=None):
        loadbalancer_backends = [{'name': 'atomic-openshift-api',
                                  'mode': 'tcp',
                                  'option': 'tcplog',
                                  'balance': 'source',
                                  'servers': FilterModule.oo_haproxy_backend_masters(servers_hostvars, api_port)}]
        if bool(strtobool(str(use_nuage))) and nuage_rest_port is not None:
            loadbalancer_backends.append({'name': 'nuage-monitor',
                                          'mode': 'tcp',
                                          'option': 'tcplog',
                                          'balance': 'source',
                                          'servers': FilterModule.oo_haproxy_backend_masters(servers_hostvars, nuage_rest_port)})
        return loadbalancer_backends 
Example #18
Source File: openshift_facts.py    From origin-ci-tool with Apache License 2.0 5 votes vote down vote up
def safe_get_bool(fact):
    """ Get a boolean fact safely.

        Args:
            facts: fact to convert
        Returns:
            bool: given fact as a bool
    """
    return bool(strtobool(str(fact))) 
Example #19
Source File: oo_filters.py    From origin-ci-tool with Apache License 2.0 5 votes vote down vote up
def oo_openshift_loadbalancer_frontends(api_port, servers_hostvars, use_nuage=False, nuage_rest_port=None):
        loadbalancer_frontends = [{'name': 'atomic-openshift-api',
                                   'mode': 'tcp',
                                   'options': ['tcplog'],
                                   'binds': ["*:{0}".format(api_port)],
                                   'default_backend': 'atomic-openshift-api'}]
        if bool(strtobool(str(use_nuage))) and nuage_rest_port is not None:
            loadbalancer_frontends.append({'name': 'nuage-monitor',
                                           'mode': 'tcp',
                                           'options': ['tcplog'],
                                           'binds': ["*:{0}".format(nuage_rest_port)],
                                           'default_backend': 'nuage-monitor'})
        return loadbalancer_frontends 
Example #20
Source File: oo_filters.py    From origin-ci-tool with Apache License 2.0 5 votes vote down vote up
def oo_openshift_loadbalancer_backends(api_port, servers_hostvars, use_nuage=False, nuage_rest_port=None):
        loadbalancer_backends = [{'name': 'atomic-openshift-api',
                                  'mode': 'tcp',
                                  'option': 'tcplog',
                                  'balance': 'source',
                                  'servers': FilterModule.oo_haproxy_backend_masters(servers_hostvars, api_port)}]
        if bool(strtobool(str(use_nuage))) and nuage_rest_port is not None:
            loadbalancer_backends.append({'name': 'nuage-monitor',
                                          'mode': 'tcp',
                                          'option': 'tcplog',
                                          'balance': 'source',
                                          'servers': FilterModule.oo_haproxy_backend_masters(servers_hostvars, nuage_rest_port)})
        return loadbalancer_backends 
Example #21
Source File: neural_networks.py    From pase with MIT License 5 votes vote down vote up
def __init__(self, options,inp_dim):
        super(GRU_cudnn, self).__init__()
        
        self.input_dim=inp_dim
        self.hidden_size=int(options['hidden_size'])
        self.num_layers=int(options['num_layers'])
        self.bias=bool(strtobool(options['bias']))
        self.batch_first=bool(strtobool(options['batch_first']))
        self.dropout=float(options['dropout'])
        self.bidirectional=bool(strtobool(options['bidirectional']))
        
        self.gru = nn.ModuleList([nn.GRU(self.input_dim, self.hidden_size, self.num_layers, 
                            bias=self.bias,dropout=self.dropout,bidirectional=self.bidirectional)])
         
        self.out_dim=self.hidden_size+self.bidirectional*self.hidden_size 
Example #22
Source File: baseparser.py    From Python24 with MIT License 5 votes vote down vote up
def _update_defaults(self, defaults):
        """Updates the given defaults with values from the config files and
        the environ. Does a little special handling for certain types of
        options (lists)."""

        # Accumulate complex default state.
        self.values = optparse.Values(self.defaults)
        late_eval = set()
        # Then set the options with those values
        for key, val in self._get_ordered_configuration_items():
            # '--' because configuration supports only long names
            option = self.get_option('--' + key)

            # Ignore options not present in this parser. E.g. non-globals put
            # in [global] by users that want them to apply to all applicable
            # commands.
            if option is None:
                continue

            if option.action in ('store_true', 'store_false', 'count'):
                val = strtobool(val)
            elif option.action == 'append':
                val = val.split()
                val = [self.check_default(option, key, v) for v in val]
            elif option.action == 'callback':
                late_eval.add(option.dest)
                opt_str = option.get_opt_string()
                val = option.convert_value(opt_str, val)
                # From take_action
                args = option.callback_args or ()
                kwargs = option.callback_kwargs or {}
                option.callback(option, opt_str, val, self, *args, **kwargs)
            else:
                val = self.check_default(option, key, val)

            defaults[option.dest] = val

        for key in late_eval:
            defaults[key] = getattr(self.values, key)
        self.values = None
        return defaults 
Example #23
Source File: run.py    From branch-protection-bot with MIT License 5 votes vote down vote up
def toggle_enforce_admin(options):
    access_token, owner, repo_name, branch_name, retries, github_repository = options.access_token, options.owner, options.repo, options.branch, int(options.retries), options.github_repository
    if not owner and not repo_name and github_repository and "/" in github_repository:
        owner = github_repository.split("/")[0]
        repo_name = github_repository.split("/")[1]

    if owner == '' or repo_name == '':
        print('Owner and repo or GITHUB_REPOSITORY not set')
        raise RuntimeError
    enforce_admins = bool(strtobool(options.enforce_admins)) if options.enforce_admins is not None and not options.enforce_admins == '' else None
    # or using an access token
    print(f"Getting branch protection settings for {owner}/{repo_name}")
    protection = get_protection(access_token, branch_name, owner, repo_name)
    print(f"Enforce admins branch protection enabled? {protection.enforce_admins.enabled}")
    print(f"Setting enforce admins branch protection to {enforce_admins if enforce_admins is not None else not protection.enforce_admins.enabled}")
    for i in range(retries):
        try:
            if enforce_admins is False:
                disable(protection)
                return
            elif enforce_admins is True:
                enable(protection)
                return
            elif protection.enforce_admins.enabled:
                disable(protection)
                return
            elif not protection.enforce_admins.enabled:
                enable(protection)
                return
        except GitHubException:
            print(f"Failed to set enforce admins to {not protection.enforce_admins.enabled}. Retrying...")
            sleep(i ** 2)  # Exponential back-off

    print(f"Failed to set enforce admins to {not protection.enforce_admins.enabled}.")
    exit(1) 
Example #24
Source File: openscenario_parser.py    From scenario_runner with MIT License 5 votes vote down vote up
def get_controller(xml_tree, catalogs):
        """
        Extract the object controller from the OSC XML or a catalog

        Args:
            xml_tree: Containing the controller information,
                or the reference to the catalog it is defined in.
            catalogs: XML Catalogs that could contain the controller definition

        returns:
           module: Python module containing the controller implementation
           args: Dictonary with (key, value) parameters for the controller
        """

        assign_action = xml_tree.find('AssignControllerAction')
        module = None
        args = {}
        for prop in assign_action.find('Controller').find('Properties'):
            if prop.attrib.get('name') == "module":
                module = prop.attrib.get('value')
            else:
                args[prop.attrib.get('name')] = prop.attrib.get('value')

        override_action = xml_tree.find('OverrideControllerValueAction')
        for child in override_action:
            if strtobool(child.attrib.get('active')):
                raise NotImplementedError("Controller override actions are not yet supported")

        return module, args 
Example #25
Source File: neural_networks.py    From pase with MIT License 5 votes vote down vote up
def __init__(self, options, inp_dim):
        super(SRU, self).__init__()
        self.input_dim = inp_dim
        self.hidden_size = int(options['sru_hidden_size'])
        self.num_layers = int(options['sru_num_layers'])
        self.dropout = float(options['sru_dropout'])
        self.rnn_dropout = float(options['sru_rnn_dropout'])
        self.use_tanh = bool(strtobool(options['sru_use_tanh']))
        self.use_relu = bool(strtobool(options['sru_use_relu']))
        self.use_selu = bool(strtobool(options['sru_use_selu']))
        self.weight_norm = bool(strtobool(options['sru_weight_norm']))
        self.layer_norm = bool(strtobool(options['sru_layer_norm']))
        self.bidirectional = bool(strtobool(options['sru_bidirectional']))
        self.is_input_normalized = bool(strtobool(options['sru_is_input_normalized']))
        self.has_skip_term = bool(strtobool(options['sru_has_skip_term']))
        self.rescale = bool(strtobool(options['sru_rescale']))
        self.highway_bias = float(options['sru_highway_bias'])
        self.n_proj = int(options['sru_n_proj'])
        self.sru = sru.SRU(self.input_dim, self.hidden_size,
                            num_layers=self.num_layers,
                            dropout=self.dropout,
                            rnn_dropout=self.rnn_dropout,
                            bidirectional=self.bidirectional,
                            n_proj=self.n_proj,
                            use_tanh=self.use_tanh,
                            use_selu=self.use_selu,
                            use_relu=self.use_relu,
                            weight_norm=self.weight_norm,
                            layer_norm=self.layer_norm,
                            has_skip_term=self.has_skip_term,
                            is_input_normalized=self.is_input_normalized,
                            highway_bias=self.highway_bias,
                            rescale=self.rescale)
        self.out_dim = self.hidden_size+self.bidirectional*self.hidden_size 
Example #26
Source File: config.py    From eks-rolling-update with Apache License 2.0 5 votes vote down vote up
def str_to_bool(val):
    return val if type(val) is bool else bool(strtobool(val)) 
Example #27
Source File: __init__.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def str2bool(s):
    if is_string(s):
        return strtobool(s)
    return bool(s) 
Example #28
Source File: util.py    From ai-platform with MIT License 5 votes vote down vote up
def ask_yes_no(question: str) -> bool:
    """Ask the user the question until the user inputs a valid answer."""
    while True:
        try:
            print("{0} [y/n]".format(question))
            return strtobool(input().lower())
        except ValueError:
            pass 
Example #29
Source File: __init__.py    From lambda-packs with MIT License 5 votes vote down vote up
def str2bool(s):
    if is_string(s):
        return strtobool(s)
    return bool(s) 
Example #30
Source File: __init__.py    From lambda-packs with MIT License 5 votes vote down vote up
def str2bool(s):
    if is_string(s):
        return strtobool(s)
    return bool(s)