def create(self):
        log_warning(
            "Create task definition to {self.region}".format(**locals()))
        if not os.path.exists(self.env_sample_file):
            raise UnrecoverableException('env.sample not found. Exiting.')
        ecr_client = EcrClient(self.name, self.region, self.build_args)
        ecr_client.set_version(self.version)
        log_intent("name: " + self.name + " | environment: " +
                   self.environment + " | version: " + str(ecr_client.version))
        log_bold("Checking image in ECR")
        ecr_client.build_and_upload_image()
        log_bold("Creating task definition\n")
        env_config = build_config(self.environment, self.name,
                                  self.env_sample_file)
        container_definition_arguments = {
            "environment": [{
                "name": k,
                "value": v
            } for (k, v) in env_config],
            "name": pascalcase(self.name) + "Container",
            "image": _complete_image_url(ecr_client),
            "essential": True,
            "logConfiguration": self._gen_log_config(pascalcase(self.name)),
            "memoryReservation": 1024
        }

        ecs_client = EcsClient(region=self.region)
        ecs_client.register_task_definition(self._task_defn_family(),
                                            [container_definition_arguments],
                                            [], None)
        log_bold("Task definition successfully created\n")
            def __init__(self, client, object_type):
                self._object_type = object_type
                self._widgets_list = dict()
                self._native_params = None
                self._client = client
                class_name = None
                if self._object_type == 'camera':
                    class_name = pascalcase(
                        self._client.get_camera()['current'])
                    class_name += 'CameraParams'
                elif self._object_type == 'renderer':
                    class_name = pascalcase(
                        self._client.get_renderer()['current'])
                    class_name += 'RendererParams'

                # Read params from Brayns
                self._native_params = self._get_params()

                # Read params from class definition
                class_ = getattr(self._client, class_name)
                self._param_descriptors = class_()

                # Only keep params that belong to the class definition
                params_to_call = getattr(self._client, class_name)
                self._params = params_to_call()
                if self._native_params is not None:
                    for param in self._native_params:
                        if param in self._params:
                            self._params[param] = self._native_params[param]

                self._create_widgets()
    def execute(self,
                *,
                root_path: Path,
                data_dir: str,
                force: Optional[bool] = False):

        format_args = asdict(self.context)

        for field in fields(Template.Context):
            field_value = getattr(self.context, field.name)
            if field_value is not None:
                format_args[sc.pascalcase(
                    field.name)] = sc.pascalcase(field_value)
        format_args["data_dir"] = data_dir

        with open(TEMPLATE_DIR_PATH /
                  self.template_file_name) as template_file:
            template_str = template_file.read()

        temp = string.Template(template_str)
        formatted_str = temp.substitute(**format_args)

        self.write_new_file(root_path / self.dest_file_path_from_root,
                            file_data=formatted_str)

        return formatted_str
Beispiel #4
0
def get_ref_type(package: str,
                 imports: set,
                 type_name: str,
                 unwrap: bool = True) -> str:
    """
    Return a Python type name for a proto type reference. Adds the import if
    necessary. Unwraps well known type if required.
    """
    # If the package name is a blank string, then this should still work
    # because by convention packages are lowercase and message/enum types are
    # pascal-cased. May require refactoring in the future.
    type_name = type_name.lstrip(".")

    is_wrapper = type_name in WRAPPER_TYPES

    if unwrap:
        if is_wrapper:
            wrapped_type = type(WRAPPER_TYPES[type_name]().value)
            return f"Optional[{wrapped_type.__name__}]"

        if type_name == "google.protobuf.Duration":
            return "timedelta"

        if type_name == "google.protobuf.Timestamp":
            return "datetime"

    if type_name.startswith(package):
        parts = type_name.lstrip(package).lstrip(".").split(".")
        if len(parts) == 1 or (len(parts) > 1
                               and parts[0][0] == parts[0][0].upper()):
            # This is the current package, which has nested types flattened.
            # foo.bar_thing => FooBarThing
            cased = [stringcase.pascalcase(part) for part in parts]
            type_name = f'"{"".join(cased)}"'

    # Use precompiled classes for google.protobuf.* objects
    if type_name.startswith("google.protobuf.") and type_name.count(".") == 2:
        type_name = type_name.rsplit(".", maxsplit=1)[1]
        import_package = "betterproto.lib.google.protobuf"
        import_alias = safe_snake_case(import_package)
        imports.add(f"import {import_package} as {import_alias}")
        return f"{import_alias}.{type_name}"

    if "." in type_name:
        # This is imported from another package. No need
        # to use a forward ref and we need to add the import.
        parts = type_name.split(".")
        parts[-1] = stringcase.pascalcase(parts[-1])
        imports.add(f"from .{'.'.join(parts[:-2])} import {parts[-2]}")
        type_name = f"{parts[-2]}.{parts[-1]}"

    return type_name
