Пример #1
0
def transform(filename):
    # read
    wb = openpyxl.load_workbook(filename=filename)

    for ws in wb:
        if not ws.title.startswith('!'):
            continue

        if isinstance(ws.cell(1, 1).value, str) and ws.cell(
                1, 1).value.startswith('!!'):
            matches = re.findall(
                r" +(.*?)=('((?:[^'\\]|\\.)*)'|\"((?:[^\"\\]|\\.)*)\")",
                ws.cell(1, 1).value)
            heading, _, _ = ws.cell(1, 1).value.partition(' ')
            for key, val, _, _ in matches:
                heading += ' {}={}'.format(stringcase.camelcase(key), val)
            ws.cell(1, 1).value = heading

        if isinstance(ws.cell(2, 1).value, str) and ws.cell(
                2, 1).value.startswith('!!'):
            matches = re.findall(
                r" +(.*?)=('((?:[^'\\]|\\.)*)'|\"((?:[^\"\\]|\\.)*)\")",
                ws.cell(2, 1).value)
            heading, _, _ = ws.cell(2, 1).value.partition(' ')
            for key, val, _, _ in matches:
                heading += ' {}={}'.format(stringcase.camelcase(key), val)
            ws.cell(2, 1).value = heading

    # save
    wb.save(filename)
Пример #2
0
def test_add_post_settings_default_to_user_level_settings(post_manager, user):
    # set user-level defaults
    defaults = {
        'comments_disabled': False,
        'likes_disabled': True,
        'sharing_disabled': False,
        'verification_hidden': True,
    }
    user.update_details(**defaults)

    # create a post with all the settings speficied to the same as user defaults, verify all good
    post = post_manager.add_post(user, str(uuid.uuid4()), PostType.IMAGE,
                                 **defaults)
    for k, v in defaults.items():
        assert post.item.get(stringcase.camelcase(k)) is v

    # create a post with all the settings speficied to the opposite as user defaults, verify all good
    post = post_manager.add_post(user, str(uuid.uuid4()), PostType.IMAGE,
                                 **{k: not v
                                    for k, v in defaults.items()})
    for k, v in defaults.items():
        assert post.item.get(stringcase.camelcase(k)) is (not v)

    # create a post with no settings speficied, verify user defaults taken
    post = post_manager.add_post(user, str(uuid.uuid4()), PostType.IMAGE)
    for k, v in defaults.items():
        assert post.item.get(stringcase.camelcase(k)) is v
Пример #3
0
def __write_casting_test_for_parent_child(child, parent, abstract_classes, of,
                                          parents_info, notebook):
    k = (child, parent)

    if k in notebook:
        return

    notebook[k] = True

    # because objects for abstract classes are not created,
    # if the class is an abstract one, skip the test
    if child not in abstract_classes:
        of.write("    ASSERT_TRUE(llvm::isa<{}>({}));\n".format(
            parent, stringcase.camelcase(child)))
        of.write("    ASSERT_NE(llvm::dyn_cast<{}>({}), nullptr);\n".format(
            parent, stringcase.camelcase(child)))

    if parent not in abstract_classes:
        of.write("    ASSERT_FALSE(llvm::isa<{}>({}));\n".format(
            child, stringcase.camelcase(parent)))
        of.write("    ASSERT_EQ(llvm::dyn_cast<{}>({}), nullptr);\n".format(
            child, stringcase.camelcase(parent)))

    if child in parents_info:
        for p in parents_info[child]:
            __write_casting_test_for_parent_child(child, p, abstract_classes,
                                                  of, parents_info, notebook)
Пример #4
0
def write_alloc_code_for_type(klass, alloc_type, abstract_classes, of,
                              written):
    # skip allocating objects for abstract classes
    if klass in written or klass in abstract_classes:
        return
    written[klass] = True

    if alloc_type == 1:
        # write allocate using new
        of.write("    {} *{} = new {}();\n".format(klass,
                                                   stringcase.camelcase(klass),
                                                   klass))

    elif alloc_type == 2:
        # write deallocate using delete
        of.write("    delete {};\n".format(stringcase.camelcase(klass)))

    elif alloc_type == 3:
        # allocate using make_unique
        of.write("    unique_ptr<{}> {} = unique_ptr<{}>();\n".format(
            klass, stringcase.camelcase(klass), klass))
    elif alloc_type == 4:
        # allocate using make_unique
        of.write("    shared_ptr<{}> {} = make_shared<{}>();\n".format(
            klass, stringcase.camelcase(klass), klass))
