Python inflection.underscore() Examples

The following are 30 code examples of inflection.underscore(). 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 inflection , or try the search function .
Example #1
Source File: base.py    From gs-quant with Apache License 2.0 6 votes vote down vote up
def camel_case_translate(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        normalised_kwargs = {}
        for arg, value in kwargs.items():
            arg = _normalise_arg(arg)

            if not arg.isupper():
                snake_case_arg = inflection.underscore(arg)
                if snake_case_arg != arg:
                    if snake_case_arg in kwargs:
                        raise ValueError('{} and {} both specified'.format(arg, snake_case_arg))

                    normalised_kwargs[snake_case_arg] = value
                else:
                    normalised_kwargs[arg] = value
            else:
                normalised_kwargs[arg] = value

        return f(*args, **normalised_kwargs)

    return wrapper 
Example #2
Source File: minio.py    From cloudstorage with MIT License 6 votes vote down vote up
def _normalize_parameters(
        params: Dict[str, str], normalizers: Dict[str, str]
    ) -> Dict[str, str]:
        normalized = params.copy()

        for key, value in params.items():
            normalized.pop(key)
            if not value:
                continue

            key_inflected = camelize(underscore(key), uppercase_first_letter=True)
            # Only include parameters found in normalizers
            key_overrider = normalizers.get(key_inflected.lower())
            if key_overrider:
                normalized[key_overrider] = value

        return normalized 
Example #3
Source File: variable_stat.py    From yolo2-pytorch with GNU Lesser General Public License v3.0 6 votes vote down vote up
def main():
    args = make_args()
    config = configparser.ConfigParser()
    utils.load_config(config, args.config)
    for cmd in args.modify:
        utils.modify_config(config, cmd)
    with open(os.path.expanduser(os.path.expandvars(args.logging)), 'r') as f:
        logging.config.dictConfig(yaml.load(f))
    model_dir = utils.get_model_dir(config)
    path, step, epoch = utils.train.load_model(model_dir)
    state_dict = torch.load(path, map_location=lambda storage, loc: storage)
    mapper = [(inflection.underscore(name), member()) for name, member in inspect.getmembers(importlib.machinery.SourceFileLoader('', __file__).load_module()) if inspect.isclass(member)]
    path = os.path.join(model_dir, os.path.basename(os.path.splitext(__file__)[0])) + '.xlsx'
    with xlsxwriter.Workbook(path, {'strings_to_urls': False, 'nan_inf_to_errors': True}) as workbook:
        worksheet = workbook.add_worksheet(args.worksheet)
        for j, (key, m) in enumerate(mapper):
            worksheet.write(0, j, key)
            for i, (name, variable) in enumerate(state_dict.items()):
                value = m(name, variable)
                worksheet.write(1 + i, j, value)
            if hasattr(m, 'format'):
                m.format(workbook, worksheet, i, j)
        worksheet.autofilter(0, 0, i, len(mapper) - 1)
        worksheet.freeze_panes(1, 0)
    logging.info(path) 
Example #4
Source File: amazon.py    From cloudstorage with MIT License 6 votes vote down vote up
def _normalize_parameters(
        params: Dict[str, str], normalizers: Dict[str, str]
    ) -> Dict[str, str]:
        normalized = params.copy()

        for key, value in params.items():
            normalized.pop(key)
            if not value:
                continue

            key_inflected = camelize(underscore(key), uppercase_first_letter=True)
            # Only include parameters found in normalizers
            key_overrider = normalizers.get(key_inflected.lower())
            if key_overrider:
                normalized[key_overrider] = value

        return normalized 
Example #5
Source File: utils.py    From django-rest-framework-json-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def format_field_names(obj, format_type=None):
    """
    Takes a dict and returns it with formatted keys as set in `format_type`
    or `JSON_API_FORMAT_FIELD_NAMES`

    :format_type: Either 'dasherize', 'camelize', 'capitalize' or 'underscore'
    """
    if format_type is None:
        format_type = json_api_settings.FORMAT_FIELD_NAMES

    if isinstance(obj, dict):
        formatted = OrderedDict()
        for key, value in obj.items():
            key = format_value(key, format_type)
            formatted[key] = value
        return formatted

    return obj 
Example #6
Source File: local.py    From cloudstorage with MIT License 6 votes vote down vote up
def _normalize_parameters(
        params: Dict[str, str], normalizers: Dict[str, str]
    ) -> Dict[str, str]:
        normalized = params.copy()

        for key, value in params.items():
            normalized.pop(key)
            if not value:
                continue

            key_inflected = underscore(key).lower()

            # Only include parameters found in normalizers
            key_overrider = normalizers.get(key_inflected)
            if key_overrider:
                normalized[key_overrider] = value

        return normalized 
Example #7
Source File: google.py    From cloudstorage with MIT License 6 votes vote down vote up
def _normalize_parameters(
        params: Dict[str, str], normalizers: Dict[str, str]
    ) -> Dict[str, str]:
        normalized = params.copy()

        for key, value in params.items():
            normalized.pop(key)
            if not value:
                continue

            key_inflected = underscore(key).lower()

            # Only include parameters found in normalizers
            key_overrider = normalizers.get(key_inflected)
            if key_overrider:
                normalized[key_overrider] = value

        return normalized 
Example #8
Source File: rhopenshift.py    From wrapanapi with MIT License 6 votes vote down vote up
def create_template_entities(self, namespace, entities):
        """Creates entities from openshift template.

        Since there is no methods in openshift/kubernetes rest api for app deployment from template,
        it is necessary to create template entities one by one using respective entity api.

        Args:
            namespace: (str) openshift namespace
            entities: (list) openshift entities

        Returns: None
        """
        self.logger.debug("passed template entities:\n %r", entities)
        kinds = set([e['kind'] for e in entities])
        entity_names = {e: inflection.underscore(e) for e in kinds}
        proc_names = {k: 'create_{e}'.format(e=p) for k, p in entity_names.items()}

        for entity in entities:
            if entity['kind'] in kinds:
                procedure = getattr(self, proc_names[entity['kind']], None)
                obtained_entity = procedure(namespace=namespace, **entity)
                self.logger.debug(obtained_entity)
            else:
                self.logger.error("some entity %s isn't present in entity creation list", entity) 
Example #9
Source File: microsoft.py    From cloudstorage with MIT License 6 votes vote down vote up
def _normalize_parameters(
        params: Dict[str, str], normalizers: Dict[str, str]
    ) -> Dict[str, str]:
        normalized = params.copy()

        for key, value in params.items():
            normalized.pop(key)
            if not value:
                continue

            key_inflected = underscore(key).lower()

            # Only include parameters found in normalizers
            key_overrider = normalizers.get(key_inflected)
            if key_overrider:
                normalized[key_overrider] = value

        return normalized 
Example #10
Source File: context.py    From dynamic-rest with MIT License 6 votes vote down vote up
def get_context(version, name, model, plural_name):
    name = inflection.underscore(inflection.singularize(name))
    model = model or name
    model_class_name = inflection.camelize(model)
    class_name = inflection.camelize(name)
    serializer_class_name = class_name + 'Serializer'
    viewset_class_name = class_name + 'ViewSet'
    plural_name = plural_name or inflection.pluralize(name)
    return {
        'version': version,
        'serializer_class_name': serializer_class_name,
        'viewset_class_name': viewset_class_name,
        'model_class_name': model_class_name,
        'name': name,
        'plural_name': plural_name
    } 
Example #11
Source File: installed_programs.py    From regipy with MIT License 6 votes vote down vote up
def _get_installed_software(self, subkey_path):
        try:
            uninstall_sk = self.registry_hive.get_key(subkey_path)
        except RegistryKeyNotFoundException as ex:
            logger.error(ex)
            return

        for installed_program in uninstall_sk.iter_subkeys():
            values = {underscore(x.name): x.value for x in
                      installed_program.iter_values(as_json=self.as_json)} if installed_program.values_count else {}
            self.entries.append({
                'service_name': installed_program.name,
                'timestamp': convert_wintime(installed_program.header.last_modified, as_json=self.as_json),
                'registry_path': subkey_path,
                **values

            }) 
Example #12
Source File: installed_programs_ntuser.py    From regipy with MIT License 6 votes vote down vote up
def _get_installed_software(self, subkey_path):
        try:
            uninstall_sk = self.registry_hive.get_key(subkey_path)
        except RegistryKeyNotFoundException as ex:
            logger.error(ex)
            return

        for installed_program in uninstall_sk.iter_subkeys():
            values = {underscore(x.name): x.value for x in
                      installed_program.iter_values(as_json=self.as_json)} if installed_program.values_count else {}
            self.entries.append({
                'service_name': installed_program.name,
                'timestamp': convert_wintime(installed_program.header.last_modified, as_json=self.as_json),
                'registry_path': subkey_path,
                **values

            }) 
Example #13
Source File: label.py    From openpose-pytorch with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, config):
        self.config = config
        self.fn = eval(inflection.underscore(type(self).__name__)) 