Beispiel #5
0
    def _parse_children_config(cls, children, scope):
        """Parses children in the given scope"""
        remaining_children = {}
        myconfig = {}
        setters = []
        for key, v in children.items():
            k, class_name = cls._split_key(key)
            if isinstance(v, Dict):
                if class_name is None:
                    class_name = stringcase.pascalcase(k)
                the_class = get_class(class_name=class_name, scope=scope)
                obj, obj_children = the_class.from_config(
                    config=v,
                    ignore_children=False,
                    try_parsing_children=True,
                    scope=scope,
                )
                if obj_children is not None and len(obj_children) > 0:
                    remaining_children[k] = obj_children
                setter_name = "set_" + k
                if hasattr(cls, setter_name):
                    setters.append((setter_name, obj))
                else:
                    myconfig[k] = obj
            elif isinstance(v, Iterable) and not isinstance(v, str):
                singular = _inflect_engine.singular_noun(k)
                if singular is False:
                    singular = k
                if class_name is None:
                    class_name = stringcase.pascalcase(singular)
                setter_name = "set_" + k
                objs = []
                for current in list(v):
                    the_class = get_class(class_name=class_name, scope=scope)
                    obj = the_class.from_config(
                        config=current,
                        ignore_children=True,
                        try_parsing_children=True,
                        scope=scope,
                    )
                    objs.append(obj)
                if hasattr(cls, setter_name):
                    setters.append((setter_name, objs))
                else:
                    myconfig[k] = objs
            else:
                # not a dictionary and not an iterable.
                remaining_children[k] = v

        return myconfig, remaining_children, setters
Beispiel #6
0
def get_ref_type(package: str,
                 imports: set,
                 type_name: str,
                 unwrap: bool = True) -> str:
    """
    Return a Python type name for a proto type reference. Adds the import if
    necessary. Unwraps well known type if required.
    """
    # If the package name is a blank string, then this should still work
    # because by convention packages are lowercase and message/enum types are
    # pascal-cased. May require refactoring in the future.
    type_name = type_name.lstrip(".")

    # Check if type is wrapper.
    wrapper_class = WRAPPER_TYPES[type_name]

    if unwrap:
        if wrapper_class:
            wrapped_type = type(wrapper_class().value)
            return f"Optional[{wrapped_type.__name__}]"

        if type_name == "google.protobuf.Duration":
            return "timedelta"

        if type_name == "google.protobuf.Timestamp":
            return "datetime"
    elif wrapper_class:
        imports.add(
            f"from {wrapper_class.__module__} import {wrapper_class.__name__}")
        return f"{wrapper_class.__name__}"

    if type_name.startswith(package):
        parts = type_name.lstrip(package).lstrip(".").split(".")
        if len(parts) == 1 or (len(parts) > 1
                               and parts[0][0] == parts[0][0].upper()):
            # This is the current package, which has nested types flattened.
            # foo.bar_thing => FooBarThing
            cased = [stringcase.pascalcase(part) for part in parts]
            type_name = f'"{"".join(cased)}"'

    if "." in type_name:
        # This is imported from another package. No need
        # to use a forward ref and we need to add the import.
        parts = type_name.split(".")
        parts[-1] = stringcase.pascalcase(parts[-1])
        imports.add(f"from .{'.'.join(parts[:-2])} import {parts[-2]}")
        type_name = f"{parts[-2]}.{parts[-1]}"

    return type_name