Пример #5
0
 def _create_vpc(self, cidr_block):
     self.vpc = VPC(camelcase("{self.env}Vpc".format(**locals())),
                    CidrBlock=cidr_block,
                    EnableDnsSupport=True,
                    EnableDnsHostnames=True,
                    InstanceTenancy='default',
                    Tags=[{
                        'Key': 'category',
                        'Value': 'services'
                    }, {
                        'Key': 'environment',
                        'Value': self.env
                    }, {
                        'Key': 'Name',
                        'Value': "{self.env}-vpc".format(**locals())
                    }])
     self.template.add_resource(self.vpc)
     self.internet_gateway = InternetGateway(
         camelcase("{self.env}Ig".format(**locals())),
         Tags=[{
             'Key': 'Name',
             'Value': "{self.env}-internet-gateway".format(**locals())
         }, {
             'Key': 'environment',
             'Value': self.env
         }])
     self.template.add_resource(self.internet_gateway)
     vpc_gateway_attachment = VPCGatewayAttachment(
         camelcase("{self.env}Attachment".format(**locals())),
         InternetGatewayId=Ref(self.internet_gateway),
         VpcId=Ref(self.vpc))
     self.template.add_resource(vpc_gateway_attachment)
     return None
Пример #6
0
def transform(filename, taxon):
    # read
    wb = openpyxl.load_workbook(filename=filename)

    for ws in wb:
        if not ws.title.startswith('!'):
            continue

        # lower camel case document and class attributes
        table_head_cell = None
        if isinstance(ws.cell(1, 1).value, str) and ws.cell(1, 1).value.startswith('!!'):
            table_head_cell = ws.cell(1, 1)
            matches = re.findall(r" +(.*?)=('((?:[^'\\]|\\.)*)'|\"((?:[^\"\\]|\\.)*)\")",
                ws.cell(1, 1).value)
            heading, _, _ = ws.cell(1, 1).value.partition(' ')
            for key, val, _, _ in matches:
                heading += ' {}={}'.format(stringcase.camelcase(key), val)
            ws.cell(1, 1).value = heading

        if isinstance(ws.cell(2, 1).value, str) and ws.cell(2, 1).value.startswith('!!'):
            table_head_cell = ws.cell(2, 1)
            matches = re.findall(r" +(.*?)=('((?:[^'\\]|\\.)*)'|\"((?:[^\"\\]|\\.)*)\")",
                ws.cell(2, 1).value)
            heading, _, _ = ws.cell(2, 1).value.partition(' ')
            for key, val, _, _ in matches:
                heading += ' {}={}'.format(stringcase.camelcase(key), val)
            ws.cell(2, 1).value = heading

        # set schema
        if taxon == 'eu':
            schema = 'wc_kb.eukaryote'
        else:
            schema = 'wc_kb.prokaryote'

        if ws.title == '!!_Schema':
            raise NotImplementedError('setting schema name not supported')
        elif ws.title != '!!_Table of contents':
            table_head_cell.value += " schema='{}'".format(schema)

        # set table format
        if ws.title in ['!!_Schema', '!!_Table of contents']:
            table_head_cell.value += ' tableFormat="row"'
        else:
            match = re.search(r" +id=('((?:[^'\\]|\\.)*)'|\"((?:[^\"\\]|\\.)*)\")",
                table_head_cell.value)
            table_id = match.group(1)[1:-1]
            if hasattr(wc_kb, table_id):
                table = getattr(wc_kb, table_id)
            elif taxon == 'eu':
                table = getattr(wc_kb.eukaryote, table_id)
            else:
                table = getattr(wc_kb.prokaryote, table_id)

            table_format = table.Meta.table_format.name
            table_head_cell.value += ' tableFormat="{}"'.format(table_format)

    # save
    wb.save(filename)
