Create example for response, from object structure

        :param def_name: --deffinition name of structure
        :type def_name: str, unicode
        :return: example of object
        :rtype: dict
195154
def get_object_example(self, def_name):
        '''
        
        '''
        def_model = self.definitions[def_name]
        example = dict()
        for opt_name, opt_value in def_model.get('properties', dict()).items():
            var_type = opt_value.get('format', None) or opt_value.get('type', None)
            example[opt_name] = self.get_response_example(opt_name, var_type, opt_value)
            if var_type == 'string':
                example[opt_name] = example[opt_name].format(opt_name)
        return example
807692
def get_response_structure(name):
        
        return {
            CreateContextName.SMB2_CREATE_DURABLE_HANDLE_REQUEST:
                SMB2CreateDurableHandleResponse(),
            CreateContextName.SMB2_CREATE_DURABLE_HANDLE_RECONNECT:
                SMB2CreateDurableHandleReconnect(),
            CreateContextName.SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST:
                SMB2CreateQueryMaximalAccessResponse(),
            CreateContextName.SMB2_CREATE_REQUEST_LEASE:
                SMB2CreateResponseLease(),
            CreateContextName.SMB2_CREATE_QUERY_ON_DISK_ID:
                SMB2CreateQueryOnDiskIDResponse(),
            CreateContextName.SMB2_CREATE_REQUEST_LEASE_V2:
                SMB2CreateResponseLeaseV2(),
            CreateContextName.SMB2_CREATE_DURABLE_HANDLE_REQUEST_V2:
                SMB2CreateDurableHandleResponseV2(),
            CreateContextName.SMB2_CREATE_DURABLE_HANDLE_RECONNECT_V2:
                SMB2CreateDurableHandleReconnectV2,
            CreateContextName.SMB2_CREATE_APP_INSTANCE_ID:
                SMB2CreateAppInstanceId(),
            CreateContextName.SMB2_CREATE_APP_INSTANCE_VERSION:
                SMB2CreateAppInstanceVersion()

        }.get(name, None)
45859
def get_structdmtypes_for_python_typeorobject(typeorobj):
    
    # not isinstance is probably a bit more lenient than 'is'
    # ie isinstance(x,str) is nicer than type(x) is str.
    # hence we use isinstance when available
    if isinstance(typeorobj, type):
        comparer = lambda test: test is typeorobj
    else:
        comparer = lambda test: isinstance(typeorobj, test)

    if comparer(int) and not -2**31 < typeorobj < 2**31 - 1:
        return 'q', 11

    for key, name, sc, types in dm_simple_names:
        for t in types:
            if comparer(t):
                return sc, key
    if comparer(str):
        return None, get_dmtype_for_name('array')  # treat all strings as arrays!
    elif comparer(unicode_type):
        return None, get_dmtype_for_name('array')  # treat all strings as arrays!
    elif comparer(array.array):
        return None, get_dmtype_for_name('array')
    elif comparer(tuple):
        return None, get_dmtype_for_name('struct')
    elif comparer(structarray):
        return None, get_dmtype_for_name('array')
    logging.warn("No appropriate DMType found for %s, %s", typeorobj, type(typeorobj))
    return None
911019
def _attribute_definition(self, attrid):
        
        attrs = self._schema["attributes"]

        try:
            # Make a new dict to avoid side effects
            return dict(attrs[attrid])
        except KeyError:
            attr_names = self._schema["attribute_names"]
            attrdef = attrs.get(attr_names.get(str(attrid).lower()))

            if not attrdef:
                return None
            else:
                return dict(attrdef)
1182255
def instance(cls, name):
        
        if not cls._instance.get(name):
            model_name = name.split('.')
            ins_name = '.'.join(
                ['models', model_name[0], 'model', model_name[1]])
            cls._instance[name] = cls.import_model(ins_name)()

        return cls._instance[name]
95906
def str_def(self):
        
        return "classname={!r}; line={!r}; column={!r}; message={!r};". \
            format(self.__class__.__name__, self.line, self.column,
                   self.args[0])
903509
def create_from_name_and_dictionary(self, name, datas):
        
        parameter = ObjectParameter()
        self.set_common_datas(parameter, name, datas)

        if "optional" in datas:
            parameter.optional = to_boolean(datas["optional"])
        if "type" in datas:
            parameter.type = str(datas["type"])
        if "generic" in datas:
            parameter.generic = to_boolean(datas["generic"])

        return parameter