Beispiel #7
0
 def _get_reference_parts(self, reference) -> dict:
     assert('#' in reference), "Reference '{}' seemed malformed".format(reference)
     url, path = reference.split('#')
     theType, name = path.split('/')[-2:]
     return {
         "url": url,
         "uri": url,
         "path": path,
         "type": theType,
         "PascalType": stringcase.pascalcase(theType),
         "name": name,
         "PascalName": stringcase.pascalcase(name),
         "snake_name": stringcase.snakecase(name),
         "pkg": url is not None and url.split(".")[0] or None,
     }
Beispiel #8
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
Beispiel #9
0
def create_transform(project, module_name):

    transform_name = stringcase.pascalcase(module_name)
    module_name = module_name.lower()

    target = project.root_dir
    transform_directory = project.transforms_dir

    if os.path.exists(os.path.join(transform_directory,
                                   '%s.py' % module_name)):
        click.echo('Transform %r already exists... quitting' % module_name,
                   err=True)
        exit(-1)

    variables = parse_config(os.path.join(target, '.mrbob.ini'))['variables']

    variables.update({
        'transform.module': module_name,
        'transform.name': transform_name
    })

    configurator = Configurator('canari.resources.templates:create_transform',
                                target, {'non_interactive': True},
                                variables=variables)

    configurator.ask_questions()

    click.echo('Creating transform %r...' % module_name, err=True)
    configurator.render()

    click.echo('done!', err=True)
Beispiel #10
0
 def custom_objects(self):
     return {
         pascalcase(self._preprocessing_layer.name):
         self._preprocessing_layer,
         'FrozenBatchNormalization':
         self._patch_keras_layers().BatchNormalization
     }
def import_data(data, session):
    """
    Import employee data into the database using the given session object.

    :param data: Employee data to import, see ``employee_data``
    :param session: SQLAlchemy session object
    """
    items = []

    for table_name, table_data in data.items():

        table_name_singular = inflect.singular_noun(table_name)
        table_name_pascal = stringcase.pascalcase(table_name_singular)

        factory = globals()[table_name_pascal]
        items += [
            # construct an instance of the Model, ignoring id columns since
            # these are auto incremented in the database.
            factory(
                **{
                    name: value
                    for name, value in construct_args.items()
                    # don't add primary key
                    if name != table_name_singular + '_id'
                }) for construct_args in table_data
        ]

    session.add_all(items)
    session.flush()
    session.commit()
Beispiel #12
0
 def jni_getter(self):
     """
     static native int jniOptionsGetVersion(long optionsPtr);
     public int getVersion() {
         return jniOptionsGetVersion(getRawPointer());
     }
     """
     if self.is_payload:
         return f"/** SKIPPED (setter) {self.fsig}*/\n"
     sub_class_reminder = f"//TODO: moved to {self.sub_obj_pc}\n" if self.sub_obj_pc else ""
     ret_obj_pc = stringcase.pascalcase(self.c_type.replace("git_", "", 1))
     return (
         f"/**{self.fsig}*/\n"
         f"static native {self.java_type} jni{self.sub_obj_pc}Get{self.var_pc}(long {self.c_sub_obj}Ptr);\n"
         f"{sub_class_reminder}"
         f"public {self.obj_pc}.{self.sub_obj_pc} get{self.var_pc}() {{\n"
         f"    return new {ret_obj_pc}(true, jni{self.sub_obj_pc}Get{self.var_pc}(getRawPointer()));\n"
         f"}}\n"
     ) if self.is_weak else (
         f"/**{self.fsig}*/\n"
         f"static native {self.java_type} jni{self.sub_obj_pc}Get{self.var_pc}(long {self.c_sub_obj}Ptr);\n"
         f"{sub_class_reminder}"
         f"public {self.java_type} get{self.var_pc}() {{\n"
         f"    return jni{self.sub_obj_pc}Get{self.var_pc}(getRawPointer());\n"
         f"}}\n"
     )
