signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def _load_referenced_schemes_from_list(the_list, val, a_scheme, a_property): | scheme = copy.copy(a_scheme)<EOL>new_list = []<EOL>if isinstance(the_list, list):<EOL><INDENT>for an_item in the_list:<EOL><INDENT>if ((not isinstance(an_item, str)) and<EOL>('<STR_LIT>' in list(an_item.keys()))):<EOL><INDENT>sub_scheme_name = generate_schema_name_from_uri(an_item['<STR_LIT>'])<EOL>content = load_schem... | takes the referenced files and loads them
returns the updated schema
:param the_list:
:param val:
:param a_scheme:
:param a_property:
:return: | f12126:m1 |
def _load_referenced_schema_from_properties(val, a_scheme, a_property): | scheme = copy.copy(a_scheme)<EOL>if _value_properties_are_referenced(val):<EOL><INDENT>ref_schema_uri = val['<STR_LIT>']['<STR_LIT>']<EOL>sub_schema = load_ref_schema(ref_schema_uri)<EOL>sub_schema_copy_level_0 = copy.deepcopy(sub_schema)<EOL>for prop_0 in sub_schema_copy_level_0['<STR_LIT>']:<EOL><INDENT>val_0 = sub_s... | :return: updated scheme | f12126:m2 |
def import_schema_to_json(name, store_it=False): | schema_file = "<STR_LIT>" % name<EOL>file_path = os.path.join(SCHEMA_ROOT, schema_file)<EOL>log.debug("<STR_LIT>" % file_path)<EOL>schema = None<EOL>try:<EOL><INDENT>schema_file = open(file_path, "<STR_LIT:r>").read()<EOL><DEDENT>except IOError as e:<EOL><INDENT>log.error("<STR_LIT>" % e)<EOL>msg = "<STR_LIT>" % file_p... | loads the given schema name
from the local filesystem
and puts it into a store if it
is not in there yet
:param name:
:param store_it: if set to True, stores the contents
:return: | f12126:m3 |
def load_ref_schema(ref_schema_uri): | sub_schema = generate_schema_name_from_uri(ref_schema_uri)<EOL>return import_schema_to_json(sub_schema)<EOL> | loads a referenced schema | f12126:m5 |
def load_schema(name): | schema = import_schema_to_json(name)<EOL>for item in schema['<STR_LIT>']:<EOL><INDENT>href_value = item['<STR_LIT>']<EOL>rel_value = item['<STR_LIT>']<EOL>schema[rel_value] = href_value<EOL>del item<EOL><DEDENT>for prop in schema['<STR_LIT>']:<EOL><INDENT>value = schema['<STR_LIT>'][prop]<EOL>is_type_array = (value['<S... | loads the schema by name
:param name name of the model | f12126:m6 |
def load_schema_raw(name): | json_obj = load_schema(name)<EOL>return json_obj<EOL> | loads the json schema and all referenced schemas
then converts to dict | f12126:m7 |
def resolve_local(self, uri, base_uri, ref): | <EOL>file_path = None<EOL>item_name = None<EOL>if (uri.startswith(u"<STR_LIT:file>") or<EOL>uri.startswith(u"<STR_LIT>")):<EOL><INDENT>if ref.startswith(u"<STR_LIT>"):<EOL><INDENT>ref = ref.split(u"<STR_LIT>")[-<NUM_LIT:1>]<EOL>org_ref = ref<EOL><DEDENT>if ref.find(u"<STR_LIT>") != -<NUM_LIT:1>:<EOL><INDENT>ref = ref.s... | Resolve a local ``uri``.
Does not check the store first.
:argument str uri: the URI to resolve
:returns: the retrieved document | f12127:c0:m0 |
@contextlib.contextmanager<EOL><INDENT>def resolving(self, ref):<DEDENT> | <EOL>full_uri = urljoin(self.resolution_scope, ref)<EOL>uri, fragment = urldefrag(full_uri)<EOL>if not uri:<EOL><INDENT>uri = self.base_uri<EOL><DEDENT>if uri in self.store:<EOL><INDENT>document = self.store[uri]<EOL><DEDENT>else:<EOL><INDENT>if (uri.startswith(u"<STR_LIT:file>") or uri.startswith(u"<STR_LIT>")):<EOL><... | Context manager which resolves a JSON ``ref`` and enters the
resolution scope of this ref.
:argument str ref: reference to resolve | f12127:c0:m1 |
def _value_properties_are_referenced(val): | if ((u'<STR_LIT>' in val.keys()) and<EOL>(u'<STR_LIT>' in val['<STR_LIT>'].keys())):<EOL><INDENT>return True<EOL><DEDENT>return False<EOL> | val is a dictionary
:param val:
:return: True/False | f12128:m0 |
def _value_is_required(val): | if ((u'<STR_LIT>' in val.keys()) and<EOL>(val['<STR_LIT>'] is True)):<EOL><INDENT>return True<EOL><DEDENT>return False<EOL> | val is a dictionary
:param val:
:return: True/False | f12128:m1 |
def _value_is_type_text(val): | if ((u'<STR_LIT:type>' in val.keys()) and<EOL>(val['<STR_LIT:type>'].lower() == u"<STR_LIT:text>")):<EOL><INDENT>return True<EOL><DEDENT>return False<EOL> | val is a dictionary
:param val:
:return: True/False | f12128:m4 |
def validate_format_iso8601(validator, fieldname, value, format_option): | try:<EOL><INDENT>iso8601.parse_date(value)<EOL><DEDENT>except ValueError:<EOL><INDENT>raise ValidationError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % locals())<EOL><DEDENT> | validates the iso8601 format
raises value error if the value for fieldname does not match the format
is iso8601 eg #"2007-06-20T12:34:40+03:00" | f12129:m0 |
def validate_format_text(validator, fieldname, value, format_option): | pass<EOL> | validates format text- always valid | f12129:m1 |
def json_schema_validation_format(value, schema_validation_type): | DEFAULT_FORMAT_VALIDATORS['<STR_LIT>'] = validate_format_iso8601<EOL>DEFAULT_FORMAT_VALIDATORS['<STR_LIT:text>'] = validate_format_text<EOL>validictory.validate(value, schema_validation_type, format_validators=DEFAULT_FORMAT_VALIDATORS)<EOL> | adds iso8601 to the datetimevalidator
raises SchemaError if validation fails | f12129:m2 |
def pluralize(data_type): | known = {<EOL>u"<STR_LIT:address>": u"<STR_LIT>", <EOL>u"<STR_LIT>": u"<STR_LIT>"<EOL>}<EOL>if data_type in known.keys():<EOL><INDENT>return known[data_type]<EOL><DEDENT>else:<EOL><INDENT>return u"<STR_LIT>" % data_type<EOL><DEDENT> | adds s to the data type or the correct english plural form | f12130:m0 |
def remove_properties_containing_None(properties_dict): | <EOL>new_dict = dict()<EOL>for key in properties_dict.keys():<EOL><INDENT>value = properties_dict[key]<EOL>if value is not None:<EOL><INDENT>new_dict[key] = value<EOL><DEDENT><DEDENT>return new_dict<EOL> | removes keys from a dict those values == None
json schema validation might fail if they are set and
the type or format of the property does not match | f12130:m1 |
def dict_to_object(d): | top = type('<STR_LIT>', (object,), d)<EOL>seqs = tuple, list, set, frozenset<EOL>for i, j in d.items():<EOL><INDENT>if isinstance(j, dict):<EOL><INDENT>setattr(top, i, dict_to_object(j))<EOL><DEDENT>elif isinstance(j, seqs):<EOL><INDENT>setattr(top, i, type(j)(dict_to_object(sj) if isinstance(sj, dict) else sj for sj i... | Recursively converts a dict to an object | f12130:m3 |
def get_collection_instance(klass, api_client = None, request_api=True, **kwargs): | _type = klass<EOL>if api_client is None and request_api:<EOL><INDENT>api_client = api.APIClient()<EOL><DEDENT>if isinstance(klass, dict):<EOL><INDENT>_type = klass['<STR_LIT:type>']<EOL><DEDENT>obj = CollectionResource(_type, api_client, **kwargs)<EOL>return obj <EOL><INDENT>/**<EOL><INDENT>* magic method for ma... | instatiates the collection lookup of json type klass
:param klass: json file name
:param api_client: transportation api
:param request_api: if True uses the default APIClient | f12131:m0 |
def get_sort(self): | return self.sort<EOL> | get sort direction | f12131:c0:m1 |
def get_sort_by(self): | return self.sort_by<EOL> | get sort by | f12131:c0:m2 |
def set_per_page(self, entries=<NUM_LIT:100>): | if isinstance(entries, int) and entries <= <NUM_LIT:200>:<EOL><INDENT>self.per_page = int(entries)<EOL>return self<EOL><DEDENT>else:<EOL><INDENT>raise SalesKingException("<STR_LIT>", "<STR_LIT>");<EOL><DEDENT> | set entries per page max 200 | f12131:c0:m3 |
def get_per_page(self): | return self.per_page<EOL> | get per page | f12131:c0:m4 |
def get_total_entries(self): | return self.total_entries<EOL> | get total entries | f12131:c0:m5 |
def get_total_pages(self): | return self.total_pages<EOL> | get total pages | f12131:c0:m6 |
def get_current_page(self): | return self.current_page<EOL> | current page | f12131:c0:m7 |
def get_items(self): | return self._items<EOL> | :returns all fetched _items (RemoteResource Json classes) | f12131:c0:m8 |
def clear_items(self): | self._items = []<EOL> | empties the items dict | f12131:c0:m9 |
def get_resource_type(self): | return self.resource_type<EOL> | get type to fetch | f12131:c0:m10 |
def set_resource_type(self, klass): | self.resource_type = klass<EOL>self.schema = loaders.load_schema_raw(self.resource_type)<EOL> | set type to load and load schema | f12131:c0:m11 |
def set_filters(self, filters): | if not isinstance(filters, dict):<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>self.filters = {}<EOL>for key in list(filters.keys()):<EOL><INDENT>value = filters[key]<EOL>self.add_filter(key,value)<EOL><DEDENT> | set and validate filters dict | f12131:c0:m12 |
def add_filter(self, key, filter_value): | seek = "<STR_LIT>" % key<EOL>if self.validate_filter(key, filter_value):<EOL><INDENT>self.filters[key] = filter_value<EOL>return True<EOL><DEDENT>else:<EOL><INDENT>msg = '<STR_LIT>' % (key, filter_value)<EOL>print(msg)<EOL>raise SalesKingException("<STR_LIT>", msg )<EOL><DEDENT> | add and validate a filter with value
returns True on success otherwise exception | f12131:c0:m13 |
def _is_type(self, instance, type): | if type not in self._types:<EOL><INDENT>raise UnknownType(type)<EOL><DEDENT>type = self._types[type]<EOL>if isinstance(instance, bool):<EOL><INDENT>type = _flatten(type)<EOL>if int in type and bool not in type:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return isinstance(instance, type)<EOL> | Check if an ``instance`` is of the provided (JSON Schema) ``type``. | f12131:c0:m14 |
def validate_filter(self, key, filter_value): | ok = False<EOL>seek = "<STR_LIT>" % key<EOL>value = None<EOL>for link in self.schema['<STR_LIT>']:<EOL><INDENT>if link['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>for property in link['<STR_LIT>']:<EOL><INDENT>if seek == property:<EOL><INDENT>value = link['<STR_LIT>'][property]<EOL>ok = True<EOL><DEDENT><DEDENT><DEDENT><D... | validate the filter key and value against the collection schema
:param key: property name
:param filter_value: value of the filter
:returns True if all is ok otherwise False | f12131:c0:m15 |
def _validate_json_format(self, filter_value, schema_validation_type): | ok = False<EOL>try:<EOL><INDENT>validators.json_schema_validation_format(filter_value, schema_validation_type)<EOL>ok = True<EOL><DEDENT>except ValueError as e:<EOL><INDENT>pass<EOL><DEDENT>return ok<EOL> | adds the type:string format:schema_validation_type
:param filter_value: value of the filter
:param schema_validation_type: format description of the json schema entry | f12131:c0:m16 |
def _build_query_url(self, page = None, verbose = False): | query = []<EOL><INDENT>for afilter in self.filters.keys():<EOL><INDENT>value = self.filters[afilter]<EOL>print"<STR_LIT>" % (afilter,value)<EOL>value = urlencode(value)<EOL>query_str = u"<STR_LIT>" % (afilter, value)<EOL><DEDENT><DEDENT>if len(self.filters) > <NUM_LIT:0>:<EOL><INDENT>query.append(urlencode(self.filters... | builds the url to call | f12131:c0:m18 |
def get_list_endpoint(self, rel="<STR_LIT>"): | schema_loaded = not self.schema is None<EOL>links_present = "<STR_LIT>" in list(self.schema.keys())<EOL>if (schema_loaded and links_present):<EOL><INDENT>for row in self.schema['<STR_LIT>']:<EOL><INDENT>if row['<STR_LIT>'] == rel:<EOL><INDENT>return row<EOL><DEDENT><DEDENT><DEDENT>raise APIException("<STR_LIT>","<STR_L... | get the configured list entpoint for the schema.type
:param rel: lookup rel: value inside the links section
:returns the value
:raises APIException | f12131:c0:m19 |
def _post_load(self, response, verbose): | try:<EOL><INDENT>if verbose:<EOL><INDENT>print(response.content)<EOL><DEDENT>log.debug(response.content)<EOL><DEDENT>except Exception as e:<EOL><INDENT>raise e<EOL><DEDENT>if response is not None and response.status_code == <NUM_LIT:200>:<EOL><INDENT>types = helpers.pluralize(self.resource_type)<EOL>body = json.loads(r... | post load processing
fills the self._items collection | f12131:c0:m21 |
def _response_item_to_object(self, resp_item): | item_cls = resources.get_model_class(self.resource_type)<EOL>properties_dict = resp_item[self.resource_type]<EOL>new_dict = helpers.remove_properties_containing_None(properties_dict)<EOL>obj = item_cls(new_dict)<EOL>return obj<EOL> | take json and make a resource out of it | f12131:c0:m22 |
def load(self, page = None, verbose=False): | url = self._build_query_url(page, verbose)<EOL>response = self._load(url, verbose)<EOL>response = self._post_load(response, verbose)<EOL>return response<EOL> | call to execute the collection loading
:param page: integer of the page to load
:param verbose: boolean to print to console
:returns response
:raises the SalesKingException | f12131:c1:m0 |
def _load(self, url, verbose): | msg = "<STR_LIT>" % url<EOL>self._last_query_str = url<EOL>log.debug(msg)<EOL>if verbose:<EOL><INDENT>print(msg)<EOL><DEDENT>response = self.__api__.request(url)<EOL>return response<EOL> | Execute a request against the Salesking API to fetch the items
:param url: url to fetch
:return response
:raises SaleskingException with the corresponding http errors | f12131:c1:m1 |
def request(self, url, method = u"<STR_LIT>", data = None, headers = None, **kwargs): | url, method, data, headers, kwargs = self._pre_request(url, <EOL>method=method,<EOL>data=data,<EOL>headers=headers,<EOL>**kwargs)<EOL>response = self._request(url, method=method, data=data, headers=headers, **kwargs)<EOL>response = self._post_request(response)<EOL>response = self._handle_response(response)<EOL>return r... | public method for doing the live request | f12133:c0:m3 |
def _pre_request(self, url, method = u"<STR_LIT>", data = None, headers=None, **kwargs): | return (url, method, data, headers, kwargs)<EOL> | hook for manipulating the _pre request data | f12133:c0:m4 |
def _post_request(self, response): | <EOL>return response<EOL> | hook for post request handling | f12133:c0:m6 |
def _handle_response(self,response): | return response<EOL> | hook for hanlding the response | f12133:c0:m7 |
def _pre_request(self, url, method = u"<STR_LIT>", data = None, headers=None, **kwargs): | header = {<EOL>u"<STR_LIT:Content-Type>": u"<STR_LIT:application/json>",<EOL>u"<STR_LIT>": u"<STR_LIT>",<EOL>}<EOL>if headers:<EOL><INDENT>headers.update(header)<EOL><DEDENT>else:<EOL><INDENT>headers = header<EOL><DEDENT>if url.find(self.base_url) !=<NUM_LIT:0>:<EOL><INDENT>url = u"<STR_LIT>" %(self.base_url, url)<EOL>... | hook for manipulating the _pre request data | f12133:c1:m0 |
def _request(self, url, method = u"<STR_LIT>", data = None, headers=None, **kwargs): | <EOL>msg = "<STR_LIT>" % (<EOL>method, url, headers, data)<EOL>if not self.use_oauth:<EOL><INDENT>auth = (self.sk_user, self.sk_pw)<EOL>if not self.client:<EOL><INDENT>self.client = requests.session()<EOL><DEDENT>r = self.client.request(method, url, headers=headers, data=data, auth=auth,**kwargs)<EOL><DEDENT>else:<EOL>... | does the request via requests
- oauth not implemented yet
- use basic auth please | f12133:c1:m1 |
def _handle_response(self, response): | status = response.status_code<EOL>if status == <NUM_LIT>:<EOL><INDENT>msg = u"<STR_LIT>"<EOL>raise exceptions.BadRequest(status, msg)<EOL><DEDENT>elif status == <NUM_LIT>:<EOL><INDENT>msg = u"<STR_LIT>" % (self.sk_user)<EOL>raise exceptions.Unauthorized(status, msg)<EOL><DEDENT>elif status == <NUM_LIT>:<EOL><INDENT>rai... | internal method to throw the correct exception if something went wrong | f12133:c1:m2 |
@abc.abstractmethod<EOL><INDENT>def read(self, address=<NUM_LIT:0>, count=<NUM_LIT:0>):<DEDENT> | return bytes()<EOL> | Returns a *number* of bytes read from a data `source` beginning at
the start *address*.
:param int address: start address.
:param int count: number of bytes to read from a data `source`.
.. note:: This abstract method must be implemented by a derived class. | f12137:c0:m0 |
@abc.abstractmethod<EOL><INDENT>def write(self, buffer=bytes(), address=<NUM_LIT:0>, count=<NUM_LIT:0>):<DEDENT> | pass<EOL> | Writes the content of the *buffer* to a data `source` beginning
at the start *address*.
:param bytes buffer: content to write.
:param int address: start address.
:param int count: number of bytes to write to a data `source`.
.. note:: This abstract method must be implemented by... | f12137:c0:m1 |
@property<EOL><INDENT>def cache(self):<DEDENT> | return self._cache<EOL> | Returns the internal byte stream cache of the `Provider` (read-only). | f12137:c1:m3 |
def read(self, address=<NUM_LIT:0>, count=<NUM_LIT:0>): | return self._cache[address:]<EOL> | Returns a *number* of bytes read from the :attr:`cache` beginning
at the start *address*.
:param int address: start address.
:param int count: number of bytes to read from the cache. | f12137:c1:m4 |
def write(self, buffer=bytes(), address=<NUM_LIT:0>, count=<NUM_LIT:0>): | view = memoryview(self._cache)<EOL>view[address:address + count] = buffer<EOL> | Writes the content of the *buffer* to the :attr:`cache` beginning
at the start *address*.
:param bytes buffer: content to write.
:param int address: start address.
:param int count: number of bytes to write to the cache. | f12137:c1:m5 |
def flush(self, file=str()): | if file:<EOL><INDENT>Path(file).write_bytes(self._cache)<EOL><DEDENT>else:<EOL><INDENT>self.path.write_bytes(self._cache)<EOL><DEDENT> | Flushes the updated file content to the given *file*.
.. note:: Overwrites an existing file.
:param str file: name and location of the file.
Default is the original file. | f12137:c1:m6 |
def clamp(value, minimum, maximum): | return min(max(value, minimum), maximum)<EOL> | Returns the *value* limited between *minimum* and *maximum*
whereby the *maximum* wins over the *minimum*.
Example:
>>> clamp(64, 0, 255)
64
>>> clamp(-128, 0, 255)
0
>>> clamp(0, 127, -128)
-128 | f12138:m0 |
def byte_order_option(default=BYTEORDER): | def decorator(method):<EOL><INDENT>@wraps(method)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>option = Option.byte_order.value<EOL>kwargs[option] = kwargs.get(option, default)<EOL>return method(*args, **kwargs)<EOL><DEDENT>return wrapper<EOL><DEDENT>return decorator<EOL> | Attaches the option ``byte_order`` with its *default* value to the
keyword arguments, when the option does not exist. All positional
arguments and keyword arguments are forwarded unchanged. | f12139:m0 |
def nested_option(default=False): | def decorator(method):<EOL><INDENT>@wraps(method)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>option = Option.nested.value<EOL>kwargs[option] = kwargs.get(option, bool(default))<EOL>return method(*args, **kwargs)<EOL><DEDENT>return wrapper<EOL><DEDENT>return decorator<EOL> | Attaches the option ``nested`` with its *default* value to the
keyword arguments when the option does not exist. All positional
arguments and keyword arguments are forwarded unchanged. | f12139:m2 |
def verbose_option(default=False): | def decorator(method):<EOL><INDENT>@wraps(method)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>option = Option.verbose.value<EOL>kwargs[option] = kwargs.get(option, bool(default))<EOL>return method(*args, **kwargs)<EOL><DEDENT>return wrapper<EOL><DEDENT>return decorator<EOL> | Attaches the option ``verbose`` with its *default* value to the
keyword arguments when the option does not exist. All positional
arguments and keyword arguments are forwarded unchanged. | f12139:m4 |
def __str__(self): | return "<STR_LIT>".format(self)<EOL> | Return str(self).
Example:
>>> class Format(Category):
... hour = 'hh'
... minute = 'mm'
... second = 'ss'
>>> str(Format.hour)
'(hour, hh)' | f12141:c0:m0 |
def __repr__(self): | return self.__class__.__name__ + "<STR_LIT>".format(self)<EOL> | Return repr(self). See help(type(self)) for accurate signature.
Example:
>>> class Format(Category):
... hour = 'hh'
... minute = 'mm'
... second = 'ss'
>>> repr(Format.hour)
"Format.hour = 'hh'" | f12141:c0:m1 |
def describe(self): | return self.name, self.value<EOL> | Returns the `name`, `value` pair to describe a specific `Category` member.
Example:
>>> class Format(Category):
... hour = 'hh'
... minute = 'mm'
... second = 'ss'
>>> Format.hour.describe()
('hour', 'hh') | f12141:c0:m2 |
@classmethod<EOL><INDENT>def names(cls):<DEDENT> | return [member.name for member in cls]<EOL> | Returns a list of the member `names` of a `Category`.
Example:
>>> class Format(Category):
... hour = 'hh'
... minute = 'mm'
... second = 'ss'
>>> Format.names()
['hour', 'minute', 'second'] | f12141:c0:m3 |
@classmethod<EOL><INDENT>def values(cls):<DEDENT> | return [member.value for member in cls]<EOL> | Returns a list of the member `values` of a `Category`.
Example:
>>> class Format(Category):
... hour = 'hh'
... minute = 'mm'
... second = 'ss'
>>> Format.values()
['hh', 'mm', 'ss'] | f12141:c0:m4 |
@classmethod<EOL><INDENT>def get_name(cls, value):<DEDENT> | for member in cls:<EOL><INDENT>if member.value == value:<EOL><INDENT>return member.name<EOL><DEDENT><DEDENT>return str()<EOL> | Returns the `name` of the `Category` member with the matching *value*
or a empty string if no member match.
Example:
>>> class Format(Category):
... hour = 'hh'
... minute = 'mm'
... second = 'ss'
>>> Format.get_name('hh')
'hour'
>>> ... | f12141:c0:m5 |
@classmethod<EOL><INDENT>def get_value(cls, name):<DEDENT> | for member in cls:<EOL><INDENT>if member.name == name:<EOL><INDENT>return member.value<EOL><DEDENT><DEDENT>return None<EOL> | Returns the `value` of the `Category` member with the matching *name*
or `None` if no member match.
Example:
>>> class Format(Category):
... hour = 'hh'
... minute = 'mm'
... second = 'ss'
>>> Format.get_value('hour')
'hh'
>>> Format.... | f12141:c0:m6 |
@classmethod<EOL><INDENT>def get_member(cls, value, default=None):<DEDENT> | for member in cls:<EOL><INDENT>if member.value == value:<EOL><INDENT>return member<EOL><DEDENT><DEDENT>return default<EOL> | Returns the first `Category` member with the matching *value*
or the specified *default* value if no member match.
Example:
>>> class Format(Category):
... hour = 'hh'
... minute = 'mm'
... second = 'ss'
>>> Format.get_member('hh')
Format.ho... | f12141:c0:m7 |
def __str__(self): | return "<STR_LIT>".format(self)<EOL> | Return str(self).
Example:
>>> class Color(Enumeration):
... black = 0x000000
... maroon = 0x080000
... white = 0xffffff
>>> str(Color.maroon)
'(maroon, 524288)' | f12143:c0:m0 |
def __repr__(self): | return self.__class__.__name__ + "<STR_LIT>".format(self)<EOL> | Return repr(self). See help(type(self)) for accurate signature.
Example:
>>> class Color(Enumeration):
... black = 0x000000
... maroon = 0x080000
... white = 0xffffff
>>> repr(Color.maroon)
'Color.maroon = 524288' | f12143:c0:m1 |
def describe(self): | return self.name, self.value<EOL> | Returns the `name`, `value` pair to describe a specific `Enumeration` member.
Example:
>>> class Color(Enumeration):
... black = 0x000000
... maroon = 0x080000
... white = 0xffffff
>>> Color.maroon.describe()
('maroon', 524288) | f12143:c0:m2 |
@classmethod<EOL><INDENT>def names(cls):<DEDENT> | return [member.name for member in cls]<EOL> | Returns a list of the member `names` of a `Enumeration`.
Example:
>>> class Color(Enumeration):
... black = 0x000000
... maroon = 0x080000
... white = 0xffffff
>>> Color.names()
['black', 'maroon', 'white'] | f12143:c0:m3 |
@classmethod<EOL><INDENT>def values(cls):<DEDENT> | return [member.value for member in cls]<EOL> | Returns a list of the member `values` of a `Enumeration`.
Example:
>>> class Color(Enumeration):
... black = 0x000000
... maroon = 0x080000
... white = 0xffffff
>>> Color.values()
[0, 524288, 16777215] | f12143:c0:m4 |
@classmethod<EOL><INDENT>def get_name(cls, value):<DEDENT> | for member in cls:<EOL><INDENT>if member.value == value:<EOL><INDENT>return member.name<EOL><DEDENT><DEDENT>return str()<EOL> | Returns the `name` of the `Enumeration` member with the matching *value*
or an empty string if no member match.
Example:
>>> class Color(Enumeration):
... black = 0x000000
... maroon = 0x080000
... white = 0xffffff
>>> Color.get_name(0xffffff)
... | f12143:c0:m5 |
@classmethod<EOL><INDENT>def get_value(cls, name):<DEDENT> | for member in cls:<EOL><INDENT>if member.name == name:<EOL><INDENT>return member.value<EOL><DEDENT><DEDENT>return None<EOL> | Returns the `value` of the `Enumeration` member with the matching *name*
or `None` if no member match.
Example:
>>> class Color(Enumeration):
... black = 0x000000
... maroon = 0x080000
... white = 0xffffff
>>> Color.get_value('white')
1677721... | f12143:c0:m6 |
@classmethod<EOL><INDENT>def get_member(cls, value, default=None):<DEDENT> | for member in cls:<EOL><INDENT>if member.value == value:<EOL><INDENT>return member<EOL><DEDENT><DEDENT>return default<EOL> | Returns the first `Enumeration` member with the matching *value*
or the specified *default* value if no member match.
Example:
>>> class Color(Enumeration):
... black = 0x000000
... maroon = 0x080000
... white = 0xffffff
>>> Color.get_member(0)
... | f12143:c0:m7 |
@abc.abstractmethod<EOL><INDENT>def view_fields(self, *attributes, **options):<DEDENT> | return<EOL> | Returns a container with the selected field *attribute* or with the
dictionary of the selected field *attributes* for each :class:`Field`
*nested* in the `Container`.
The *attributes* of each :class:`Field` for containers *nested* in the
`Container` are viewed as well (chained method ca... | f12145:c1:m0 |
@nested_option()<EOL><INDENT>def to_json(self, *attributes, **options):<DEDENT> | nested = options.pop('<STR_LIT>', False)<EOL>fieldnames = options.pop('<STR_LIT>', attributes)<EOL>if '<STR_LIT>' in options.keys():<EOL><INDENT>return json.dumps(self.view_fields(*attributes,<EOL>nested=nested,<EOL>fieldnames=fieldnames),<EOL>**options)<EOL><DEDENT>else:<EOL><INDENT>return json.dumps(self.view_fields(... | Returns the selected field *attributes* for each :class:`Field` *nested*
in the `Container` as a JSON formatted string.
The *attributes* of each :class:`Field` for containers *nested* in the
`Container` are viewed as well (chained method call).
:param str attributes: selected :class:`F... | f12145:c1:m1 |
@abc.abstractmethod<EOL><INDENT>def field_items(self, path=str(), **options):<DEDENT> | return list()<EOL> | Returns a **flatten** list of ``('field path', field item)`` tuples
for each :class:`Field` *nested* in the `Container`.
:param str path: item path.
:keyword bool nested: if ``True`` all :class:`Pointer` fields in the
:attr:`~Pointer.data` objects of all :class:`Pointer` fields in
... | f12145:c1:m2 |
@nested_option()<EOL><INDENT>def to_list(self, *attributes, **options):<DEDENT> | <EOL>name = options.pop('<STR_LIT:name>', self.__class__.__name__)<EOL>fields = list()<EOL>if attributes:<EOL><INDENT>field_getter = attrgetter(*attributes)<EOL><DEDENT>else:<EOL><INDENT>field_getter = attrgetter('<STR_LIT:value>')<EOL><DEDENT>for item in self.field_items(**options):<EOL><INDENT>field_path, field = ite... | Returns a **flatten** list of ``('field path', attribute)`` or
``('field path', tuple(attributes))`` tuples for each :class:`Field`
*nested* in the `Container`.
:param str attributes: selected :class:`Field` attributes.
Fallback is the field :attr:`~Field.value`.
:keyword st... | f12145:c1:m3 |
@nested_option()<EOL><INDENT>def to_dict(self, *attributes, **options):<DEDENT> | <EOL>name = options.pop('<STR_LIT:name>', self.__class__.__name__)<EOL>save = options.pop('<STR_LIT>', False)<EOL>fields = OrderedDict()<EOL>fields[name] = OrderedDict()<EOL>if attributes:<EOL><INDENT>field_getter = attrgetter(*attributes)<EOL><DEDENT>else:<EOL><INDENT>field_getter = attrgetter('<STR_LIT:value>')<EOL><... | Returns a **flatten** :class:`ordered dictionary <collections.OrderedDict>`
of ``{'field path': attribute}`` or ``{'field path': tuple(attributes)}``
pairs for each :class:`Field` *nested* in the `Container`.
:param str attributes: selected :class:`Field` attributes.
Fallback is the... | f12145:c1:m4 |
@nested_option()<EOL><INDENT>def to_csv(self, *attributes, **options):<DEDENT> | keys = self._get_fieldnames(*attributes, **options)<EOL>options['<STR_LIT>'] = True<EOL>return [dict(zip(keys, field)) for field in<EOL>self.to_list(*attributes, **options)]<EOL> | Returns a **flatten** list of dictionaries containing the field *path*
and the selected field *attributes* for each :class:`Field` *nested* in the
`Container`.
:param str attributes: selected :class:`Field` attributes.
Fallback is the field :attr:`~Field.value`.
:keyword str... | f12145:c1:m6 |
@nested_option()<EOL><INDENT>def write_csv(self, file, *attributes, **options):<DEDENT> | with open(file, '<STR_LIT:w>', newline='<STR_LIT>') as file_handle:<EOL><INDENT>fieldnames = self._get_fieldnames(*attributes, **options)<EOL>writer = csv.DictWriter(file_handle, fieldnames)<EOL>writer.writeheader()<EOL>for row in self.to_csv(*attributes, **options):<EOL><INDENT>writer.writerow(row)<EOL><DEDENT><DEDENT... | Writes the field *path* and the selected field *attributes* for each
:class:`Field` *nested* in the `Container` to a ``.csv`` *file*.
:param str file: name and location of the ``.csv`` *file*.
:param str attributes: selected :class:`Field` attributes.
Fallback is the field :attr:`~... | f12145:c1:m7 |
@nested_option()<EOL><INDENT>def save(self, file, *attributes, **options):<DEDENT> | options['<STR_LIT>'] = True<EOL>parser = ConfigParser()<EOL>parser.read_dict(self.to_dict(*attributes, **options))<EOL>with open(file, '<STR_LIT:w>') as file_handle:<EOL><INDENT>parser.write(file_handle)<EOL><DEDENT>file_handle.close()<EOL> | Saves the selected field *attributes* for each :class:`Field` *nested*
in the `Container` to an ``.ini`` *file*.
:param str file: name and location of the ``.ini`` *file*.
:param str attributes: selected :class:`Field` attributes.
Fallback is the field :attr:`~Field.value`.
... | f12145:c1:m8 |
@nested_option()<EOL><INDENT>@verbose_option(True)<EOL>def load(self, file, **options):<DEDENT> | section = options.pop('<STR_LIT>', self.__class__.__name__)<EOL>parser = ConfigParser()<EOL>parser.read(file)<EOL>if parser.has_section(section):<EOL><INDENT>verbose(options, "<STR_LIT>".format(section))<EOL>for field_path, field in self.field_items(**options):<EOL><INDENT>if field_path.startswith('<STR_LIT:[>'):<EOL><... | Loads the field *value* for each :class:`Field` *nested* in the
`Container` from an ``.ini`` *file*.
:param str file: name and location of the ``.ini`` *file*.
:keyword str section: section in the ``.ini`` *file* to lookup the
value for each :class:`Field` in the `Container`.
... | f12145:c1:m9 |
def __getattr__(self, name): | <EOL>if name.startswith('<STR_LIT>'):<EOL><INDENT>return super().__getattribute__(name)<EOL><DEDENT>try:<EOL><INDENT>return self[name]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise AttributeError("<STR_LIT>".format(<EOL>self.__class__.__name__, name))<EOL><DEDENT> | Returns the :class:`Field` of the `Structure` member whose dictionary key
is equal to the *name*.
If the attribute *name* is in the namespace of the `Ordered Dictionary`
base class then the base class is called instead.
The `__getattr__` method is only called when the method
`_... | f12145:c2:m4 |
def __setattr__(self, name, item): | <EOL>if name.startswith('<STR_LIT>'):<EOL><INDENT>return super().__setattr__(name, item)<EOL><DEDENT>elif is_any(item):<EOL><INDENT>self[name] = item<EOL><DEDENT>elif callable(item):<EOL><INDENT>setitem = item()<EOL>if is_any(setitem):<EOL><INDENT>super().__setitem__(name, setitem)<EOL><DEDENT>else:<EOL><INDENT>raise F... | Assigns the *item* to the member of the `Structure` whose dictionary
key is equal to the *name*.
If the attribute *name* is in the namespace of the `Ordered Dictionary`
base class then the base class is called instead. | f12145:c2:m5 |
@nested_option()<EOL><INDENT>def read_from(self, provider, **options):<DEDENT> | for item in self.values():<EOL><INDENT>if is_mixin(item):<EOL><INDENT>item.read_from(provider, **options)<EOL><DEDENT><DEDENT> | All :class:`Pointer` fields in the `Structure` read the necessary
number of bytes from the data :class:`Provider` for their referenced
:attr:`~Pointer.data` object. Null pointer are ignored.
:param Provider provider: data :class:`Provider`.
:keyword bool nested: if ``True`` all :class:`... | f12145:c2:m6 |
@byte_order_option()<EOL><INDENT>@nested_option()<EOL>def deserialize(self, buffer=bytes(), index=Index(), **options):<DEDENT> | for item in self.values():<EOL><INDENT>index = item.deserialize(buffer, index, **options)<EOL><DEDENT>return index<EOL> | De-serializes the `Structure` from the byte *buffer* starting at
the begin of the *buffer* or with the given *index* by mapping the
bytes to the :attr:`~Field.value` for each :class:`Field` in the
`Structure` in accordance with the decoding *byte order* for the
de-serialization and the d... | f12145:c2:m7 |
@byte_order_option()<EOL><INDENT>@nested_option()<EOL>def serialize(self, buffer=bytearray(), index=Index(), **options):<DEDENT> | for item in self.values():<EOL><INDENT>index = item.serialize(buffer, index, **options)<EOL><DEDENT>return index<EOL> | Serializes the `Structure` to the byte *buffer* starting at begin
of the *buffer* or with the given *index* by mapping the
:attr:`~Field.value` for each :class:`Field` in the `Structure` to the
byte *buffer* in accordance with the encoding *byte order* for the
serialization and the encod... | f12145:c2:m8 |
@nested_option()<EOL><INDENT>def index_fields(self, index=Index(), **options):<DEDENT> | for name, item in self.items():<EOL><INDENT>if is_container(item):<EOL><INDENT>index = item.index_fields(index, **options)<EOL><DEDENT>elif is_pointer(item) and get_nested(options):<EOL><INDENT>index = item.index_field(index)<EOL>item.index_data()<EOL><DEDENT>elif is_field(item):<EOL><INDENT>index = item.index_field(in... | Indexes all fields in the `Structure` starting with the given
*index* and returns the :class:`Index` after the last :class:`Field`
in the `Structure`.
:param Index index: start :class:`Index` for the first :class:`Field`
in the `Structure`.
:keyword bool nested: if ``True`` ... | f12145:c2:m9 |
def container_size(self): | length = <NUM_LIT:0><EOL>for name, item in self.items():<EOL><INDENT>if is_container(item):<EOL><INDENT>byte_length, bit_length = item.container_size()<EOL>length += bit_length + byte_length * <NUM_LIT:8><EOL><DEDENT>elif is_field(item):<EOL><INDENT>length += item.bit_size<EOL><DEDENT>else:<EOL><INDENT>raise MemberType... | Returns the accumulated bit size of all fields in the `Structure` as
a tuple in the form of ``(number of bytes, remaining number of bits)``. | f12145:c2:m10 |
def first_field(self): | for name, item in self.items():<EOL><INDENT>if is_container(item):<EOL><INDENT>field = item.first_field()<EOL>if field is not None:<EOL><INDENT>return field<EOL><DEDENT><DEDENT>elif is_field(item):<EOL><INDENT>return item<EOL><DEDENT>else:<EOL><INDENT>raise MemberTypeError(self, item, name)<EOL><DEDENT><DEDENT>return N... | Returns the first :class:`Field` in the `Structure` or ``None``
for an empty `Structure`. | f12145:c2:m11 |
def initialize_fields(self, content): | for name, value in content.items():<EOL><INDENT>item = self[name]<EOL>if is_mixin(item):<EOL><INDENT>item.initialize_fields(value)<EOL><DEDENT>elif is_field(item):<EOL><INDENT>item.value = value<EOL><DEDENT>else:<EOL><INDENT>raise MemberTypeError(self, item, name)<EOL><DEDENT><DEDENT> | Initializes the :class:`Field` members in the `Structure` with
the *values* in the *content* dictionary.
:param dict content: a dictionary contains the :class:`Field`
values for each member in the `Structure`. | f12145:c2:m12 |
@nested_option()<EOL><INDENT>def view_fields(self, *attributes, **options):<DEDENT> | members = OrderedDict()<EOL>for name, item in self.items():<EOL><INDENT>if is_container(item):<EOL><INDENT>members[name] = item.view_fields(*attributes, **options)<EOL><DEDENT>elif is_pointer(item) and get_nested(options):<EOL><INDENT>members[name] = item.view_fields(*attributes, **options)<EOL><DEDENT>elif is_field(it... | Returns an :class:`ordered dictionary <collections.OrderedDict>` which
contains the ``{'member name': field attribute}`` or the
``{'member name': dict(field attributes)}`` pairs for each :class:`Field`
*nested* in the `Structure`.
The *attributes* of each :class:`Field` for containers *... | f12145:c2:m13 |
@nested_option()<EOL><INDENT>def field_items(self, path=str(), **options):<DEDENT> | parent = path if path else str()<EOL>items = list()<EOL>for name, item in self.items():<EOL><INDENT>item_path = '<STR_LIT>'.format(parent, name) if parent else name<EOL>if is_container(item):<EOL><INDENT>for field in item.field_items(item_path, **options):<EOL><INDENT>items.append(field)<EOL><DEDENT><DEDENT>elif is_poi... | Returns a **flatten** list of ``('field path', field item)`` tuples
for each :class:`Field` *nested* in the `Structure`.
:param str path: field path of the `Structure`.
:keyword bool nested: if ``True`` all :class:`Pointer` fields in the
:attr:`~Pointer.data` objects of all :class:`... | f12145:c2:m14 |
@nested_option(True)<EOL><INDENT>def describe(self, name=str(), **options):<DEDENT> | members = list()<EOL>metadata = OrderedDict()<EOL>metadata['<STR_LIT:class>'] = self.__class__.__name__<EOL>metadata['<STR_LIT:name>'] = name if name else self.__class__.__name__<EOL>metadata['<STR_LIT:size>'] = len(self)<EOL>metadata['<STR_LIT:type>'] = self.item_type.name<EOL>metadata['<STR_LIT>'] = members<EOL>for m... | Returns the **metadata** of the `Structure` as an
:class:`ordered dictionary <collections.OrderedDict>`.
.. code-block:: python
metadata = {
'class': self.__class__.__name__,
'name': name if name else self.__class__.__name__,
'size': len(self... | f12145:c2:m15 |
def append(self, item): | if not is_any(item):<EOL><INDENT>raise MemberTypeError(self, item, member=len(self))<EOL><DEDENT>self._data.append(item)<EOL> | Appends the *item* to the end of the `Sequence`.
:param item: any :class:`Structure`, :class:`Sequence`, :class:`Array`
or :class:`Field` instance. | f12145:c3:m10 |
def insert(self, index, item): | if not is_any(item):<EOL><INDENT>raise MemberTypeError(self, item, member=len(self))<EOL><DEDENT>self._data.insert(index, item)<EOL> | Inserts the *item* before the *index* into the `Sequence`.
:param int index: `Sequence` index.
:param item: any :class:`Structure`, :class:`Sequence`, :class:`Array`
or :class:`Field` instance. | f12145:c3:m11 |
def pop(self, index=-<NUM_LIT:1>): | return self._data.pop(index)<EOL> | Removes and returns the item at the *index* from the `Sequence`.
:param int index: `Sequence` index. | f12145:c3:m12 |
def clear(self): | self._data.clear()<EOL> | Remove all items from the `Sequence`. | f12145:c3:m13 |
def remove(self, item): | self._data.remove(item)<EOL> | Removes the first occurrence of an *item* from the `Sequence`.
:param item: any :class:`Structure`, :class:`Sequence`, :class:`Array`
or :class:`Field` instance. | f12145:c3:m14 |
def reverse(self): | self._data.reverse()<EOL> | In place reversing of the `Sequence` items. | f12145:c3:m15 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.