531562
def varnames(func):
    
    cache = getattr(func, "__dict__", {})
    try:
        return cache["_varnames"]
    except KeyError:
        pass

    if inspect.isclass(func):
        try:
            func = func.__init__
        except AttributeError:
            return (), ()
    elif not inspect.isroutine(func):  # callable object?
        try:
            func = getattr(func, "__call__", func)
        except Exception:
            return ()

    try:  # func MUST be a function or method here or we won't parse any args
        spec = _getargspec(func)
    except TypeError:
        return (), ()

    args, defaults = tuple(spec.args), spec.defaults
    if defaults:
        index = -len(defaults)
        args, defaults = args[:index], tuple(args[index:])
    else:
        defaults = ()

    # strip any implicit instance arg
    # pypy3 uses "obj" instead of "self" for default dunder methods
    implicit_names = ("self",) if not _PYPY3 else ("self", "obj")
    if args:
        if inspect.ismethod(func) or (
            "." in getattr(func, "__qualname__", ()) and args[0] in implicit_names
        ):
            args = args[1:]

    try:
        cache["_varnames"] = args, defaults
    except TypeError:
        pass
    return args, defaults
1046099
def as_dict(self):
        

        output_dictionary = dict()

        for attribute_name, type_instance in inspect.getmembers(self):

            if attribute_name.startswith('__') or inspect.ismethod(type_instance):
                continue

            if isinstance(type_instance, bool):
                output_dictionary[attribute_name] = type_instance
            elif isinstance(type_instance, self.__class__):
                output_dictionary[attribute_name] = type_instance.as_dict()

        return output_dictionary
291856
def __response_message_descriptor(self, message_type, method_id):
    

    # Skeleton response descriptor, common to all response objects
    descriptor = {'200': {'description': 'A successful response'}}

    if message_type != message_types.VoidMessage():
      self.__parser.add_message(message_type.__class__)
      self.__response_schema[method_id] = self.__parser.ref_for_message_type(
          message_type.__class__)
      descriptor['200']['schema'] = {'$ref': '#/definitions/{0}'.format(
          self.__response_schema[method_id])}

    return dict(descriptor)
1132711
def _example_from_allof(self, prop_spec):
        
        example_dict = {}
        for definition in prop_spec['allOf']:
            update = self.get_example_from_prop_spec(definition, True)
            example_dict.update(update)
        return example_dict
447011
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'examples' in _dict:
            args['examples'] = [
                TrainingExample._from_dict(x) for x in (_dict.get('examples'))
            ]
        return cls(**args)
427622
def to_example(dictionary):
  """"""
  features = {}
  for (k, v) in six.iteritems(dictionary):
    if not v:
      raise ValueError("Empty generated field: %s" % str((k, v)))
    if isinstance(v[0], six.integer_types):
      features[k] = tf.train.Feature(int64_list=tf.train.Int64List(value=v))
    elif isinstance(v[0], float):
      features[k] = tf.train.Feature(float_list=tf.train.FloatList(value=v))
    elif isinstance(v[0], six.string_types):
      if not six.PY2:  # Convert in python 3.
        v = [bytes(x, "utf-8") for x in v]
      features[k] = tf.train.Feature(bytes_list=tf.train.BytesList(value=v))
    elif isinstance(v[0], bytes):
      features[k] = tf.train.Feature(bytes_list=tf.train.BytesList(value=v))
    else:
      raise ValueError("Value for %s is not a recognized type; v: %s type: %s" %
                       (k, str(v[0]), str(type(v[0]))))
  return tf.train.Example(features=tf.train.Features(feature=features))
459765
def get_structure_from_name(self, structure_name):
        
        return next((st for st in self.structures if st.name == structure_name), None)
1157536
def make_instance_to_initdict(attributes: List[str]) -> InstanceToDictFnType:
    
    def custom_instance_to_initdict(x: Instance) -> InitDict:
        kwargs = {}
        for a in attributes:
            kwargs[a] = getattr(x, a)
        return kwargs_to_initdict(kwargs)

    return custom_instance_to_initdict
1307043
def get_response_example(cls, operation, response):
        
        path = "#/paths/'{}'/{}/responses/{}".format(
            operation.path, operation.method, response.name)
        kwargs = dict(paths=[path])

        if response.type in PRIMITIVE_TYPES:
            result = cls.get_example_value_for_primitive_type(
                response.type, response.properties, response.type_format, **kwargs)
        else:
            schema = SchemaObjects.get(response.type)
            result = cls.get_example_by_schema(schema, **kwargs)

        return result
1251562
def describe(cls) -> None:
        
        max_lengths = []
        for attr_name in cls.attr_names():
            attr_func = "%ss" % attr_name
            attr_list = list(map(str, getattr(cls, attr_func)())) + [attr_name]
            max_lengths.append(max(list(map(len, attr_list))))
        row_format = "{:>%d} | {:>%d} | {:>%d}" % tuple(max_lengths)
        headers = [attr_name.capitalize() for attr_name in cls.attr_names()]
        header_line = row_format.format(*headers)
        output = "Class: %s\n" % cls.__name__
        output += header_line + "\n"
        output += "-"*(len(header_line)) + "\n"
        for item in cls:
            format_list = [str(getattr(item, attr_name))
                           for attr_name in cls.attr_names()]
            output += row_format.format(*format_list) + "\n"
        print(output)