def from_command_str(command: str) -> AbcCommand:
    try:
        commandClass = importlib.import_module('src.commands.' + command)
        return getattr(commandClass, pascalcase(command))
    except Exception as e:
        print(e)
        return None
Beispiel #14
0
    def as_class_name(self,
                      classname: Optional[str],
                      parent_name: Optional[str] = None) -> Optional[str]:
        """ This method formulates a class name from the given arguments,
        applying formatting according to config.
        """
        if classname is None or len(classname) == 0:
            return None

        classmap = self.generator_config.mapping_rules.classmap

        if parent_name is not None:
            # if we have a parent, do we have a mapped class?
            pathname = f"{parent_name}.{classname}"
            if pathname in classmap:
                return classmap[pathname]

        # is our plain class mapped?
        if classname in classmap:
            return classmap[classname]

        # CamelCase or just plain
        if self.generator_config.naming_rules.camelcase_classes:
            return stringcase.pascalcase(classname)  # upper camelcase
        return classname
Beispiel #15
0
    def __init__(self,
                 source_path: str,
                 save_path: str,
                 training_file_name: str,
                 testing_file_name: str,
                 split_ratio: float = 0.2,
                 convert_type: str = "hdf5",
                 name_handler: str = 'common_name_handler'):
        """
        Initial data related information.
        :param source_path: source path
        :param save_path: target path
        :param training_file_name: training file name, will delete '.h5' if exist, and append '_001'...'_999' if file
        number exceed one_file_limit.
        :param testing_file_name: same as training file name. if training_file_name same as testing_file_name, then will
        append to the same file.
        :param convert_type: current only option is "hdf5"
        :param split_ratio: split ratio for testing 0.2
        :param name_handler: customized file name parser. Because the keys in the target file are based on different
        Nifti name patterns or other reference files, you need to customize how to store the Nifti file in H5.
        """
        self.source_path = source_path
        self.save_path = save_path
        os.makedirs(save_path, exist_ok=True)
        self.training_file_name = training_file_name.replace(".h5", "")
        self.testing_file_name = testing_file_name.replace(".h5", "")
        self.convert_type = convert_type
        self.split_ratio = split_ratio

        module_ = importlib.import_module("preprocess.misc." + name_handler)

        self.name_handler = getattr(module_,
                                    stringcase.pascalcase(name_handler))

        self.acceptable_file_format = re.compile(r'\.nii\.gz$')
Beispiel #16
0
 def GenerateServers(self, spec, url):
     genFiles = GeneratedFiles()
     if 'servers' in spec:
         for serverName, serverObj in spec['servers'].items():
             path = "{}#/servers/{}".format(url, serverName)
             headerFilename = self.resolver.cpp_get_header(path)
             sourceFilename = "{}.cpp".format(
                 self.resolver.cpp_get_filename_base(path))
             name = stringcase.pascalcase(stringcase.snakecase(serverName))
             self.srcGenerator.render_template(
                 template_name="broker.cpp.jinja2",
                 output_name=sourceFilename,
                 usings=self.resolver.cpp_get_usings(),
                 ns=self.namespace,
                 resolver=self.resolver,
                 includes=[headerFilename],
                 Name=name,
                 server=serverObj)
             genFiles += GeneratedFiles(cppFile=sourceFilename)
             self.headerGenerator.render_template(
                 template_name="broker.hpp.jinja2",
                 output_name=headerFilename,
                 ns=self.namespace,
                 resolver=self.resolver,
                 Name=name,
                 server=serverObj)
             genFiles += GeneratedFiles(hppFile=headerFilename)
     return genFiles