Пример #7
0
 def compute_value(self, value, attributes, optionals=False):
     for attribute in attributes:
         if optionals:
             if hasattr(self, attribute) and getattr(self, attribute):
                 value[stringcase.camelcase(attribute)] = getattr(
                     self, attribute)
         else:
             value[stringcase.camelcase(attribute)] = getattr(
                 self, attribute)
     return value
    def _create_public_network(self, subnet_configs):
        public_route_table = RouteTable(
            camelcase("{self.env}Public".format(**locals())),
            VpcId=Ref(self.vpc),
            Tags=[
                {
                    'Key': 'Name',
                    'Value': "{self.env}-public".format(**locals())
                },
                {'Key': 'environment', 'Value': self.env}
            ],
            DependsOn=self.vpc.title)
        self.template.add_resource(public_route_table)
        subnet_count = 0

        existing_subnet_ids, existing_subnet_azs, az_balance = self._get_existing_subnet_info("PublicSubnet")
        for subnet_title, subnet_config in subnet_configs.items():
            subnet_count += 1
            if f"PublicSubnet{subnet_count}" in existing_subnet_ids:
                availability_zone = existing_subnet_azs[existing_subnet_ids[f"PublicSubnet{subnet_count}"]]
            else:
                availability_zone = min(az_balance, key=az_balance.get)

            subnet_title = camelcase("{self.env}Public".format(**locals())) + \
                pascalcase(re.sub('[^a-zA-Z0-9*]', '', subnet_title))
            subnet_name = "{self.env}-public-{subnet_count}".format(**locals())
            subnet = Subnet(
                subnet_title,
                AvailabilityZone=availability_zone,
                CidrBlock=subnet_config['cidr'],
                VpcId=Ref(self.vpc),
                MapPublicIpOnLaunch=True,
                Tags=[
                    {'Key': 'Name', 'Value': subnet_name},
                    {'Key': 'environment', 'Value': self.env}
                ]
            )
            self.public_subnets.append(subnet)
            self.template.add_resource(subnet)
            subnet_route_table_association = SubnetRouteTableAssociation(
                camelcase("{self.env}PublicSubnet{subnet_count}Assoc".format(**locals())),
                RouteTableId=Ref(public_route_table),
                SubnetId=Ref(subnet)
            )
            self.template.add_resource(subnet_route_table_association)

        internet_gateway_route = Route(
            camelcase("{self.env}IgRoute".format(**locals())),
            DestinationCidrBlock='0.0.0.0/0',
            GatewayId=Ref(self.internet_gateway),
            RouteTableId=Ref(public_route_table)
        )
        self.template.add_resource(internet_gateway_route)
        return None
Пример #9
0
 def default(self, o: Company) -> Dict[str, Any]:  # pylint: disable=E0202
     arrow_attrs = [
         x for x in dir(o) if isinstance(getattr(o, x), arrow.Arrow)
         and x[:2] != "__" and x[-2:] != "__"
     ]
     company = {
         camelcase(k): v
         for k, v in o.__dict__.items() if v and k not in arrow_attrs
     }
     for x in arrow_attrs:
         company[camelcase(x)] = getattr(o, x).isoformat()
     return company
Пример #10
0
def write_abmormal_casting_test_code(all_parents, all_classes,
                                     abstract_classes, of):

    of.write("    // BEGIN of casting unrelated classes\n")
    for c in all_parents.keys():
        for t in all_classes:
            if t not in all_parents[c]:
                of.write("    ASSERT_FALSE(llvm::isa<{}>({}));\n".format(
                    c, stringcase.camelcase(t)))

                of.write("    ASSERT_FALSE(llvm::isa<{}>({}));\n".format(
                    t, stringcase.camelcase(c)))
    of.write("    // END of casting unrelated classes\n\n\n")
Пример #11
0
    def to_camelcase(self, data, **kwargs):
        camel_case_object = dict()

        for key, value in data.items():
            if isinstance(value, dict):
                value = {
                    camelcase(sub_key): sub_val
                    for sub_key, sub_val in value.items()
                }

            camel_case_object[camelcase(key)] = value

        return camel_case_object
