Ejemplo n.º 1
0
    def get_description(self, path: _t.Text, method: _t.Text) -> _t.Text:
        # pylint: disable=simplifiable-if-statement,redefined-outer-name
        method_name: _t.Text = getattr(self.view, 'action', method.lower())
        method_obj: _t.Optional[_t.Callable] = getattr(self.view, method_name, None)
        method_view: _t.Optional[_t.Type[rvs.APIView]] = (
            getattr(method_obj, '_nested_view', None)
            if method_obj else None
        )

        if method_obj.__doc__:
            return method_obj.__doc__.strip()
        if not method_view:
            return super().get_description(path, method)

        method_view_obj = method_view()
        action = path.split('/')[-2]
        submethod = getattr(method_view, action, None)
        if submethod.__doc__:
            return str(submethod.__doc__).strip()  # nocv
        if method == 'GET' and '{' not in path[:-1].split('/')[-1]:
            action = 'list'
        elif method == 'POST':
            action = 'create'
        elif method == 'GET':
            action = 'retrieve'
        elif method == 'PUT':
            action = 'update'
        elif method == 'PATCH':
            action = 'partial_update'
        elif method == 'DELETE':
            action = 'destroy'
        method_view_obj.action = action  # type: ignore
        if method_view_obj.schema is None:
            return 'No description'  # nocv
        return method_view_obj.schema.get_description(path, method)  # type: ignore
Ejemplo n.º 2
0
 def parse_image_path(image_path: t.Text,
                      prefix: t.Optional[t.Text] = None) -> DockerImage:
     """ Split benchmark image into name and tag, verify image path points to a valid directory.
     Args:
         image_path: Image path provided by a user, e.g., tensorrt/21.08.
         prefix: Image prefix to use.
     Returns:
         A structure that provides docker image information (prefix, name and tag).
     """
     parts = image_path.split(os.path.sep)
     if len(parts) == 3 and (parts[2] == 'Dockerfile' or parts[2] == ''):
         del parts[2]
     if len(parts) != 2:
         raise ValueError(
             f"Invalid image path ({image_path}). Expecting FRAMEWORK/VERSION."
         )
     full_path = os.path.join(os.path.dirname(__file__), image_path)
     if not os.path.isdir(full_path):
         raise ValueError(
             f"Invalid image path ({image_path}). Not a directory: {full_path}."
         )
     if not os.path.isfile(os.path.join(full_path, 'Dockerfile')):
         raise ValueError(
             f"Invalid image path ({image_path}). Not a file: {os.path.join(full_path, 'Dockerfile')}."
         )
     return DockerImage(prefix, parts[0], parts[1])
Ejemplo n.º 3
0
def _format_spaces(value: typing.Text, context: types.Context):
    "The string is long, try to break it on spaces. And newlines."
    # Break up the content on spaces but retain the
    # spaces so we can also break on newlines
    words = value.split(" ")
    for i in range(len(words) - 1):
        words[i] = words[i] + " "
    # For each word see if we can make a line. Once it's
    # too long we step back and add the line to our results.
    results = []
    line = []
    while words:
        word = words.pop(0)
        # If the line has a newline then gather all the newlines
        # together into a single line and break there.
        newlines_start = word.find("\n")
        newlines_end = newlines_start
        if newlines_start > -1:
            while newlines_end < len(word) and word[newlines_end] == "\n" :
                newlines_end += 1
            # Whatever is left that is not a newline needs to
            # be added back to our stack for processing.
            remainder = word[newlines_end:]
            if remainder:
                words.insert(0, remainder)
            word = word[:newlines_end]
            word = word.replace("\n", r"\n")
            results.append(_make_string_line(line + [word], context.override(indent=0)))
            line = []
            continue
        possible_line = line + [word]
        test_line = _make_string_line(possible_line, context)
        if len(test_line) < context.max_line_length:
            line = possible_line
            continue
        results.append(_make_string_line(line, context.override(indent=0)))
        line = []
        words.insert(0, word)
    if line:
        results.append(_make_string_line(line, context.override(indent=0)))
    content = "\n".join(results)
    return "(\n" + content + "\n)"
    return "{quote}{result}{quote}".format(
        quote=context.quote,
        result=result,
    )