Beispiel #17
0
async def sync_report_interval(client, account_id, report_stream,
                               start_date, end_date):
    state_key = '{}_{}'.format(account_id, report_stream.stream)
    report_name = stringcase.pascalcase(report_stream.stream)

    report_schema = get_report_schema(client, report_name)
    singer.write_schema(report_stream.stream, report_schema, [])

    report_time = arrow.get().isoformat()

    request_id = get_report_request_id(client, account_id, report_stream,
                                       report_name, start_date, end_date,
                                       state_key)

    singer.write_bookmark(STATE, state_key, 'request_id', request_id)
    singer.write_state(STATE)

    download_url = await poll_report(client, report_name, start_date, end_date,
                                     request_id)

    if download_url:
        LOGGER.info('Streaming report: {} for account {} - from {} to {}'.format(
            report_name,
            account_id,
            start_date,
            end_date))

        stream_report(report_stream.stream,
                      report_name,
                      download_url,
                      report_time)
        singer.write_bookmark(STATE, state_key, 'request_id', None)
        singer.write_bookmark(STATE, state_key, 'date', end_date.isoformat())

    singer.write_state(STATE)
 def _default_service_configuration(self):
     cwd = basename(getcwd())
     return {
         u'ecr_repo': {
             u'name': spinalcase("{}-repo".format(cwd)),
         },
         u'service_role_arn': None,
         u'services': {
             pascalcase(self.service_name): {
                 u'http_interface': {
                     u'internal': False,
                     u'alb': {
                         u'create_new': True,
                     },
                     u'restrict_access_to': [u'0.0.0.0/0'],
                     u'container_port': 80,
                     u'health_check_path': u'/elb-check',
                     u'load_balancing_algorithm': DEFAULT_LOAD_BALANCING_ALGORITHM,
                     u'deregistration_delay': DEFAULT_TARGET_GROUP_DEREGISTRATION_DELAY
                 },
                 u'secrets_name': spinalcase("{}-{}".format(self.service_name, self.environment)),
                 u'system_controls': [],
                 u'memory_reservation': 1000,
                 u'command': None,
                 u'task_arn': None,
                 u'task_execution_arn': None,
             }
         }
     }
Beispiel #19
0
def get_class(
    class_name: Union[str, Type],
    module_name: str = None,
    scope: dict = None,
    allow_nonstandard_names=False,
) -> Type:
    """Imports and creates a class object for the given class name"""
    if not isinstance(class_name, str):
        return class_name
    modules: List[str] = []
    if module_name is not None:
        modules = module_name.split(".")
    modules += class_name.split(".")
    if len(modules) < 1:
        raise ValueError(
            f"Cannot get the class {class_name} in module {module_name}  (modules {modules})"
        )
    if not class_name.startswith("builtins") or allow_nonstandard_names:
        class_name = stringcase.pascalcase(modules[-1])
    else:
        class_name = modules[-1]
    if len(modules) < 2:
        return eval(class_name, scope)
    module_name = ".".join(modules[:-1])
    module = importlib.import_module(module_name)
    return getattr(module, class_name)
Beispiel #20
0
 def __getattr__(self, item: str):
     """Accessor to help get morphosyntatic features from a word object."""
     feature_name = sc.pascalcase(item)
     if feature_name in ud_mod.__dict__:
         return self.features[feature_name]
     else:
         raise AttributeError(item)
Beispiel #21
0
    def convertCase(self, data):
        txt = self.txtInput.text()
        result = txt

        if data == 'Alpha Num Case':
            result = stringcase.alphanumcase(txt)
        if data == 'Camel Case':
            result = stringcase.camelcase(txt)
        if data == 'Capital Case':
            result = stringcase.capitalcase(txt)
        if data == 'Const Case':
            result = stringcase.constcase(txt)
        if data == 'Lower Case':
            result = stringcase.lowercase(txt)
        if data == 'Pascal Case':
            result = stringcase.pascalcase(txt)
        if data == 'Path Case':
            result = stringcase.pathcase(txt)
        if data == 'Sentence Case':
            result = stringcase.sentencecase(txt)
        if data == 'Snake Case':
            result = stringcase.snakecase(txt)
        if data == 'Spinal Case':
            result = stringcase.spinalcase(txt)
        if data == 'Title Case':
            result = stringcase.titlecase(txt)
        if data == 'Trim Case':
            result = stringcase.trimcase(txt)
        if data == 'Upper Case':
            result = stringcase.uppercase(txt)

        self.lblResult.setText(result)
        pyperclip.copy(result)