Пример #12
0
def merge_jdbc_conf(job_jdbc_conf, global_jdbc_conf):
    for key, val in global_jdbc_conf.items():
        job_val = job_jdbc_conf.get(key)
        if val and job_val:
            print('{k}: job: {v}, global: {gv}'.format(k=key, v=job_val, gv=val))
            if stringcase.camelcase(key) == 'numPartitions' and job_val > val:
                raise ValueError("""{key} set to {j_val} in job conf,
                    which can not be larger than global setting: {g_val}""".format(
                    key=key, j_val=job_val, g_val=val
                ))
        elif val and not job_val:
            job_jdbc_conf[stringcase.camelcase(key)] = val
    return job_jdbc_conf
Пример #13
0
    def to_proto_map(self):
        from .management.commands.genproto import ProtoGen
        proto_map = {}
        for field in self._meta.get_fields():
            field_type = type(field)
            field_name = field.name

            if getattr(self, field_name) is None:
                continue

            if field.related_model:
                field_type = type(field.related_model._meta.pk)
                field_name = field.name + '_id'
                proto_map[field_name] = ProtoGen.type_map[
                    field_type].serialize(getattr(self, field_name))
            elif field.choices:
                camel_capital_name = stringcase.capitalcase(
                    stringcase.camelcase(field.name))
                choices: Choices = getattr(self, camel_capital_name)
                proto_map[field_name] = choices.get_by_key(
                    getattr(self, field.name)).index
            else:
                proto_map[field_name] = ProtoGen.type_map[
                    field_type].serialize(getattr(self, field_name))
        return proto_map
Пример #14
0
def to_camel(s):
    try:
        return CAMEL_CACHE[s]
    except KeyError:
        camel = stringcase.camelcase(s)
        CAMEL_CACHE[s] = camel
        return camel
Пример #15
0
    def __init__(
        self,
        api: ApiClient,
        hass: HomeAssistant,
        async_see: AsyncSeeCallback,
        scan_interval: timedelta,
        max_accuracy: int,
        skip_accuracy_on: bool,
        custom_attributes: list[str],
        event_types: list[str],
    ) -> None:
        """Initialize."""

        if EVENT_ALL_EVENTS in event_types:
            event_types = EVENTS
        self._event_types = {camelcase(evt): evt for evt in event_types}
        self._custom_attributes = custom_attributes
        self._scan_interval = scan_interval
        self._async_see = async_see
        self._api = api
        self._hass = hass
        self._max_accuracy = max_accuracy
        self._skip_accuracy_on = skip_accuracy_on
        self._devices: list[DeviceModel] = []
        self._positions: list[PositionModel] = []
        self._geofences: list[GeofenceModel] = []
Пример #16
0
def convertFile(file, convertType='c'):
    readFile = ''
    if len(file) > 1:
        readFile = file[0].strip()
        convertType = file[1].strip()
    else:
        readFile = file[0].strip()
    if readFile[-3:] == 'txt':
        outfile = readFile.strip('.txt') + "_out.txt"
        print "Output File: ", outfile
        o = open(outfile, "w+")
        f = open(readFile, "r")
        f1 = f.readlines()
        for line in f1:
            if convertType == 's':
                o.write(stringcase.snakecase(line).strip('_') + '\n')
            elif convertType == 'a':
                o.write(stringcase.uppercase(line))
            elif convertType == 'l':
                o.write(stringcase.lowercase(line))
            elif convertType == 'p':
                o.write(stringcase.pascalcase(line))
            elif convertType == 'd':
                o.write(stringcase.pathcase(line).strip('/') + '\n')
            elif convertType == 'm':
                o.write(stringcase.spinalcase(line).strip('-') + '\n')
            else:
                o.write(stringcase.camelcase(stringcase.lowercase(line)))
        f.close()
        o.close()
    else:
        print 'You will need to you use a .txt'
Пример #17
0
 def _add_vpc(self, vpc_id):
     self.vpc = Parameter(
         camelcase("{self.env}Vpc".format(**locals())),
         Type="AWS::EC2::VPC::Id",
         Default=vpc_id
     )
     self.template.add_parameter(self.vpc)