Ejemplo n.º 4
0
    def add_indent_string(self, text: typing.Text) -> typing.Text:
        """Indent a string, if it has newlines.

		This will take a string of the form "(\nfoo,\nbar,\n)"
		and return a string of the form "(\n\tfoo,\n\tbar,\n\t).
		In other words, it will indent all lines but the first.
		This will not indent beyond the current context's indentation
		level.
		"""
        lines = text.split("\n")
        if len(lines) == 1:
            return text
        indented = []
        max_tab = self.tab * self.indent
        for line in lines[1:]:
            if line.startswith(max_tab):
                indented.append(line)
            else:
                indented.append(self.tab + line)
        return lines[0] + "\n" + ("\n".join(indented))
Ejemplo n.º 5
0
    def get_view(self, name: _t.Text, **options):
        # pylint: disable=redefined-outer-name,too-many-statements
        mixin_class: _t.Type[NestedViewMixin] = NestedViewMixin
        if hasattr(self.view, 'create'):
            if self.kwargs.get('allow_append', False):
                mixin_class = NestedWithAppendMixin
            else:
                mixin_class = NestedWithoutAppendMixin

        tp = name.split('_')[-1]
        if tp == 'detail':
            detail = True
        elif tp == 'list':
            detail = False
        else:
            detail = getattr(self.view, options['nested_sub']).detail

        manager_name = self.kwargs.get('manager_name', self.name)
        view_class = utils.get_if_lazy(self.view)

        class NestedView(mixin_class, view_class):  # type: ignore
            __slots__ = ('nested_detail', )  # pylint: disable=class-variable-slots-conflict
            __doc__ = self.view.__doc__
            format_kwarg = None
            queryset_filters = self.queryset_filters

        NestedView.__name__ = self.view.__name__  # type: ignore
        NestedView.nested_detail = detail  # type: ignore

        def nested_view_function_wrapper(view_obj, request, *args, **kwargs):
            kwargs.update(options)
            view_obj.nested_parent_object = view_obj.get_object()
            nested_append_arg = view_obj.nested_append_arg
            nested_request_arg = view_obj.nested_arg
            nested_parent_object = view_obj.nested_parent_object

            if nested_append_arg:
                nested_id = getattr(nested_parent_object, nested_append_arg,
                                    None)
            else:
                nested_id = None

            if callable(manager_name):
                nested_manager = manager_name(nested_parent_object)
            else:
                if hasattr(nested_parent_object, manager_name):
                    nested_manager = getattr(nested_parent_object,
                                             manager_name)
                else:
                    view_manager_function_name = f'get_manager_{manager_name}'
                    nested_manager_func = getattr(view_obj,
                                                  view_manager_function_name)
                    nested_manager = nested_manager_func(nested_parent_object)

            NestedView.__name__ = self.view.__name__
            NestedView.master_view = view_obj
            NestedView.lookup_field = nested_append_arg
            NestedView.lookup_url_kwarg = nested_request_arg
            NestedView.nested_detail = detail
            NestedView.nested_allow_append = view_obj.nested_allow_append
            NestedView.nested_append_arg = nested_append_arg
            NestedView.nested_request_arg = nested_request_arg
            NestedView.nested_parent_object = nested_parent_object
            NestedView.nested_id = nested_id
            NestedView.nested_manager = nested_manager

            getattr(view_obj, 'nested_allow_check',
                    lambda *args, **kwargs: None)()
            return nested_view_function(view_obj, NestedView, request, *args,
                                        **kwargs)

        nested_view_function_wrapper.__name__ = name
        nested_view_function_wrapper.__doc__ = self.view.__doc__
        nested_view_function_wrapper._nested_view = self.view  # type: ignore
        nested_view_function_wrapper._nested_wrapped_view = NestedView  # type: ignore
        return name, nested_view_function_wrapper
Ejemplo n.º 6
0
def recursive_getattr(obj: typing.Any, attributes: typing.Text) -> typing.Any:
    return functools.reduce(getattr, [obj] + attributes.split("."))
def parse_resolution(string: typing.Text) -> typing.Tuple[int, int]:
    [width, height] = string.split('x')
    return (int(width), int(height))