Beispiel #22
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'
Beispiel #23
0
async def sync_report_interval(client, account_id, report_stream,
                               start_date, end_date):
    state_key = '{}_{}'.format(account_id, report_stream.stream)
    report_name = stringcase.pascalcase(report_stream.stream)

    report_schema = get_report_schema(client, report_name)
    singer.write_schema(report_stream.stream, report_schema, [])

    report_time = arrow.get().isoformat()

    request_id = get_report_request_id(client, account_id, report_stream,
                                       report_name, start_date, end_date,
                                       state_key)

    singer.write_bookmark(STATE, state_key, 'request_id', request_id)
    singer.write_state(STATE)

    try:
        success, download_url = await poll_report(client, account_id, report_name,
                                                  start_date, end_date, request_id)

    except Exception as some_error:
        LOGGER.info('The request_id %s for %s is invalid, generating a new one',
                    request_id,
                    state_key)
        request_id = get_report_request_id(client, account_id, report_stream,
                                           report_name, start_date, end_date,
                                           state_key, force_refresh=True)

        singer.write_bookmark(STATE, state_key, 'request_id', request_id)
        singer.write_state(STATE)

        success, download_url = await poll_report(client, account_id, report_name,
                                                  start_date, end_date, request_id)

    if success and download_url:
        LOGGER.info('Streaming report: {} for account {} - from {} to {}'
                    .format(report_name, account_id, start_date, end_date))

        stream_report(report_stream.stream,
                      report_name,
                      download_url,
                      report_time)
        singer.write_bookmark(STATE, state_key, 'request_id', None)
        singer.write_bookmark(STATE, state_key, 'date', end_date.isoformat())
        singer.write_state(STATE)
        return True
    elif success and not download_url:
        LOGGER.info('No data for report: {} for account {} - from {} to {}'
                    .format(report_name, account_id, start_date, end_date))
        singer.write_bookmark(STATE, state_key, 'request_id', None)
        singer.write_bookmark(STATE, state_key, 'date', end_date.isoformat())
        singer.write_state(STATE)
        return True
    else:
        LOGGER.info('Unsuccessful request for report: {} for account {} - from {} to {}'
                    .format(report_name, account_id, start_date, end_date))
        singer.write_bookmark(STATE, state_key, 'request_id', None)
        singer.write_state(STATE)
        return False
Beispiel #24
0
def make_init_text(name):
    init_text = '''
from skybeard.beards import BeardChatHandler
from skybeard.decorators import onerror
from skybeard.utils import get_args


class {beardclassname}(BeardChatHandler):

    __userhelp__ = """Default help message."""

    __commands__ = [
        # command, callback coro, help text
        ("echo", 'echo', 'Echos arguments. e.g. <code>/echo [arg1 [arg2 ... ]]</code>')
    ]

    # __init__ is implicit

    @onerror()
    async def echo(self, msg):
        args = get_args(msg)
        if args:
            await self.sender.sendMessage("Args: {{}}".format(args))
        else:
            await self.sender.sendMessage("No arguments given.")

    '''.strip().format(beardclassname=stringcase.pascalcase(name))

    return init_text
Beispiel #25
0
 def __init__(self, obj: dict, base_name: str):
     try:
         self._iterator = [None]
         self._functions = {}
         if obj is not None:
             iterator = obj['list']
             if isinstance(iterator, str):
                 self._iterator = eval(iterator)
             elif isinstance(iterator, list):
                 self._iterator = iterator
             else:
                 raise Exception(
                     'Malformed generator list {0}'.format(iterator))
             if 'module' in obj:
                 self._module = obj['module']
                 self._args = {'base_name': base_name}
                 if 'args' in obj:
                     self._args.update(obj['args'])
                 class_name = stringcase.pascalcase(self._module)
                 module = __import__(self._module)
                 _class = getattr(module, class_name)
                 self._instance = _class(self._args)
                 class_objs = dir(self._instance)
                 self._functions = {}
                 for c_obj in class_objs:
                     attr = getattr(self._instance, c_obj)
                     if not c_obj.startswith('_') and callable(attr):
                         self._functions[c_obj] = attr
     except Exception as ex:
         pass
 def _get_reference_parts(self, reference) -> tuple:
     pkg = None
     fn = reference.split('#')[0] or None
     path = reference.split('#')[1]
     parts = path.split('/')
     if fn:
         pkg = fn.split('.')[0]
     return (pkg, parts[-2], stringcase.pascalcase(parts[-1]))