Пример #18
0
    def resolve_accounts(self, info, account_ids):
        requested_fields = get_fields(info).keys()
        clan_specific_account_fields = list(map(camelcase, ('joined_at', 'role', 'role_i18n',)))
        request_clan_account_fields = [field for field in requested_fields if field in clan_specific_account_fields]
        loaders = info.context['data_loaders']

        accounts_promise = loaders.account_loader.load(','.join(account_ids)).then(
            lambda result: list(result['data'].values())
        )
        accounts_data = accounts_promise.get()

        if request_clan_account_fields:
            clan_ids = {str(account_data['clan_id']) for account_data in accounts_data if account_data.get('clan_id')}
            clans_data = None
            if clan_ids:
                clans_promise = loaders.clan_loader.load(','.join(clan_ids)).then(lambda result: result['data'])
                clans_data = clans_promise.get()
            for account in accounts_data:
                account_clan_data = None
                if account.get('clan_id'):
                    account_clan_data = [
                        member for member in clans_data[str(account['clan_id'])]['members'] if
                        member['account_id'] == account['account_id']
                    ][0]

                account_clans_data = {
                    snakecase(field): account_clan_data[snakecase(field)] if account_clan_data else None
                    for field in request_clan_account_fields
                }
                account.update(account_clans_data)

        return list(map(lambda data: Account(**{
            'clan_id': data['clan_id'],
            **{field: value for field, value in data.items() if camelcase(field) in requested_fields}
        }), accounts_data))
Пример #19
0
 def update_details(
     self,
     full_name=None,
     bio=None,
     language_code=None,
     theme_code=None,
     follow_counts_hidden=None,
     view_counts_hidden=None,
     comments_disabled=None,
     likes_disabled=None,
     sharing_disabled=None,
     verification_hidden=None,
 ):
     "To delete details, set them to the empty string. Ex: `full_name=''`"
     kwargs = {
         k: v
         for k, v in locals().items() if k != 'self' and v is not None
     }
     # remove writes where requested value matches pre-existing value
     kwargs = {
         k: v
         for k, v in kwargs.items()
         if v != self.item.get(stringcase.camelcase(k), '')
     }
     if kwargs:
         self.item = self.dynamo.set_user_details(self.id, **kwargs)
     return self
Пример #20
0
 def __init__(self, descriptor=None, *, source=None, type=None, **options):
     self.setinitial("source", source)
     self.setinitial("type", type)
     for key, value in options.items():
         # TODO: review
         self.setinitial(stringcase.camelcase(key), value)
     super().__init__(descriptor)
Пример #21
0
 def CppParamList(self,
                  resolver,
                  names=True,
                  types=True,
                  constRef=True,
                  prepend='',
                  append=''):
     params = []
     try:
         prepend = len(self.data['parameters']) > 0 and prepend or ''
         append = len(self.data['parameters']) > 0 and append or ''
         for paramName, paramObj in self.data['parameters'].items():
             params.append((stringcase.camelcase(paramName),
                            paramObj.GetType(resolver)))
     except KeyError:
         append = ''
         prepend = ''
     s = prepend
     i = 0
     for name, theType in params:
         if i != 0:
             s += ", "
         i += 1
         if types:
             if constRef:
                 s += "const %s&" % (theType)
             else:
                 s += theType
             if names:
                 s += ' '
         if names:
             s += name
     s += append
     return s
Пример #22
0
    def get_data_type(self, schema: JsonSchemaObject, suffix: str = '') -> DataType:
        if schema.ref:
            data_type = self.openapi_model_parser.get_ref_data_type(schema.ref)
            self.imports.append(
                Import(
                    # TODO: Improve import statements
                    from_=model_module_name_var.get(),
                    import_=data_type.type_hint,
                )
            )
            return data_type
        elif schema.is_array:
            # TODO: Improve handling array
            items = schema.items if isinstance(schema.items, list) else [schema.items]
            return self.openapi_model_parser.data_type(
                data_types=[self.get_data_type(i, suffix) for i in items], is_list=True
            )
        elif schema.is_object:
            camelcase_path = stringcase.camelcase(self.path[1:].replace("/", "_"))
            capitalized_suffix = suffix.capitalize()
            name: str = f'{camelcase_path}{self.type.capitalize()}{capitalized_suffix}'
            path = ['paths', self.path, self.type, capitalized_suffix]

            data_type = self.openapi_model_parser.parse_object(name, schema, path)

            self.imports.append(
                Import(from_=model_module_name_var.get(), import_=data_type.type_hint,)
            )
            return data_type

        return self.openapi_model_parser.get_data_type(schema)