Example #14
Source File: utils.py    From BoxOfficeMojo with MIT License 5 votes vote down vote up
def standardize_keys(obj):
    if isinstance(obj, list):
        for element in obj:
            standardize_keys(element)
    elif isinstance(obj, dict):
        temp = []
        for key, val in obj.iteritems():
            standardize_keys(val)
            temp.append(key)
        for key in temp:
            obj[inflection.underscore(key.replace(" ", ""))] = obj.pop(key)
    else:
        pass 
Example #15
Source File: label.py    From openpose-pytorch with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self.fn = eval(inflection.underscore(type(self).__name__)) 
Example #16
Source File: label.py    From openpose-pytorch with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self.fn = eval(inflection.underscore(type(self).__name__)) 
Example #17
Source File: utils.py    From benchling-api with MIT License 5 votes vote down vote up
def underscore_keys(data):
    """Recursively transform keys to underscore format."""
    return _recursive_apply_to_keys(data, underscore, underscore_keys) 
Example #18
Source File: utils.py    From benchling-api with MIT License 5 votes vote down vote up
def underscore(k):
    """Transform keys like 'benchlingKey' to 'benchling_key'."""
    return inflection.underscore(k) 
Example #19
Source File: schema.py    From diffy with Apache License 2.0 5 votes vote down vote up
def under(self, data, many=None):
        items = []
        if many:
            for i in data:
                items.append({underscore(key): value for key, value in i.items()})
            return items
        return {underscore(key): value for key, value in data.items()} 