Beispiel #27
0
    def __init__(self, name, fields, context):

        self.package = context.package
        self.name = 'OneOf{}'.format(stringcase.pascalcase(name))
        self.fqn = '{}.{}'.format(context.fqn, self.name)
        self.include_path = context.include_path

        self.fields = [Field(f, context) for f in fields]
Beispiel #28
0
    def __init__(self, name, fields, context):

        self.package = context.package
        self.name = 'OneOf{}'.format(stringcase.pascalcase(name))
        self.fqn = '{}.{}'.format(context.fqn, self.name)
        self.include_path = context.include_path

        self.fields = [Field(f, context) for f in fields]
Beispiel #29
0
    def __init__(self, fsig: str, clazz: str):
        """
        Initialize with object name

        for example: `git_checkout_options checkout_opts` is parsed to:
        - c_obj = {str} 'clone'
        - c_sub_obj = {str} 'options'
        - c_type = {str} 'git_checkout_options '
        - c_var = {str} 'checkout_opts'
        - fsig = {str} 'git_checkout_options checkout_opts'
        - java_type = {str} 'long'
        - jtype = {str} 'jlong'
        - obj_cc = {str} 'clone'
        - obj_pc = {str} 'Clone'
        - sub_obj_cc = {str} 'options'
        - sub_obj_pc = {str} 'Options'
        - var_cc = {str} 'checkoutOpts'
        - var_pc = {str} 'CheckoutOpts'
        """
        splits = clazz.split(".")
        obj_name = splits[0]
        sub_obj_name = splits[-1] if len(splits) > 1 else ""
        self.c_obj = obj_name
        self.c_sub_obj = sub_obj_name
        # InitOptions
        self.obj_pc = stringcase.pascalcase(self.c_obj)
        self.sub_obj_pc = stringcase.pascalcase(self.c_sub_obj)
        # initOptions
        self.obj_cc = stringcase.camelcase(self.c_obj)
        self.sub_obj_cc = stringcase.camelcase(self.c_sub_obj)

        self.group_dict = dict(obj_name=obj_name)
        fsig = fsig.strip().rstrip(";")
        self.fsig = fsig
        sx = [m.end() for m in re.finditer(r'[ *]', fsig)][-1]
        self.c_var = fsig[sx:]
        self.c_type = fsig[:sx].strip()  # unsigned int
        self.jtype = get_jtype(self.c_type)  # jint
        self.java_type = get_java_type(self.jtype)  # int
        # CheckoutOpts
        self.var_pc = stringcase.pascalcase(self.c_var)
        # checkoutOpts
        self.var_cc = stringcase.camelcase(self.c_var)
        self.is_weak = is_returnning_weak(self.c_type, self.jtype)
        self.is_cb = "_cb" in self.fsig
        self.is_payload = "payload" in self.fsig
def prepare_renderer(configurator):
    configurator = base_prepare_renderer(configurator)
    configurator.variables['template_id'] = 'behavior'
    behavior_name = configurator.variables['behavior_name'].strip('_')
    configurator.variables['behavior_name_klass'] = stringcase.pascalcase(
        behavior_name)
    configurator.variables['behavior_name_normalized'] = stringcase.snakecase(  # NOQA: E501
        behavior_name)
    configurator.target_directory = configurator.variables['package_folder']