Пример #23
0
def convert_to_camelcase(data):
    """
    stringcase.camelcase('foo_bar_baz') # => "fooBarBaz"
    """
    EXCEPTIONS = ['awslogs_group', 'awslogs_region', 'awslogs_stream_prefix']
    EXCEPTIONS_CHILD = ['docker_labels']

    if isinstance(data, dict):
        _data = {}
        for key, value in data.items():
            if key in EXCEPTIONS:
                _key = key.replace('_', '-')
            else:
                _key = stringcase.camelcase(key)
            if key in EXCEPTIONS_CHILD:
                _value = value
            else:
                _value = convert_to_camelcase(value)
            _data[_key] = _value
        return _data
    elif isinstance(data, list):
        _list = []
        for value in data:
            _list.append(convert_to_camelcase(value))
        return _list
    else:
        return data
Пример #24
0
 def _create_log_group(self):
     log_group = LogGroup(camelcase(
         "{self.env}LogGroup".format(**locals())),
                          LogGroupName="{self.env}-logs".format(**locals()),
                          RetentionInDays=365)
     self.template.add_resource(log_group)
     return None
Пример #25
0
    def __setattr__(self, name, value):
        if name == "_Snaked__target" or name == "_Snaked__resolution_cache" or name == "_Snaked__use_cache":
            return super().__setattr__(name, value)

        if self.__use_cache and name in self.__resolution_cache:
            return setattr(self.__target, self.__resolution_cache[name], value)
        if hasattr(self.__target, name):
            if self.__use_cache: self.__resolution_cache[name] = name
            return setattr(self.__target, name, value)
        else:
            camel_case = camelcase(name)
            if hasattr(self.__target, camel_case) and snakecase(name) == name:
                # snakecase(name) == name makes sure that we're only auto-converting snake-case names. Anything else may lead to unexpected results.
                if self.__use_cache: self.__resolution_cache[name] = camel_case
                return setattr(self.__target, camel_case, value)
            else:
                pascal_case = pascalcase(name)
                if hasattr(self.__target,
                           pascal_case) and snakecase(name) == name:
                    # snakecase(name) == name makes sure that we're only auto-converting snake-case names. Anything else may lead to unexpected results.
                    if self.__use_cache:
                        self.__resolution_cache[name] = pascal_case
                    return setattr(self.__target, pascal_case, value)
                else:
                    if name == "__clear_cache":
                        return self.__clear_cache
                    return setattr(
                        self.__target, name, value
                    )  # go through the usual (now potentially error-throwing) routine of obtaining an attribute
Пример #26
0
def generate_variations(name):
    return [
        # stringcase.snakecase(name),
        stringcase.camelcase(name),
        stringcase.uppercase(stringcase.snakecase(name)),
        stringcase.capitalcase(name),
    ]
Пример #27
0
    def _info_wrapper(*args):
        query = method(*args)
        total = query.count()
        info_array["code"] = 200
        info_array["attributionText"] = f"Data provided by Marvel. © {now.year} MARVEL"
        info_array["totalCreators"] = total
        data = {}
        if total:
            query = query.dicts()

            if "character_id" in query[0]:
                data["characterId"] = query[0]["character_id"]
                data["characterName"] = query[0]["character_name"]

            data["creators"] = []

            for qry in query.dicts():
                corrected_keys = {}
                for k, v in qry.items():
                    if "character" not in k:
                        k = "resourceURI" if k == "resource_uri" else camelcase(k)
                        v = json.loads(v) if k == "thumbnail" else v
                        corrected_keys[k] = v
                data["creators"].append(corrected_keys)
        info_array["data"] = data
        return info_array