Example #20
Source File: reprotobuf.py    From reprotobuf with MIT License 5 votes vote down vote up
def structure_packages(self):
        for name in self.tree['sub']:
            # extract package and outer name
            parts = name.split('/')
            filename_part = parts.pop()
            package = '.'.join(parts)
            filename = inflection.underscore(filename_part) + '.proto'
            file_properties = {
                    'name': filename,
                    'package': filename_part,
                    'options': {
                        'java_package': '"%s"' % package,
                        'java_outer_classname': '"%s"' % filename_part,
                        },
                    'imports': set(),
                    }
            # if there's a class at this level
            if 'class' in self.tree['sub'][name]:
                file_properties['options']['java_multiple_files'] = 'true';
                file_properties['messages'] = {
                        'sub': {
                            filename_part: self.tree['sub'][name]
                            }
                        }
            else:
                file_properties['messages'] = self.tree['sub'][name]
            # add this file to our list
            assert filename not in self.files
            self.files[filename] = file_properties 
Example #21
Source File: amcache.py    From regipy with MIT License 5 votes vote down vote up
def parse_amcache_file_entry(self, subkey):
        entry = {underscore(x.name): x.value for x in subkey.iter_values(as_json=self.as_json)}

        # Sometimes the value names might be numeric instead. Translate them:
        for k, v in AMCACHE_FIELD_NUMERIC_MAPPINGS.items():
            content = entry.pop(k, None)
            if content:
                entry[v] = content

        if 'sha1' in entry:
            entry['sha1'] = entry['sha1'][4:]

        if 'file_id' in entry:
            entry['file_id'] = entry['file_id'][4:]
            if 'sha1' not in entry:
                entry['sha1'] = entry['file_id']

        entry['program_id'] = entry['program_id'][4:]

        entry['timestamp'] = convert_wintime(subkey.header.last_modified, as_json=self.as_json)

        if 'size' in entry:
            entry['size'] = int(entry['size'], 16) if isinstance(entry['size'], str) else entry['size']

        is_pefile = entry.get('is_pe_file')
        if is_pefile is not None:
            entry['is_pe_file'] = bool(is_pefile)

        is_os_component = entry.get('is_os_component')
        if is_os_component is not None:
            entry['is_os_component'] = bool(is_os_component)

        if entry.get('link_date') == 0:
            entry.pop('link_date')

        for ts_field_name in WIN8_TS_FIELDS:
            ts = entry.pop(ts_field_name, None)
            if ts:
                entry[ts_field_name] = convert_wintime(ts, as_json=self.as_json)

        self.entries.append(entry) 