Beispiel #31
0
def generate_enums_cs(core_api: munch.Munch) -> None:
    """Replaces the code in the Enums.cs file"""
    line_blocks = []

    # Normal enums
    for enum, elems in core_api.enums.items():
        name_prefix = ''
        if enum == 'error_code':
            values = range(0, -len(elems), -1)
        elif enum == 'verbosity':
            values = range(-1, len(elems) - 1)
        elif enum == 'http_status':
            name_prefix = 'Http'
            values = elems.keys()
        else:
            values = range(len(elems))

        lines = []
        for val, (name, comment) in zip(values, elems.items()):
            lines += [
                f'', f'        /// <summary>{comment}</summary>',
                f'        {name_prefix}{stringcase.pascalcase(str(name).lower())} = {val},'
            ]

        line_blocks += [lines]

    # Flags
    for enum, flags in core_api.flags.items():
        lines = []
        for name, props in flags.items():
            lines += ['']

            # Help text
            if '\n' in props.help:
                lines += [f'        /// <summary>']
                for comment_line in props.help.rstrip().split('\n'):
                    lines += [f'        /// {comment_line}']
                lines += [f'        /// </summary>']
            else:
                lines += [f'        /// <summary>{props.help}</summary>']

            # Code line
            line = f'        {stringcase.pascalcase(name.lower())} = '
            if 'bit' in props:
                line += '0' if props.bit is None else f'1 << {props.bit}'
            else:
                line += ' | '.join(
                    [stringcase.pascalcase(x.lower()) for x in props.combine])

            lines += [f'{line},']

        line_blocks += [lines]

    for block_idx, lines in enumerate(line_blocks):
        replace_block_in_file('yogi-dotnet/yogi/Enums.cs',
                              lines + [''],
                              block_idx=block_idx)
def generate_cpp_header(python_enum: Enum):
    name = python_enum.__name__
    with open(name + '.h', 'w') as f:
        f.write('#pragma once\n')
        f.write('\n')
        f.write('enum class ' + name + '\n')
        f.write('{')
        enum_strings = []
        for element in python_enum:
            enum_strings.append('\n	' + pascalcase(element.name) + ' = ' + str(element.value))
        f.write(','.join(enum_strings))
        f.write('\n};\n')
    def test_pascalcase(self):
        from stringcase import pascalcase

        eq = self.assertEqual

        eq('FooBar', pascalcase('foo_bar'))
        eq('FooBar', pascalcase('foo-bar'))
        eq('FooBar', pascalcase('foo.bar'))
        eq('BarBaz', pascalcase('_bar_baz'))
        eq('BarBaz', pascalcase('.bar_baz'))
        eq('', pascalcase(''))
        eq('None', pascalcase(None))
Beispiel #34
0
def create_widget_class(id, loader):
    (config_path, method_path) = loader.find_widget(id)
    base_class = type_from_config(config_path)
    if base_class == UtilityWidget:
        typing = class_from_config(id, method_path)
    else:
        description = description_from_config(config_path)
        inputs = inputs_from_config(config_path)
        typing = type(pascalcase(id),
                      (base_class,),
                      {
                          "__init__": __init__,
                          "description": description,
                          "inputs": inputs,
                          "method_path": method_path
                      })
    return typing
Beispiel #35
0
    def __init__(self, oneof_name, oneof_fields, context):
        self.name = oneof_name

        # Some booleans to describe the type
        self.one_of = True
        self.type = 'OneOf{}'.format(stringcase.pascalcase(self.name))
        self.fqn = '{}.{}'.format(context.fqn, self.type)
        self.default_value = '{}()'.format(self.type)

        self.map_type = False
        self.repeated = False
        self.pointer = False
        self.array_size = 0
        self.bytes_type = False
        self.basic = False

        self.oneof_fields = [Field(f, context) for f in oneof_fields]

        # Since our cpp_type is used a lot, precalculate it
        self.cpp_type = self.fqn.replace('.', '::')
        self.special_cpp_type = False
Beispiel #36
0
def type_name_from_config(config_file):
    with open(config_file, 'r') as cfile:
        override_yaml = yaml.safe_load(cfile)
    the_type = pascalcase(override_yaml['type'])
    return the_type
Beispiel #37
0
def class_from_config(id, method_file):
    modes = imp.get_suffixes()
    with open(method_file) as open_mf:
        the_module = imp.load_module('{}.{}'.format(id, id), open_mf, '{}.py'.format(id), modes[-2])
    return getattr(the_module, pascalcase(id))