Пример #28
0
def _cloudformation_to_boto3_payload(data,
                                     ignore_keys=set(),
                                     ignore_camelcase=False):
    if not isinstance(data, dict):
        return data

    result = dict()
    for k, v in data.items():
        key = camelcase(k) if not ignore_camelcase else k
        ignore_camelcase_for_all_children = k in ignore_keys
        if isinstance(v, dict):
            result[key] = _cloudformation_to_boto3_payload(
                v,
                ignore_keys,
                ignore_camelcase=ignore_camelcase_for_all_children)
        elif isinstance(v, list):
            elements = list()
            for each in v:
                elements.append(
                    _cloudformation_to_boto3_payload(
                        each,
                        ignore_keys,
                        ignore_camelcase=ignore_camelcase_for_all_children))
            result[key] = elements
        elif isinstance(v, str):
            if v == 'true' or v == 'false':
                result[key] = v == 'true'
            else:
                result[key] = v
        else:
            result[key] = v
    return result
Пример #29
0
 def serialized(self) -> dict:
     """Get the serialized representation as a dictionary."""
     dict_repr = {}
     for key, val in vars(self).items():
         dict_repr[stringcase.camelcase(key)] = val
     del dict_repr['beam']
     return dict_repr
def add_basic_keywords(output, kwargs, kwarg_to_schema_key_mapper):
    # A list of non-nested schema.org properties
    basic_keywords = [
        "applicationDeadline",
        "description",
        "name",
        "url",
        "endDate",  # Dates should use ISO-8601 format – do we need to validate?
        "startDate",
        "maximumEnrollment",
        "occupationalCredentialAwarded",
        "timeOfDay",
        "timeToComplete", # Again, should be ISO-8601 format (for durations) – should this library validate for this?
        "applicationStartDate" # ISO-8601 format
    ]

    for key, value in kwargs.items():
        try:
            key = kwarg_to_schema_key_mapper[key]
        except KeyError:
            pass

        camel_case_key = stringcase.camelcase(key)
        if camel_case_key not in basic_keywords:
            continue

        output[camel_case_key] = value

    return output
Пример #31
0
 def __init__(self, api, hass, async_see, scan_interval,
              custom_attributes,
              event_types):
     """Initialize."""
     from stringcase import camelcase
     self._event_types = {camelcase(evt): evt for evt in event_types}
     self._custom_attributes = custom_attributes
     self._scan_interval = scan_interval
     self._async_see = async_see
     self._api = api
     self._hass = hass
    def test_camelcase(self):
        from stringcase import camelcase

        eq = self.assertEqual

        eq('fooBar', camelcase('foo_bar'))
        eq('fooBar', camelcase('FooBar'))
        eq('fooBar', camelcase('foo-bar'))
        eq('fooBar', camelcase('foo.bar'))
        eq('barBaz', camelcase('_bar_baz'))
        eq('barBaz', camelcase('.bar_baz'))
        eq('', camelcase(''))
        eq('none', camelcase(None))
Пример #33
0
    def update(self):
        """Get the monitored data from firebase."""
        from stringcase import camelcase, snakecase
        try:
            values = self.mgr.data(self.serial)

            # set state from data based on type of sensor
            self._state = values.get(camelcase(self.type))

            # set units
            self.update_unit()

            # set basic attributes for all sensors
            self._attributes = {
                'time': values['time'],
                'localtime': values['localtime']
            }

            # set extended attributes for main probe sensors
            if self.type in [PROBE_1, PROBE_2]:
                for key, val in values.items():
                    # add all attributes that don't contain any probe name
                    # or contain a matching probe name
                    if (
                            (self.type == PROBE_1 and key.find(PROBE_2) == -1)
                            or
                            (self.type == PROBE_2 and key.find(PROBE_1) == -1)
                    ):
                        if key == BATTERY_LEVEL:
                            key = ATTR_BATTERY_LEVEL
                        else:
                            # strip probe label and convert to snake_case
                            key = snakecase(key.replace(self.type, ''))
                        # add to attrs
                        if key and key not in EXCLUDE_KEYS:
                            self._attributes[key] = val
                # store actual unit because attributes are not converted
                self._attributes['unit_of_min_max'] = self._unit_of_measurement

        except (RequestException, ValueError, KeyError):
            _LOGGER.warning("Could not update status for %s", self.name)