Example #22
Source File: last_logon.py    From regipy with MIT License 5 votes vote down vote up
def run(self):
        try:
            subkey = self.registry_hive.get_key(LAST_LOGON_KEY_PATH)
        except RegistryKeyNotFoundException as ex:
            logger.error(f'Could not find {self.NAME} subkey at {LAST_LOGON_KEY_PATH}: {ex}')
            return None

        self.entries = {
            'last_write': convert_wintime(subkey.header.last_modified, as_json=self.as_json),
            **{underscore(x.name): x.value for x in subkey.iter_values(as_json=self.as_json)}
        } 
Example #23
Source File: image.py    From openpose-pytorch with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, config):
        name = inflection.underscore(type(self).__name__)
        self.adjust = tuple(map(float, config.get('augmentation', name).split())) 
Example #24
Source File: image.py    From openpose-pytorch with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, config):
        name = inflection.underscore(type(self).__name__)
        self.adjust = tuple(map(float, config.get('augmentation', name).split())) 
Example #25
Source File: typed_urls.py    From regipy with MIT License 5 votes vote down vote up
def run(self):
        try:
            subkey = self.registry_hive.get_key(TYPED_URLS_KEY_PATH)
        except RegistryKeyNotFoundException as ex:
            logger.error(f'Could not find {self.NAME} plugin data at: {TYPED_URLS_KEY_PATH}: {ex}')
            return None

        self.entries = {
            'last_write': convert_wintime(subkey.header.last_modified, as_json=self.as_json),
            'entries': [{underscore(x.name): x.value} for x in subkey.iter_values(as_json=self.as_json)]
        } 
Example #26
Source File: requests.py    From knowledge-repo with Apache License 2.0 5 votes vote down vote up
def from_request_get_feed_params(request):
    """Given the request, return an object that contains the parameters.

    :param request: The request obj
    :type request: Flask request
    :return: Select parameters passed in through headers or the url
    :rtype: object
    """

    feed_params = {}

    feed_params["filters"] = request.args.get('filters')
    feed_params["authors"] = request.args.get('authors')
    feed_params["start"] = int(request.args.get('start', 0))
    feed_params["results"] = int(request.args.get('results', 10))
    feed_params["sort_by"] = inflection.underscore(
        request.args.get('sort_by', 'updated_at'))
    feed_params["sort_desc"] = not bool(request.args.get('sort_asc', ''))
    username, user_id = current_user.identifier, current_user.id
    feed_params["username"] = username
    feed_params["user_id"] = user_id

    user_obj = (db_session.query(User)
                          .filter(User.id == user_id)
                          .first())

    if user_obj:
        feed_params["subscriptions"] = user_obj.subscriptions
    return feed_params 
Example #27
Source File: base.py    From gs-quant with Apache License 2.0 5 votes vote down vote up
def __setattr__(self, key, value):
        properties = super().__getattribute__('properties')()
        snake_case_key = inflection.underscore(key)
        key_is_property = key in properties
        snake_case_key_is_property = snake_case_key in properties

        if snake_case_key_is_property and not key_is_property:
            return super().__setattr__(snake_case_key, value)
        else:
            return super().__setattr__(key, value) 
Example #28
Source File: base.py    From gs-quant with Apache License 2.0 5 votes vote down vote up
def __getattr__(self, item):
        snake_case_item = inflection.underscore(item)
        if snake_case_item in super().__getattribute__('properties')():
            return super().__getattribute__(snake_case_item)
        else:
            return super().__getattribute__(item) 
Example #29
Source File: image.py    From openpose-pytorch with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, config):
        name = inflection.underscore(type(self).__name__)
        mean, std = tuple(map(float, config.get('transform', name).split()))
        torchvision.transforms.Normalize.__init__(self, (mean, mean, mean), (std, std, std)) 
Example #30
Source File: utils.py    From benchling-api with MIT License 5 votes vote down vote up
def un_underscore_keys(data):
    """Recursively un-transfrom keys from underscore format to benchling
    format."""
    return _recursive_apply_to_keys(data, un_underscore, underscore_keys)