repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
Tanganelli/CoAPthon3
coapthon/serializer.py
Serializer.read_option_value_len_from_byte
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. """ 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
python
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. """ 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", ")", ":", "h_nibble", "=", "(", "byte", "&", "0xF0", ")", ">>", "4", "l_nibble", "=", "byte", "&", "0x0F", "value", "=", "0", "length", "=", "0", "if", "h_nibble", "<=", ...
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.
[ "Calculates", "the", "value", "and", "length", "used", "in", "the", "extended", "option", "fields", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/serializer.py#L291-L324
train
210,700
Tanganelli/CoAPthon3
coapthon/serializer.py
Serializer.convert_to_raw
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 """ 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)
python
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 """ 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", ")", ":", "opt_type", "=", "defines", ".", "OptionRegistry", ".", "LIST", "[", "number", "]", ".", "value_type", "if", "length", "==", "0", "and", "opt_type", "!=", "defines", ".", "INT...
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
[ "Get", "the", "value", "of", "an", "option", "as", "a", "ByteArray", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/serializer.py#L327-L360
train
210,701
Tanganelli/CoAPthon3
coapthon/serializer.py
Serializer.as_sorted_list
def as_sorted_list(options): """ Returns all options in a list sorted according to their option numbers. :return: the sorted list """ if len(options) > 0: options = sorted(options, key=lambda o: o.number) return options
python
def as_sorted_list(options): """ Returns all options in a list sorted according to their option numbers. :return: the sorted list """ if len(options) > 0: options = sorted(options, key=lambda o: o.number) return options
[ "def", "as_sorted_list", "(", "options", ")", ":", "if", "len", "(", "options", ")", ">", "0", ":", "options", "=", "sorted", "(", "options", ",", "key", "=", "lambda", "o", ":", "o", ".", "number", ")", "return", "options" ]
Returns all options in a list sorted according to their option numbers. :return: the sorted list
[ "Returns", "all", "options", "in", "a", "list", "sorted", "according", "to", "their", "option", "numbers", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/serializer.py#L363-L371
train
210,702
Tanganelli/CoAPthon3
coapthon/serializer.py
Serializer.int_to_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. """ 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
python
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. """ 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", ")", ":", "max_int", "=", "2", "**", "(", "word_size", "*", "num_words", ")", "-", "1", "max_word_size", "=", "2", "**", "word_size", "-", "1", "if", "not...
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.
[ "Convert", "a", "int", "value", "to", "bytes", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/serializer.py#L391-L418
train
210,703
Tanganelli/CoAPthon3
coapthon/layers/messagelayer.py
str_append_hash
def str_append_hash(*args): """ Convert each argument to a lower case string, appended, then hash """ ret_hash = "" for i in args: ret_hash += str(i).lower() return hash(ret_hash)
python
def str_append_hash(*args): """ Convert each argument to a lower case string, appended, then hash """ ret_hash = "" for i in args: ret_hash += str(i).lower() return hash(ret_hash)
[ "def", "str_append_hash", "(", "*", "args", ")", ":", "ret_hash", "=", "\"\"", "for", "i", "in", "args", ":", "ret_hash", "+=", "str", "(", "i", ")", ".", "lower", "(", ")", "return", "hash", "(", "ret_hash", ")" ]
Convert each argument to a lower case string, appended, then hash
[ "Convert", "each", "argument", "to", "a", "lower", "case", "string", "appended", "then", "hash" ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/messagelayer.py#L14-L20
train
210,704
Tanganelli/CoAPthon3
coapthon/layers/messagelayer.py
MessageLayer.fetch_mid
def fetch_mid(self): """ Gets the next valid MID. :return: the mid to use """ current_mid = self._current_mid self._current_mid += 1 self._current_mid %= 65535 return current_mid
python
def fetch_mid(self): """ Gets the next valid MID. :return: the mid to use """ current_mid = self._current_mid self._current_mid += 1 self._current_mid %= 65535 return current_mid
[ "def", "fetch_mid", "(", "self", ")", ":", "current_mid", "=", "self", ".", "_current_mid", "self", ".", "_current_mid", "+=", "1", "self", ".", "_current_mid", "%=", "65535", "return", "current_mid" ]
Gets the next valid MID. :return: the mid to use
[ "Gets", "the", "next", "valid", "MID", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/messagelayer.py#L40-L49
train
210,705
Tanganelli/CoAPthon3
coapthon/layers/messagelayer.py
MessageLayer.receive_request
def receive_request(self, request): """ Handle duplicates and store received messages. :type request: Request :param request: the incoming request :rtype : Transaction :return: the edited transaction """ logger.debug("receive_request - " + str(request)) try: host, port = request.source except AttributeError: return key_mid = str_append_hash(host, port, request.mid) key_token = str_append_hash(host, port, request.token) if key_mid in list(self._transactions.keys()): # Duplicated self._transactions[key_mid].request.duplicated = True transaction = self._transactions[key_mid] else: request.timestamp = time.time() transaction = Transaction(request=request, timestamp=request.timestamp) with transaction: self._transactions[key_mid] = transaction self._transactions_token[key_token] = transaction return transaction
python
def receive_request(self, request): """ Handle duplicates and store received messages. :type request: Request :param request: the incoming request :rtype : Transaction :return: the edited transaction """ logger.debug("receive_request - " + str(request)) try: host, port = request.source except AttributeError: return key_mid = str_append_hash(host, port, request.mid) key_token = str_append_hash(host, port, request.token) if key_mid in list(self._transactions.keys()): # Duplicated self._transactions[key_mid].request.duplicated = True transaction = self._transactions[key_mid] else: request.timestamp = time.time() transaction = Transaction(request=request, timestamp=request.timestamp) with transaction: self._transactions[key_mid] = transaction self._transactions_token[key_token] = transaction return transaction
[ "def", "receive_request", "(", "self", ",", "request", ")", ":", "logger", ".", "debug", "(", "\"receive_request - \"", "+", "str", "(", "request", ")", ")", "try", ":", "host", ",", "port", "=", "request", ".", "source", "except", "AttributeError", ":", ...
Handle duplicates and store received messages. :type request: Request :param request: the incoming request :rtype : Transaction :return: the edited transaction
[ "Handle", "duplicates", "and", "store", "received", "messages", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/messagelayer.py#L65-L92
train
210,706
Tanganelli/CoAPthon3
coapthon/layers/messagelayer.py
MessageLayer.receive_response
def receive_response(self, response): """ Pair responses with requests. :type response: Response :param response: the received response :rtype : Transaction :return: the transaction to which the response belongs to """ logger.debug("receive_response - " + str(response)) try: host, port = response.source except AttributeError: return key_mid = str_append_hash(host, port, response.mid) key_mid_multicast = str_append_hash(defines.ALL_COAP_NODES, port, response.mid) key_token = str_append_hash(host, port, response.token) key_token_multicast = str_append_hash(defines.ALL_COAP_NODES, port, response.token) if key_mid in list(self._transactions.keys()): transaction = self._transactions[key_mid] if response.token != transaction.request.token: logger.warning("Tokens does not match - response message " + str(host) + ":" + str(port)) return None, False elif key_token in self._transactions_token: transaction = self._transactions_token[key_token] elif key_mid_multicast in list(self._transactions.keys()): transaction = self._transactions[key_mid_multicast] elif key_token_multicast in self._transactions_token: transaction = self._transactions_token[key_token_multicast] if response.token != transaction.request.token: logger.warning("Tokens does not match - response message " + str(host) + ":" + str(port)) return None, False else: logger.warning("Un-Matched incoming response message " + str(host) + ":" + str(port)) return None, False send_ack = False if response.type == defines.Types["CON"]: send_ack = True transaction.request.acknowledged = True transaction.completed = True transaction.response = response if transaction.retransmit_stop is not None: transaction.retransmit_stop.set() return transaction, send_ack
python
def receive_response(self, response): """ Pair responses with requests. :type response: Response :param response: the received response :rtype : Transaction :return: the transaction to which the response belongs to """ logger.debug("receive_response - " + str(response)) try: host, port = response.source except AttributeError: return key_mid = str_append_hash(host, port, response.mid) key_mid_multicast = str_append_hash(defines.ALL_COAP_NODES, port, response.mid) key_token = str_append_hash(host, port, response.token) key_token_multicast = str_append_hash(defines.ALL_COAP_NODES, port, response.token) if key_mid in list(self._transactions.keys()): transaction = self._transactions[key_mid] if response.token != transaction.request.token: logger.warning("Tokens does not match - response message " + str(host) + ":" + str(port)) return None, False elif key_token in self._transactions_token: transaction = self._transactions_token[key_token] elif key_mid_multicast in list(self._transactions.keys()): transaction = self._transactions[key_mid_multicast] elif key_token_multicast in self._transactions_token: transaction = self._transactions_token[key_token_multicast] if response.token != transaction.request.token: logger.warning("Tokens does not match - response message " + str(host) + ":" + str(port)) return None, False else: logger.warning("Un-Matched incoming response message " + str(host) + ":" + str(port)) return None, False send_ack = False if response.type == defines.Types["CON"]: send_ack = True transaction.request.acknowledged = True transaction.completed = True transaction.response = response if transaction.retransmit_stop is not None: transaction.retransmit_stop.set() return transaction, send_ack
[ "def", "receive_response", "(", "self", ",", "response", ")", ":", "logger", ".", "debug", "(", "\"receive_response - \"", "+", "str", "(", "response", ")", ")", "try", ":", "host", ",", "port", "=", "response", ".", "source", "except", "AttributeError", "...
Pair responses with requests. :type response: Response :param response: the received response :rtype : Transaction :return: the transaction to which the response belongs to
[ "Pair", "responses", "with", "requests", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/messagelayer.py#L94-L138
train
210,707
Tanganelli/CoAPthon3
coapthon/layers/messagelayer.py
MessageLayer.receive_empty
def receive_empty(self, message): """ Pair ACKs with requests. :type message: Message :param message: the received message :rtype : Transaction :return: the transaction to which the message belongs to """ logger.debug("receive_empty - " + str(message)) try: host, port = message.source except AttributeError: return key_mid = str_append_hash(host, port, message.mid) key_mid_multicast = str_append_hash(defines.ALL_COAP_NODES, port, message.mid) key_token = str_append_hash(host, port, message.token) key_token_multicast = str_append_hash(defines.ALL_COAP_NODES, port, message.token) if key_mid in list(self._transactions.keys()): transaction = self._transactions[key_mid] elif key_token in self._transactions_token: transaction = self._transactions_token[key_token] elif key_mid_multicast in list(self._transactions.keys()): transaction = self._transactions[key_mid_multicast] elif key_token_multicast in self._transactions_token: transaction = self._transactions_token[key_token_multicast] else: logger.warning("Un-Matched incoming empty message " + str(host) + ":" + str(port)) return None if message.type == defines.Types["ACK"]: if not transaction.request.acknowledged: transaction.request.acknowledged = True elif (transaction.response is not None) and (not transaction.response.acknowledged): transaction.response.acknowledged = True elif message.type == defines.Types["RST"]: if not transaction.request.acknowledged: transaction.request.rejected = True elif not transaction.response.acknowledged: transaction.response.rejected = True elif message.type == defines.Types["CON"]: #implicit ACK (might have been lost) logger.debug("Implicit ACK on received CON for waiting transaction") transaction.request.acknowledged = True else: logger.warning("Unhandled message type...") if transaction.retransmit_stop is not None: transaction.retransmit_stop.set() return transaction
python
def receive_empty(self, message): """ Pair ACKs with requests. :type message: Message :param message: the received message :rtype : Transaction :return: the transaction to which the message belongs to """ logger.debug("receive_empty - " + str(message)) try: host, port = message.source except AttributeError: return key_mid = str_append_hash(host, port, message.mid) key_mid_multicast = str_append_hash(defines.ALL_COAP_NODES, port, message.mid) key_token = str_append_hash(host, port, message.token) key_token_multicast = str_append_hash(defines.ALL_COAP_NODES, port, message.token) if key_mid in list(self._transactions.keys()): transaction = self._transactions[key_mid] elif key_token in self._transactions_token: transaction = self._transactions_token[key_token] elif key_mid_multicast in list(self._transactions.keys()): transaction = self._transactions[key_mid_multicast] elif key_token_multicast in self._transactions_token: transaction = self._transactions_token[key_token_multicast] else: logger.warning("Un-Matched incoming empty message " + str(host) + ":" + str(port)) return None if message.type == defines.Types["ACK"]: if not transaction.request.acknowledged: transaction.request.acknowledged = True elif (transaction.response is not None) and (not transaction.response.acknowledged): transaction.response.acknowledged = True elif message.type == defines.Types["RST"]: if not transaction.request.acknowledged: transaction.request.rejected = True elif not transaction.response.acknowledged: transaction.response.rejected = True elif message.type == defines.Types["CON"]: #implicit ACK (might have been lost) logger.debug("Implicit ACK on received CON for waiting transaction") transaction.request.acknowledged = True else: logger.warning("Unhandled message type...") if transaction.retransmit_stop is not None: transaction.retransmit_stop.set() return transaction
[ "def", "receive_empty", "(", "self", ",", "message", ")", ":", "logger", ".", "debug", "(", "\"receive_empty - \"", "+", "str", "(", "message", ")", ")", "try", ":", "host", ",", "port", "=", "message", ".", "source", "except", "AttributeError", ":", "re...
Pair ACKs with requests. :type message: Message :param message: the received message :rtype : Transaction :return: the transaction to which the message belongs to
[ "Pair", "ACKs", "with", "requests", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/messagelayer.py#L140-L190
train
210,708
Tanganelli/CoAPthon3
coapthon/layers/messagelayer.py
MessageLayer.send_request
def send_request(self, request): """ Create the transaction and fill it with the outgoing request. :type request: Request :param request: the request to send :rtype : Transaction :return: the created transaction """ logger.debug("send_request - " + str(request)) assert isinstance(request, Request) try: host, port = request.destination except AttributeError: return request.timestamp = time.time() transaction = Transaction(request=request, timestamp=request.timestamp) if transaction.request.type is None: transaction.request.type = defines.Types["CON"] if transaction.request.mid is None: transaction.request.mid = self.fetch_mid() key_mid = str_append_hash(host, port, request.mid) self._transactions[key_mid] = transaction key_token = str_append_hash(host, port, request.token) self._transactions_token[key_token] = transaction return self._transactions[key_mid]
python
def send_request(self, request): """ Create the transaction and fill it with the outgoing request. :type request: Request :param request: the request to send :rtype : Transaction :return: the created transaction """ logger.debug("send_request - " + str(request)) assert isinstance(request, Request) try: host, port = request.destination except AttributeError: return request.timestamp = time.time() transaction = Transaction(request=request, timestamp=request.timestamp) if transaction.request.type is None: transaction.request.type = defines.Types["CON"] if transaction.request.mid is None: transaction.request.mid = self.fetch_mid() key_mid = str_append_hash(host, port, request.mid) self._transactions[key_mid] = transaction key_token = str_append_hash(host, port, request.token) self._transactions_token[key_token] = transaction return self._transactions[key_mid]
[ "def", "send_request", "(", "self", ",", "request", ")", ":", "logger", ".", "debug", "(", "\"send_request - \"", "+", "str", "(", "request", ")", ")", "assert", "isinstance", "(", "request", ",", "Request", ")", "try", ":", "host", ",", "port", "=", "...
Create the transaction and fill it with the outgoing request. :type request: Request :param request: the request to send :rtype : Transaction :return: the created transaction
[ "Create", "the", "transaction", "and", "fill", "it", "with", "the", "outgoing", "request", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/messagelayer.py#L192-L222
train
210,709
Tanganelli/CoAPthon3
coapthon/layers/messagelayer.py
MessageLayer.send_response
def send_response(self, transaction): """ Set the type, the token and eventually the MID for the outgoing response :type transaction: Transaction :param transaction: the transaction that owns the response :rtype : Transaction :return: the edited transaction """ logger.debug("send_response - " + str(transaction.response)) if transaction.response.type is None: if transaction.request.type == defines.Types["CON"] and not transaction.request.acknowledged: transaction.response.type = defines.Types["ACK"] transaction.response.mid = transaction.request.mid transaction.response.acknowledged = True transaction.completed = True elif transaction.request.type == defines.Types["NON"]: transaction.response.type = defines.Types["NON"] else: transaction.response.type = defines.Types["CON"] transaction.response.token = transaction.request.token if transaction.response.mid is None: transaction.response.mid = self.fetch_mid() try: host, port = transaction.response.destination except AttributeError: return key_mid = str_append_hash(host, port, transaction.response.mid) self._transactions[key_mid] = transaction transaction.request.acknowledged = True return transaction
python
def send_response(self, transaction): """ Set the type, the token and eventually the MID for the outgoing response :type transaction: Transaction :param transaction: the transaction that owns the response :rtype : Transaction :return: the edited transaction """ logger.debug("send_response - " + str(transaction.response)) if transaction.response.type is None: if transaction.request.type == defines.Types["CON"] and not transaction.request.acknowledged: transaction.response.type = defines.Types["ACK"] transaction.response.mid = transaction.request.mid transaction.response.acknowledged = True transaction.completed = True elif transaction.request.type == defines.Types["NON"]: transaction.response.type = defines.Types["NON"] else: transaction.response.type = defines.Types["CON"] transaction.response.token = transaction.request.token if transaction.response.mid is None: transaction.response.mid = self.fetch_mid() try: host, port = transaction.response.destination except AttributeError: return key_mid = str_append_hash(host, port, transaction.response.mid) self._transactions[key_mid] = transaction transaction.request.acknowledged = True return transaction
[ "def", "send_response", "(", "self", ",", "transaction", ")", ":", "logger", ".", "debug", "(", "\"send_response - \"", "+", "str", "(", "transaction", ".", "response", ")", ")", "if", "transaction", ".", "response", ".", "type", "is", "None", ":", "if", ...
Set the type, the token and eventually the MID for the outgoing response :type transaction: Transaction :param transaction: the transaction that owns the response :rtype : Transaction :return: the edited transaction
[ "Set", "the", "type", "the", "token", "and", "eventually", "the", "MID", "for", "the", "outgoing", "response" ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/messagelayer.py#L224-L256
train
210,710
Tanganelli/CoAPthon3
coapthon/layers/messagelayer.py
MessageLayer.send_empty
def send_empty(self, transaction, related, message): """ Manage ACK or RST related to a transaction. Sets if the transaction has been acknowledged or rejected. :param transaction: the transaction :param related: if the ACK/RST message is related to the request or the response. Must be equal to transaction.request or to transaction.response or None :type message: Message :param message: the ACK or RST message to send """ logger.debug("send_empty - " + str(message)) if transaction is None: try: host, port = message.destination except AttributeError: return key_mid = str_append_hash(host, port, message.mid) key_token = str_append_hash(host, port, message.token) if key_mid in self._transactions: transaction = self._transactions[key_mid] related = transaction.response elif key_token in self._transactions_token: transaction = self._transactions_token[key_token] related = transaction.response else: return message if message.type == defines.Types["ACK"]: if transaction.request == related: transaction.request.acknowledged = True transaction.completed = True message.mid = transaction.request.mid message.code = 0 message.destination = transaction.request.source elif transaction.response == related: transaction.response.acknowledged = True transaction.completed = True message.mid = transaction.response.mid message.code = 0 message.token = transaction.response.token message.destination = transaction.response.source elif message.type == defines.Types["RST"]: if transaction.request == related: transaction.request.rejected = True message._mid = transaction.request.mid if message.mid is None: message.mid = self.fetch_mid() message.code = 0 message.token = transaction.request.token message.destination = transaction.request.source elif transaction.response == related: transaction.response.rejected = True transaction.completed = True message._mid = transaction.response.mid if message.mid is None: message.mid = self.fetch_mid() message.code = 0 message.token = transaction.response.token message.destination = transaction.response.source return message
python
def send_empty(self, transaction, related, message): """ Manage ACK or RST related to a transaction. Sets if the transaction has been acknowledged or rejected. :param transaction: the transaction :param related: if the ACK/RST message is related to the request or the response. Must be equal to transaction.request or to transaction.response or None :type message: Message :param message: the ACK or RST message to send """ logger.debug("send_empty - " + str(message)) if transaction is None: try: host, port = message.destination except AttributeError: return key_mid = str_append_hash(host, port, message.mid) key_token = str_append_hash(host, port, message.token) if key_mid in self._transactions: transaction = self._transactions[key_mid] related = transaction.response elif key_token in self._transactions_token: transaction = self._transactions_token[key_token] related = transaction.response else: return message if message.type == defines.Types["ACK"]: if transaction.request == related: transaction.request.acknowledged = True transaction.completed = True message.mid = transaction.request.mid message.code = 0 message.destination = transaction.request.source elif transaction.response == related: transaction.response.acknowledged = True transaction.completed = True message.mid = transaction.response.mid message.code = 0 message.token = transaction.response.token message.destination = transaction.response.source elif message.type == defines.Types["RST"]: if transaction.request == related: transaction.request.rejected = True message._mid = transaction.request.mid if message.mid is None: message.mid = self.fetch_mid() message.code = 0 message.token = transaction.request.token message.destination = transaction.request.source elif transaction.response == related: transaction.response.rejected = True transaction.completed = True message._mid = transaction.response.mid if message.mid is None: message.mid = self.fetch_mid() message.code = 0 message.token = transaction.response.token message.destination = transaction.response.source return message
[ "def", "send_empty", "(", "self", ",", "transaction", ",", "related", ",", "message", ")", ":", "logger", ".", "debug", "(", "\"send_empty - \"", "+", "str", "(", "message", ")", ")", "if", "transaction", "is", "None", ":", "try", ":", "host", ",", "po...
Manage ACK or RST related to a transaction. Sets if the transaction has been acknowledged or rejected. :param transaction: the transaction :param related: if the ACK/RST message is related to the request or the response. Must be equal to transaction.request or to transaction.response or None :type message: Message :param message: the ACK or RST message to send
[ "Manage", "ACK", "or", "RST", "related", "to", "a", "transaction", ".", "Sets", "if", "the", "transaction", "has", "been", "acknowledged", "or", "rejected", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/messagelayer.py#L258-L318
train
210,711
Tanganelli/CoAPthon3
coapthon/messages/response.py
Response.location_path
def location_path(self): """ Return the Location-Path of the response. :rtype : String :return: the Location-Path option """ value = [] for option in self.options: if option.number == defines.OptionRegistry.LOCATION_PATH.number: value.append(str(option.value)) return "/".join(value)
python
def location_path(self): """ Return the Location-Path of the response. :rtype : String :return: the Location-Path option """ value = [] for option in self.options: if option.number == defines.OptionRegistry.LOCATION_PATH.number: value.append(str(option.value)) return "/".join(value)
[ "def", "location_path", "(", "self", ")", ":", "value", "=", "[", "]", "for", "option", "in", "self", ".", "options", ":", "if", "option", ".", "number", "==", "defines", ".", "OptionRegistry", ".", "LOCATION_PATH", ".", "number", ":", "value", ".", "a...
Return the Location-Path of the response. :rtype : String :return: the Location-Path option
[ "Return", "the", "Location", "-", "Path", "of", "the", "response", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/response.py#L13-L24
train
210,712
Tanganelli/CoAPthon3
coapthon/messages/response.py
Response.location_path
def location_path(self, path): """ Set the Location-Path of the response. :type path: String :param path: the Location-Path as a string """ path = path.strip("/") tmp = path.split("?") path = tmp[0] paths = path.split("/") for p in paths: option = Option() option.number = defines.OptionRegistry.LOCATION_PATH.number option.value = p self.add_option(option)
python
def location_path(self, path): """ Set the Location-Path of the response. :type path: String :param path: the Location-Path as a string """ path = path.strip("/") tmp = path.split("?") path = tmp[0] paths = path.split("/") for p in paths: option = Option() option.number = defines.OptionRegistry.LOCATION_PATH.number option.value = p self.add_option(option)
[ "def", "location_path", "(", "self", ",", "path", ")", ":", "path", "=", "path", ".", "strip", "(", "\"/\"", ")", "tmp", "=", "path", ".", "split", "(", "\"?\"", ")", "path", "=", "tmp", "[", "0", "]", "paths", "=", "path", ".", "split", "(", "...
Set the Location-Path of the response. :type path: String :param path: the Location-Path as a string
[ "Set", "the", "Location", "-", "Path", "of", "the", "response", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/response.py#L27-L42
train
210,713
Tanganelli/CoAPthon3
coapthon/messages/response.py
Response.location_query
def location_query(self): """ Return the Location-Query of the response. :rtype : String :return: the Location-Query option """ value = [] for option in self.options: if option.number == defines.OptionRegistry.LOCATION_QUERY.number: value.append(option.value) return value
python
def location_query(self): """ Return the Location-Query of the response. :rtype : String :return: the Location-Query option """ value = [] for option in self.options: if option.number == defines.OptionRegistry.LOCATION_QUERY.number: value.append(option.value) return value
[ "def", "location_query", "(", "self", ")", ":", "value", "=", "[", "]", "for", "option", "in", "self", ".", "options", ":", "if", "option", ".", "number", "==", "defines", ".", "OptionRegistry", ".", "LOCATION_QUERY", ".", "number", ":", "value", ".", ...
Return the Location-Query of the response. :rtype : String :return: the Location-Query option
[ "Return", "the", "Location", "-", "Query", "of", "the", "response", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/response.py#L55-L66
train
210,714
Tanganelli/CoAPthon3
coapthon/messages/response.py
Response.location_query
def location_query(self, value): """ Set the Location-Query of the response. :type path: String :param path: the Location-Query as a string """ del self.location_query queries = value.split("&") for q in queries: option = Option() option.number = defines.OptionRegistry.LOCATION_QUERY.number option.value = str(q) self.add_option(option)
python
def location_query(self, value): """ Set the Location-Query of the response. :type path: String :param path: the Location-Query as a string """ del self.location_query queries = value.split("&") for q in queries: option = Option() option.number = defines.OptionRegistry.LOCATION_QUERY.number option.value = str(q) self.add_option(option)
[ "def", "location_query", "(", "self", ",", "value", ")", ":", "del", "self", ".", "location_query", "queries", "=", "value", ".", "split", "(", "\"&\"", ")", "for", "q", "in", "queries", ":", "option", "=", "Option", "(", ")", "option", ".", "number", ...
Set the Location-Query of the response. :type path: String :param path: the Location-Query as a string
[ "Set", "the", "Location", "-", "Query", "of", "the", "response", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/response.py#L69-L82
train
210,715
Tanganelli/CoAPthon3
coapthon/messages/response.py
Response.max_age
def max_age(self): """ Return the MaxAge of the response. :rtype : int :return: the MaxAge option """ value = defines.OptionRegistry.MAX_AGE.default for option in self.options: if option.number == defines.OptionRegistry.MAX_AGE.number: value = int(option.value) return value
python
def max_age(self): """ Return the MaxAge of the response. :rtype : int :return: the MaxAge option """ value = defines.OptionRegistry.MAX_AGE.default for option in self.options: if option.number == defines.OptionRegistry.MAX_AGE.number: value = int(option.value) return value
[ "def", "max_age", "(", "self", ")", ":", "value", "=", "defines", ".", "OptionRegistry", ".", "MAX_AGE", ".", "default", "for", "option", "in", "self", ".", "options", ":", "if", "option", ".", "number", "==", "defines", ".", "OptionRegistry", ".", "MAX_...
Return the MaxAge of the response. :rtype : int :return: the MaxAge option
[ "Return", "the", "MaxAge", "of", "the", "response", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/response.py#L92-L103
train
210,716
Tanganelli/CoAPthon3
coapthon/messages/response.py
Response.max_age
def max_age(self, value): """ Set the MaxAge of the response. :type value: int :param value: the MaxAge option """ option = Option() option.number = defines.OptionRegistry.MAX_AGE.number option.value = int(value) self.del_option_by_number(defines.OptionRegistry.MAX_AGE.number) self.add_option(option)
python
def max_age(self, value): """ Set the MaxAge of the response. :type value: int :param value: the MaxAge option """ option = Option() option.number = defines.OptionRegistry.MAX_AGE.number option.value = int(value) self.del_option_by_number(defines.OptionRegistry.MAX_AGE.number) self.add_option(option)
[ "def", "max_age", "(", "self", ",", "value", ")", ":", "option", "=", "Option", "(", ")", "option", ".", "number", "=", "defines", ".", "OptionRegistry", ".", "MAX_AGE", ".", "number", "option", ".", "value", "=", "int", "(", "value", ")", "self", "....
Set the MaxAge of the response. :type value: int :param value: the MaxAge option
[ "Set", "the", "MaxAge", "of", "the", "response", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/response.py#L106-L117
train
210,717
Tanganelli/CoAPthon3
coapthon/server/coap.py
CoAP.receive_request
def receive_request(self, transaction): """ Handle requests coming from the udp socket. :param transaction: the transaction created to manage the request """ with transaction: transaction.separate_timer = self._start_separate_timer(transaction) self._blockLayer.receive_request(transaction) if transaction.block_transfer: self._stop_separate_timer(transaction.separate_timer) self._messageLayer.send_response(transaction) self.send_datagram(transaction.response) return self._observeLayer.receive_request(transaction) self._requestLayer.receive_request(transaction) if transaction.resource is not None and transaction.resource.changed: self.notify(transaction.resource) transaction.resource.changed = False elif transaction.resource is not None and transaction.resource.deleted: self.notify(transaction.resource) transaction.resource.deleted = False self._observeLayer.send_response(transaction) self._blockLayer.send_response(transaction) self._stop_separate_timer(transaction.separate_timer) self._messageLayer.send_response(transaction) if transaction.response is not None: if transaction.response.type == defines.Types["CON"]: self._start_retransmission(transaction, transaction.response) self.send_datagram(transaction.response)
python
def receive_request(self, transaction): """ Handle requests coming from the udp socket. :param transaction: the transaction created to manage the request """ with transaction: transaction.separate_timer = self._start_separate_timer(transaction) self._blockLayer.receive_request(transaction) if transaction.block_transfer: self._stop_separate_timer(transaction.separate_timer) self._messageLayer.send_response(transaction) self.send_datagram(transaction.response) return self._observeLayer.receive_request(transaction) self._requestLayer.receive_request(transaction) if transaction.resource is not None and transaction.resource.changed: self.notify(transaction.resource) transaction.resource.changed = False elif transaction.resource is not None and transaction.resource.deleted: self.notify(transaction.resource) transaction.resource.deleted = False self._observeLayer.send_response(transaction) self._blockLayer.send_response(transaction) self._stop_separate_timer(transaction.separate_timer) self._messageLayer.send_response(transaction) if transaction.response is not None: if transaction.response.type == defines.Types["CON"]: self._start_retransmission(transaction, transaction.response) self.send_datagram(transaction.response)
[ "def", "receive_request", "(", "self", ",", "transaction", ")", ":", "with", "transaction", ":", "transaction", ".", "separate_timer", "=", "self", ".", "_start_separate_timer", "(", "transaction", ")", "self", ".", "_blockLayer", ".", "receive_request", "(", "t...
Handle requests coming from the udp socket. :param transaction: the transaction created to manage the request
[ "Handle", "requests", "coming", "from", "the", "udp", "socket", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/server/coap.py#L197-L238
train
210,718
Tanganelli/CoAPthon3
coapthon/server/coap.py
CoAP.add_resource
def add_resource(self, path, resource): """ Helper function to add resources to the resource directory during server initialization. :param path: the path for the new created resource :type resource: Resource :param resource: the resource to be added """ assert isinstance(resource, Resource) path = path.strip("/") paths = path.split("/") actual_path = "" i = 0 for p in paths: i += 1 actual_path += "/" + p try: res = self.root[actual_path] except KeyError: res = None if res is None: resource.path = actual_path self.root[actual_path] = resource return True
python
def add_resource(self, path, resource): """ Helper function to add resources to the resource directory during server initialization. :param path: the path for the new created resource :type resource: Resource :param resource: the resource to be added """ assert isinstance(resource, Resource) path = path.strip("/") paths = path.split("/") actual_path = "" i = 0 for p in paths: i += 1 actual_path += "/" + p try: res = self.root[actual_path] except KeyError: res = None if res is None: resource.path = actual_path self.root[actual_path] = resource return True
[ "def", "add_resource", "(", "self", ",", "path", ",", "resource", ")", ":", "assert", "isinstance", "(", "resource", ",", "Resource", ")", "path", "=", "path", ".", "strip", "(", "\"/\"", ")", "paths", "=", "path", ".", "split", "(", "\"/\"", ")", "a...
Helper function to add resources to the resource directory during server initialization. :param path: the path for the new created resource :type resource: Resource :param resource: the resource to be added
[ "Helper", "function", "to", "add", "resources", "to", "the", "resource", "directory", "during", "server", "initialization", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/server/coap.py#L254-L278
train
210,719
Tanganelli/CoAPthon3
coapthon/server/coap.py
CoAP.remove_resource
def remove_resource(self, path): """ Helper function to remove resources. :param path: the path for the unwanted resource :rtype : the removed object """ path = path.strip("/") paths = path.split("/") actual_path = "" i = 0 for p in paths: i += 1 actual_path += "/" + p try: res = self.root[actual_path] except KeyError: res = None if res is not None: del(self.root[actual_path]) return res
python
def remove_resource(self, path): """ Helper function to remove resources. :param path: the path for the unwanted resource :rtype : the removed object """ path = path.strip("/") paths = path.split("/") actual_path = "" i = 0 for p in paths: i += 1 actual_path += "/" + p try: res = self.root[actual_path] except KeyError: res = None if res is not None: del(self.root[actual_path]) return res
[ "def", "remove_resource", "(", "self", ",", "path", ")", ":", "path", "=", "path", ".", "strip", "(", "\"/\"", ")", "paths", "=", "path", ".", "split", "(", "\"/\"", ")", "actual_path", "=", "\"\"", "i", "=", "0", "for", "p", "in", "paths", ":", ...
Helper function to remove resources. :param path: the path for the unwanted resource :rtype : the removed object
[ "Helper", "function", "to", "remove", "resources", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/server/coap.py#L280-L301
train
210,720
Tanganelli/CoAPthon3
coapthon/server/coap.py
CoAP._send_ack
def _send_ack(self, transaction): """ Sends an ACK message for the request. :param transaction: the transaction that owns the request """ ack = Message() ack.type = defines.Types['ACK'] # TODO handle mutex on transaction if not transaction.request.acknowledged and transaction.request.type == defines.Types["CON"]: ack = self._messageLayer.send_empty(transaction, transaction.request, ack) self.send_datagram(ack)
python
def _send_ack(self, transaction): """ Sends an ACK message for the request. :param transaction: the transaction that owns the request """ ack = Message() ack.type = defines.Types['ACK'] # TODO handle mutex on transaction if not transaction.request.acknowledged and transaction.request.type == defines.Types["CON"]: ack = self._messageLayer.send_empty(transaction, transaction.request, ack) self.send_datagram(ack)
[ "def", "_send_ack", "(", "self", ",", "transaction", ")", ":", "ack", "=", "Message", "(", ")", "ack", ".", "type", "=", "defines", ".", "Types", "[", "'ACK'", "]", "# TODO handle mutex on transaction", "if", "not", "transaction", ".", "request", ".", "ack...
Sends an ACK message for the request. :param transaction: the transaction that owns the request
[ "Sends", "an", "ACK", "message", "for", "the", "request", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/server/coap.py#L376-L388
train
210,721
Tanganelli/CoAPthon3
coapthon/server/coap.py
CoAP.notify
def notify(self, resource): """ Notifies the observers of a certain resource. :param resource: the resource """ observers = self._observeLayer.notify(resource) logger.debug("Notify") for transaction in observers: with transaction: transaction.response = None transaction = self._requestLayer.receive_request(transaction) transaction = self._observeLayer.send_response(transaction) transaction = self._blockLayer.send_response(transaction) transaction = self._messageLayer.send_response(transaction) if transaction.response is not None: if transaction.response.type == defines.Types["CON"]: self._start_retransmission(transaction, transaction.response) self.send_datagram(transaction.response)
python
def notify(self, resource): """ Notifies the observers of a certain resource. :param resource: the resource """ observers = self._observeLayer.notify(resource) logger.debug("Notify") for transaction in observers: with transaction: transaction.response = None transaction = self._requestLayer.receive_request(transaction) transaction = self._observeLayer.send_response(transaction) transaction = self._blockLayer.send_response(transaction) transaction = self._messageLayer.send_response(transaction) if transaction.response is not None: if transaction.response.type == defines.Types["CON"]: self._start_retransmission(transaction, transaction.response) self.send_datagram(transaction.response)
[ "def", "notify", "(", "self", ",", "resource", ")", ":", "observers", "=", "self", ".", "_observeLayer", ".", "notify", "(", "resource", ")", "logger", ".", "debug", "(", "\"Notify\"", ")", "for", "transaction", "in", "observers", ":", "with", "transaction...
Notifies the observers of a certain resource. :param resource: the resource
[ "Notifies", "the", "observers", "of", "a", "certain", "resource", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/server/coap.py#L390-L409
train
210,722
Tanganelli/CoAPthon3
coapthon/layers/resourcelayer.py
ResourceLayer.create_resource
def create_resource(self, path, transaction): """ Render a POST request. :param path: the path of the request :param transaction: the transaction :return: the response """ t = self._parent.root.with_prefix(path) max_len = 0 imax = None for i in t: if i == path: # Resource already present return self.edit_resource(transaction, path) elif len(i) > max_len: imax = i max_len = len(i) lp = path parent_resource = self._parent.root[imax] if parent_resource.allow_children: return self.add_resource(transaction, parent_resource, lp) else: transaction.response.code = defines.Codes.METHOD_NOT_ALLOWED.number return transaction
python
def create_resource(self, path, transaction): """ Render a POST request. :param path: the path of the request :param transaction: the transaction :return: the response """ t = self._parent.root.with_prefix(path) max_len = 0 imax = None for i in t: if i == path: # Resource already present return self.edit_resource(transaction, path) elif len(i) > max_len: imax = i max_len = len(i) lp = path parent_resource = self._parent.root[imax] if parent_resource.allow_children: return self.add_resource(transaction, parent_resource, lp) else: transaction.response.code = defines.Codes.METHOD_NOT_ALLOWED.number return transaction
[ "def", "create_resource", "(", "self", ",", "path", ",", "transaction", ")", ":", "t", "=", "self", ".", "_parent", ".", "root", ".", "with_prefix", "(", "path", ")", "max_len", "=", "0", "imax", "=", "None", "for", "i", "in", "t", ":", "if", "i", ...
Render a POST request. :param path: the path of the request :param transaction: the transaction :return: the response
[ "Render", "a", "POST", "request", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/resourcelayer.py#L210-L235
train
210,723
Tanganelli/CoAPthon3
coapthon/layers/resourcelayer.py
ResourceLayer.delete_resource
def delete_resource(self, transaction, path): """ Render a DELETE request. :param transaction: the transaction :param path: the path :return: the response """ resource = transaction.resource method = getattr(resource, 'render_DELETE', None) try: ret = method(request=transaction.request) except NotImplementedError: try: method = getattr(transaction.resource, "render_DELETE_advanced", None) ret = method(request=transaction.request, response=transaction.response) if isinstance(ret, tuple) and len(ret) == 2 and isinstance(ret[1], Response) \ and isinstance(ret[0], bool): # Advanced handler delete, response = ret if delete: del self._parent.root[path] transaction.response = response if transaction.response.code is None: transaction.response.code = defines.Codes.DELETED.number return transaction elif isinstance(ret, tuple) and len(ret) == 3 and isinstance(ret[1], Response) \ and isinstance(ret[0], Resource): # Advanced handler separate resource, response, callback = ret ret = self._handle_separate_advanced(transaction, callback) if not isinstance(ret, tuple) or \ not (isinstance(ret[0], bool) and isinstance(ret[1], Response)): # pragma: no cover transaction.response.code = defines.Codes.INTERNAL_SERVER_ERROR.number return transaction delete, response = ret if delete: del self._parent.root[path] transaction.response = response if transaction.response.code is None: transaction.response.code = defines.Codes.DELETED.number return transaction else: raise NotImplementedError except NotImplementedError: transaction.response.code = defines.Codes.METHOD_NOT_ALLOWED.number return transaction if isinstance(ret, bool): pass elif isinstance(ret, tuple) and len(ret) == 2: resource, callback = ret ret = self._handle_separate(transaction, callback) if not isinstance(ret, bool): # pragma: no cover transaction.response.code = defines.Codes.INTERNAL_SERVER_ERROR.number return transaction else: # pragma: no cover # Handle error transaction.response.code = defines.Codes.INTERNAL_SERVER_ERROR.number return transaction if ret: del self._parent.root[path] transaction.response.code = defines.Codes.DELETED.number transaction.response.payload = None transaction.resource.deleted = True else: # pragma: no cover transaction.response.code = defines.Codes.INTERNAL_SERVER_ERROR.number return transaction
python
def delete_resource(self, transaction, path): """ Render a DELETE request. :param transaction: the transaction :param path: the path :return: the response """ resource = transaction.resource method = getattr(resource, 'render_DELETE', None) try: ret = method(request=transaction.request) except NotImplementedError: try: method = getattr(transaction.resource, "render_DELETE_advanced", None) ret = method(request=transaction.request, response=transaction.response) if isinstance(ret, tuple) and len(ret) == 2 and isinstance(ret[1], Response) \ and isinstance(ret[0], bool): # Advanced handler delete, response = ret if delete: del self._parent.root[path] transaction.response = response if transaction.response.code is None: transaction.response.code = defines.Codes.DELETED.number return transaction elif isinstance(ret, tuple) and len(ret) == 3 and isinstance(ret[1], Response) \ and isinstance(ret[0], Resource): # Advanced handler separate resource, response, callback = ret ret = self._handle_separate_advanced(transaction, callback) if not isinstance(ret, tuple) or \ not (isinstance(ret[0], bool) and isinstance(ret[1], Response)): # pragma: no cover transaction.response.code = defines.Codes.INTERNAL_SERVER_ERROR.number return transaction delete, response = ret if delete: del self._parent.root[path] transaction.response = response if transaction.response.code is None: transaction.response.code = defines.Codes.DELETED.number return transaction else: raise NotImplementedError except NotImplementedError: transaction.response.code = defines.Codes.METHOD_NOT_ALLOWED.number return transaction if isinstance(ret, bool): pass elif isinstance(ret, tuple) and len(ret) == 2: resource, callback = ret ret = self._handle_separate(transaction, callback) if not isinstance(ret, bool): # pragma: no cover transaction.response.code = defines.Codes.INTERNAL_SERVER_ERROR.number return transaction else: # pragma: no cover # Handle error transaction.response.code = defines.Codes.INTERNAL_SERVER_ERROR.number return transaction if ret: del self._parent.root[path] transaction.response.code = defines.Codes.DELETED.number transaction.response.payload = None transaction.resource.deleted = True else: # pragma: no cover transaction.response.code = defines.Codes.INTERNAL_SERVER_ERROR.number return transaction
[ "def", "delete_resource", "(", "self", ",", "transaction", ",", "path", ")", ":", "resource", "=", "transaction", ".", "resource", "method", "=", "getattr", "(", "resource", ",", "'render_DELETE'", ",", "None", ")", "try", ":", "ret", "=", "method", "(", ...
Render a DELETE request. :param transaction: the transaction :param path: the path :return: the response
[ "Render", "a", "DELETE", "request", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/resourcelayer.py#L344-L414
train
210,724
Tanganelli/CoAPthon3
coapthon/layers/resourcelayer.py
ResourceLayer.corelinkformat
def corelinkformat(resource): """ Return a formatted string representation of the corelinkformat in the tree. :return: the string """ msg = "<" + resource.path + ">;" assert(isinstance(resource, Resource)) keys = sorted(list(resource.attributes.keys())) for k in keys: method = getattr(resource, defines.corelinkformat[k], None) if method is not None and method != "": v = method msg = msg[:-1] + ";" + str(v) + "," else: v = resource.attributes[k] if v is not None: msg = msg[:-1] + ";" + k + "=" + v + "," return msg
python
def corelinkformat(resource): """ Return a formatted string representation of the corelinkformat in the tree. :return: the string """ msg = "<" + resource.path + ">;" assert(isinstance(resource, Resource)) keys = sorted(list(resource.attributes.keys())) for k in keys: method = getattr(resource, defines.corelinkformat[k], None) if method is not None and method != "": v = method msg = msg[:-1] + ";" + str(v) + "," else: v = resource.attributes[k] if v is not None: msg = msg[:-1] + ";" + k + "=" + v + "," return msg
[ "def", "corelinkformat", "(", "resource", ")", ":", "msg", "=", "\"<\"", "+", "resource", ".", "path", "+", "\">;\"", "assert", "(", "isinstance", "(", "resource", ",", "Resource", ")", ")", "keys", "=", "sorted", "(", "list", "(", "resource", ".", "at...
Return a formatted string representation of the corelinkformat in the tree. :return: the string
[ "Return", "a", "formatted", "string", "representation", "of", "the", "corelinkformat", "in", "the", "tree", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/resourcelayer.py#L546-L564
train
210,725
Tanganelli/CoAPthon3
coapthon/layers/requestlayer.py
RequestLayer.receive_request
def receive_request(self, transaction): """ Handle request and execute the requested method :type transaction: Transaction :param transaction: the transaction that owns the request :rtype : Transaction :return: the edited transaction with the response to the request """ method = transaction.request.code if method == defines.Codes.GET.number: transaction = self._handle_get(transaction) elif method == defines.Codes.POST.number: transaction = self._handle_post(transaction) elif method == defines.Codes.PUT.number: transaction = self._handle_put(transaction) elif method == defines.Codes.DELETE.number: transaction = self._handle_delete(transaction) else: transaction.response = None return transaction
python
def receive_request(self, transaction): """ Handle request and execute the requested method :type transaction: Transaction :param transaction: the transaction that owns the request :rtype : Transaction :return: the edited transaction with the response to the request """ method = transaction.request.code if method == defines.Codes.GET.number: transaction = self._handle_get(transaction) elif method == defines.Codes.POST.number: transaction = self._handle_post(transaction) elif method == defines.Codes.PUT.number: transaction = self._handle_put(transaction) elif method == defines.Codes.DELETE.number: transaction = self._handle_delete(transaction) else: transaction.response = None return transaction
[ "def", "receive_request", "(", "self", ",", "transaction", ")", ":", "method", "=", "transaction", ".", "request", ".", "code", "if", "method", "==", "defines", ".", "Codes", ".", "GET", ".", "number", ":", "transaction", "=", "self", ".", "_handle_get", ...
Handle request and execute the requested method :type transaction: Transaction :param transaction: the transaction that owns the request :rtype : Transaction :return: the edited transaction with the response to the request
[ "Handle", "request", "and", "execute", "the", "requested", "method" ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/requestlayer.py#L14-L34
train
210,726
Tanganelli/CoAPthon3
coapthon/layers/requestlayer.py
RequestLayer._handle_delete
def _handle_delete(self, transaction): """ Handle DELETE requests :type transaction: Transaction :param transaction: the transaction that owns the request :rtype : Transaction :return: the edited transaction with the response to the request """ path = str("/" + transaction.request.uri_path) transaction.response = Response() transaction.response.destination = transaction.request.source transaction.response.token = transaction.request.token try: resource = self._server.root[path] except KeyError: resource = None if resource is None: transaction.response.code = defines.Codes.NOT_FOUND.number else: # Delete transaction.resource = resource transaction = self._server.resourceLayer.delete_resource(transaction, path) return transaction
python
def _handle_delete(self, transaction): """ Handle DELETE requests :type transaction: Transaction :param transaction: the transaction that owns the request :rtype : Transaction :return: the edited transaction with the response to the request """ path = str("/" + transaction.request.uri_path) transaction.response = Response() transaction.response.destination = transaction.request.source transaction.response.token = transaction.request.token try: resource = self._server.root[path] except KeyError: resource = None if resource is None: transaction.response.code = defines.Codes.NOT_FOUND.number else: # Delete transaction.resource = resource transaction = self._server.resourceLayer.delete_resource(transaction, path) return transaction
[ "def", "_handle_delete", "(", "self", ",", "transaction", ")", ":", "path", "=", "str", "(", "\"/\"", "+", "transaction", ".", "request", ".", "uri_path", ")", "transaction", ".", "response", "=", "Response", "(", ")", "transaction", ".", "response", ".", ...
Handle DELETE requests :type transaction: Transaction :param transaction: the transaction that owns the request :rtype : Transaction :return: the edited transaction with the response to the request
[ "Handle", "DELETE", "requests" ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/requestlayer.py#L117-L141
train
210,727
Tanganelli/CoAPthon3
coapthon/messages/request.py
Request.uri_path
def uri_path(self): """ Return the Uri-Path of a request :rtype : String :return: the Uri-Path """ value = [] for option in self.options: if option.number == defines.OptionRegistry.URI_PATH.number: value.append(str(option.value) + '/') value = "".join(value) value = value[:-1] return value
python
def uri_path(self): """ Return the Uri-Path of a request :rtype : String :return: the Uri-Path """ value = [] for option in self.options: if option.number == defines.OptionRegistry.URI_PATH.number: value.append(str(option.value) + '/') value = "".join(value) value = value[:-1] return value
[ "def", "uri_path", "(", "self", ")", ":", "value", "=", "[", "]", "for", "option", "in", "self", ".", "options", ":", "if", "option", ".", "number", "==", "defines", ".", "OptionRegistry", ".", "URI_PATH", ".", "number", ":", "value", ".", "append", ...
Return the Uri-Path of a request :rtype : String :return: the Uri-Path
[ "Return", "the", "Uri", "-", "Path", "of", "a", "request" ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/request.py#L20-L33
train
210,728
Tanganelli/CoAPthon3
coapthon/messages/request.py
Request.uri_path
def uri_path(self, path): """ Set the Uri-Path of a request. :param path: the Uri-Path """ path = path.strip("/") tmp = path.split("?") path = tmp[0] paths = path.split("/") for p in paths: option = Option() option.number = defines.OptionRegistry.URI_PATH.number option.value = p self.add_option(option) if len(tmp) > 1: query = tmp[1] self.uri_query = query
python
def uri_path(self, path): """ Set the Uri-Path of a request. :param path: the Uri-Path """ path = path.strip("/") tmp = path.split("?") path = tmp[0] paths = path.split("/") for p in paths: option = Option() option.number = defines.OptionRegistry.URI_PATH.number option.value = p self.add_option(option) if len(tmp) > 1: query = tmp[1] self.uri_query = query
[ "def", "uri_path", "(", "self", ",", "path", ")", ":", "path", "=", "path", ".", "strip", "(", "\"/\"", ")", "tmp", "=", "path", ".", "split", "(", "\"?\"", ")", "path", "=", "tmp", "[", "0", "]", "paths", "=", "path", ".", "split", "(", "\"/\"...
Set the Uri-Path of a request. :param path: the Uri-Path
[ "Set", "the", "Uri", "-", "Path", "of", "a", "request", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/request.py#L36-L53
train
210,729
Tanganelli/CoAPthon3
coapthon/messages/request.py
Request.uri_query
def uri_query(self): """ Get the Uri-Query of a request. :return: the Uri-Query :rtype : String :return: the Uri-Query string """ value = [] for option in self.options: if option.number == defines.OptionRegistry.URI_QUERY.number: value.append(str(option.value)) return "&".join(value)
python
def uri_query(self): """ Get the Uri-Query of a request. :return: the Uri-Query :rtype : String :return: the Uri-Query string """ value = [] for option in self.options: if option.number == defines.OptionRegistry.URI_QUERY.number: value.append(str(option.value)) return "&".join(value)
[ "def", "uri_query", "(", "self", ")", ":", "value", "=", "[", "]", "for", "option", "in", "self", ".", "options", ":", "if", "option", ".", "number", "==", "defines", ".", "OptionRegistry", ".", "URI_QUERY", ".", "number", ":", "value", ".", "append", ...
Get the Uri-Query of a request. :return: the Uri-Query :rtype : String :return: the Uri-Query string
[ "Get", "the", "Uri", "-", "Query", "of", "a", "request", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/request.py#L63-L75
train
210,730
Tanganelli/CoAPthon3
coapthon/messages/request.py
Request.uri_query
def uri_query(self, value): """ Adds a query. :param value: the query """ del self.uri_query queries = value.split("&") for q in queries: option = Option() option.number = defines.OptionRegistry.URI_QUERY.number option.value = str(q) self.add_option(option)
python
def uri_query(self, value): """ Adds a query. :param value: the query """ del self.uri_query queries = value.split("&") for q in queries: option = Option() option.number = defines.OptionRegistry.URI_QUERY.number option.value = str(q) self.add_option(option)
[ "def", "uri_query", "(", "self", ",", "value", ")", ":", "del", "self", ".", "uri_query", "queries", "=", "value", ".", "split", "(", "\"&\"", ")", "for", "q", "in", "queries", ":", "option", "=", "Option", "(", ")", "option", ".", "number", "=", "...
Adds a query. :param value: the query
[ "Adds", "a", "query", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/request.py#L78-L90
train
210,731
Tanganelli/CoAPthon3
coapthon/messages/request.py
Request.accept
def accept(self): """ Get the Accept option of a request. :return: the Accept value or None if not specified by the request :rtype : String """ for option in self.options: if option.number == defines.OptionRegistry.ACCEPT.number: return option.value return None
python
def accept(self): """ Get the Accept option of a request. :return: the Accept value or None if not specified by the request :rtype : String """ for option in self.options: if option.number == defines.OptionRegistry.ACCEPT.number: return option.value return None
[ "def", "accept", "(", "self", ")", ":", "for", "option", "in", "self", ".", "options", ":", "if", "option", ".", "number", "==", "defines", ".", "OptionRegistry", ".", "ACCEPT", ".", "number", ":", "return", "option", ".", "value", "return", "None" ]
Get the Accept option of a request. :return: the Accept value or None if not specified by the request :rtype : String
[ "Get", "the", "Accept", "option", "of", "a", "request", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/request.py#L100-L110
train
210,732
Tanganelli/CoAPthon3
coapthon/messages/request.py
Request.accept
def accept(self, value): """ Add an Accept option to a request. :param value: the Accept value """ if value in list(defines.Content_types.values()): option = Option() option.number = defines.OptionRegistry.ACCEPT.number option.value = value self.add_option(option)
python
def accept(self, value): """ Add an Accept option to a request. :param value: the Accept value """ if value in list(defines.Content_types.values()): option = Option() option.number = defines.OptionRegistry.ACCEPT.number option.value = value self.add_option(option)
[ "def", "accept", "(", "self", ",", "value", ")", ":", "if", "value", "in", "list", "(", "defines", ".", "Content_types", ".", "values", "(", ")", ")", ":", "option", "=", "Option", "(", ")", "option", ".", "number", "=", "defines", ".", "OptionRegist...
Add an Accept option to a request. :param value: the Accept value
[ "Add", "an", "Accept", "option", "to", "a", "request", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/request.py#L113-L123
train
210,733
Tanganelli/CoAPthon3
coapthon/messages/request.py
Request.if_match
def if_match(self): """ Get the If-Match option of a request. :return: the If-Match values or [] if not specified by the request :rtype : list """ value = [] for option in self.options: if option.number == defines.OptionRegistry.IF_MATCH.number: value.append(option.value) return value
python
def if_match(self): """ Get the If-Match option of a request. :return: the If-Match values or [] if not specified by the request :rtype : list """ value = [] for option in self.options: if option.number == defines.OptionRegistry.IF_MATCH.number: value.append(option.value) return value
[ "def", "if_match", "(", "self", ")", ":", "value", "=", "[", "]", "for", "option", "in", "self", ".", "options", ":", "if", "option", ".", "number", "==", "defines", ".", "OptionRegistry", ".", "IF_MATCH", ".", "number", ":", "value", ".", "append", ...
Get the If-Match option of a request. :return: the If-Match values or [] if not specified by the request :rtype : list
[ "Get", "the", "If", "-", "Match", "option", "of", "a", "request", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/request.py#L133-L144
train
210,734
Tanganelli/CoAPthon3
coapthon/messages/request.py
Request.if_match
def if_match(self, values): """ Set the If-Match option of a request. :param values: the If-Match values :type values : list """ assert isinstance(values, list) for v in values: option = Option() option.number = defines.OptionRegistry.IF_MATCH.number option.value = v self.add_option(option)
python
def if_match(self, values): """ Set the If-Match option of a request. :param values: the If-Match values :type values : list """ assert isinstance(values, list) for v in values: option = Option() option.number = defines.OptionRegistry.IF_MATCH.number option.value = v self.add_option(option)
[ "def", "if_match", "(", "self", ",", "values", ")", ":", "assert", "isinstance", "(", "values", ",", "list", ")", "for", "v", "in", "values", ":", "option", "=", "Option", "(", ")", "option", ".", "number", "=", "defines", ".", "OptionRegistry", ".", ...
Set the If-Match option of a request. :param values: the If-Match values :type values : list
[ "Set", "the", "If", "-", "Match", "option", "of", "a", "request", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/request.py#L147-L159
train
210,735
Tanganelli/CoAPthon3
coapthon/messages/request.py
Request.if_none_match
def if_none_match(self): """ Get the if-none-match option of a request. :return: True, if if-none-match is present :rtype : bool """ for option in self.options: if option.number == defines.OptionRegistry.IF_NONE_MATCH.number: return True return False
python
def if_none_match(self): """ Get the if-none-match option of a request. :return: True, if if-none-match is present :rtype : bool """ for option in self.options: if option.number == defines.OptionRegistry.IF_NONE_MATCH.number: return True return False
[ "def", "if_none_match", "(", "self", ")", ":", "for", "option", "in", "self", ".", "options", ":", "if", "option", ".", "number", "==", "defines", ".", "OptionRegistry", ".", "IF_NONE_MATCH", ".", "number", ":", "return", "True", "return", "False" ]
Get the if-none-match option of a request. :return: True, if if-none-match is present :rtype : bool
[ "Get", "the", "if", "-", "none", "-", "match", "option", "of", "a", "request", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/request.py#L169-L179
train
210,736
Tanganelli/CoAPthon3
coapthon/messages/request.py
Request.add_if_none_match
def add_if_none_match(self): """ Add the if-none-match option to the request. """ option = Option() option.number = defines.OptionRegistry.IF_NONE_MATCH.number option.value = None self.add_option(option)
python
def add_if_none_match(self): """ Add the if-none-match option to the request. """ option = Option() option.number = defines.OptionRegistry.IF_NONE_MATCH.number option.value = None self.add_option(option)
[ "def", "add_if_none_match", "(", "self", ")", ":", "option", "=", "Option", "(", ")", "option", ".", "number", "=", "defines", ".", "OptionRegistry", ".", "IF_NONE_MATCH", ".", "number", "option", ".", "value", "=", "None", "self", ".", "add_option", "(", ...
Add the if-none-match option to the request.
[ "Add", "the", "if", "-", "none", "-", "match", "option", "to", "the", "request", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/request.py#L181-L188
train
210,737
Tanganelli/CoAPthon3
coapthon/messages/request.py
Request.proxy_uri
def proxy_uri(self): """ Get the Proxy-Uri option of a request. :return: the Proxy-Uri values or None if not specified by the request :rtype : String """ for option in self.options: if option.number == defines.OptionRegistry.PROXY_URI.number: return option.value return None
python
def proxy_uri(self): """ Get the Proxy-Uri option of a request. :return: the Proxy-Uri values or None if not specified by the request :rtype : String """ for option in self.options: if option.number == defines.OptionRegistry.PROXY_URI.number: return option.value return None
[ "def", "proxy_uri", "(", "self", ")", ":", "for", "option", "in", "self", ".", "options", ":", "if", "option", ".", "number", "==", "defines", ".", "OptionRegistry", ".", "PROXY_URI", ".", "number", ":", "return", "option", ".", "value", "return", "None"...
Get the Proxy-Uri option of a request. :return: the Proxy-Uri values or None if not specified by the request :rtype : String
[ "Get", "the", "Proxy", "-", "Uri", "option", "of", "a", "request", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/request.py#L208-L218
train
210,738
Tanganelli/CoAPthon3
coapthon/messages/request.py
Request.proxy_uri
def proxy_uri(self, value): """ Set the Proxy-Uri option of a request. :param value: the Proxy-Uri value """ option = Option() option.number = defines.OptionRegistry.PROXY_URI.number option.value = str(value) self.add_option(option)
python
def proxy_uri(self, value): """ Set the Proxy-Uri option of a request. :param value: the Proxy-Uri value """ option = Option() option.number = defines.OptionRegistry.PROXY_URI.number option.value = str(value) self.add_option(option)
[ "def", "proxy_uri", "(", "self", ",", "value", ")", ":", "option", "=", "Option", "(", ")", "option", ".", "number", "=", "defines", ".", "OptionRegistry", ".", "PROXY_URI", ".", "number", "option", ".", "value", "=", "str", "(", "value", ")", "self", ...
Set the Proxy-Uri option of a request. :param value: the Proxy-Uri value
[ "Set", "the", "Proxy", "-", "Uri", "option", "of", "a", "request", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/request.py#L221-L230
train
210,739
Tanganelli/CoAPthon3
coapthon/messages/request.py
Request.proxy_schema
def proxy_schema(self): """ Get the Proxy-Schema option of a request. :return: the Proxy-Schema values or None if not specified by the request :rtype : String """ for option in self.options: if option.number == defines.OptionRegistry.PROXY_SCHEME.number: return option.value return None
python
def proxy_schema(self): """ Get the Proxy-Schema option of a request. :return: the Proxy-Schema values or None if not specified by the request :rtype : String """ for option in self.options: if option.number == defines.OptionRegistry.PROXY_SCHEME.number: return option.value return None
[ "def", "proxy_schema", "(", "self", ")", ":", "for", "option", "in", "self", ".", "options", ":", "if", "option", ".", "number", "==", "defines", ".", "OptionRegistry", ".", "PROXY_SCHEME", ".", "number", ":", "return", "option", ".", "value", "return", ...
Get the Proxy-Schema option of a request. :return: the Proxy-Schema values or None if not specified by the request :rtype : String
[ "Get", "the", "Proxy", "-", "Schema", "option", "of", "a", "request", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/request.py#L240-L250
train
210,740
Tanganelli/CoAPthon3
coapthon/messages/request.py
Request.proxy_schema
def proxy_schema(self, value): """ Set the Proxy-Schema option of a request. :param value: the Proxy-Schema value """ option = Option() option.number = defines.OptionRegistry.PROXY_SCHEME.number option.value = str(value) self.add_option(option)
python
def proxy_schema(self, value): """ Set the Proxy-Schema option of a request. :param value: the Proxy-Schema value """ option = Option() option.number = defines.OptionRegistry.PROXY_SCHEME.number option.value = str(value) self.add_option(option)
[ "def", "proxy_schema", "(", "self", ",", "value", ")", ":", "option", "=", "Option", "(", ")", "option", ".", "number", "=", "defines", ".", "OptionRegistry", ".", "PROXY_SCHEME", ".", "number", "option", ".", "value", "=", "str", "(", "value", ")", "s...
Set the Proxy-Schema option of a request. :param value: the Proxy-Schema value
[ "Set", "the", "Proxy", "-", "Schema", "option", "of", "a", "request", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/request.py#L253-L262
train
210,741
Tanganelli/CoAPthon3
coapthon/caching/cache.py
Cache.cache_add
def cache_add(self, request, response): """ checks for full cache and valid code before updating the cache :param request: :param response: :return: """ logger.debug("adding response to the cache") """ checking for valid code - """ code = response.code try: utils.check_code(code) except utils.InvalidResponseCode: # pragma no cover logger.error("Invalid response code") return """ return if max_age is 0 """ if response.max_age == 0: return """ Initialising new cache element based on the mode and updating the cache """ if self.mode == defines.FORWARD_PROXY: new_key = CacheKey(request) else: new_key = ReverseCacheKey(request) logger.debug("MaxAge = {maxage}".format(maxage=response.max_age)) new_element = CacheElement(new_key, response, request, response.max_age) self.cache.update(new_key, new_element) logger.debug("Cache Size = {size}".format(size=self.cache.debug_print()))
python
def cache_add(self, request, response): """ checks for full cache and valid code before updating the cache :param request: :param response: :return: """ logger.debug("adding response to the cache") """ checking for valid code - """ code = response.code try: utils.check_code(code) except utils.InvalidResponseCode: # pragma no cover logger.error("Invalid response code") return """ return if max_age is 0 """ if response.max_age == 0: return """ Initialising new cache element based on the mode and updating the cache """ if self.mode == defines.FORWARD_PROXY: new_key = CacheKey(request) else: new_key = ReverseCacheKey(request) logger.debug("MaxAge = {maxage}".format(maxage=response.max_age)) new_element = CacheElement(new_key, response, request, response.max_age) self.cache.update(new_key, new_element) logger.debug("Cache Size = {size}".format(size=self.cache.debug_print()))
[ "def", "cache_add", "(", "self", ",", "request", ",", "response", ")", ":", "logger", ".", "debug", "(", "\"adding response to the cache\"", ")", "\"\"\"\n checking for valid code\n- \"\"\"", "code", "=", "response", ".", "code", "try", ":", "utils", "....
checks for full cache and valid code before updating the cache :param request: :param response: :return:
[ "checks", "for", "full", "cache", "and", "valid", "code", "before", "updating", "the", "cache" ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/caching/cache.py#L27-L66
train
210,742
Tanganelli/CoAPthon3
coapthon/caching/cache.py
Cache.search_related
def search_related(self, request): logger.debug("Cache Search Request") if self.cache.is_empty() is True: logger.debug("Empty Cache") return None """ extracting everything from the cache """ result = [] items = list(self.cache.cache.items()) for key, item in items: element = self.cache.get(item.key) logger.debug("Element : {elm}".format(elm=str(element))) if request.proxy_uri == element.uri: result.append(item) return result
python
def search_related(self, request): logger.debug("Cache Search Request") if self.cache.is_empty() is True: logger.debug("Empty Cache") return None """ extracting everything from the cache """ result = [] items = list(self.cache.cache.items()) for key, item in items: element = self.cache.get(item.key) logger.debug("Element : {elm}".format(elm=str(element))) if request.proxy_uri == element.uri: result.append(item) return result
[ "def", "search_related", "(", "self", ",", "request", ")", ":", "logger", ".", "debug", "(", "\"Cache Search Request\"", ")", "if", "self", ".", "cache", ".", "is_empty", "(", ")", "is", "True", ":", "logger", ".", "debug", "(", "\"Empty Cache\"", ")", "...
extracting everything from the cache
[ "extracting", "everything", "from", "the", "cache" ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/caching/cache.py#L68-L87
train
210,743
Tanganelli/CoAPthon3
coapthon/caching/cache.py
Cache.search_response
def search_response(self, request): """ creates a key from the request and searches the cache with it :param request: :return CacheElement: returns None if there's a cache miss """ logger.debug("Cache Search Response") if self.cache.is_empty() is True: logger.debug("Empty Cache") return None """ create a new cache key from the request """ if self.mode == defines.FORWARD_PROXY: search_key = CacheKey(request) else: search_key = ReverseCacheKey(request) response = self.cache.get(search_key) return response
python
def search_response(self, request): """ creates a key from the request and searches the cache with it :param request: :return CacheElement: returns None if there's a cache miss """ logger.debug("Cache Search Response") if self.cache.is_empty() is True: logger.debug("Empty Cache") return None """ create a new cache key from the request """ if self.mode == defines.FORWARD_PROXY: search_key = CacheKey(request) else: search_key = ReverseCacheKey(request) response = self.cache.get(search_key) return response
[ "def", "search_response", "(", "self", ",", "request", ")", ":", "logger", ".", "debug", "(", "\"Cache Search Response\"", ")", "if", "self", ".", "cache", ".", "is_empty", "(", ")", "is", "True", ":", "logger", ".", "debug", "(", "\"Empty Cache\"", ")", ...
creates a key from the request and searches the cache with it :param request: :return CacheElement: returns None if there's a cache miss
[ "creates", "a", "key", "from", "the", "request", "and", "searches", "the", "cache", "with", "it" ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/caching/cache.py#L89-L113
train
210,744
Tanganelli/CoAPthon3
coapthon/caching/cache.py
Cache.validate
def validate(self, request, response): """ refreshes a resource when a validation response is received :param request: :param response: :return: """ element = self.search_response(request) if element is not None: element.cached_response.options = response.options element.freshness = True element.max_age = response.max_age element.creation_time = time.time() element.uri = request.proxy_uri
python
def validate(self, request, response): """ refreshes a resource when a validation response is received :param request: :param response: :return: """ element = self.search_response(request) if element is not None: element.cached_response.options = response.options element.freshness = True element.max_age = response.max_age element.creation_time = time.time() element.uri = request.proxy_uri
[ "def", "validate", "(", "self", ",", "request", ",", "response", ")", ":", "element", "=", "self", ".", "search_response", "(", "request", ")", "if", "element", "is", "not", "None", ":", "element", ".", "cached_response", ".", "options", "=", "response", ...
refreshes a resource when a validation response is received :param request: :param response: :return:
[ "refreshes", "a", "resource", "when", "a", "validation", "response", "is", "received" ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/caching/cache.py#L115-L129
train
210,745
Tanganelli/CoAPthon3
coapthon/layers/forwardLayer.py
ForwardLayer._forward_request
def _forward_request(transaction, destination, path): """ Forward requests. :type transaction: Transaction :param transaction: the transaction that owns the request :param destination: the destination of the request (IP, port) :param path: the path of the request. :rtype : Transaction :return: the edited transaction """ client = HelperClient(destination) request = Request() request.options = copy.deepcopy(transaction.request.options) del request.block2 del request.block1 del request.uri_path del request.proxy_uri del request.proxy_schema # TODO handle observing del request.observe # request.observe = transaction.request.observe request.uri_path = path request.destination = destination request.payload = transaction.request.payload request.code = transaction.request.code response = client.send_request(request) client.stop() if response is not None: transaction.response.payload = response.payload transaction.response.code = response.code transaction.response.options = response.options else: transaction.response.code = defines.Codes.SERVICE_UNAVAILABLE.number return transaction
python
def _forward_request(transaction, destination, path): """ Forward requests. :type transaction: Transaction :param transaction: the transaction that owns the request :param destination: the destination of the request (IP, port) :param path: the path of the request. :rtype : Transaction :return: the edited transaction """ client = HelperClient(destination) request = Request() request.options = copy.deepcopy(transaction.request.options) del request.block2 del request.block1 del request.uri_path del request.proxy_uri del request.proxy_schema # TODO handle observing del request.observe # request.observe = transaction.request.observe request.uri_path = path request.destination = destination request.payload = transaction.request.payload request.code = transaction.request.code response = client.send_request(request) client.stop() if response is not None: transaction.response.payload = response.payload transaction.response.code = response.code transaction.response.options = response.options else: transaction.response.code = defines.Codes.SERVICE_UNAVAILABLE.number return transaction
[ "def", "_forward_request", "(", "transaction", ",", "destination", ",", "path", ")", ":", "client", "=", "HelperClient", "(", "destination", ")", "request", "=", "Request", "(", ")", "request", ".", "options", "=", "copy", ".", "deepcopy", "(", "transaction"...
Forward requests. :type transaction: Transaction :param transaction: the transaction that owns the request :param destination: the destination of the request (IP, port) :param path: the path of the request. :rtype : Transaction :return: the edited transaction
[ "Forward", "requests", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/forwardLayer.py#L83-L119
train
210,746
Tanganelli/CoAPthon3
coapthon/client/coap.py
CoAP.close
def close(self): """ Stop the client. """ self.stopped.set() for event in self.to_be_stopped: event.set() if self._receiver_thread is not None: self._receiver_thread.join() self._socket.close()
python
def close(self): """ Stop the client. """ self.stopped.set() for event in self.to_be_stopped: event.set() if self._receiver_thread is not None: self._receiver_thread.join() self._socket.close()
[ "def", "close", "(", "self", ")", ":", "self", ".", "stopped", ".", "set", "(", ")", "for", "event", "in", "self", ".", "to_be_stopped", ":", "event", ".", "set", "(", ")", "if", "self", ".", "_receiver_thread", "is", "not", "None", ":", "self", "....
Stop the client.
[ "Stop", "the", "client", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/client/coap.py#L69-L79
train
210,747
Tanganelli/CoAPthon3
coapthon/client/coap.py
CoAP.send_message
def send_message(self, message): """ Prepare a message to send on the UDP socket. Eventually set retransmissions. :param message: the message to send """ if isinstance(message, Request): request = self._requestLayer.send_request(message) request = self._observeLayer.send_request(request) request = self._blockLayer.send_request(request) transaction = self._messageLayer.send_request(request) self.send_datagram(transaction.request) if transaction.request.type == defines.Types["CON"]: self._start_retransmission(transaction, transaction.request) elif isinstance(message, Message): message = self._observeLayer.send_empty(message) message = self._messageLayer.send_empty(None, None, message) self.send_datagram(message)
python
def send_message(self, message): """ Prepare a message to send on the UDP socket. Eventually set retransmissions. :param message: the message to send """ if isinstance(message, Request): request = self._requestLayer.send_request(message) request = self._observeLayer.send_request(request) request = self._blockLayer.send_request(request) transaction = self._messageLayer.send_request(request) self.send_datagram(transaction.request) if transaction.request.type == defines.Types["CON"]: self._start_retransmission(transaction, transaction.request) elif isinstance(message, Message): message = self._observeLayer.send_empty(message) message = self._messageLayer.send_empty(None, None, message) self.send_datagram(message)
[ "def", "send_message", "(", "self", ",", "message", ")", ":", "if", "isinstance", "(", "message", ",", "Request", ")", ":", "request", "=", "self", ".", "_requestLayer", ".", "send_request", "(", "message", ")", "request", "=", "self", ".", "_observeLayer"...
Prepare a message to send on the UDP socket. Eventually set retransmissions. :param message: the message to send
[ "Prepare", "a", "message", "to", "send", "on", "the", "UDP", "socket", ".", "Eventually", "set", "retransmissions", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/client/coap.py#L100-L117
train
210,748
Tanganelli/CoAPthon3
coapthon/client/coap.py
CoAP._wait_for_retransmit_thread
def _wait_for_retransmit_thread(transaction): """ Only one retransmit thread at a time, wait for other to finish """ if hasattr(transaction, 'retransmit_thread'): while transaction.retransmit_thread is not None: logger.debug("Waiting for retransmit thread to finish ...") time.sleep(0.01) continue
python
def _wait_for_retransmit_thread(transaction): """ Only one retransmit thread at a time, wait for other to finish """ if hasattr(transaction, 'retransmit_thread'): while transaction.retransmit_thread is not None: logger.debug("Waiting for retransmit thread to finish ...") time.sleep(0.01) continue
[ "def", "_wait_for_retransmit_thread", "(", "transaction", ")", ":", "if", "hasattr", "(", "transaction", ",", "'retransmit_thread'", ")", ":", "while", "transaction", ".", "retransmit_thread", "is", "not", "None", ":", "logger", ".", "debug", "(", "\"Waiting for r...
Only one retransmit thread at a time, wait for other to finish
[ "Only", "one", "retransmit", "thread", "at", "a", "time", "wait", "for", "other", "to", "finish" ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/client/coap.py#L120-L129
train
210,749
Tanganelli/CoAPthon3
coapthon/client/coap.py
CoAP.send_datagram
def send_datagram(self, message): """ Send a message over the UDP socket. :param message: the message to send """ host, port = message.destination logger.debug("send_datagram - " + str(message)) serializer = Serializer() raw_message = serializer.serialize(message) try: self._socket.sendto(raw_message, (host, port)) except Exception as e: if self._cb_ignore_write_exception is not None and isinstance(self._cb_ignore_write_exception, collections.Callable): if not self._cb_ignore_write_exception(e, self): raise # if you're explicitly setting that you don't want a response, don't wait for it # https://tools.ietf.org/html/rfc7967#section-2.1 for opt in message.options: if opt.number == defines.OptionRegistry.NO_RESPONSE.number: if opt.value == 26: return if self._receiver_thread is None or not self._receiver_thread.isAlive(): self._receiver_thread = threading.Thread(target=self.receive_datagram) self._receiver_thread.daemon = True self._receiver_thread.start()
python
def send_datagram(self, message): """ Send a message over the UDP socket. :param message: the message to send """ host, port = message.destination logger.debug("send_datagram - " + str(message)) serializer = Serializer() raw_message = serializer.serialize(message) try: self._socket.sendto(raw_message, (host, port)) except Exception as e: if self._cb_ignore_write_exception is not None and isinstance(self._cb_ignore_write_exception, collections.Callable): if not self._cb_ignore_write_exception(e, self): raise # if you're explicitly setting that you don't want a response, don't wait for it # https://tools.ietf.org/html/rfc7967#section-2.1 for opt in message.options: if opt.number == defines.OptionRegistry.NO_RESPONSE.number: if opt.value == 26: return if self._receiver_thread is None or not self._receiver_thread.isAlive(): self._receiver_thread = threading.Thread(target=self.receive_datagram) self._receiver_thread.daemon = True self._receiver_thread.start()
[ "def", "send_datagram", "(", "self", ",", "message", ")", ":", "host", ",", "port", "=", "message", ".", "destination", "logger", ".", "debug", "(", "\"send_datagram - \"", "+", "str", "(", "message", ")", ")", "serializer", "=", "Serializer", "(", ")", ...
Send a message over the UDP socket. :param message: the message to send
[ "Send", "a", "message", "over", "the", "UDP", "socket", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/client/coap.py#L145-L173
train
210,750
Tanganelli/CoAPthon3
coapthon/client/coap.py
CoAP._start_retransmission
def _start_retransmission(self, transaction, message): """ Start the retransmission task. :type transaction: Transaction :param transaction: the transaction that owns the message that needs retransmission :type message: Message :param message: the message that needs the retransmission task """ with transaction: if message.type == defines.Types['CON']: future_time = random.uniform(defines.ACK_TIMEOUT, (defines.ACK_TIMEOUT * defines.ACK_RANDOM_FACTOR)) transaction.retransmit_stop = threading.Event() self.to_be_stopped.append(transaction.retransmit_stop) transaction.retransmit_thread = threading.Thread(target=self._retransmit, name=str('%s-Retry-%d' % (threading.current_thread().name, message.mid)), args=(transaction, message, future_time, 0)) transaction.retransmit_thread.start()
python
def _start_retransmission(self, transaction, message): """ Start the retransmission task. :type transaction: Transaction :param transaction: the transaction that owns the message that needs retransmission :type message: Message :param message: the message that needs the retransmission task """ with transaction: if message.type == defines.Types['CON']: future_time = random.uniform(defines.ACK_TIMEOUT, (defines.ACK_TIMEOUT * defines.ACK_RANDOM_FACTOR)) transaction.retransmit_stop = threading.Event() self.to_be_stopped.append(transaction.retransmit_stop) transaction.retransmit_thread = threading.Thread(target=self._retransmit, name=str('%s-Retry-%d' % (threading.current_thread().name, message.mid)), args=(transaction, message, future_time, 0)) transaction.retransmit_thread.start()
[ "def", "_start_retransmission", "(", "self", ",", "transaction", ",", "message", ")", ":", "with", "transaction", ":", "if", "message", ".", "type", "==", "defines", ".", "Types", "[", "'CON'", "]", ":", "future_time", "=", "random", ".", "uniform", "(", ...
Start the retransmission task. :type transaction: Transaction :param transaction: the transaction that owns the message that needs retransmission :type message: Message :param message: the message that needs the retransmission task
[ "Start", "the", "retransmission", "task", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/client/coap.py#L175-L192
train
210,751
Tanganelli/CoAPthon3
coapthon/client/coap.py
CoAP.receive_datagram
def receive_datagram(self): """ Receive datagram from the UDP socket and invoke the callback function. """ logger.debug("Start receiver Thread") while not self.stopped.isSet(): self._socket.settimeout(0.1) try: datagram, addr = self._socket.recvfrom(1152) except socket.timeout: # pragma: no cover continue except Exception as e: # pragma: no cover if self._cb_ignore_read_exception is not None and isinstance(self._cb_ignore_read_exception, collections.Callable): if self._cb_ignore_read_exception(e, self): continue return else: # pragma: no cover if len(datagram) == 0: logger.debug("Exiting receiver Thread due to orderly shutdown on server end") return serializer = Serializer() try: host, port = addr except ValueError: host, port, tmp1, tmp2 = addr source = (host, port) message = serializer.deserialize(datagram, source) if isinstance(message, Response): logger.debug("receive_datagram - " + str(message)) transaction, send_ack = self._messageLayer.receive_response(message) if transaction is None: # pragma: no cover continue self._wait_for_retransmit_thread(transaction) if send_ack: self._send_ack(transaction) self._blockLayer.receive_response(transaction) if transaction.block_transfer: self._send_block_request(transaction) continue elif transaction is None: # pragma: no cover self._send_rst(transaction) return self._observeLayer.receive_response(transaction) if transaction.notification: # pragma: no cover ack = Message() ack.type = defines.Types['ACK'] ack = self._messageLayer.send_empty(transaction, transaction.response, ack) self.send_datagram(ack) self._callback(transaction.response) else: self._callback(transaction.response) elif isinstance(message, Message): self._messageLayer.receive_empty(message) logger.debug("Exiting receiver Thread due to request")
python
def receive_datagram(self): """ Receive datagram from the UDP socket and invoke the callback function. """ logger.debug("Start receiver Thread") while not self.stopped.isSet(): self._socket.settimeout(0.1) try: datagram, addr = self._socket.recvfrom(1152) except socket.timeout: # pragma: no cover continue except Exception as e: # pragma: no cover if self._cb_ignore_read_exception is not None and isinstance(self._cb_ignore_read_exception, collections.Callable): if self._cb_ignore_read_exception(e, self): continue return else: # pragma: no cover if len(datagram) == 0: logger.debug("Exiting receiver Thread due to orderly shutdown on server end") return serializer = Serializer() try: host, port = addr except ValueError: host, port, tmp1, tmp2 = addr source = (host, port) message = serializer.deserialize(datagram, source) if isinstance(message, Response): logger.debug("receive_datagram - " + str(message)) transaction, send_ack = self._messageLayer.receive_response(message) if transaction is None: # pragma: no cover continue self._wait_for_retransmit_thread(transaction) if send_ack: self._send_ack(transaction) self._blockLayer.receive_response(transaction) if transaction.block_transfer: self._send_block_request(transaction) continue elif transaction is None: # pragma: no cover self._send_rst(transaction) return self._observeLayer.receive_response(transaction) if transaction.notification: # pragma: no cover ack = Message() ack.type = defines.Types['ACK'] ack = self._messageLayer.send_empty(transaction, transaction.response, ack) self.send_datagram(ack) self._callback(transaction.response) else: self._callback(transaction.response) elif isinstance(message, Message): self._messageLayer.receive_empty(message) logger.debug("Exiting receiver Thread due to request")
[ "def", "receive_datagram", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"Start receiver Thread\"", ")", "while", "not", "self", ".", "stopped", ".", "isSet", "(", ")", ":", "self", ".", "_socket", ".", "settimeout", "(", "0.1", ")", "try", ":", ...
Receive datagram from the UDP socket and invoke the callback function.
[ "Receive", "datagram", "from", "the", "UDP", "socket", "and", "invoke", "the", "callback", "function", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/client/coap.py#L234-L293
train
210,752
Tanganelli/CoAPthon3
coapthon/client/coap.py
CoAP._send_rst
def _send_rst(self, transaction): # pragma: no cover """ Sends an RST message for the response. :param transaction: transaction that holds the response """ rst = Message() rst.type = defines.Types['RST'] if not transaction.response.acknowledged: rst = self._messageLayer.send_empty(transaction, transaction.response, rst) self.send_datagram(rst)
python
def _send_rst(self, transaction): # pragma: no cover """ Sends an RST message for the response. :param transaction: transaction that holds the response """ rst = Message() rst.type = defines.Types['RST'] if not transaction.response.acknowledged: rst = self._messageLayer.send_empty(transaction, transaction.response, rst) self.send_datagram(rst)
[ "def", "_send_rst", "(", "self", ",", "transaction", ")", ":", "# pragma: no cover", "rst", "=", "Message", "(", ")", "rst", ".", "type", "=", "defines", ".", "Types", "[", "'RST'", "]", "if", "not", "transaction", ".", "response", ".", "acknowledged", "...
Sends an RST message for the response. :param transaction: transaction that holds the response
[ "Sends", "an", "RST", "message", "for", "the", "response", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/client/coap.py#L309-L321
train
210,753
Tanganelli/CoAPthon3
coapthon/layers/cachelayer.py
CacheLayer.receive_request
def receive_request(self, transaction): """ checks the cache for a response to the request :param transaction: :return: """ transaction.cached_element = self.cache.search_response(transaction.request) if transaction.cached_element is None: transaction.cacheHit = False else: transaction.response = transaction.cached_element.cached_response transaction.response.mid = transaction.request.mid transaction.cacheHit = True age = transaction.cached_element.creation_time + transaction.cached_element.max_age - time.time() if transaction.cached_element.freshness is True: if age <= 0: logger.debug("resource not fresh") """ if the resource is not fresh, its Etag must be added to the request so that the server might validate it instead of sending a new one """ transaction.cached_element.freshness = False """ ensuring that the request goes to the server """ transaction.cacheHit = False logger.debug("requesting etag %s", transaction.response.etag) transaction.request.etag = transaction.response.etag else: transaction.response.max_age = age else: transaction.cacheHit = False return transaction
python
def receive_request(self, transaction): """ checks the cache for a response to the request :param transaction: :return: """ transaction.cached_element = self.cache.search_response(transaction.request) if transaction.cached_element is None: transaction.cacheHit = False else: transaction.response = transaction.cached_element.cached_response transaction.response.mid = transaction.request.mid transaction.cacheHit = True age = transaction.cached_element.creation_time + transaction.cached_element.max_age - time.time() if transaction.cached_element.freshness is True: if age <= 0: logger.debug("resource not fresh") """ if the resource is not fresh, its Etag must be added to the request so that the server might validate it instead of sending a new one """ transaction.cached_element.freshness = False """ ensuring that the request goes to the server """ transaction.cacheHit = False logger.debug("requesting etag %s", transaction.response.etag) transaction.request.etag = transaction.response.etag else: transaction.response.max_age = age else: transaction.cacheHit = False return transaction
[ "def", "receive_request", "(", "self", ",", "transaction", ")", ":", "transaction", ".", "cached_element", "=", "self", ".", "cache", ".", "search_response", "(", "transaction", ".", "request", ")", "if", "transaction", ".", "cached_element", "is", "None", ":"...
checks the cache for a response to the request :param transaction: :return:
[ "checks", "the", "cache", "for", "a", "response", "to", "the", "request" ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/cachelayer.py#L21-L55
train
210,754
Tanganelli/CoAPthon3
coapthon/layers/cachelayer.py
CacheLayer.send_response
def send_response(self, transaction): """ updates the cache with the response if there was a cache miss :param transaction: :return: """ if transaction.cacheHit is False: """ handling response based on the code """ logger.debug("handling response") self._handle_response(transaction) return transaction
python
def send_response(self, transaction): """ updates the cache with the response if there was a cache miss :param transaction: :return: """ if transaction.cacheHit is False: """ handling response based on the code """ logger.debug("handling response") self._handle_response(transaction) return transaction
[ "def", "send_response", "(", "self", ",", "transaction", ")", ":", "if", "transaction", ".", "cacheHit", "is", "False", ":", "\"\"\"\n handling response based on the code\n \"\"\"", "logger", ".", "debug", "(", "\"handling response\"", ")", "self", ...
updates the cache with the response if there was a cache miss :param transaction: :return:
[ "updates", "the", "cache", "with", "the", "response", "if", "there", "was", "a", "cache", "miss" ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/cachelayer.py#L57-L70
train
210,755
Tanganelli/CoAPthon3
coapthon/layers/cachelayer.py
CacheLayer._handle_response
def _handle_response(self, transaction): """ handles responses based on their type :param transaction: :return: """ code = transaction.response.code utils.check_code(code) """ VALID response: change the current cache value by switching the option set with the one provided also resets the timestamp if the request etag is different from the response, send the cached response """ if code == Codes.VALID.number: logger.debug("received VALID") self.cache.validate(transaction.request, transaction.response) if transaction.request.etag != transaction.response.etag: element = self.cache.search_response(transaction.request) transaction.response = element.cached_response return transaction """ CHANGED, CREATED or DELETED response: mark the requested resource as not fresh """ if code == Codes.CHANGED.number or code == Codes.CREATED.number or code == Codes.DELETED.number: target = self.cache.search_related(transaction.request) if target is not None: for element in target: self.cache.mark(element) return transaction """ any other response code can be cached normally """ self.cache.cache_add(transaction.request, transaction.response) return transaction
python
def _handle_response(self, transaction): """ handles responses based on their type :param transaction: :return: """ code = transaction.response.code utils.check_code(code) """ VALID response: change the current cache value by switching the option set with the one provided also resets the timestamp if the request etag is different from the response, send the cached response """ if code == Codes.VALID.number: logger.debug("received VALID") self.cache.validate(transaction.request, transaction.response) if transaction.request.etag != transaction.response.etag: element = self.cache.search_response(transaction.request) transaction.response = element.cached_response return transaction """ CHANGED, CREATED or DELETED response: mark the requested resource as not fresh """ if code == Codes.CHANGED.number or code == Codes.CREATED.number or code == Codes.DELETED.number: target = self.cache.search_related(transaction.request) if target is not None: for element in target: self.cache.mark(element) return transaction """ any other response code can be cached normally """ self.cache.cache_add(transaction.request, transaction.response) return transaction
[ "def", "_handle_response", "(", "self", ",", "transaction", ")", ":", "code", "=", "transaction", ".", "response", ".", "code", "utils", ".", "check_code", "(", "code", ")", "\"\"\"\n VALID response:\n change the current cache value by switching the option set...
handles responses based on their type :param transaction: :return:
[ "handles", "responses", "based", "on", "their", "type" ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/layers/cachelayer.py#L72-L110
train
210,756
Tanganelli/CoAPthon3
coapthon/messages/message.py
Message.version
def version(self, v): """ Sets the CoAP version :param v: the version :raise AttributeError: if value is not 1 """ if not isinstance(v, int) or v != 1: raise AttributeError self._version = v
python
def version(self, v): """ Sets the CoAP version :param v: the version :raise AttributeError: if value is not 1 """ if not isinstance(v, int) or v != 1: raise AttributeError self._version = v
[ "def", "version", "(", "self", ",", "v", ")", ":", "if", "not", "isinstance", "(", "v", ",", "int", ")", "or", "v", "!=", "1", ":", "raise", "AttributeError", "self", ".", "_version", "=", "v" ]
Sets the CoAP version :param v: the version :raise AttributeError: if value is not 1
[ "Sets", "the", "CoAP", "version" ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/message.py#L42-L51
train
210,757
Tanganelli/CoAPthon3
coapthon/messages/message.py
Message.type
def type(self, value): """ Sets the type of the message. :type value: Types :param value: the type :raise AttributeError: if value is not a valid type """ if value not in list(defines.Types.values()): raise AttributeError self._type = value
python
def type(self, value): """ Sets the type of the message. :type value: Types :param value: the type :raise AttributeError: if value is not a valid type """ if value not in list(defines.Types.values()): raise AttributeError self._type = value
[ "def", "type", "(", "self", ",", "value", ")", ":", "if", "value", "not", "in", "list", "(", "defines", ".", "Types", ".", "values", "(", ")", ")", ":", "raise", "AttributeError", "self", ".", "_type", "=", "value" ]
Sets the type of the message. :type value: Types :param value: the type :raise AttributeError: if value is not a valid type
[ "Sets", "the", "type", "of", "the", "message", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/message.py#L63-L73
train
210,758
Tanganelli/CoAPthon3
coapthon/messages/message.py
Message.mid
def mid(self, value): """ Sets the MID of the message. :type value: Integer :param value: the MID :raise AttributeError: if value is not int or cannot be represented on 16 bits. """ if not isinstance(value, int) or value > 65536: raise AttributeError self._mid = value
python
def mid(self, value): """ Sets the MID of the message. :type value: Integer :param value: the MID :raise AttributeError: if value is not int or cannot be represented on 16 bits. """ if not isinstance(value, int) or value > 65536: raise AttributeError self._mid = value
[ "def", "mid", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "int", ")", "or", "value", ">", "65536", ":", "raise", "AttributeError", "self", ".", "_mid", "=", "value" ]
Sets the MID of the message. :type value: Integer :param value: the MID :raise AttributeError: if value is not int or cannot be represented on 16 bits.
[ "Sets", "the", "MID", "of", "the", "message", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/message.py#L85-L95
train
210,759
Tanganelli/CoAPthon3
coapthon/messages/message.py
Message.token
def token(self, value): """ Set the Token of the message. :type value: String :param value: the Token :raise AttributeError: if value is longer than 256 """ if value is None: self._token = value return if not isinstance(value, str): value = str(value) if len(value) > 256: raise AttributeError self._token = value
python
def token(self, value): """ Set the Token of the message. :type value: String :param value: the Token :raise AttributeError: if value is longer than 256 """ if value is None: self._token = value return if not isinstance(value, str): value = str(value) if len(value) > 256: raise AttributeError self._token = value
[ "def", "token", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "self", ".", "_token", "=", "value", "return", "if", "not", "isinstance", "(", "value", ",", "str", ")", ":", "value", "=", "str", "(", "value", ")", "if", "le...
Set the Token of the message. :type value: String :param value: the Token :raise AttributeError: if value is longer than 256
[ "Set", "the", "Token", "of", "the", "message", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/message.py#L114-L129
train
210,760
Tanganelli/CoAPthon3
coapthon/messages/message.py
Message.options
def options(self, value): """ Set the options of the CoAP message. :type value: list :param value: list of options """ if value is None: value = [] assert isinstance(value, list) self._options = value
python
def options(self, value): """ Set the options of the CoAP message. :type value: list :param value: list of options """ if value is None: value = [] assert isinstance(value, list) self._options = value
[ "def", "options", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "value", "=", "[", "]", "assert", "isinstance", "(", "value", ",", "list", ")", "self", ".", "_options", "=", "value" ]
Set the options of the CoAP message. :type value: list :param value: list of options
[ "Set", "the", "options", "of", "the", "CoAP", "message", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/message.py#L149-L159
train
210,761
Tanganelli/CoAPthon3
coapthon/messages/message.py
Message.payload
def payload(self, value): """ Sets the payload of the message and eventually the Content-Type :param value: the payload """ if isinstance(value, tuple): content_type, payload = value self.content_type = content_type self._payload = payload else: self._payload = value
python
def payload(self, value): """ Sets the payload of the message and eventually the Content-Type :param value: the payload """ if isinstance(value, tuple): content_type, payload = value self.content_type = content_type self._payload = payload else: self._payload = value
[ "def", "payload", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "tuple", ")", ":", "content_type", ",", "payload", "=", "value", "self", ".", "content_type", "=", "content_type", "self", ".", "_payload", "=", "payload", "els...
Sets the payload of the message and eventually the Content-Type :param value: the payload
[ "Sets", "the", "payload", "of", "the", "message", "and", "eventually", "the", "Content", "-", "Type" ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/message.py#L171-L182
train
210,762
Tanganelli/CoAPthon3
coapthon/messages/message.py
Message.destination
def destination(self, value): """ Set the destination of the message. :type value: tuple :param value: (ip, port) :raise AttributeError: if value is not a ip and a port. """ if value is not None and (not isinstance(value, tuple) or len(value)) != 2: raise AttributeError self._destination = value
python
def destination(self, value): """ Set the destination of the message. :type value: tuple :param value: (ip, port) :raise AttributeError: if value is not a ip and a port. """ if value is not None and (not isinstance(value, tuple) or len(value)) != 2: raise AttributeError self._destination = value
[ "def", "destination", "(", "self", ",", "value", ")", ":", "if", "value", "is", "not", "None", "and", "(", "not", "isinstance", "(", "value", ",", "tuple", ")", "or", "len", "(", "value", ")", ")", "!=", "2", ":", "raise", "AttributeError", "self", ...
Set the destination of the message. :type value: tuple :param value: (ip, port) :raise AttributeError: if value is not a ip and a port.
[ "Set", "the", "destination", "of", "the", "message", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/message.py#L195-L205
train
210,763
Tanganelli/CoAPthon3
coapthon/messages/message.py
Message.source
def source(self, value): """ Set the source of the message. :type value: tuple :param value: (ip, port) :raise AttributeError: if value is not a ip and a port. """ if not isinstance(value, tuple) or len(value) != 2: raise AttributeError self._source = value
python
def source(self, value): """ Set the source of the message. :type value: tuple :param value: (ip, port) :raise AttributeError: if value is not a ip and a port. """ if not isinstance(value, tuple) or len(value) != 2: raise AttributeError self._source = value
[ "def", "source", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "tuple", ")", "or", "len", "(", "value", ")", "!=", "2", ":", "raise", "AttributeError", "self", ".", "_source", "=", "value" ]
Set the source of the message. :type value: tuple :param value: (ip, port) :raise AttributeError: if value is not a ip and a port.
[ "Set", "the", "source", "of", "the", "message", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/message.py#L218-L228
train
210,764
Tanganelli/CoAPthon3
coapthon/messages/message.py
Message.code
def code(self, value): """ Set the code of the message. :type value: Codes :param value: the code :raise AttributeError: if value is not a valid code """ if value not in list(defines.Codes.LIST.keys()) and value is not None: raise AttributeError self._code = value
python
def code(self, value): """ Set the code of the message. :type value: Codes :param value: the code :raise AttributeError: if value is not a valid code """ if value not in list(defines.Codes.LIST.keys()) and value is not None: raise AttributeError self._code = value
[ "def", "code", "(", "self", ",", "value", ")", ":", "if", "value", "not", "in", "list", "(", "defines", ".", "Codes", ".", "LIST", ".", "keys", "(", ")", ")", "and", "value", "is", "not", "None", ":", "raise", "AttributeError", "self", ".", "_code"...
Set the code of the message. :type value: Codes :param value: the code :raise AttributeError: if value is not a valid code
[ "Set", "the", "code", "of", "the", "message", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/message.py#L241-L251
train
210,765
Tanganelli/CoAPthon3
coapthon/messages/message.py
Message.acknowledged
def acknowledged(self, value): """ Marks this message as acknowledged. :type value: Boolean :param value: if acknowledged """ assert (isinstance(value, bool)) self._acknowledged = value if value: self._timeouted = False self._rejected = False self._cancelled = False
python
def acknowledged(self, value): """ Marks this message as acknowledged. :type value: Boolean :param value: if acknowledged """ assert (isinstance(value, bool)) self._acknowledged = value if value: self._timeouted = False self._rejected = False self._cancelled = False
[ "def", "acknowledged", "(", "self", ",", "value", ")", ":", "assert", "(", "isinstance", "(", "value", ",", "bool", ")", ")", "self", ".", "_acknowledged", "=", "value", "if", "value", ":", "self", ".", "_timeouted", "=", "False", "self", ".", "_reject...
Marks this message as acknowledged. :type value: Boolean :param value: if acknowledged
[ "Marks", "this", "message", "as", "acknowledged", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/message.py#L263-L275
train
210,766
Tanganelli/CoAPthon3
coapthon/messages/message.py
Message.rejected
def rejected(self, value): """ Marks this message as rejected. :type value: Boolean :param value: if rejected """ assert (isinstance(value, bool)) self._rejected = value if value: self._timeouted = False self._acknowledged = False self._cancelled = True
python
def rejected(self, value): """ Marks this message as rejected. :type value: Boolean :param value: if rejected """ assert (isinstance(value, bool)) self._rejected = value if value: self._timeouted = False self._acknowledged = False self._cancelled = True
[ "def", "rejected", "(", "self", ",", "value", ")", ":", "assert", "(", "isinstance", "(", "value", ",", "bool", ")", ")", "self", ".", "_rejected", "=", "value", "if", "value", ":", "self", ".", "_timeouted", "=", "False", "self", ".", "_acknowledged",...
Marks this message as rejected. :type value: Boolean :param value: if rejected
[ "Marks", "this", "message", "as", "rejected", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/message.py#L287-L299
train
210,767
Tanganelli/CoAPthon3
coapthon/messages/message.py
Message._already_in
def _already_in(self, option): """ Check if an option is already in the message. :type option: Option :param option: the option to be checked :return: True if already present, False otherwise """ for opt in self._options: if option.number == opt.number: return True return False
python
def _already_in(self, option): """ Check if an option is already in the message. :type option: Option :param option: the option to be checked :return: True if already present, False otherwise """ for opt in self._options: if option.number == opt.number: return True return False
[ "def", "_already_in", "(", "self", ",", "option", ")", ":", "for", "opt", "in", "self", ".", "_options", ":", "if", "option", ".", "number", "==", "opt", ".", "number", ":", "return", "True", "return", "False" ]
Check if an option is already in the message. :type option: Option :param option: the option to be checked :return: True if already present, False otherwise
[ "Check", "if", "an", "option", "is", "already", "in", "the", "message", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/message.py#L364-L375
train
210,768
Tanganelli/CoAPthon3
coapthon/messages/message.py
Message.add_option
def add_option(self, option): """ Add an option to the message. :type option: Option :param option: the option :raise TypeError: if the option is not repeatable and such option is already present in the message """ assert isinstance(option, Option) repeatable = defines.OptionRegistry.LIST[option.number].repeatable if not repeatable: ret = self._already_in(option) if ret: raise TypeError("Option : %s is not repeatable", option.name) else: self._options.append(option) else: self._options.append(option)
python
def add_option(self, option): """ Add an option to the message. :type option: Option :param option: the option :raise TypeError: if the option is not repeatable and such option is already present in the message """ assert isinstance(option, Option) repeatable = defines.OptionRegistry.LIST[option.number].repeatable if not repeatable: ret = self._already_in(option) if ret: raise TypeError("Option : %s is not repeatable", option.name) else: self._options.append(option) else: self._options.append(option)
[ "def", "add_option", "(", "self", ",", "option", ")", ":", "assert", "isinstance", "(", "option", ",", "Option", ")", "repeatable", "=", "defines", ".", "OptionRegistry", ".", "LIST", "[", "option", ".", "number", "]", ".", "repeatable", "if", "not", "re...
Add an option to the message. :type option: Option :param option: the option :raise TypeError: if the option is not repeatable and such option is already present in the message
[ "Add", "an", "option", "to", "the", "message", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/message.py#L377-L394
train
210,769
Tanganelli/CoAPthon3
coapthon/messages/message.py
Message.del_option
def del_option(self, option): """ Delete an option from the message :type option: Option :param option: the option """ assert isinstance(option, Option) while option in list(self._options): self._options.remove(option)
python
def del_option(self, option): """ Delete an option from the message :type option: Option :param option: the option """ assert isinstance(option, Option) while option in list(self._options): self._options.remove(option)
[ "def", "del_option", "(", "self", ",", "option", ")", ":", "assert", "isinstance", "(", "option", ",", "Option", ")", "while", "option", "in", "list", "(", "self", ".", "_options", ")", ":", "self", ".", "_options", ".", "remove", "(", "option", ")" ]
Delete an option from the message :type option: Option :param option: the option
[ "Delete", "an", "option", "from", "the", "message" ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/message.py#L396-L405
train
210,770
Tanganelli/CoAPthon3
coapthon/messages/message.py
Message.del_option_by_name
def del_option_by_name(self, name): """ Delete an option from the message by name :type name: String :param name: option name """ for o in list(self._options): assert isinstance(o, Option) if o.name == name: self._options.remove(o)
python
def del_option_by_name(self, name): """ Delete an option from the message by name :type name: String :param name: option name """ for o in list(self._options): assert isinstance(o, Option) if o.name == name: self._options.remove(o)
[ "def", "del_option_by_name", "(", "self", ",", "name", ")", ":", "for", "o", "in", "list", "(", "self", ".", "_options", ")", ":", "assert", "isinstance", "(", "o", ",", "Option", ")", "if", "o", ".", "name", "==", "name", ":", "self", ".", "_optio...
Delete an option from the message by name :type name: String :param name: option name
[ "Delete", "an", "option", "from", "the", "message", "by", "name" ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/message.py#L407-L417
train
210,771
Tanganelli/CoAPthon3
coapthon/messages/message.py
Message.del_option_by_number
def del_option_by_number(self, number): """ Delete an option from the message by number :type number: Integer :param number: option naumber """ for o in list(self._options): assert isinstance(o, Option) if o.number == number: self._options.remove(o)
python
def del_option_by_number(self, number): """ Delete an option from the message by number :type number: Integer :param number: option naumber """ for o in list(self._options): assert isinstance(o, Option) if o.number == number: self._options.remove(o)
[ "def", "del_option_by_number", "(", "self", ",", "number", ")", ":", "for", "o", "in", "list", "(", "self", ".", "_options", ")", ":", "assert", "isinstance", "(", "o", ",", "Option", ")", "if", "o", ".", "number", "==", "number", ":", "self", ".", ...
Delete an option from the message by number :type number: Integer :param number: option naumber
[ "Delete", "an", "option", "from", "the", "message", "by", "number" ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/message.py#L419-L429
train
210,772
Tanganelli/CoAPthon3
coapthon/messages/message.py
Message.etag
def etag(self): """ Get the ETag option of the message. :rtype: list :return: the ETag values or [] if not specified by the request """ value = [] for option in self.options: if option.number == defines.OptionRegistry.ETAG.number: value.append(option.value) return value
python
def etag(self): """ Get the ETag option of the message. :rtype: list :return: the ETag values or [] if not specified by the request """ value = [] for option in self.options: if option.number == defines.OptionRegistry.ETAG.number: value.append(option.value) return value
[ "def", "etag", "(", "self", ")", ":", "value", "=", "[", "]", "for", "option", "in", "self", ".", "options", ":", "if", "option", ".", "number", "==", "defines", ".", "OptionRegistry", ".", "ETAG", ".", "number", ":", "value", ".", "append", "(", "...
Get the ETag option of the message. :rtype: list :return: the ETag values or [] if not specified by the request
[ "Get", "the", "ETag", "option", "of", "the", "message", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/message.py#L432-L443
train
210,773
Tanganelli/CoAPthon3
coapthon/messages/message.py
Message.etag
def etag(self, etag): """ Add an ETag option to the message. :param etag: the etag """ if not isinstance(etag, list): etag = [etag] for e in etag: option = Option() option.number = defines.OptionRegistry.ETAG.number if not isinstance(e, bytes): e = bytes(e, "utf-8") option.value = e self.add_option(option)
python
def etag(self, etag): """ Add an ETag option to the message. :param etag: the etag """ if not isinstance(etag, list): etag = [etag] for e in etag: option = Option() option.number = defines.OptionRegistry.ETAG.number if not isinstance(e, bytes): e = bytes(e, "utf-8") option.value = e self.add_option(option)
[ "def", "etag", "(", "self", ",", "etag", ")", ":", "if", "not", "isinstance", "(", "etag", ",", "list", ")", ":", "etag", "=", "[", "etag", "]", "for", "e", "in", "etag", ":", "option", "=", "Option", "(", ")", "option", ".", "number", "=", "de...
Add an ETag option to the message. :param etag: the etag
[ "Add", "an", "ETag", "option", "to", "the", "message", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/message.py#L446-L460
train
210,774
Tanganelli/CoAPthon3
coapthon/messages/message.py
Message.content_type
def content_type(self): """ Get the Content-Type option of a response. :return: the Content-Type value or 0 if not specified by the response """ value = 0 for option in self.options: if option.number == defines.OptionRegistry.CONTENT_TYPE.number: value = int(option.value) return value
python
def content_type(self): """ Get the Content-Type option of a response. :return: the Content-Type value or 0 if not specified by the response """ value = 0 for option in self.options: if option.number == defines.OptionRegistry.CONTENT_TYPE.number: value = int(option.value) return value
[ "def", "content_type", "(", "self", ")", ":", "value", "=", "0", "for", "option", "in", "self", ".", "options", ":", "if", "option", ".", "number", "==", "defines", ".", "OptionRegistry", ".", "CONTENT_TYPE", ".", "number", ":", "value", "=", "int", "(...
Get the Content-Type option of a response. :return: the Content-Type value or 0 if not specified by the response
[ "Get", "the", "Content", "-", "Type", "option", "of", "a", "response", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/message.py#L471-L481
train
210,775
Tanganelli/CoAPthon3
coapthon/messages/message.py
Message.content_type
def content_type(self, content_type): """ Set the Content-Type option of a response. :type content_type: int :param content_type: the Content-Type """ option = Option() option.number = defines.OptionRegistry.CONTENT_TYPE.number option.value = int(content_type) self.add_option(option)
python
def content_type(self, content_type): """ Set the Content-Type option of a response. :type content_type: int :param content_type: the Content-Type """ option = Option() option.number = defines.OptionRegistry.CONTENT_TYPE.number option.value = int(content_type) self.add_option(option)
[ "def", "content_type", "(", "self", ",", "content_type", ")", ":", "option", "=", "Option", "(", ")", "option", ".", "number", "=", "defines", ".", "OptionRegistry", ".", "CONTENT_TYPE", ".", "number", "option", ".", "value", "=", "int", "(", "content_type...
Set the Content-Type option of a response. :type content_type: int :param content_type: the Content-Type
[ "Set", "the", "Content", "-", "Type", "option", "of", "a", "response", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/message.py#L484-L494
train
210,776
Tanganelli/CoAPthon3
coapthon/messages/message.py
Message.observe
def observe(self): """ Check if the request is an observing request. :return: 0, if the request is an observing request """ for option in self.options: if option.number == defines.OptionRegistry.OBSERVE.number: # if option.value is None: # return 0 if option.value is None: return 0 return option.value return None
python
def observe(self): """ Check if the request is an observing request. :return: 0, if the request is an observing request """ for option in self.options: if option.number == defines.OptionRegistry.OBSERVE.number: # if option.value is None: # return 0 if option.value is None: return 0 return option.value return None
[ "def", "observe", "(", "self", ")", ":", "for", "option", "in", "self", ".", "options", ":", "if", "option", ".", "number", "==", "defines", ".", "OptionRegistry", ".", "OBSERVE", ".", "number", ":", "# if option.value is None:", "# return 0", "if", "opti...
Check if the request is an observing request. :return: 0, if the request is an observing request
[ "Check", "if", "the", "request", "is", "an", "observing", "request", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/message.py#L505-L518
train
210,777
Tanganelli/CoAPthon3
coapthon/messages/message.py
Message.observe
def observe(self, ob): """ Add the Observe option. :param ob: observe count """ option = Option() option.number = defines.OptionRegistry.OBSERVE.number option.value = ob self.del_option_by_number(defines.OptionRegistry.OBSERVE.number) self.add_option(option)
python
def observe(self, ob): """ Add the Observe option. :param ob: observe count """ option = Option() option.number = defines.OptionRegistry.OBSERVE.number option.value = ob self.del_option_by_number(defines.OptionRegistry.OBSERVE.number) self.add_option(option)
[ "def", "observe", "(", "self", ",", "ob", ")", ":", "option", "=", "Option", "(", ")", "option", ".", "number", "=", "defines", ".", "OptionRegistry", ".", "OBSERVE", ".", "number", "option", ".", "value", "=", "ob", "self", ".", "del_option_by_number", ...
Add the Observe option. :param ob: observe count
[ "Add", "the", "Observe", "option", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/message.py#L521-L531
train
210,778
Tanganelli/CoAPthon3
coapthon/messages/message.py
Message.block1
def block1(self): """ Get the Block1 option. :return: the Block1 value """ value = None for option in self.options: if option.number == defines.OptionRegistry.BLOCK1.number: value = parse_blockwise(option.value) return value
python
def block1(self): """ Get the Block1 option. :return: the Block1 value """ value = None for option in self.options: if option.number == defines.OptionRegistry.BLOCK1.number: value = parse_blockwise(option.value) return value
[ "def", "block1", "(", "self", ")", ":", "value", "=", "None", "for", "option", "in", "self", ".", "options", ":", "if", "option", ".", "number", "==", "defines", ".", "OptionRegistry", ".", "BLOCK1", ".", "number", ":", "value", "=", "parse_blockwise", ...
Get the Block1 option. :return: the Block1 value
[ "Get", "the", "Block1", "option", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/message.py#L541-L551
train
210,779
Tanganelli/CoAPthon3
coapthon/messages/message.py
Message.block1
def block1(self, value): """ Set the Block1 option. :param value: the Block1 value """ option = Option() option.number = defines.OptionRegistry.BLOCK1.number num, m, size = value if size > 512: szx = 6 elif 256 < size <= 512: szx = 5 elif 128 < size <= 256: szx = 4 elif 64 < size <= 128: szx = 3 elif 32 < size <= 64: szx = 2 elif 16 < size <= 32: szx = 1 else: szx = 0 value = (num << 4) value |= (m << 3) value |= szx option.value = value self.add_option(option)
python
def block1(self, value): """ Set the Block1 option. :param value: the Block1 value """ option = Option() option.number = defines.OptionRegistry.BLOCK1.number num, m, size = value if size > 512: szx = 6 elif 256 < size <= 512: szx = 5 elif 128 < size <= 256: szx = 4 elif 64 < size <= 128: szx = 3 elif 32 < size <= 64: szx = 2 elif 16 < size <= 32: szx = 1 else: szx = 0 value = (num << 4) value |= (m << 3) value |= szx option.value = value self.add_option(option)
[ "def", "block1", "(", "self", ",", "value", ")", ":", "option", "=", "Option", "(", ")", "option", ".", "number", "=", "defines", ".", "OptionRegistry", ".", "BLOCK1", ".", "number", "num", ",", "m", ",", "size", "=", "value", "if", "size", ">", "5...
Set the Block1 option. :param value: the Block1 value
[ "Set", "the", "Block1", "option", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/message.py#L554-L583
train
210,780
Tanganelli/CoAPthon3
coapthon/messages/message.py
Message.block2
def block2(self): """ Get the Block2 option. :return: the Block2 value """ value = None for option in self.options: if option.number == defines.OptionRegistry.BLOCK2.number: value = parse_blockwise(option.value) return value
python
def block2(self): """ Get the Block2 option. :return: the Block2 value """ value = None for option in self.options: if option.number == defines.OptionRegistry.BLOCK2.number: value = parse_blockwise(option.value) return value
[ "def", "block2", "(", "self", ")", ":", "value", "=", "None", "for", "option", "in", "self", ".", "options", ":", "if", "option", ".", "number", "==", "defines", ".", "OptionRegistry", ".", "BLOCK2", ".", "number", ":", "value", "=", "parse_blockwise", ...
Get the Block2 option. :return: the Block2 value
[ "Get", "the", "Block2", "option", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/message.py#L593-L603
train
210,781
Tanganelli/CoAPthon3
coapthon/messages/message.py
Message.block2
def block2(self, value): """ Set the Block2 option. :param value: the Block2 value """ option = Option() option.number = defines.OptionRegistry.BLOCK2.number num, m, size = value if size > 512: szx = 6 elif 256 < size <= 512: szx = 5 elif 128 < size <= 256: szx = 4 elif 64 < size <= 128: szx = 3 elif 32 < size <= 64: szx = 2 elif 16 < size <= 32: szx = 1 else: szx = 0 value = (num << 4) value |= (m << 3) value |= szx option.value = value self.add_option(option)
python
def block2(self, value): """ Set the Block2 option. :param value: the Block2 value """ option = Option() option.number = defines.OptionRegistry.BLOCK2.number num, m, size = value if size > 512: szx = 6 elif 256 < size <= 512: szx = 5 elif 128 < size <= 256: szx = 4 elif 64 < size <= 128: szx = 3 elif 32 < size <= 64: szx = 2 elif 16 < size <= 32: szx = 1 else: szx = 0 value = (num << 4) value |= (m << 3) value |= szx option.value = value self.add_option(option)
[ "def", "block2", "(", "self", ",", "value", ")", ":", "option", "=", "Option", "(", ")", "option", ".", "number", "=", "defines", ".", "OptionRegistry", ".", "BLOCK2", ".", "number", "num", ",", "m", ",", "size", "=", "value", "if", "size", ">", "5...
Set the Block2 option. :param value: the Block2 value
[ "Set", "the", "Block2", "option", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/message.py#L606-L635
train
210,782
Tanganelli/CoAPthon3
coapthon/messages/message.py
Message.line_print
def line_print(self): """ Return the message as a one-line string. :return: the string representing the message """ inv_types = {v: k for k, v in defines.Types.items()} if self._code is None: self._code = defines.Codes.EMPTY.number msg = "From {source}, To {destination}, {type}-{mid}, {code}-{token}, ["\ .format(source=self._source, destination=self._destination, type=inv_types[self._type], mid=self._mid, code=defines.Codes.LIST[self._code].name, token=self._token) for opt in self._options: msg += "{name}: {value}, ".format(name=opt.name, value=opt.value) msg += "]" if self.payload is not None: if isinstance(self.payload, dict): tmp = list(self.payload.values())[0][0:20] else: tmp = self.payload[0:20] msg += " {payload}...{length} bytes".format(payload=tmp, length=len(self.payload)) else: msg += " No payload" return msg
python
def line_print(self): """ Return the message as a one-line string. :return: the string representing the message """ inv_types = {v: k for k, v in defines.Types.items()} if self._code is None: self._code = defines.Codes.EMPTY.number msg = "From {source}, To {destination}, {type}-{mid}, {code}-{token}, ["\ .format(source=self._source, destination=self._destination, type=inv_types[self._type], mid=self._mid, code=defines.Codes.LIST[self._code].name, token=self._token) for opt in self._options: msg += "{name}: {value}, ".format(name=opt.name, value=opt.value) msg += "]" if self.payload is not None: if isinstance(self.payload, dict): tmp = list(self.payload.values())[0][0:20] else: tmp = self.payload[0:20] msg += " {payload}...{length} bytes".format(payload=tmp, length=len(self.payload)) else: msg += " No payload" return msg
[ "def", "line_print", "(", "self", ")", ":", "inv_types", "=", "{", "v", ":", "k", "for", "k", ",", "v", "in", "defines", ".", "Types", ".", "items", "(", ")", "}", "if", "self", ".", "_code", "is", "None", ":", "self", ".", "_code", "=", "defin...
Return the message as a one-line string. :return: the string representing the message
[ "Return", "the", "message", "as", "a", "one", "-", "line", "string", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/message.py#L645-L670
train
210,783
Tanganelli/CoAPthon3
coapthon/messages/message.py
Message.pretty_print
def pretty_print(self): """ Return the message as a formatted string. :return: the string representing the message """ msg = "Source: " + str(self._source) + "\n" msg += "Destination: " + str(self._destination) + "\n" inv_types = {v: k for k, v in defines.Types.items()} msg += "Type: " + str(inv_types[self._type]) + "\n" msg += "MID: " + str(self._mid) + "\n" if self._code is None: self._code = 0 msg += "Code: " + str(defines.Codes.LIST[self._code].name) + "\n" msg += "Token: " + str(self._token) + "\n" for opt in self._options: msg += str(opt) msg += "Payload: " + "\n" msg += str(self._payload) + "\n" return msg
python
def pretty_print(self): """ Return the message as a formatted string. :return: the string representing the message """ msg = "Source: " + str(self._source) + "\n" msg += "Destination: " + str(self._destination) + "\n" inv_types = {v: k for k, v in defines.Types.items()} msg += "Type: " + str(inv_types[self._type]) + "\n" msg += "MID: " + str(self._mid) + "\n" if self._code is None: self._code = 0 msg += "Code: " + str(defines.Codes.LIST[self._code].name) + "\n" msg += "Token: " + str(self._token) + "\n" for opt in self._options: msg += str(opt) msg += "Payload: " + "\n" msg += str(self._payload) + "\n" return msg
[ "def", "pretty_print", "(", "self", ")", ":", "msg", "=", "\"Source: \"", "+", "str", "(", "self", ".", "_source", ")", "+", "\"\\n\"", "msg", "+=", "\"Destination: \"", "+", "str", "(", "self", ".", "_destination", ")", "+", "\"\\n\"", "inv_types", "=",...
Return the message as a formatted string. :return: the string representing the message
[ "Return", "the", "message", "as", "a", "formatted", "string", "." ]
985763bfe2eb9e00f49ec100c5b8877c2ed7d531
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/messages/message.py#L675-L695
train
210,784
timothydmorton/isochrones
isochrones/interp.py
interp_box
def interp_box(x, y, z, box, values): """ box is 8x3 array, though not really a box values is length-8 array, corresponding to values at the "box" coords TODO: should make power `p` an argument """ # Calculate the distance to each vertex val = 0 norm = 0 for i in range(8): # Inv distance, or Inv-dsq weighting distance = sqrt((x-box[i,0])**2 + (y-box[i,1])**2 + (z-box[i, 2])**2) # If you happen to land on exactly a corner, you're done. if distance == 0: val = values[i] norm = 1. break w = 1./distance # w = 1./((x-box[i,0])*(x-box[i,0]) + # (y-box[i,1])*(y-box[i,1]) + # (z-box[i, 2])*(z-box[i, 2])) val += w * values[i] norm += w return val/norm
python
def interp_box(x, y, z, box, values): """ box is 8x3 array, though not really a box values is length-8 array, corresponding to values at the "box" coords TODO: should make power `p` an argument """ # Calculate the distance to each vertex val = 0 norm = 0 for i in range(8): # Inv distance, or Inv-dsq weighting distance = sqrt((x-box[i,0])**2 + (y-box[i,1])**2 + (z-box[i, 2])**2) # If you happen to land on exactly a corner, you're done. if distance == 0: val = values[i] norm = 1. break w = 1./distance # w = 1./((x-box[i,0])*(x-box[i,0]) + # (y-box[i,1])*(y-box[i,1]) + # (z-box[i, 2])*(z-box[i, 2])) val += w * values[i] norm += w return val/norm
[ "def", "interp_box", "(", "x", ",", "y", ",", "z", ",", "box", ",", "values", ")", ":", "# Calculate the distance to each vertex", "val", "=", "0", "norm", "=", "0", "for", "i", "in", "range", "(", "8", ")", ":", "# Inv distance, or Inv-dsq weighting", "di...
box is 8x3 array, though not really a box values is length-8 array, corresponding to values at the "box" coords TODO: should make power `p` an argument
[ "box", "is", "8x3", "array", "though", "not", "really", "a", "box" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/interp.py#L6-L36
train
210,785
timothydmorton/isochrones
isochrones/query/catalog.py
Catalog.get_photometry
def get_photometry(self, brightest=False, min_unc=0.02, convert=True): """Returns dictionary of photometry of closest match unless brightest is True, in which case the brightest match. """ if brightest: row = self.brightest else: row = self.closest if not hasattr(self, 'conversions'): convert = False if convert: bands = self.conversions else: bands = self.bands.keys() d = {} for b in bands: if convert: key = b mag, dmag = getattr(self, b)(brightest=brightest) else: key = self.bands[b] mag, dmag = row[b], row['e_{}'.format(b)] d[key] = mag, max(dmag, min_unc) return d
python
def get_photometry(self, brightest=False, min_unc=0.02, convert=True): """Returns dictionary of photometry of closest match unless brightest is True, in which case the brightest match. """ if brightest: row = self.brightest else: row = self.closest if not hasattr(self, 'conversions'): convert = False if convert: bands = self.conversions else: bands = self.bands.keys() d = {} for b in bands: if convert: key = b mag, dmag = getattr(self, b)(brightest=brightest) else: key = self.bands[b] mag, dmag = row[b], row['e_{}'.format(b)] d[key] = mag, max(dmag, min_unc) return d
[ "def", "get_photometry", "(", "self", ",", "brightest", "=", "False", ",", "min_unc", "=", "0.02", ",", "convert", "=", "True", ")", ":", "if", "brightest", ":", "row", "=", "self", ".", "brightest", "else", ":", "row", "=", "self", ".", "closest", "...
Returns dictionary of photometry of closest match unless brightest is True, in which case the brightest match.
[ "Returns", "dictionary", "of", "photometry", "of", "closest", "match" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/query/catalog.py#L70-L99
train
210,786
timothydmorton/isochrones
isochrones/isochrone.py
get_ichrone
def get_ichrone(models, bands=None, default=False, **kwargs): """Gets Isochrone Object by name, or type, with the right bands If `default` is `True`, then will set bands to be the union of bands and default_bands """ if isinstance(models, Isochrone): return models def actual(bands, ictype): if bands is None: return list(ictype.default_bands) elif default: return list(set(bands).union(set(ictype.default_bands))) else: return bands if type(models) is type(type): ichrone = models(actual(bands, models)) elif models=='dartmouth': from isochrones.dartmouth import Dartmouth_Isochrone ichrone = Dartmouth_Isochrone(bands=actual(bands, Dartmouth_Isochrone), **kwargs) elif models=='dartmouthfast': from isochrones.dartmouth import Dartmouth_FastIsochrone ichrone = Dartmouth_FastIsochrone(bands=actual(bands, Dartmouth_FastIsochrone), **kwargs) elif models=='mist': from isochrones.mist import MIST_Isochrone ichrone = MIST_Isochrone(bands=actual(bands, MIST_Isochrone), **kwargs) elif models=='padova': from isochrones.padova import Padova_Isochrone ichrone = Padova_Isochrone(bands=actual(bands, Padova_Isochrone), **kwargs) elif models=='basti': from isochrones.basti import Basti_Isochrone ichrone = Basti_Isochrone(bands=actual(bands, Basti_Isochrone), **kwargs) else: raise ValueError('Unknown stellar models: {}'.format(models)) return ichrone
python
def get_ichrone(models, bands=None, default=False, **kwargs): """Gets Isochrone Object by name, or type, with the right bands If `default` is `True`, then will set bands to be the union of bands and default_bands """ if isinstance(models, Isochrone): return models def actual(bands, ictype): if bands is None: return list(ictype.default_bands) elif default: return list(set(bands).union(set(ictype.default_bands))) else: return bands if type(models) is type(type): ichrone = models(actual(bands, models)) elif models=='dartmouth': from isochrones.dartmouth import Dartmouth_Isochrone ichrone = Dartmouth_Isochrone(bands=actual(bands, Dartmouth_Isochrone), **kwargs) elif models=='dartmouthfast': from isochrones.dartmouth import Dartmouth_FastIsochrone ichrone = Dartmouth_FastIsochrone(bands=actual(bands, Dartmouth_FastIsochrone), **kwargs) elif models=='mist': from isochrones.mist import MIST_Isochrone ichrone = MIST_Isochrone(bands=actual(bands, MIST_Isochrone), **kwargs) elif models=='padova': from isochrones.padova import Padova_Isochrone ichrone = Padova_Isochrone(bands=actual(bands, Padova_Isochrone), **kwargs) elif models=='basti': from isochrones.basti import Basti_Isochrone ichrone = Basti_Isochrone(bands=actual(bands, Basti_Isochrone), **kwargs) else: raise ValueError('Unknown stellar models: {}'.format(models)) return ichrone
[ "def", "get_ichrone", "(", "models", ",", "bands", "=", "None", ",", "default", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "models", ",", "Isochrone", ")", ":", "return", "models", "def", "actual", "(", "bands", ",", "i...
Gets Isochrone Object by name, or type, with the right bands If `default` is `True`, then will set bands to be the union of bands and default_bands
[ "Gets", "Isochrone", "Object", "by", "name", "or", "type", "with", "the", "right", "bands" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/isochrone.py#L32-L68
train
210,787
timothydmorton/isochrones
isochrones/isochrone.py
Isochrone.delta_nu
def delta_nu(self, *args): """Returns asteroseismic delta_nu in uHz reference: https://arxiv.org/pdf/1312.3853v1.pdf, Eq (2) """ return 134.88 * np.sqrt(self.mass(*args) / self.radius(*args)**3)
python
def delta_nu(self, *args): """Returns asteroseismic delta_nu in uHz reference: https://arxiv.org/pdf/1312.3853v1.pdf, Eq (2) """ return 134.88 * np.sqrt(self.mass(*args) / self.radius(*args)**3)
[ "def", "delta_nu", "(", "self", ",", "*", "args", ")", ":", "return", "134.88", "*", "np", ".", "sqrt", "(", "self", ".", "mass", "(", "*", "args", ")", "/", "self", ".", "radius", "(", "*", "args", ")", "**", "3", ")" ]
Returns asteroseismic delta_nu in uHz reference: https://arxiv.org/pdf/1312.3853v1.pdf, Eq (2)
[ "Returns", "asteroseismic", "delta_nu", "in", "uHz" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/isochrone.py#L211-L216
train
210,788
timothydmorton/isochrones
isochrones/isochrone.py
Isochrone.nu_max
def nu_max(self, *args): """Returns asteroseismic nu_max in uHz reference: https://arxiv.org/pdf/1312.3853v1.pdf, Eq (3) """ return 3120.* (self.mass(*args) / (self.radius(*args)**2 * np.sqrt(self.Teff(*args)/5777.)))
python
def nu_max(self, *args): """Returns asteroseismic nu_max in uHz reference: https://arxiv.org/pdf/1312.3853v1.pdf, Eq (3) """ return 3120.* (self.mass(*args) / (self.radius(*args)**2 * np.sqrt(self.Teff(*args)/5777.)))
[ "def", "nu_max", "(", "self", ",", "*", "args", ")", ":", "return", "3120.", "*", "(", "self", ".", "mass", "(", "*", "args", ")", "/", "(", "self", ".", "radius", "(", "*", "args", ")", "**", "2", "*", "np", ".", "sqrt", "(", "self", ".", ...
Returns asteroseismic nu_max in uHz reference: https://arxiv.org/pdf/1312.3853v1.pdf, Eq (3)
[ "Returns", "asteroseismic", "nu_max", "in", "uHz" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/isochrone.py#L218-L224
train
210,789
timothydmorton/isochrones
isochrones/isochrone.py
Isochrone.agerange
def agerange(self, m, feh=0.0): """ For a given mass and feh, returns the min and max allowed ages. """ ages = np.arange(self.minage, self.maxage, 0.01) rs = self.radius(m, ages, feh) w = np.where(np.isfinite(rs))[0] return ages[w[0]],ages[w[-1]]
python
def agerange(self, m, feh=0.0): """ For a given mass and feh, returns the min and max allowed ages. """ ages = np.arange(self.minage, self.maxage, 0.01) rs = self.radius(m, ages, feh) w = np.where(np.isfinite(rs))[0] return ages[w[0]],ages[w[-1]]
[ "def", "agerange", "(", "self", ",", "m", ",", "feh", "=", "0.0", ")", ":", "ages", "=", "np", ".", "arange", "(", "self", ".", "minage", ",", "self", ".", "maxage", ",", "0.01", ")", "rs", "=", "self", ".", "radius", "(", "m", ",", "ages", "...
For a given mass and feh, returns the min and max allowed ages.
[ "For", "a", "given", "mass", "and", "feh", "returns", "the", "min", "and", "max", "allowed", "ages", "." ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/isochrone.py#L307-L314
train
210,790
timothydmorton/isochrones
isochrones/isochrone.py
Isochrone.evtrack
def evtrack(self,m,feh=0.0,minage=None,maxage=None,dage=0.02, return_df=True): """ Returns evolution track for a single initial mass and feh. :param m: Initial mass of desired evolution track. :param feh: (optional) Metallicity of desired track. Default = 0.0 (solar) :param minage, maxage: (optional) Minimum and maximum log(age) of desired track. Will default to min and max age of model isochrones. :param dage: (optional) Spacing in log(age) at which to evaluate models. Default = 0.02 :param return_df: (optional) Whether to return a ``DataFrame`` or dicionary. Default is ``True``. :return: Either a :class:`pandas.DataFrame` or dictionary representing the evolution track---fixed mass, sampled at chosen range of ages. """ if minage is None: minage = self.minage if maxage is None: maxage = self.maxage ages = np.arange(minage,maxage,dage) Ms = self.mass(m,ages,feh) Rs = self.radius(m,ages,feh) logLs = self.logL(m,ages,feh) loggs = self.logg(m,ages,feh) Teffs = self.Teff(m,ages,feh) mags = {band:self.mag[band](m,ages,feh) for band in self.bands} props = {'age':ages,'mass':Ms,'radius':Rs,'logL':logLs, 'logg':loggs, 'Teff':Teffs, 'mag':mags} if not return_df: return props else: d = {} for key in props.keys(): if key=='mag': for m in props['mag'].keys(): d['{}_mag'.format(m)] = props['mag'][m] else: d[key] = props[key] try: df = pd.DataFrame(d) except ValueError: df = pd.DataFrame(d, index=[0]) return df
python
def evtrack(self,m,feh=0.0,minage=None,maxage=None,dage=0.02, return_df=True): """ Returns evolution track for a single initial mass and feh. :param m: Initial mass of desired evolution track. :param feh: (optional) Metallicity of desired track. Default = 0.0 (solar) :param minage, maxage: (optional) Minimum and maximum log(age) of desired track. Will default to min and max age of model isochrones. :param dage: (optional) Spacing in log(age) at which to evaluate models. Default = 0.02 :param return_df: (optional) Whether to return a ``DataFrame`` or dicionary. Default is ``True``. :return: Either a :class:`pandas.DataFrame` or dictionary representing the evolution track---fixed mass, sampled at chosen range of ages. """ if minage is None: minage = self.minage if maxage is None: maxage = self.maxage ages = np.arange(minage,maxage,dage) Ms = self.mass(m,ages,feh) Rs = self.radius(m,ages,feh) logLs = self.logL(m,ages,feh) loggs = self.logg(m,ages,feh) Teffs = self.Teff(m,ages,feh) mags = {band:self.mag[band](m,ages,feh) for band in self.bands} props = {'age':ages,'mass':Ms,'radius':Rs,'logL':logLs, 'logg':loggs, 'Teff':Teffs, 'mag':mags} if not return_df: return props else: d = {} for key in props.keys(): if key=='mag': for m in props['mag'].keys(): d['{}_mag'.format(m)] = props['mag'][m] else: d[key] = props[key] try: df = pd.DataFrame(d) except ValueError: df = pd.DataFrame(d, index=[0]) return df
[ "def", "evtrack", "(", "self", ",", "m", ",", "feh", "=", "0.0", ",", "minage", "=", "None", ",", "maxage", "=", "None", ",", "dage", "=", "0.02", ",", "return_df", "=", "True", ")", ":", "if", "minage", "is", "None", ":", "minage", "=", "self", ...
Returns evolution track for a single initial mass and feh. :param m: Initial mass of desired evolution track. :param feh: (optional) Metallicity of desired track. Default = 0.0 (solar) :param minage, maxage: (optional) Minimum and maximum log(age) of desired track. Will default to min and max age of model isochrones. :param dage: (optional) Spacing in log(age) at which to evaluate models. Default = 0.02 :param return_df: (optional) Whether to return a ``DataFrame`` or dicionary. Default is ``True``. :return: Either a :class:`pandas.DataFrame` or dictionary representing the evolution track---fixed mass, sampled at chosen range of ages.
[ "Returns", "evolution", "track", "for", "a", "single", "initial", "mass", "and", "feh", "." ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/isochrone.py#L316-L373
train
210,791
timothydmorton/isochrones
isochrones/isochrone.py
Isochrone.isochrone
def isochrone(self,age,feh=0.0,minm=None,maxm=None,dm=0.02, return_df=True,distance=None,AV=0.0): """ Returns stellar models at constant age and feh, for a range of masses :param age: log10(age) of desired isochrone. :param feh: (optional) Metallicity of desired isochrone (default = 0.0) :param minm, maxm: (optional) Mass range of desired isochrone (will default to max and min available) :param dm: (optional) Spacing in mass of desired isochrone. Default = 0.02 Msun. :param return_df: (optional) Whether to return a :class:``pandas.DataFrame`` or dictionary. Default is ``True``. :param distance: Distance in pc. If passed, then mags will be converted to apparent mags based on distance (and ``AV``). :param AV: V-band extinction (magnitudes). :return: :class:`pandas.DataFrame` or dictionary containing results. """ if minm is None: minm = self.minmass if maxm is None: maxm = self.maxmass ms = np.arange(minm,maxm,dm) ages = np.ones(ms.shape)*age Ms = self.mass(ms,ages,feh) Rs = self.radius(ms,ages,feh) logLs = self.logL(ms,ages,feh) loggs = self.logg(ms,ages,feh) Teffs = self.Teff(ms,ages,feh) mags = {band:self.mag[band](ms,ages,feh) for band in self.bands} #for band in self.bands: # mags[band] = self.mag[band](ms,ages) if distance is not None: dm = 5*np.log10(distance) - 5 for band in mags: A = AV*EXTINCTION[band] mags[band] = mags[band] + dm + A props = {'M':Ms,'R':Rs,'logL':logLs,'logg':loggs, 'Teff':Teffs,'mag':mags} if not return_df: return props else: d = {} for key in props.keys(): if key=='mag': for m in props['mag'].keys(): d['{}_mag'.format(m)] = props['mag'][m] else: d[key] = props[key] try: df = pd.DataFrame(d) except ValueError: df = pd.DataFrame(d, index=[0]) return df
python
def isochrone(self,age,feh=0.0,minm=None,maxm=None,dm=0.02, return_df=True,distance=None,AV=0.0): """ Returns stellar models at constant age and feh, for a range of masses :param age: log10(age) of desired isochrone. :param feh: (optional) Metallicity of desired isochrone (default = 0.0) :param minm, maxm: (optional) Mass range of desired isochrone (will default to max and min available) :param dm: (optional) Spacing in mass of desired isochrone. Default = 0.02 Msun. :param return_df: (optional) Whether to return a :class:``pandas.DataFrame`` or dictionary. Default is ``True``. :param distance: Distance in pc. If passed, then mags will be converted to apparent mags based on distance (and ``AV``). :param AV: V-band extinction (magnitudes). :return: :class:`pandas.DataFrame` or dictionary containing results. """ if minm is None: minm = self.minmass if maxm is None: maxm = self.maxmass ms = np.arange(minm,maxm,dm) ages = np.ones(ms.shape)*age Ms = self.mass(ms,ages,feh) Rs = self.radius(ms,ages,feh) logLs = self.logL(ms,ages,feh) loggs = self.logg(ms,ages,feh) Teffs = self.Teff(ms,ages,feh) mags = {band:self.mag[band](ms,ages,feh) for band in self.bands} #for band in self.bands: # mags[band] = self.mag[band](ms,ages) if distance is not None: dm = 5*np.log10(distance) - 5 for band in mags: A = AV*EXTINCTION[band] mags[band] = mags[band] + dm + A props = {'M':Ms,'R':Rs,'logL':logLs,'logg':loggs, 'Teff':Teffs,'mag':mags} if not return_df: return props else: d = {} for key in props.keys(): if key=='mag': for m in props['mag'].keys(): d['{}_mag'.format(m)] = props['mag'][m] else: d[key] = props[key] try: df = pd.DataFrame(d) except ValueError: df = pd.DataFrame(d, index=[0]) return df
[ "def", "isochrone", "(", "self", ",", "age", ",", "feh", "=", "0.0", ",", "minm", "=", "None", ",", "maxm", "=", "None", ",", "dm", "=", "0.02", ",", "return_df", "=", "True", ",", "distance", "=", "None", ",", "AV", "=", "0.0", ")", ":", "if",...
Returns stellar models at constant age and feh, for a range of masses :param age: log10(age) of desired isochrone. :param feh: (optional) Metallicity of desired isochrone (default = 0.0) :param minm, maxm: (optional) Mass range of desired isochrone (will default to max and min available) :param dm: (optional) Spacing in mass of desired isochrone. Default = 0.02 Msun. :param return_df: (optional) Whether to return a :class:``pandas.DataFrame`` or dictionary. Default is ``True``. :param distance: Distance in pc. If passed, then mags will be converted to apparent mags based on distance (and ``AV``). :param AV: V-band extinction (magnitudes). :return: :class:`pandas.DataFrame` or dictionary containing results.
[ "Returns", "stellar", "models", "at", "constant", "age", "and", "feh", "for", "a", "range", "of", "masses" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/isochrone.py#L376-L445
train
210,792
timothydmorton/isochrones
isochrones/isochrone.py
Isochrone.random_points
def random_points(self,n,minmass=None,maxmass=None, minage=None,maxage=None, minfeh=None,maxfeh=None): """ Returns n random mass, age, feh points, none of which are out of range. :param n: Number of desired points. :param minmass, maxmass: (optional) Desired allowed range. Default is mass range of ``self``. :param minage, maxage: (optional) Desired allowed range. Default is log10(age) range of ``self``. :param minfehs, maxfeh: (optional) Desired allowed range. Default is feh range of ``self``. :return: :class:`np.ndarray` arrays of randomly selected mass, log10(age), and feh values within allowed ranges. Used, e.g., to initialize random walkers for :class:`StarModel` fits. .. todo:: Should change this to drawing from priors! Current implementation is a bit outdated. """ if minmass is None: minmass = self.minmass if maxmass is None: maxmass = self.maxmass if minage is None: minage = self.minage if maxage is None: maxage = self.maxage if minfeh is None: minfeh = self.minfeh if maxfeh is None: maxfeh = self.maxfeh ms = rand.uniform(minmass,maxmass,size=n) ages = rand.uniform(minage,maxage,size=n) fehs = rand.uniform(minage,maxage,size=n) Rs = self.radius(ms,ages,fehs) bad = np.isnan(Rs) nbad = bad.sum() while nbad > 0: ms[bad] = rand.uniform(minmass,maxmass,size=nbad) ages[bad] = rand.uniform(minage,maxage,size=nbad) fehs[bad] = rand.uniform(minfeh,maxfeh,size=nbad) Rs = self.radius(ms,ages,fehs) bad = np.isnan(Rs) nbad = bad.sum() return ms,ages,fehs
python
def random_points(self,n,minmass=None,maxmass=None, minage=None,maxage=None, minfeh=None,maxfeh=None): """ Returns n random mass, age, feh points, none of which are out of range. :param n: Number of desired points. :param minmass, maxmass: (optional) Desired allowed range. Default is mass range of ``self``. :param minage, maxage: (optional) Desired allowed range. Default is log10(age) range of ``self``. :param minfehs, maxfeh: (optional) Desired allowed range. Default is feh range of ``self``. :return: :class:`np.ndarray` arrays of randomly selected mass, log10(age), and feh values within allowed ranges. Used, e.g., to initialize random walkers for :class:`StarModel` fits. .. todo:: Should change this to drawing from priors! Current implementation is a bit outdated. """ if minmass is None: minmass = self.minmass if maxmass is None: maxmass = self.maxmass if minage is None: minage = self.minage if maxage is None: maxage = self.maxage if minfeh is None: minfeh = self.minfeh if maxfeh is None: maxfeh = self.maxfeh ms = rand.uniform(minmass,maxmass,size=n) ages = rand.uniform(minage,maxage,size=n) fehs = rand.uniform(minage,maxage,size=n) Rs = self.radius(ms,ages,fehs) bad = np.isnan(Rs) nbad = bad.sum() while nbad > 0: ms[bad] = rand.uniform(minmass,maxmass,size=nbad) ages[bad] = rand.uniform(minage,maxage,size=nbad) fehs[bad] = rand.uniform(minfeh,maxfeh,size=nbad) Rs = self.radius(ms,ages,fehs) bad = np.isnan(Rs) nbad = bad.sum() return ms,ages,fehs
[ "def", "random_points", "(", "self", ",", "n", ",", "minmass", "=", "None", ",", "maxmass", "=", "None", ",", "minage", "=", "None", ",", "maxage", "=", "None", ",", "minfeh", "=", "None", ",", "maxfeh", "=", "None", ")", ":", "if", "minmass", "is"...
Returns n random mass, age, feh points, none of which are out of range. :param n: Number of desired points. :param minmass, maxmass: (optional) Desired allowed range. Default is mass range of ``self``. :param minage, maxage: (optional) Desired allowed range. Default is log10(age) range of ``self``. :param minfehs, maxfeh: (optional) Desired allowed range. Default is feh range of ``self``. :return: :class:`np.ndarray` arrays of randomly selected mass, log10(age), and feh values within allowed ranges. Used, e.g., to initialize random walkers for :class:`StarModel` fits. .. todo:: Should change this to drawing from priors! Current implementation is a bit outdated.
[ "Returns", "n", "random", "mass", "age", "feh", "points", "none", "of", "which", "are", "out", "of", "range", "." ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/isochrone.py#L447-L504
train
210,793
timothydmorton/isochrones
isochrones/starmodel.py
StarModel._parse_band
def _parse_band(cls, kw): """Returns photometric band from inifile keyword """ m = re.search('([a-zA-Z0-9]+)(_\d+)?', kw) if m: if m.group(1) in cls._not_a_band: return None else: return m.group(1)
python
def _parse_band(cls, kw): """Returns photometric band from inifile keyword """ m = re.search('([a-zA-Z0-9]+)(_\d+)?', kw) if m: if m.group(1) in cls._not_a_band: return None else: return m.group(1)
[ "def", "_parse_band", "(", "cls", ",", "kw", ")", ":", "m", "=", "re", ".", "search", "(", "'([a-zA-Z0-9]+)(_\\d+)?'", ",", "kw", ")", "if", "m", ":", "if", "m", ".", "group", "(", "1", ")", "in", "cls", ".", "_not_a_band", ":", "return", "None", ...
Returns photometric band from inifile keyword
[ "Returns", "photometric", "band", "from", "inifile", "keyword" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/starmodel.py#L160-L168
train
210,794
timothydmorton/isochrones
isochrones/starmodel.py
StarModel._build_obs
def _build_obs(self, **kwargs): """ Builds ObservationTree out of keyword arguments Ignores anything that is not a photometric bandpass. This should not be used if there are multiple stars observed. Creates self.obs """ logging.debug('Building ObservationTree...') tree = ObservationTree() for k,v in kwargs.items(): if k in self.ic.bands: if np.size(v) != 2: logging.warning('{}={} ignored.'.format(k,v)) # continue v = [v, np.nan] o = Observation('', k, 99) #bogus resolution=99 s = Source(v[0], v[1]) o.add_source(s) logging.debug('Adding {} ({})'.format(s,o)) tree.add_observation(o) self.obs = tree
python
def _build_obs(self, **kwargs): """ Builds ObservationTree out of keyword arguments Ignores anything that is not a photometric bandpass. This should not be used if there are multiple stars observed. Creates self.obs """ logging.debug('Building ObservationTree...') tree = ObservationTree() for k,v in kwargs.items(): if k in self.ic.bands: if np.size(v) != 2: logging.warning('{}={} ignored.'.format(k,v)) # continue v = [v, np.nan] o = Observation('', k, 99) #bogus resolution=99 s = Source(v[0], v[1]) o.add_source(s) logging.debug('Adding {} ({})'.format(s,o)) tree.add_observation(o) self.obs = tree
[ "def", "_build_obs", "(", "self", ",", "*", "*", "kwargs", ")", ":", "logging", ".", "debug", "(", "'Building ObservationTree...'", ")", "tree", "=", "ObservationTree", "(", ")", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "if", ...
Builds ObservationTree out of keyword arguments Ignores anything that is not a photometric bandpass. This should not be used if there are multiple stars observed. Creates self.obs
[ "Builds", "ObservationTree", "out", "of", "keyword", "arguments" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/starmodel.py#L412-L435
train
210,795
timothydmorton/isochrones
isochrones/starmodel.py
StarModel._add_properties
def _add_properties(self, **kwargs): """ Adds non-photometry properties to ObservationTree """ for k,v in kwargs.items(): if k=='parallax': self.obs.add_parallax(v) elif k in ['Teff', 'logg', 'feh', 'density']: par = {k:v} self.obs.add_spectroscopy(**par) elif re.search('_', k): m = re.search('^(\w+)_(\w+)$', k) prop = m.group(1) tag = m.group(2) self.obs.add_spectroscopy(**{prop:v, 'label':'0_{}'.format(tag)})
python
def _add_properties(self, **kwargs): """ Adds non-photometry properties to ObservationTree """ for k,v in kwargs.items(): if k=='parallax': self.obs.add_parallax(v) elif k in ['Teff', 'logg', 'feh', 'density']: par = {k:v} self.obs.add_spectroscopy(**par) elif re.search('_', k): m = re.search('^(\w+)_(\w+)$', k) prop = m.group(1) tag = m.group(2) self.obs.add_spectroscopy(**{prop:v, 'label':'0_{}'.format(tag)})
[ "def", "_add_properties", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "if", "k", "==", "'parallax'", ":", "self", ".", "obs", ".", "add_parallax", "(", "v", ")", "elif", "k", ...
Adds non-photometry properties to ObservationTree
[ "Adds", "non", "-", "photometry", "properties", "to", "ObservationTree" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/starmodel.py#L437-L451
train
210,796
timothydmorton/isochrones
isochrones/starmodel.py
StarModel.mnest_basename
def mnest_basename(self): """Full path to basename """ if not hasattr(self, '_mnest_basename'): s = self.labelstring if s=='0_0': s = 'single' elif s=='0_0-0_1': s = 'binary' elif s=='0_0-0_1-0_2': s = 'triple' s = '{}-{}'.format(self.ic.name, s) self._mnest_basename = os.path.join('chains', s+'-') if os.path.isabs(self._mnest_basename): return self._mnest_basename else: return os.path.join(self.directory, self._mnest_basename)
python
def mnest_basename(self): """Full path to basename """ if not hasattr(self, '_mnest_basename'): s = self.labelstring if s=='0_0': s = 'single' elif s=='0_0-0_1': s = 'binary' elif s=='0_0-0_1-0_2': s = 'triple' s = '{}-{}'.format(self.ic.name, s) self._mnest_basename = os.path.join('chains', s+'-') if os.path.isabs(self._mnest_basename): return self._mnest_basename else: return os.path.join(self.directory, self._mnest_basename)
[ "def", "mnest_basename", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_mnest_basename'", ")", ":", "s", "=", "self", ".", "labelstring", "if", "s", "==", "'0_0'", ":", "s", "=", "'single'", "elif", "s", "==", "'0_0-0_1'", ":", "...
Full path to basename
[ "Full", "path", "to", "basename" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/starmodel.py#L559-L577
train
210,797
timothydmorton/isochrones
isochrones/starmodel.py
StarModel.samples
def samples(self): """Dataframe with samples drawn from isochrone according to posterior Columns include both the sampling parameters from the MCMC fit (mass, age, Fe/H, [distance, A_V]), and also evaluation of the :class:`Isochrone` at each of these sample points---this is how chains of physical/observable parameters get produced. """ if not hasattr(self,'sampler') and self._samples is None: raise AttributeError('Must run MCMC (or load from file) '+ 'before accessing samples') if self._samples is not None: df = self._samples else: self._make_samples() df = self._samples return df
python
def samples(self): """Dataframe with samples drawn from isochrone according to posterior Columns include both the sampling parameters from the MCMC fit (mass, age, Fe/H, [distance, A_V]), and also evaluation of the :class:`Isochrone` at each of these sample points---this is how chains of physical/observable parameters get produced. """ if not hasattr(self,'sampler') and self._samples is None: raise AttributeError('Must run MCMC (or load from file) '+ 'before accessing samples') if self._samples is not None: df = self._samples else: self._make_samples() df = self._samples return df
[ "def", "samples", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'sampler'", ")", "and", "self", ".", "_samples", "is", "None", ":", "raise", "AttributeError", "(", "'Must run MCMC (or load from file) '", "+", "'before accessing samples'", ")"...
Dataframe with samples drawn from isochrone according to posterior Columns include both the sampling parameters from the MCMC fit (mass, age, Fe/H, [distance, A_V]), and also evaluation of the :class:`Isochrone` at each of these sample points---this is how chains of physical/observable parameters get produced.
[ "Dataframe", "with", "samples", "drawn", "from", "isochrone", "according", "to", "posterior" ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/starmodel.py#L918-L937
train
210,798
timothydmorton/isochrones
isochrones/starmodel.py
StarModel.random_samples
def random_samples(self, n): """ Returns a random sampling of given size from the existing samples. :param n: Number of samples :return: :class:`pandas.DataFrame` of length ``n`` with random samples. """ samples = self.samples inds = rand.randint(len(samples),size=int(n)) newsamples = samples.iloc[inds] newsamples.reset_index(inplace=True) return newsamples
python
def random_samples(self, n): """ Returns a random sampling of given size from the existing samples. :param n: Number of samples :return: :class:`pandas.DataFrame` of length ``n`` with random samples. """ samples = self.samples inds = rand.randint(len(samples),size=int(n)) newsamples = samples.iloc[inds] newsamples.reset_index(inplace=True) return newsamples
[ "def", "random_samples", "(", "self", ",", "n", ")", ":", "samples", "=", "self", ".", "samples", "inds", "=", "rand", ".", "randint", "(", "len", "(", "samples", ")", ",", "size", "=", "int", "(", "n", ")", ")", "newsamples", "=", "samples", ".", ...
Returns a random sampling of given size from the existing samples. :param n: Number of samples :return: :class:`pandas.DataFrame` of length ``n`` with random samples.
[ "Returns", "a", "random", "sampling", "of", "given", "size", "from", "the", "existing", "samples", "." ]
d84495573044c66db2fd6b959fe69e370757ea14
https://github.com/timothydmorton/isochrones/blob/d84495573044c66db2fd6b959fe69e370757ea14/isochrones/starmodel.py#L939-L954
train
210,799