code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
item = build_item(title, key, synonyms, description, img_url) self._items.append(item) return self
def add_item(self, title, key, synonyms=None, description=None, img_url=None)
Adds item to a list or carousel card. A list must contain at least 2 items, each requiring a title and object key. Arguments: title {str} -- Name of the item object key {str} -- Key refering to the item. This string will be used to send a query to your app if selected Keyword Arguments: synonyms {list} -- Words and phrases the user may send to select the item (default: {None}) description {str} -- A description of the item (default: {None}) img_url {str} -- URL of the image to represent the item (default: {None})
3.041522
5.143413
0.591343
endpoint = self._intent_uri() intents = self._get(endpoint) # should be list of dicts if isinstance(intents, dict): # if error: intents = {status: {error}} raise Exception(intents["status"]) return [Intent(intent_json=i) for i in intents]
def agent_intents(self)
Returns a list of intent json objects
6.347395
5.721992
1.109298
endpoint = self._intent_uri(intent_id=intent_id) return self._get(endpoint)
def get_intent(self, intent_id)
Returns the intent object with the given intent_id
5.99659
6.127493
0.978637
endpoint = self._intent_uri() return self._post(endpoint, data=intent_json)
def post_intent(self, intent_json)
Sends post request to create a new intent
6.722007
5.99988
1.120357
endpoint = self._intent_uri(intent_id) return self._put(endpoint, intent_json)
def put_intent(self, intent_id, intent_json)
Send a put request to update the intent with intent_id
4.493506
4.434835
1.01323
endpoint = self._entity_uri() entities = self._get(endpoint) # should be list of dicts if isinstance(entities, dict): # error: entities = {status: {error}} raise Exception(entities["status"]) return [Entity(entity_json=i) for i in entities if isinstance(i, dict)]
def agent_entities(self)
Returns a list of intent json objects
7.076193
6.294916
1.124112
return getattr(current_app, "assist") else: if hasattr(current_app, "blueprints"): blueprints = getattr(current_app, "blueprints") for blueprint_name in blueprints: if hasattr(blueprints[blueprint_name], "assist"): return getattr(blueprints[blueprint_name], "assist")
def find_assistant(): # Taken from Flask-ask courtesy of @voutilad if hasattr(current_app, "assist")
Find our instance of Assistant, navigating Local's and possible blueprints. Note: This only supports returning a reference to the first instance of Assistant found.
2.250631
2.295455
0.980473
if self._route is not None: raise TypeError("route cannot be set when using blueprints!") # we need to tuck our reference to this Assistant instance # into the blueprint object and find it later! blueprint.assist = self # BlueprintSetupState.add_url_rule gets called underneath the covers and # concats the rule string, so we should set to an empty string to allow # Blueprint('blueprint_api', __name__, url_prefix="/assist") to result in # exposing the rule at "/assist" and not "/assist/". blueprint.add_url_rule( "", view_func=self._flask_assitant_view_func, methods=["POST"] )
def init_blueprint(self, blueprint, path="templates.yaml")
Initialize a Flask Blueprint, similar to init_app, but without the access to the application config. Keyword Arguments: blueprint {Flask Blueprint} -- Flask Blueprint instance to initialize (Default: {None}) path {str} -- path to templates yaml file, relative to Blueprint (Default: {'templates.yaml'})
11.293623
11.470909
0.984545
def decorator(f): action_funcs = self._intent_action_funcs.get(intent_name, []) action_funcs.append(f) self._intent_action_funcs[intent_name] = action_funcs self._intent_mappings[intent_name] = mapping self._intent_converts[intent_name] = convert self._intent_defaults[intent_name] = default self._intent_fallbacks[intent_name] = is_fallback self._intent_events[intent_name] = events self._register_context_to_func(intent_name, with_context) @wraps(f) def wrapper(*args, **kw): self._flask_assitant_view_func(*args, **kw) return f return decorator
def action( self, intent_name, is_fallback=False, mapping={}, convert={}, default={}, with_context=[], events=[], *args, **kw )
Decorates an intent_name's Action view function. The wrapped function is called when a request with the given intent_name is recieved along with all required parameters.
2.421673
2.5616
0.945375
def decorator(f): prompts = self._intent_prompts.get(intent_name) if prompts: prompts[next_param] = f else: self._intent_prompts[intent_name] = {} self._intent_prompts[intent_name][next_param] = f @wraps(f) def wrapper(*args, **kw): self._flask_assitant_view_func(*args, **kw) return f return decorator
def prompt_for(self, next_param, intent_name)
Decorates a function to prompt for an action's required parameter. The wrapped function is called if next_param was not recieved with the given intent's request and is required for the fulfillment of the intent's action. Arguments: next_param {str} -- name of the parameter required for action function intent_name {str} -- name of the intent the dependent action belongs to
2.93989
3.201105
0.918398
possible_views = [] for func in self._func_contexts: if self._context_satified(func): logger.debug("{} context conditions satisified".format(func.__name__)) possible_views.append(func) return possible_views
def _context_views(self)
Returns view functions for which the context requirements are met
7.198983
5.459052
1.318724
agent_name = os.path.splitext(filename)[0] try: agent_module = import_with_3( agent_name, os.path.join(os.getcwd(), filename)) except ImportError: agent_module = import_with_2( agent_name, os.path.join(os.getcwd(), filename)) for name, obj in agent_module.__dict__.items(): if isinstance(obj, Assistant): return obj
def get_assistant(filename)
Imports a module from filename as a string, returns the contained Assistant object
2.888824
2.700296
1.069818
annotation = {} annotation['text'] = word annotation['meta'] = '@' + self.entity_map[word] annotation['alias'] = self.entity_map[word].replace('sys.', '') annotation['userDefined'] = True self.data.append(annotation)
def _annotate_params(self, word)
Annotates a given word for the UserSays data field of an Intent object. Annotations are created using the entity map within the user_says.yaml template.
5.61464
4.433954
1.266283
from_app = [] for intent_name in self.assist._intent_action_funcs: intent = self.build_intent(intent_name) from_app.append(intent) return from_app
def app_intents(self)
Returns a list of Intent objects created from the assistant's acion functions
7.001817
4.921211
1.422783
# TODO: contexts is_fallback = self.assist._intent_fallbacks[intent_name] contexts = self.assist._required_contexts[intent_name] events = self.assist._intent_events[intent_name] new_intent = Intent(intent_name, fallback_intent=is_fallback, contexts=contexts, events=events) self.build_action(new_intent) self.build_user_says(new_intent) # TODO return new_intent
def build_intent(self, intent_name)
Builds an Intent object of the given name
4.185387
4.147232
1.0092
params = [] action_func = self.assist._intent_action_funcs[intent_name][0] argspec = inspect.getargspec(action_func) param_entity_map = self.assist._intent_mappings.get(intent_name) args, defaults = argspec.args, argspec.defaults default_map = {} if defaults: default_map = dict(zip(args[-len(defaults):], defaults)) # import ipdb; ipdb.set_trace() for arg in args: param_info = {} param_entity = param_entity_map.get(arg, arg) param_name = param_entity.replace('sys.', '') # param_name = arg param_info['name'] = param_name param_info['value'] = '$' + param_name param_info['dataType'] = '@' + param_entity param_info['prompts'] = [] # TODO: fill in provided prompts param_info['required'] = arg not in default_map param_info['isList'] = isinstance(default_map.get(arg), list) if param_info['isList']: param_info['defaultValue'] = '' else: param_info['defaultValue'] = default_map.get(arg, '') params.append(param_info) return params
def parse_params(self, intent_name)
Parses params from an intent's action decorator and view function. Returns a list of parameter field dicts to be included in the intent object's response field.
2.724226
2.628965
1.036235
if intent.id: print('Updating {} intent'.format(intent.name)) self.update(intent) else: print('Registering {} intent'.format(intent.name)) intent = self.register(intent) return intent
def push_intent(self, intent)
Registers or updates an intent and returns the intent_json with an ID
3.456727
2.886827
1.197414
response = self.api.post_intent(intent.serialize) print(response) print() if response['status']['code'] == 200: intent.id = response['id'] elif response['status']['code'] == 409: # intent already exists intent.id = next(i.id for i in self.api.agent_intents if i.name == intent.name) self.update(intent) return intent
def register(self, intent)
Registers a new intent and returns the Intent object with an ID
3.328871
3.389548
0.982099
response = self.api.post_entity(entity.serialize) print(response) print() if response['status']['code'] == 200: entity.id = response['id'] if response['status']['code'] == 409: # entity already exists entity.id = next(i.id for i in self.api.agent_entities if i.name == entity.name) self.update(entity) return entity
def register(self, entity)
Registers a new entity and returns the entity object with an ID
3.579239
3.614575
0.990224
if entity.id: print('Updating {} entity'.format(entity.name)) self.update(entity) else: print('Registering {} entity'.format(entity.name)) entity = self.register(entity) return entity
def push_entity(self, entity)
Registers or updates an entity and returns the entity_json with an ID
3.2985
2.833425
1.164139
"Updates or creates the current state of an entity." return remote.set_state(self.api, new_state, **kwargs)
def set_state(self, entity_id, new_state, **kwargs)
Updates or creates the current state of an entity.
11.909001
9.240764
1.288746
return remote.is_state(self.api, entity_id, state)
def is_state(self, entity_id, state)
Checks if the entity has the given state
7.923906
7.865745
1.007394
if not isinstance(etag, bytes): etag = bytes(etag, "utf-8") self._etag.append(etag)
def etag(self, etag)
Set the ETag of the resource. :param etag: the ETag
3.392614
5.074652
0.668541
if self._content_type is not None: try: return self._payload[self._content_type] except KeyError: raise KeyError("Content-Type not available") else: if defines.Content_types["text/plain"] in self._payload: return self._payload[defines.Content_types["text/plain"]] else: val = list(self._payload.keys()) return val[0], self._payload[val[0]]
def payload(self)
Get the payload of the resource according to the content type specified by required_content_type or "text/plain" by default. :return: the payload.
3.598774
3.195119
1.126335
if isinstance(p, tuple): k = p[0] v = p[1] self.actual_content_type = k self._payload[k] = v else: self._payload = {defines.Content_types["text/plain"]: p}
def payload(self, p)
Set the payload of the resource. :param p: the new payload
5.736724
6.028771
0.951558
value = "" lst = self._attributes.get("ct") if lst is not None and len(lst) > 0: value = "ct=" for v in lst: value += str(v) + " " if len(value) > 0: value = value[:-1] return value
def content_type(self)
Get the CoRE Link Format ct attribute of the resource. :return: the CoRE Link Format ct attribute
3.463924
3.744362
0.925104
value = [] if isinstance(lst, str): ct = defines.Content_types[lst] self.add_content_type(ct) elif isinstance(lst, list): for ct in lst: self.add_content_type(ct)
def content_type(self, lst)
Set the CoRE Link Format ct attribute of the resource. :param lst: the list of CoRE Link Format ct attribute of the resource
3.862453
3.800148
1.016396
lst = self._attributes.get("ct") if lst is None: lst = [] if isinstance(ct, str): ct = defines.Content_types[ct] lst.append(ct) self._attributes["ct"] = lst
def add_content_type(self, ct)
Add a CoRE Link Format ct attribute to the resource. :param ct: the CoRE Link Format ct attribute
3.844474
4.222329
0.91051
value = "rt=" lst = self._attributes.get("rt") if lst is None: value = "" else: value += "\"" + str(lst) + "\"" return value
def resource_type(self)
Get the CoRE Link Format rt attribute of the resource. :return: the CoRE Link Format rt attribute
8.140729
7.841799
1.03812
if not isinstance(rt, str): rt = str(rt) self._attributes["rt"] = rt
def resource_type(self, rt)
Set the CoRE Link Format rt attribute of the resource. :param rt: the CoRE Link Format rt attribute
5.110593
5.712013
0.89471
value = "if=" lst = self._attributes.get("if") if lst is None: value = "" else: value += "\"" + str(lst) + "\"" return value
def interface_type(self)
Get the CoRE Link Format if attribute of the resource. :return: the CoRE Link Format if attribute
7.788014
9.624703
0.809169
if not isinstance(ift, str): ift = str(ift) self._attributes["if"] = ift
def interface_type(self, ift)
Set the CoRE Link Format if attribute of the resource. :param ift: the CoRE Link Format if attribute
5.045424
5.997358
0.841274
value = "sz=" lst = self._attributes.get("sz") if lst is None: value = "" else: value += "\"" + str(lst) + "\"" return value
def maximum_size_estimated(self)
Get the CoRE Link Format sz attribute of the resource. :return: the CoRE Link Format sz attribute
7.709138
7.988056
0.965083
if not isinstance(sz, str): sz = str(sz) self._attributes["sz"] = sz
def maximum_size_estimated(self, sz)
Set the CoRE Link Format sz attribute of the resource. :param sz: the CoRE Link Format sz attribute
5.841766
5.950768
0.981683
res.location_query = request.uri_query res.payload = (request.content_type, request.payload) return res
def init_resource(self, request, res)
Helper function to initialize a new resource. :param request: the request that generate the new resource :param res: the resource :return: the edited resource
8.732761
10.739907
0.813113
self.location_query = request.uri_query self.payload = (request.content_type, request.payload)
def edit_resource(self, request)
Helper function to edit a resource :param request: the request that edit the resource
10.262617
12.227998
0.839272
if self.cache.currsize == self.cache.maxsize: return True return False
def is_full(self)
:return:
7.542059
5.955699
1.26636
if transaction.request.block2 is not None: host, port = transaction.request.source key_token = hash(str(host) + str(port) + str(transaction.request.token)) num, m, size = transaction.request.block2 if key_token in self._block2_receive: self._block2_receive[key_token].num = num self._block2_receive[key_token].size = size self._block2_receive[key_token].m = m del transaction.request.block2 else: # early negotiation byte = 0 self._block2_receive[key_token] = BlockItem(byte, num, m, size) del transaction.request.block2 elif transaction.request.block1 is not None: # POST or PUT host, port = transaction.request.source key_token = hash(str(host) + str(port) + str(transaction.request.token)) num, m, size = transaction.request.block1 if key_token in self._block1_receive: content_type = transaction.request.content_type if num != self._block1_receive[key_token].num \ or content_type != self._block1_receive[key_token].content_type: # Error Incomplete return self.incomplete(transaction) self._block1_receive[key_token].payload += transaction.request.payload else: # first block if num != 0: # Error Incomplete return self.incomplete(transaction) content_type = transaction.request.content_type self._block1_receive[key_token] = BlockItem(size, num, m, size, transaction.request.payload, content_type) if m == 0: transaction.request.payload = self._block1_receive[key_token].payload # end of blockwise del transaction.request.block1 transaction.block_transfer = False del self._block1_receive[key_token] return transaction else: # Continue transaction.block_transfer = True transaction.response = Response() transaction.response.destination = transaction.request.source transaction.response.token = transaction.request.token transaction.response.code = defines.Codes.CONTINUE.number transaction.response.block1 = (num, m, size) num += 1 byte = size self._block1_receive[key_token].byte = byte self._block1_receive[key_token].num = num self._block1_receive[key_token].size = size self._block1_receive[key_token].m = m return transaction
def receive_request(self, transaction)
Handles the Blocks option in a incoming request. :type transaction: Transaction :param transaction: the transaction that owns the request :rtype : Transaction :return: the edited transaction
2.330567
2.348531
0.992351
host, port = transaction.response.source key_token = hash(str(host) + str(port) + str(transaction.response.token)) if key_token in self._block1_sent and transaction.response.block1 is not None: item = self._block1_sent[key_token] transaction.block_transfer = True if item.m == 0: transaction.block_transfer = False del transaction.request.block1 return transaction n_num, n_m, n_size = transaction.response.block1 if n_num != item.num: # pragma: no cover logger.warning("Blockwise num acknowledged error, expected " + str(item.num) + " received " + str(n_num)) return None if n_size < item.size: logger.debug("Scale down size, was " + str(item.size) + " become " + str(n_size)) item.size = n_size request = transaction.request del request.mid del request.block1 request.payload = item.payload[item.byte: item.byte+item.size] item.num += 1 item.byte += item.size if len(item.payload) <= item.byte: item.m = 0 else: item.m = 1 request.block1 = (item.num, item.m, item.size) elif transaction.response.block2 is not None: num, m, size = transaction.response.block2 if m == 1: transaction.block_transfer = True if key_token in self._block2_sent: item = self._block2_sent[key_token] if num != item.num: # pragma: no cover logger.error("Receive unwanted block") return self.error(transaction, defines.Codes.REQUEST_ENTITY_INCOMPLETE.number) if item.content_type is None: item.content_type = transaction.response.content_type if item.content_type != transaction.response.content_type: # pragma: no cover logger.error("Content-type Error") return self.error(transaction, defines.Codes.UNSUPPORTED_CONTENT_FORMAT.number) item.byte += size item.num = num + 1 item.size = size item.m = m item.payload += transaction.response.payload else: item = BlockItem(size, num + 1, m, size, transaction.response.payload, transaction.response.content_type) self._block2_sent[key_token] = item request = transaction.request del request.mid del request.block2 request.block2 = (item.num, 0, item.size) else: transaction.block_transfer = False if key_token in self._block2_sent: if self._block2_sent[key_token].content_type != transaction.response.content_type: # pragma: no cover logger.error("Content-type Error") return self.error(transaction, defines.Codes.UNSUPPORTED_CONTENT_FORMAT.number) transaction.response.payload = self._block2_sent[key_token].payload + transaction.response.payload del self._block2_sent[key_token] else: transaction.block_transfer = False return transaction
def receive_response(self, transaction)
Handles the Blocks option in a incoming response. :type transaction: Transaction :param transaction: the transaction that owns the response :rtype : Transaction :return: the edited transaction
2.509512
2.507621
1.000754
host, port = transaction.request.source key_token = hash(str(host) + str(port) + str(transaction.request.token)) if (key_token in self._block2_receive and transaction.response.payload is not None) or \ (transaction.response.payload is not None and len(transaction.response.payload) > defines.MAX_PAYLOAD): if key_token in self._block2_receive: byte = self._block2_receive[key_token].byte size = self._block2_receive[key_token].size num = self._block2_receive[key_token].num else: byte = 0 num = 0 size = defines.MAX_PAYLOAD m = 1 self._block2_receive[key_token] = BlockItem(byte, num, m, size) if len(transaction.response.payload) > (byte + size): m = 1 else: m = 0 transaction.response.payload = transaction.response.payload[byte:byte + size] del transaction.response.block2 transaction.response.block2 = (num, m, size) self._block2_receive[key_token].byte += size self._block2_receive[key_token].num += 1 if m == 0: del self._block2_receive[key_token] return transaction
def send_response(self, transaction)
Handles the Blocks option in a outgoing response. :type transaction: Transaction :param transaction: the transaction that owns the response :rtype : Transaction :return: the edited transaction
2.911086
2.89602
1.005202
assert isinstance(request, Request) if request.block1 or (request.payload is not None and len(request.payload) > defines.MAX_PAYLOAD): host, port = request.destination key_token = hash(str(host) + str(port) + str(request.token)) if request.block1: num, m, size = request.block1 else: num = 0 m = 1 size = defines.MAX_PAYLOAD self._block1_sent[key_token] = BlockItem(size, num, m, size, request.payload, request.content_type) request.payload = request.payload[0:size] del request.block1 request.block1 = (num, m, size) elif request.block2: host, port = request.destination key_token = hash(str(host) + str(port) + str(request.token)) num, m, size = request.block2 item = BlockItem(size, num, m, size, "", None) self._block2_sent[key_token] = item return request return request
def send_request(self, request)
Handles the Blocks option in a outgoing request. :type request: Request :param request: the outgoing request :return: the edited request
3.312311
3.266326
1.014078
transaction.block_transfer = True transaction.response = Response() transaction.response.destination = transaction.request.source transaction.response.token = transaction.request.token transaction.response.code = defines.Codes.REQUEST_ENTITY_INCOMPLETE.number return transaction
def incomplete(transaction)
Notifies incomplete blockwise exchange. :type transaction: Transaction :param transaction: the transaction that owns the response :rtype : Transaction :return: the edited transaction
6.620984
6.296096
1.051601
def error(transaction, code): # pragma: no cover transaction.block_transfer = True transaction.response = Response() transaction.response.destination = transaction.request.source transaction.response.type = defines.Types["RST"] transaction.response.token = transaction.request.token transaction.response.code = code return transaction
Notifies generic error on blockwise exchange. :type transaction: Transaction :param transaction: the transaction that owns the response :rtype : Transaction :return: the edited transaction
null
null
null
if request.observe == 0: # Observe request host, port = request.destination key_token = hash(str(host) + str(port) + str(request.token)) self._relations[key_token] = ObserveItem(time.time(), None, True, None) return request
def send_request(self, request)
Add itself to the observing list :param request: the request :return: the request unmodified
8.941991
8.498529
1.052181
host, port = transaction.response.source key_token = hash(str(host) + str(port) + str(transaction.response.token)) if key_token in self._relations and transaction.response.type == defines.Types["CON"]: transaction.notification = True return transaction
def receive_response(self, transaction)
Sets notification's parameters. :type transaction: Transaction :param transaction: the transaction :rtype : Transaction :return: the modified transaction
8.195625
9.000099
0.910615
host, port = message.destination key_token = hash(str(host) + str(port) + str(message.token)) if key_token in self._relations and message.type == defines.Types["RST"]: del self._relations[key_token] return message
def send_empty(self, message)
Eventually remove from the observer list in case of a RST message. :type message: Message :param message: the message :return: the message unmodified
7.151216
6.054613
1.181119
if transaction.request.observe == 0: # Observe request host, port = transaction.request.source key_token = hash(str(host) + str(port) + str(transaction.request.token)) non_counter = 0 if key_token in self._relations: # Renew registration allowed = True else: allowed = False self._relations[key_token] = ObserveItem(time.time(), non_counter, allowed, transaction) elif transaction.request.observe == 1: host, port = transaction.request.source key_token = hash(str(host) + str(port) + str(transaction.request.token)) logger.info("Remove Subscriber") try: del self._relations[key_token] except KeyError: pass return transaction
def receive_request(self, transaction)
Manage the observe option in the request end eventually initialize the client for adding to the list of observers or remove from the list. :type transaction: Transaction :param transaction: the transaction that owns the request :rtype : Transaction :return: the modified transaction
4.082167
4.067621
1.003576
if empty.type == defines.Types["RST"]: host, port = transaction.request.source key_token = hash(str(host) + str(port) + str(transaction.request.token)) logger.info("Remove Subscriber") try: del self._relations[key_token] except KeyError: pass transaction.completed = True return transaction
def receive_empty(self, empty, transaction)
Manage the observe feature to remove a client in case of a RST message receveide in reply to a notification. :type empty: Message :param empty: the received message :type transaction: Transaction :param transaction: the transaction that owns the notification message :rtype : Transaction :return: the modified transaction
7.885325
6.596119
1.195449
host, port = transaction.request.source key_token = hash(str(host) + str(port) + str(transaction.request.token)) if key_token in self._relations: if transaction.response.code == defines.Codes.CONTENT.number: if transaction.resource is not None and transaction.resource.observable: transaction.response.observe = transaction.resource.observe_count self._relations[key_token].allowed = True self._relations[key_token].transaction = transaction self._relations[key_token].timestamp = time.time() else: del self._relations[key_token] elif transaction.response.code >= defines.Codes.ERROR_LOWER_BOUND: del self._relations[key_token] return transaction
def send_response(self, transaction)
Finalize to add the client to the list of observer. :type transaction: Transaction :param transaction: the transaction that owns the response :return: the transaction unmodified
4.110827
4.066148
1.010988
ret = [] if root is not None: resource_list = root.with_prefix_resource(resource.path) else: resource_list = [resource] for key in list(self._relations.keys()): if self._relations[key].transaction.resource in resource_list: if self._relations[key].non_counter > defines.MAX_NON_NOTIFICATIONS \ or self._relations[key].transaction.request.type == defines.Types["CON"]: self._relations[key].transaction.response.type = defines.Types["CON"] self._relations[key].non_counter = 0 elif self._relations[key].transaction.request.type == defines.Types["NON"]: self._relations[key].non_counter += 1 self._relations[key].transaction.response.type = defines.Types["NON"] self._relations[key].transaction.resource = resource del self._relations[key].transaction.response.mid del self._relations[key].transaction.response.token ret.append(self._relations[key].transaction) return ret
def notify(self, resource, root=None)
Prepare notification for the resource to all interested observers. :rtype: list :param resource: the resource for which send a new notification :param root: deprecated :return: the list of transactions to be notified
3.212897
3.077025
1.044157
logger.debug("Remove Subcriber") host, port = message.destination key_token = hash(str(host) + str(port) + str(message.token)) try: self._relations[key_token].transaction.completed = True del self._relations[key_token] except KeyError: logger.warning("No Subscriber")
def remove_subscriber(self, message)
Remove a subscriber based on token. :param message: the message
5.484678
5.65005
0.970731
while not self.stopped.isSet(): self.stopped.wait(timeout=defines.EXCHANGE_LIFETIME) self._messageLayer.purge()
def purge(self)
Clean old transactions
12.188549
12.022954
1.013773
self._socket.settimeout(float(timeout)) while not self.stopped.isSet(): try: data, client_address = self._socket.recvfrom(4096) except socket.timeout: continue try: #Start a new thread not to block other requests args = ((data, client_address), ) t = threading.Thread(target=self.receive_datagram, args=args) t.daemon = True t.start() except RuntimeError: logging.exception("Exception with Executor") logging.debug("closing socket") self._socket.close()
def listen(self, timeout=10)
Listen for incoming messages. Timeout is used to check if the server must be switched off. :param timeout: Socket Timeout in seconds
3.844001
3.962015
0.970213
logger.info("Stop server") self.stopped.set() for event in self.to_be_stopped: event.set() self._socket.close()
def close(self)
Stop the server.
6.62639
5.335006
1.242059
if not self.stopped.isSet(): host, port = message.destination logger.debug("send_datagram - " + str(message)) serializer = Serializer() message = serializer.serialize(message) self._socket.sendto(message, (host, port))
def send_datagram(self, message)
Send a message through the udp socket. :type message: Message :param message: the message to send
4.860303
5.506548
0.882641
with transaction: while retransmit_count < defines.MAX_RETRANSMIT and (not message.acknowledged and not message.rejected) \ and not self.stopped.isSet(): transaction.retransmit_stop.wait(timeout=future_time) if not message.acknowledged and not message.rejected and not self.stopped.isSet(): retransmit_count += 1 future_time *= 2 self.send_datagram(message) if message.acknowledged or message.rejected: message.timeouted = False else: logger.warning("Give up on message {message}".format(message=message.line_print)) message.timeouted = True if message.observe is not None: self._observeLayer.remove_subscriber(message) try: self.to_be_stopped.remove(transaction.retransmit_stop) except ValueError: pass transaction.retransmit_stop = None transaction.retransmit_thread = None
def _retransmit(self, transaction, message, future_time, retransmit_count)
Thread function to retransmit the message in the future :param transaction: the transaction that owns the message that needs retransmission :param message: the message that needs the retransmission task :param future_time: the amount of time to wait before a new attempt :param retransmit_count: the number of retransmissions
4.328674
4.479036
0.96643
t = threading.Timer(defines.ACK_TIMEOUT, self._send_ack, (transaction,)) t.start() return t
def _start_separate_timer(self, transaction)
Start a thread to handle separate mode. :type transaction: Transaction :param transaction: the transaction that is in processing :rtype : the Timer object
6.735874
7.857865
0.857214
tree = ElementTree.parse(self.file_xml) root = tree.getroot() for server in root.findall('server'): destination = server.text name = server.get("name") self.discover_remote(destination, name)
def parse_config(self)
Parse the xml file with remote servers and discover resources on each found server.
5.181824
3.344938
1.549154
assert (isinstance(destination, str)) if destination.startswith("["): split = destination.split("]", 1) host = split[0][1:] port = int(split[1][1:]) else: split = destination.split(":", 1) host = split[0] port = int(split[1]) server = (host, port) client = HelperClient(server) response = client.discover() client.stop() self.discover_remote_results(response, name)
def discover_remote(self, destination, name)
Discover resources on remote servers. :param destination: the remote server (ip, port) :type destination: tuple :param name: the name of the remote server :type name: String
3.089989
3.236963
0.954595
host, port = response.source if response.code == defines.Codes.CONTENT.number: resource = Resource('server', self, visible=True, observable=False, allow_children=True) self.add_resource(name, resource) self._mapping[name] = (host, port) self.parse_core_link_format(response.payload, name, (host, port)) else: logger.error("Server: " + response.source + " isn't valid.")
def discover_remote_results(self, response, name)
Create a new remote server resource for each valid discover response. :param response: the response to the discovery request :param name: the server name
9.008442
8.474749
1.062975
while len(link_format) > 0: pattern = "<([^>]*)>;" result = re.match(pattern, link_format) path = result.group(1) path = path.split("/") path = path[1:][0] link_format = link_format[result.end(1) + 2:] pattern = "([^<,])*" result = re.match(pattern, link_format) attributes = result.group(0) dict_att = {} if len(attributes) > 0: attributes = attributes.split(";") for att in attributes: a = att.split("=") if len(a) > 1: dict_att[a[0]] = a[1] else: dict_att[a[0]] = a[0] link_format = link_format[result.end(0) + 1:] # TODO handle observing resource = RemoteResource('server', remote_server, path, coap_server=self, visible=True, observable=False, allow_children=True) resource.attributes = dict_att self.add_resource(base_path + "/" + path, resource) logger.info(self.root.dump())
def parse_core_link_format(self, link_format, base_path, remote_server)
Parse discovery results. :param link_format: the payload of the response to the discovery request :param base_path: the base path used to create child resources discovered on the remote server :param remote_server: the (ip, port) of the remote server
3.238275
3.174544
1.020076
self._socket.settimeout(float(timeout)) while not self.stopped.isSet(): try: data, client_address = self._socket.recvfrom(4096) except socket.timeout: continue try: self.receive_datagram((data, client_address)) except RuntimeError: logger.exception("Exception with Executor") self._socket.close()
def listen(self, timeout=10)
Listen for incoming messages. Timeout is used to check if the server must be switched off. :param timeout: Socket Timeout in seconds
4.426488
4.60762
0.960689
data, client_address = args serializer = Serializer() message = serializer.deserialize(data, client_address) if isinstance(message, int): logger.error("receive_datagram - BAD REQUEST") rst = Message() rst.destination = client_address rst.type = defines.Types["RST"] rst.code = message self.send_datagram(rst) return logger.debug("receive_datagram - " + str(message)) if isinstance(message, Request): transaction = self._messageLayer.receive_request(message) if transaction.request.duplicated and transaction.completed: logger.debug("message duplicated,transaction completed") transaction = self._observeLayer.send_response(transaction) transaction = self._blockLayer.send_response(transaction) transaction = self._messageLayer.send_response(transaction) self.send_datagram(transaction.response) return elif transaction.request.duplicated and not transaction.completed: logger.debug("message duplicated,transaction NOT completed") self._send_ack(transaction) return transaction.separate_timer = self._start_separate_timer(transaction) transaction = self._blockLayer.receive_request(transaction) if transaction.block_transfer: self._stop_separate_timer(transaction.separate_timer) transaction = self._messageLayer.send_response(transaction) self.send_datagram(transaction.response) return transaction = self._observeLayer.receive_request(transaction) if self._cacheLayer is not None: transaction = self._cacheLayer.receive_request(transaction) if transaction.cacheHit is False: logger.debug(transaction.request) transaction = self._forwardLayer.receive_request_reverse(transaction) logger.debug(transaction.response) transaction = self._observeLayer.send_response(transaction) transaction = self._blockLayer.send_response(transaction) transaction = self._cacheLayer.send_response(transaction) else: transaction = self._forwardLayer.receive_request_reverse(transaction) transaction = self._observeLayer.send_response(transaction) transaction = self._blockLayer.send_response(transaction) self._stop_separate_timer(transaction.separate_timer) transaction = self._messageLayer.send_response(transaction) if transaction.response is not None: if transaction.response.type == defines.Types["CON"]: self._start_retrasmission(transaction, transaction.response) self.send_datagram(transaction.response) elif isinstance(message, Message): transaction = self._messageLayer.receive_empty(message) if transaction is not None: transaction = self._blockLayer.receive_empty(message, transaction) self._observeLayer.receive_empty(message, transaction) else: # pragma: no cover logger.error("Received response from %s", message.source)
def receive_datagram(self, args)
Handle messages coming from the udp socket. :param args: (data, client_address)
2.844419
2.84177
1.000932
if message is None or message.code != defines.Codes.CONTINUE.number: self.queue.put(message)
def _wait_response(self, message)
Private function to get responses from the server. :param message: the received message
11.702423
16.034498
0.729828
self.protocol.send_message(request) while not self.protocol.stopped.isSet(): response = self.queue.get(block=True) callback(response)
def _thread_body(self, request, callback)
Private function. Send a request, wait for response and call the callback function. :param request: the request to send :param callback: the callback function
4.651545
4.836483
0.961762
message = Message() message.destination = self.server message.code = defines.Codes.EMPTY.number message.type = defines.Types["RST"] message.token = response.token message.mid = response.mid self.protocol.send_message(message) self.stop()
def cancel_observing(self, response, send_rst): # pragma: no cover if send_rst
Delete observing on the remote server. :param response: the last received response :param send_rst: if explicitly send RST message :type send_rst: bool
8.354774
6.827966
1.223611
if hasattr(request, k): setattr(request, k, v) return self.send_request(request, callback, timeout)
def observe(self, path, callback, timeout=None, **kwargs): # pragma: no cover request = self.mk_request(defines.Codes.GET, path) request.observe = 0 for k, v in kwargs.items()
Perform a GET with observe on a certain path. :param path: the path :param callback: the callback function to invoke upon notifications :param timeout: the timeout of the request :return: the response to the observe request
4.794751
8.011976
0.598448
if hasattr(request, k): setattr(request, k, v) return self.send_request(request, callback, timeout)
def delete(self, path, callback=None, timeout=None, **kwargs): # pragma: no cover request = self.mk_request(defines.Codes.DELETE, path) for k, v in kwargs.items()
Perform a DELETE on a certain path. :param path: the path :param callback: the callback function to invoke upon response :param timeout: the timeout of the request :return: the response
4.447934
8.878936
0.500953
request.add_no_response() request.type = defines.Types["NON"] for k, v in kwargs.items(): if hasattr(request, k): setattr(request, k, v) return self.send_request(request, callback, timeout, no_response=no_response)
def post(self, path, payload, callback=None, timeout=None, no_response=False, **kwargs): # pragma: no cover request = self.mk_request(defines.Codes.POST, path) request.token = generate_random_token(2) request.payload = payload if no_response
Perform a POST on a certain path. :param path: the path :param payload: the request payload :param callback: the callback function to invoke upon response :param timeout: the timeout of the request :return: the response
4.006654
4.984491
0.803824
if hasattr(request, k): setattr(request, k, v) return self.send_request(request, callback, timeout)
def discover(self, callback=None, timeout=None, **kwargs): # pragma: no cover request = self.mk_request(defines.Codes.GET, defines.DISCOVERY_URL) for k, v in kwargs.items()
Perform a Discover request on the server. :param callback: the callback function to invoke upon response :param timeout: the timeout of the request :return: the response
4.813344
9.187815
0.523883
thread = threading.Thread(target=self._thread_body, args=(request, callback)) thread.start() else: self.protocol.send_message(request) if no_response: return try: response = self.queue.get(block=True, timeout=timeout) except Empty: #if timeout is set response = None return response
def send_request(self, request, callback=None, timeout=None, no_response=False): # pragma: no cover if callback is not None
Send a request to the remote server. :param request: the request to send :param callback: the callback function to invoke upon response :param timeout: the timeout of the request :return: the response
3.620726
3.856329
0.938905
request = Request() request.destination = self.server request.code = method.number request.uri_path = path return request
def mk_request(self, method, path)
Create a request. :param method: the CoAP method :param path: the path of the request :return: the request
6.297703
5.20085
1.210899
request = Request() request.destination = self.server request.code = method.number request.uri_path = path request.type = defines.Types["NON"] return request
def mk_request_non(self, method, path)
Create a request. :param method: the CoAP method :param path: the path of the request :return: the request
6.733642
5.038294
1.336492
server_address = (self.ip, self.hc_port) hc_proxy = HTTPServer(server_address, HCProxyHandler) logger.info('Starting HTTP-CoAP Proxy...') hc_proxy.serve_forever()
def run(self)
Start the proxy.
5.522044
4.84272
1.140277
if path[0] != '/': path = '/' + path if path[-1] != '/': path = '{0}/'.format(path) return path
def get_formatted_path(path)
Uniform the path string :param path: the path :return: the uniform path
2.844249
3.348543
0.849399
temp = self.get_uri_as_list() query_string = temp[4] if query_string == "": return None # Bad request error code query_string_as_list = str.split(query_string, "=") return query_string_as_list[1]
def get_payload(self)
Return the query string of the uri. :return: the query string as a list
6.730125
5.133455
1.311032
if not self.request_hc_path_corresponds(): # the http URI of the request is not the same of the one specified by the admin for the hc proxy, # so I do not answer # For example the admin setup the http proxy URI like: "http://127.0.0.1:8080:/my_hc_path/" and the URI of # the requests asks for "http://127.0.0.1:8080:/another_hc_path/" return self.set_coap_uri() self.client = HelperClient(server=(self.coap_uri.host, self.coap_uri.port))
def do_initial_operations(self)
Setup the client for interact with remote server
7.687001
7.137302
1.077018
self.do_initial_operations() coap_response = self.client.get(self.coap_uri.path) self.client.stop() logger.info("Server response: %s", coap_response.pretty_print()) self.set_http_response(coap_response)
def do_GET(self)
Perform a GET request
5.584075
5.247122
1.064217
self.do_initial_operations() # the HEAD method is not present in CoAP, so we treat it # like if it was a GET and then we exclude the body from the response # with send_body=False we say that we do not need the body, because it is a HEAD request coap_response = self.client.get(self.coap_uri.path) self.client.stop() logger.info("Server response: %s", coap_response.pretty_print()) self.set_http_header(coap_response)
def do_HEAD(self)
Perform a HEAD request
8.434568
8.475204
0.995205
# Doesn't do anything with posted data # print "uri: ", self.client_address, self.path self.do_initial_operations() payload = self.coap_uri.get_payload() if payload is None: logger.error("BAD POST REQUEST") self.send_error(BAD_REQUEST) return coap_response = self.client.post(self.coap_uri.path, payload) self.client.stop() logger.info("Server response: %s", coap_response.pretty_print()) self.set_http_response(coap_response)
def do_POST(self)
Perform a POST request
4.914671
5.073824
0.968632
self.do_initial_operations() payload = self.coap_uri.get_payload() if payload is None: logger.error("BAD PUT REQUEST") self.send_error(BAD_REQUEST) return logger.debug(payload) coap_response = self.client.put(self.coap_uri.path, payload) self.client.stop() logger.debug("Server response: %s", coap_response.pretty_print()) self.set_http_response(coap_response)
def do_PUT(self)
Perform a PUT request
4.091603
3.98833
1.025894
self.do_initial_operations() coap_response = self.client.delete(self.coap_uri.path) self.client.stop() logger.debug("Server response: %s", coap_response.pretty_print()) self.set_http_response(coap_response)
def do_DELETE(self)
Perform a DELETE request
5.328175
5.104869
1.043744
uri_path = self.path.split(COAP_PREFACE) request_hc_path = uri_path[0] logger.debug("HCPATH: %s", hc_path) # print HC_PATH logger.debug("URI: %s", request_hc_path) if hc_path != request_hc_path: return False else: return True
def request_hc_path_corresponds(self)
Tells if the hc path of the request corresponds to that specified by the admin :return: a boolean that says if it corresponds or not
4.866664
4.727827
1.029366
logger.debug( ("Server: %s\n"\ "codice risposta: %s\n"\ "PROXED: %s\n"\ "payload risposta: %s"), coap_response.source, coap_response.code, CoAP_HTTP[Codes.LIST[coap_response.code].name], coap_response.payload) self.send_response(int(CoAP_HTTP[Codes.LIST[coap_response.code].name])) self.send_header('Content-type', 'text/html') self.end_headers()
def set_http_header(self, coap_response)
Sets http headers. :param coap_response: the coap response
4.717154
5.021959
0.939305
if coap_response.payload is not None: body = "<html><body><h1>", coap_response.payload, "</h1></body></html>" self.wfile.write("".join(body)) else: self.wfile.write("<html><body><h1>None</h1></body></html>")
def set_http_body(self, coap_response)
Set http body. :param coap_response: the coap response
2.449857
2.839607
0.862745
length = byte_len(value) if length == 1: num = value & 0xF0 num >>= 4 m = value & 0x08 m >>= 3 size = value & 0x07 elif length == 2: num = value & 0xFFF0 num >>= 4 m = value & 0x0008 m >>= 3 size = value & 0x0007 else: num = value & 0xFFFFF0 num >>= 4 m = value & 0x000008 m >>= 3 size = value & 0x000007 return num, int(m), pow(2, (size + 4))
def parse_blockwise(value)
Parse Blockwise option. :param value: option value :return: num, m, size
2.373986
2.058903
1.153035
length = 0 while int_type: int_type >>= 1 length += 1 if length > 0: if length % 8 != 0: length = int(length / 8) + 1 else: length = int(length / 8) return length
def byte_len(int_type)
Get the number of byte needed to encode the int passed. :param int_type: the int to be converted :return: the number of bits needed to encode the int passed.
2.540684
2.446246
1.038605
if type(self._value) is None: self._value = bytearray() opt_type = defines.OptionRegistry.LIST[self._number].value_type if opt_type == defines.INTEGER: if byte_len(self._value) > 0: return int(self._value) else: return defines.OptionRegistry.LIST[self._number].default return self._value
def value(self)
Return the option value. :return: the option value in the correct format depending on the option
5.82386
5.649435
1.030875
opt_type = defines.OptionRegistry.LIST[self._number].value_type if opt_type == defines.INTEGER: if type(value) is not int: value = int(value) if byte_len(value) == 0: value = 0 elif opt_type == defines.STRING: if type(value) is not str: value = str(value) elif opt_type == defines.OPAQUE: if type(value) is bytes: pass else: if value is not None: value = bytes(value, "utf-8") self._value = value
def value(self, value)
Set the value of the option. :param value: the option value
3.411184
3.377874
1.009861
if isinstance(self._value, int): return byte_len(self._value) if self._value is None: return 0 return len(self._value)
def length(self)
Return the value length :rtype : int
3.552673
3.908628
0.908931
if self._number == defines.OptionRegistry.URI_HOST.number \ or self._number == defines.OptionRegistry.URI_PORT.number \ or self._number == defines.OptionRegistry.URI_PATH.number \ or self._number == defines.OptionRegistry.MAX_AGE.number \ or self._number == defines.OptionRegistry.URI_QUERY.number \ or self._number == defines.OptionRegistry.PROXY_URI.number \ or self._number == defines.OptionRegistry.PROXY_SCHEME.number: return False return True
def is_safe(self)
Check if the option is safe. :rtype : bool :return: True, if option is safe
2.754275
2.722295
1.011748
opt_bytes = array.array('B', '\0\0') if option_num < 256: s = struct.Struct("!B") s.pack_into(opt_bytes, 0, option_num) else: s = struct.Struct("H") s.pack_into(opt_bytes, 0, option_num) critical = (opt_bytes[0] & 0x01) > 0 unsafe = (opt_bytes[0] & 0x02) > 0 nocache = ((opt_bytes[0] & 0x1e) == 0x1c) return (critical, unsafe, nocache)
def get_option_flags(option_num)
Get Critical, UnSafe, NoCacheKey flags from the option number as per RFC 7252, section 5.4.6 :param option_num: option number :return: option flags :rtype: 3-tuple (critical, unsafe, no-cache)
2.467694
2.198719
1.122332
try: fmt = "!BBH" pos = struct.calcsize(fmt) s = struct.Struct(fmt) values = s.unpack_from(datagram) first = values[0] code = values[1] mid = values[2] version = (first & 0xC0) >> 6 message_type = (first & 0x30) >> 4 token_length = (first & 0x0F) if Serializer.is_response(code): message = Response() message.code = code elif Serializer.is_request(code): message = Request() message.code = code else: message = Message() message.source = source message.destination = None message.version = version message.type = message_type message.mid = mid if token_length > 0: fmt = "%ss" % token_length s = struct.Struct(fmt) token_value = s.unpack_from(datagram[pos:])[0] message.token = token_value.decode("utf-8") else: message.token = None pos += token_length current_option = 0 values = datagram[pos:] length_packet = len(values) pos = 0 while pos < length_packet: next_byte = struct.unpack("B", values[pos].to_bytes(1, "big"))[0] pos += 1 if next_byte != int(defines.PAYLOAD_MARKER): # the first 4 bits of the byte represent the option delta # delta = self._reader.read(4).uint num, option_length, pos = Serializer.read_option_value_len_from_byte(next_byte, pos, values) current_option += num # read option try: option_item = defines.OptionRegistry.LIST[current_option] except KeyError: (opt_critical, _, _) = defines.OptionRegistry.get_option_flags(current_option) if opt_critical: raise AttributeError("Critical option %s unknown" % current_option) else: # If the non-critical option is unknown # (vendor-specific, proprietary) - just skip it #log.err("unrecognized option %d" % current_option) pass else: if option_length == 0: value = None elif option_item.value_type == defines.INTEGER: tmp = values[pos: pos + option_length] value = 0 for b in tmp: value = (value << 8) | struct.unpack("B", b.to_bytes(1, "big"))[0] elif option_item.value_type == defines.OPAQUE: tmp = values[pos: pos + option_length] value = tmp else: value = values[pos: pos + option_length] option = Option() option.number = current_option option.value = Serializer.convert_to_raw(current_option, value, option_length) message.add_option(option) if option.number == defines.OptionRegistry.CONTENT_TYPE.number: message.payload_type = option.value finally: pos += option_length else: if length_packet <= pos: # log.err("Payload Marker with no payload") raise AttributeError("Packet length %s, pos %s" % (length_packet, pos)) message.payload = "" payload = values[pos:] try: if message.payload_type == defines.Content_types["application/octet-stream"]: message.payload = payload else: message.payload = payload.decode("utf-8") except AttributeError: message.payload = payload.decode("utf-8") pos += len(payload) return message except AttributeError: return defines.Codes.BAD_REQUEST.number except struct.error: return defines.Codes.BAD_REQUEST.number
def deserialize(datagram, source)
De-serialize a stream of byte to a message. :param datagram: the incoming udp message :param source: the source address and port (ip, port) :return: the message :rtype: Message
3.092066
3.05895
1.010826
fmt = "!BBH" if message.token is None or message.token == "": tkl = 0 else: tkl = len(message.token) tmp = (defines.VERSION << 2) tmp |= message.type tmp <<= 4 tmp |= tkl values = [tmp, message.code, message.mid] if message.token is not None and tkl > 0: for b in str(message.token): fmt += "c" values.append(bytes(b, "utf-8")) options = Serializer.as_sorted_list(message.options) # already sorted lastoptionnumber = 0 for option in options: # write 4-bit option delta optiondelta = option.number - lastoptionnumber optiondeltanibble = Serializer.get_option_nibble(optiondelta) tmp = (optiondeltanibble << defines.OPTION_DELTA_BITS) # write 4-bit option length optionlength = option.length optionlengthnibble = Serializer.get_option_nibble(optionlength) tmp |= optionlengthnibble fmt += "B" values.append(tmp) # write extended option delta field (0 - 2 bytes) if optiondeltanibble == 13: fmt += "B" values.append(optiondelta - 13) elif optiondeltanibble == 14: fmt += "H" values.append(optiondelta - 269) # write extended option length field (0 - 2 bytes) if optionlengthnibble == 13: fmt += "B" values.append(optionlength - 13) elif optionlengthnibble == 14: fmt += "H" values.append(optionlength - 269) # write option value if optionlength > 0: opt_type = defines.OptionRegistry.LIST[option.number].value_type if opt_type == defines.INTEGER: words = Serializer.int_to_words(option.value, optionlength, 8) for num in range(0, optionlength): fmt += "B" values.append(words[num]) elif opt_type == defines.STRING: fmt += str(len(bytes(option.value, "utf-8"))) + "s" values.append(bytes(option.value, "utf-8")) else: # OPAQUE for b in option.value: fmt += "B" values.append(b) # update last option number lastoptionnumber = option.number payload = message.payload if payload is not None and len(payload) > 0: # if payload is present and of non-zero length, it is prefixed by # an one-byte Payload Marker (0xFF) which indicates the end of # options and the start of the payload fmt += "B" values.append(defines.PAYLOAD_MARKER) if isinstance(payload, bytes): fmt += str(len(payload)) + "s" values.append(payload) else: fmt += str(len(bytes(payload, "utf-8"))) + "s" values.append(bytes(payload, "utf-8")) # for b in str(payload): # fmt += "c" # values.append(bytes(b, "utf-8")) datagram = None if values[1] is None: values[1] = 0 if values[2] is None: values[2] = 0 try: s = struct.Struct(fmt) datagram = ctypes.create_string_buffer(s.size) s.pack_into(datagram, 0, *values) except struct.error: # The .exception method will report on the exception encountered # and provide a traceback. logger.debug(fmt) logger.debug(values) logging.exception('Failed to pack structure') return datagram
def serialize(message)
Serialize a message to a udp packet :type message: Message :param message: the message to be serialized :rtype: stream of byte :return: the message serialized
2.835565
2.85357
0.99369
if nibble <= 12: return nibble, pos elif nibble == 13: tmp = struct.unpack("!B", values[pos].to_bytes(1, "big"))[0] + 13 pos += 1 return tmp, pos elif nibble == 14: s = struct.Struct("!H") tmp = s.unpack_from(values[pos:].to_bytes(2, "big"))[0] + 269 pos += 2 return tmp, pos else: raise AttributeError("Unsupported option nibble " + str(nibble))
def read_option_value_from_nibble(nibble, pos, values)
Calculates the value used in the extended option fields. :param nibble: the 4-bit option header value. :return: the value calculated from the nibble and the extended option value.
2.53452
2.60614
0.972519
h_nibble = (byte & 0xF0) >> 4 l_nibble = byte & 0x0F value = 0 length = 0 if h_nibble <= 12: value = h_nibble elif h_nibble == 13: value = struct.unpack("!B", values[pos].to_bytes(1, "big"))[0] + 13 pos += 1 elif h_nibble == 14: s = struct.Struct("!H") value = s.unpack_from(values[pos:].to_bytes(2, "big"))[0] + 269 pos += 2 else: raise AttributeError("Unsupported option number nibble " + str(h_nibble)) if l_nibble <= 12: length = l_nibble elif l_nibble == 13: length = struct.unpack("!B", values[pos].to_bytes(1, "big"))[0] + 13 pos += 1 elif l_nibble == 14: length = s.unpack_from(values[pos:].to_bytes(2, "big"))[0] + 269 pos += 2 else: raise AttributeError("Unsupported option length nibble " + str(l_nibble)) return value, length, pos
def read_option_value_len_from_byte(byte, pos, values)
Calculates the value and length used in the extended option fields. :param byte: 1-byte option header value. :return: the value and length, calculated from the header including the extended fields.
1.792493
1.76865
1.013481
opt_type = defines.OptionRegistry.LIST[number].value_type if length == 0 and opt_type != defines.INTEGER: return bytes() elif length == 0 and opt_type == defines.INTEGER: return 0 elif opt_type == defines.STRING: if isinstance(value, bytes): return value.decode("utf-8") elif opt_type == defines.OPAQUE: if isinstance(value, bytes): return value else: return bytes(value, "utf-8") if isinstance(value, tuple): value = value[0] if isinstance(value, str): value = str(value) if isinstance(value, str): return bytearray(value, "utf-8") elif isinstance(value, int): return value else: return bytearray(value)
def convert_to_raw(number, value, length)
Get the value of an option as a ByteArray. :param number: the option number :param value: the option value :param length: the option length :return: the value of an option as a BitArray
3.003194
2.827605
1.062098
if len(options) > 0: options = sorted(options, key=lambda o: o.number) return options
def as_sorted_list(options)
Returns all options in a list sorted according to their option numbers. :return: the sorted list
3.83176
4.454208
0.860256
max_int = 2 ** (word_size*num_words) - 1 max_word_size = 2 ** word_size - 1 if not 0 <= int_val <= max_int: raise AttributeError('integer %r is out of bounds!' % hex(int_val)) words = [] for _ in range(num_words): word = int_val & max_word_size words.append(int(word)) int_val >>= word_size words.reverse() return words
def int_to_words(int_val, num_words=4, word_size=32)
Convert a int value to bytes. :param int_val: an arbitrary length Python integer to be split up. Network byte order is assumed. Raises an IndexError if width of integer (in bits) exceeds word_size * num_words. :param num_words: number of words expected in return value tuple. :param word_size: size/width of individual words (in bits). :return: a list of fixed width words based on provided parameters.
2.627504
2.793966
0.940421
ret_hash = "" for i in args: ret_hash += str(i).lower() return hash(ret_hash)
def str_append_hash(*args)
Convert each argument to a lower case string, appended, then hash
5.017821
3.728433
1.345826