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
openstack/networking-cisco
networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py
FabricBase.delete_dcnm_in_nwk
def delete_dcnm_in_nwk(self, tenant_id, fw_dict, is_fw_virt=False): """Delete the DCNM In Network and store the result in DB. """ tenant_name = fw_dict.get('tenant_name') ret = self._delete_service_nwk(tenant_id, tenant_name, 'in') if ret: res = fw_const.DCNM_IN_NETWORK_DEL_SUCCESS LOG.info("In Service network deleted for tenant %s", tenant_id) else: res = fw_const.DCNM_IN_NETWORK_DEL_FAIL LOG.info("In Service network deleted failed for tenant %s", tenant_id) self.update_fw_db_result(tenant_id, dcnm_status=res) return ret
python
def delete_dcnm_in_nwk(self, tenant_id, fw_dict, is_fw_virt=False): """Delete the DCNM In Network and store the result in DB. """ tenant_name = fw_dict.get('tenant_name') ret = self._delete_service_nwk(tenant_id, tenant_name, 'in') if ret: res = fw_const.DCNM_IN_NETWORK_DEL_SUCCESS LOG.info("In Service network deleted for tenant %s", tenant_id) else: res = fw_const.DCNM_IN_NETWORK_DEL_FAIL LOG.info("In Service network deleted failed for tenant %s", tenant_id) self.update_fw_db_result(tenant_id, dcnm_status=res) return ret
[ "def", "delete_dcnm_in_nwk", "(", "self", ",", "tenant_id", ",", "fw_dict", ",", "is_fw_virt", "=", "False", ")", ":", "tenant_name", "=", "fw_dict", ".", "get", "(", "'tenant_name'", ")", "ret", "=", "self", ".", "_delete_service_nwk", "(", "tenant_id", ","...
Delete the DCNM In Network and store the result in DB.
[ "Delete", "the", "DCNM", "In", "Network", "and", "store", "the", "result", "in", "DB", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L1304-L1317
train
38,100
openstack/networking-cisco
networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py
FabricBase.update_dcnm_in_part
def update_dcnm_in_part(self, tenant_id, fw_dict, is_fw_virt=False): """Update DCNM's in partition information. Update the In partition service node IP address in DCNM and update the result """ res = fw_const.DCNM_IN_PART_UPDATE_SUCCESS tenant_name = fw_dict.get('tenant_name') ret = True try: self._update_partition_in_create(tenant_id, tenant_name) except Exception as exc: LOG.error("Update of In Partition failed for tenant %(tenant)s" " Exception %(exc)s", {'tenant': tenant_id, 'exc': str(exc)}) res = fw_const.DCNM_IN_PART_UPDATE_FAIL ret = False self.update_fw_db_result(tenant_id, dcnm_status=res) LOG.info("In partition updated with service ip addr") return ret
python
def update_dcnm_in_part(self, tenant_id, fw_dict, is_fw_virt=False): """Update DCNM's in partition information. Update the In partition service node IP address in DCNM and update the result """ res = fw_const.DCNM_IN_PART_UPDATE_SUCCESS tenant_name = fw_dict.get('tenant_name') ret = True try: self._update_partition_in_create(tenant_id, tenant_name) except Exception as exc: LOG.error("Update of In Partition failed for tenant %(tenant)s" " Exception %(exc)s", {'tenant': tenant_id, 'exc': str(exc)}) res = fw_const.DCNM_IN_PART_UPDATE_FAIL ret = False self.update_fw_db_result(tenant_id, dcnm_status=res) LOG.info("In partition updated with service ip addr") return ret
[ "def", "update_dcnm_in_part", "(", "self", ",", "tenant_id", ",", "fw_dict", ",", "is_fw_virt", "=", "False", ")", ":", "res", "=", "fw_const", ".", "DCNM_IN_PART_UPDATE_SUCCESS", "tenant_name", "=", "fw_dict", ".", "get", "(", "'tenant_name'", ")", "ret", "="...
Update DCNM's in partition information. Update the In partition service node IP address in DCNM and update the result
[ "Update", "DCNM", "s", "in", "partition", "information", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L1319-L1338
train
38,101
openstack/networking-cisco
networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py
FabricBase.clear_dcnm_in_part
def clear_dcnm_in_part(self, tenant_id, fw_dict, is_fw_virt=False): """Clear the DCNM in partition service information. Clear the In partition service node IP address in DCNM and update the result. """ res = fw_const.DCNM_IN_PART_UPDDEL_SUCCESS tenant_name = fw_dict.get('tenant_name') ret = True try: self._update_partition_in_delete(tenant_name) except Exception as exc: LOG.error("Clear of In Partition failed for tenant %(tenant)s" " , Exception %(exc)s", {'tenant': tenant_id, 'exc': str(exc)}) res = fw_const.DCNM_IN_PART_UPDDEL_FAIL ret = False self.update_fw_db_result(tenant_id, dcnm_status=res) LOG.info("In partition cleared off service ip addr") return ret
python
def clear_dcnm_in_part(self, tenant_id, fw_dict, is_fw_virt=False): """Clear the DCNM in partition service information. Clear the In partition service node IP address in DCNM and update the result. """ res = fw_const.DCNM_IN_PART_UPDDEL_SUCCESS tenant_name = fw_dict.get('tenant_name') ret = True try: self._update_partition_in_delete(tenant_name) except Exception as exc: LOG.error("Clear of In Partition failed for tenant %(tenant)s" " , Exception %(exc)s", {'tenant': tenant_id, 'exc': str(exc)}) res = fw_const.DCNM_IN_PART_UPDDEL_FAIL ret = False self.update_fw_db_result(tenant_id, dcnm_status=res) LOG.info("In partition cleared off service ip addr") return ret
[ "def", "clear_dcnm_in_part", "(", "self", ",", "tenant_id", ",", "fw_dict", ",", "is_fw_virt", "=", "False", ")", ":", "res", "=", "fw_const", ".", "DCNM_IN_PART_UPDDEL_SUCCESS", "tenant_name", "=", "fw_dict", ".", "get", "(", "'tenant_name'", ")", "ret", "=",...
Clear the DCNM in partition service information. Clear the In partition service node IP address in DCNM and update the result.
[ "Clear", "the", "DCNM", "in", "partition", "service", "information", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L1340-L1359
train
38,102
openstack/networking-cisco
networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py
FabricBase.create_dcnm_out_part
def create_dcnm_out_part(self, tenant_id, fw_dict, is_fw_virt=False): """Create the DCNM OUT partition and update the result. """ res = fw_const.DCNM_OUT_PART_CREATE_SUCCESS tenant_name = fw_dict.get('tenant_name') ret = True try: self._create_out_partition(tenant_id, tenant_name) except Exception as exc: LOG.error("Create of Out Partition failed for tenant " "%(tenant)s ,Exception %(exc)s", {'tenant': tenant_id, 'exc': str(exc)}) res = fw_const.DCNM_OUT_PART_CREATE_FAIL ret = False self.update_fw_db_result(tenant_id, dcnm_status=res) LOG.info("Out partition created") return ret
python
def create_dcnm_out_part(self, tenant_id, fw_dict, is_fw_virt=False): """Create the DCNM OUT partition and update the result. """ res = fw_const.DCNM_OUT_PART_CREATE_SUCCESS tenant_name = fw_dict.get('tenant_name') ret = True try: self._create_out_partition(tenant_id, tenant_name) except Exception as exc: LOG.error("Create of Out Partition failed for tenant " "%(tenant)s ,Exception %(exc)s", {'tenant': tenant_id, 'exc': str(exc)}) res = fw_const.DCNM_OUT_PART_CREATE_FAIL ret = False self.update_fw_db_result(tenant_id, dcnm_status=res) LOG.info("Out partition created") return ret
[ "def", "create_dcnm_out_part", "(", "self", ",", "tenant_id", ",", "fw_dict", ",", "is_fw_virt", "=", "False", ")", ":", "res", "=", "fw_const", ".", "DCNM_OUT_PART_CREATE_SUCCESS", "tenant_name", "=", "fw_dict", ".", "get", "(", "'tenant_name'", ")", "ret", "...
Create the DCNM OUT partition and update the result.
[ "Create", "the", "DCNM", "OUT", "partition", "and", "update", "the", "result", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L1361-L1376
train
38,103
openstack/networking-cisco
networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py
FabricBase.delete_dcnm_out_part
def delete_dcnm_out_part(self, tenant_id, fw_dict, is_fw_virt=False): """Delete the DCNM OUT partition and update the result. """ res = fw_const.DCNM_OUT_PART_DEL_SUCCESS tenant_name = fw_dict.get('tenant_name') ret = True try: self._delete_partition(tenant_id, tenant_name) except Exception as exc: LOG.error("deletion of Out Partition failed for tenant " "%(tenant)s, Exception %(exc)s", {'tenant': tenant_id, 'exc': str(exc)}) res = fw_const.DCNM_OUT_PART_DEL_FAIL ret = False self.update_fw_db_result(tenant_id, dcnm_status=res) LOG.info("Out partition deleted") return ret
python
def delete_dcnm_out_part(self, tenant_id, fw_dict, is_fw_virt=False): """Delete the DCNM OUT partition and update the result. """ res = fw_const.DCNM_OUT_PART_DEL_SUCCESS tenant_name = fw_dict.get('tenant_name') ret = True try: self._delete_partition(tenant_id, tenant_name) except Exception as exc: LOG.error("deletion of Out Partition failed for tenant " "%(tenant)s, Exception %(exc)s", {'tenant': tenant_id, 'exc': str(exc)}) res = fw_const.DCNM_OUT_PART_DEL_FAIL ret = False self.update_fw_db_result(tenant_id, dcnm_status=res) LOG.info("Out partition deleted") return ret
[ "def", "delete_dcnm_out_part", "(", "self", ",", "tenant_id", ",", "fw_dict", ",", "is_fw_virt", "=", "False", ")", ":", "res", "=", "fw_const", ".", "DCNM_OUT_PART_DEL_SUCCESS", "tenant_name", "=", "fw_dict", ".", "get", "(", "'tenant_name'", ")", "ret", "=",...
Delete the DCNM OUT partition and update the result.
[ "Delete", "the", "DCNM", "OUT", "partition", "and", "update", "the", "result", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L1378-L1393
train
38,104
openstack/networking-cisco
networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py
FabricBase.create_dcnm_out_nwk
def create_dcnm_out_nwk(self, tenant_id, fw_dict, is_fw_virt=False): """Create the DCNM OUT Network and update the result. """ tenant_name = fw_dict.get('tenant_name') ret = self._create_service_nwk(tenant_id, tenant_name, 'out') if ret: res = fw_const.DCNM_OUT_NETWORK_CREATE_SUCCESS LOG.info("out Service network created for tenant %s", tenant_id) else: res = fw_const.DCNM_OUT_NETWORK_CREATE_FAIL LOG.info("out Service network create failed for tenant %s", tenant_id) self.update_fw_db_result(tenant_id, dcnm_status=res) return ret
python
def create_dcnm_out_nwk(self, tenant_id, fw_dict, is_fw_virt=False): """Create the DCNM OUT Network and update the result. """ tenant_name = fw_dict.get('tenant_name') ret = self._create_service_nwk(tenant_id, tenant_name, 'out') if ret: res = fw_const.DCNM_OUT_NETWORK_CREATE_SUCCESS LOG.info("out Service network created for tenant %s", tenant_id) else: res = fw_const.DCNM_OUT_NETWORK_CREATE_FAIL LOG.info("out Service network create failed for tenant %s", tenant_id) self.update_fw_db_result(tenant_id, dcnm_status=res) return ret
[ "def", "create_dcnm_out_nwk", "(", "self", ",", "tenant_id", ",", "fw_dict", ",", "is_fw_virt", "=", "False", ")", ":", "tenant_name", "=", "fw_dict", ".", "get", "(", "'tenant_name'", ")", "ret", "=", "self", ".", "_create_service_nwk", "(", "tenant_id", ",...
Create the DCNM OUT Network and update the result.
[ "Create", "the", "DCNM", "OUT", "Network", "and", "update", "the", "result", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L1395-L1408
train
38,105
openstack/networking-cisco
networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py
FabricBase.delete_dcnm_out_nwk
def delete_dcnm_out_nwk(self, tenant_id, fw_dict, is_fw_virt=False): """Delete the DCNM OUT network and update the result. """ tenant_name = fw_dict.get('tenant_name') ret = self._delete_service_nwk(tenant_id, tenant_name, 'out') if ret: res = fw_const.DCNM_OUT_NETWORK_DEL_SUCCESS LOG.info("out Service network deleted for tenant %s", tenant_id) else: res = fw_const.DCNM_OUT_NETWORK_DEL_FAIL LOG.info("out Service network deleted failed for tenant %s", tenant_id) self.update_fw_db_result(tenant_id, dcnm_status=res) return ret
python
def delete_dcnm_out_nwk(self, tenant_id, fw_dict, is_fw_virt=False): """Delete the DCNM OUT network and update the result. """ tenant_name = fw_dict.get('tenant_name') ret = self._delete_service_nwk(tenant_id, tenant_name, 'out') if ret: res = fw_const.DCNM_OUT_NETWORK_DEL_SUCCESS LOG.info("out Service network deleted for tenant %s", tenant_id) else: res = fw_const.DCNM_OUT_NETWORK_DEL_FAIL LOG.info("out Service network deleted failed for tenant %s", tenant_id) self.update_fw_db_result(tenant_id, dcnm_status=res) return ret
[ "def", "delete_dcnm_out_nwk", "(", "self", ",", "tenant_id", ",", "fw_dict", ",", "is_fw_virt", "=", "False", ")", ":", "tenant_name", "=", "fw_dict", ".", "get", "(", "'tenant_name'", ")", "ret", "=", "self", ".", "_delete_service_nwk", "(", "tenant_id", ",...
Delete the DCNM OUT network and update the result.
[ "Delete", "the", "DCNM", "OUT", "network", "and", "update", "the", "result", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L1410-L1423
train
38,106
openstack/networking-cisco
networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py
FabricBase.update_dcnm_out_part
def update_dcnm_out_part(self, tenant_id, fw_dict, is_fw_virt=False): """Update DCNM OUT partition service node IP address and result. """ res = fw_const.DCNM_OUT_PART_UPDATE_SUCCESS tenant_name = fw_dict.get('tenant_name') ret = True try: ret = self._update_partition_out_create(tenant_id, tenant_name) if not ret: res = fw_const.DCNM_OUT_PART_UPDATE_FAIL except Exception as exc: LOG.error("Update of Out Partition failed for tenant " "%(tenant)s Exception %(exc)s", {'tenant': tenant_id, 'exc': str(exc)}) res = fw_const.DCNM_OUT_PART_UPDATE_FAIL ret = False self.update_fw_db_result(tenant_id, dcnm_status=res) LOG.info("Out partition updated with service ip addr") return ret
python
def update_dcnm_out_part(self, tenant_id, fw_dict, is_fw_virt=False): """Update DCNM OUT partition service node IP address and result. """ res = fw_const.DCNM_OUT_PART_UPDATE_SUCCESS tenant_name = fw_dict.get('tenant_name') ret = True try: ret = self._update_partition_out_create(tenant_id, tenant_name) if not ret: res = fw_const.DCNM_OUT_PART_UPDATE_FAIL except Exception as exc: LOG.error("Update of Out Partition failed for tenant " "%(tenant)s Exception %(exc)s", {'tenant': tenant_id, 'exc': str(exc)}) res = fw_const.DCNM_OUT_PART_UPDATE_FAIL ret = False self.update_fw_db_result(tenant_id, dcnm_status=res) LOG.info("Out partition updated with service ip addr") return ret
[ "def", "update_dcnm_out_part", "(", "self", ",", "tenant_id", ",", "fw_dict", ",", "is_fw_virt", "=", "False", ")", ":", "res", "=", "fw_const", ".", "DCNM_OUT_PART_UPDATE_SUCCESS", "tenant_name", "=", "fw_dict", ".", "get", "(", "'tenant_name'", ")", "ret", "...
Update DCNM OUT partition service node IP address and result.
[ "Update", "DCNM", "OUT", "partition", "service", "node", "IP", "address", "and", "result", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L1425-L1442
train
38,107
openstack/networking-cisco
networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py
FabricBase.clear_dcnm_out_part
def clear_dcnm_out_part(self, tenant_id, fw_dict, is_fw_virt=False): """Clear DCNM out partition information. Clear the DCNM OUT partition service node IP address and update the result """ res = fw_const.DCNM_OUT_PART_UPDDEL_SUCCESS self.update_fw_db_result(tenant_id, dcnm_status=res) LOG.info("Out partition cleared -noop- with service ip addr") return True
python
def clear_dcnm_out_part(self, tenant_id, fw_dict, is_fw_virt=False): """Clear DCNM out partition information. Clear the DCNM OUT partition service node IP address and update the result """ res = fw_const.DCNM_OUT_PART_UPDDEL_SUCCESS self.update_fw_db_result(tenant_id, dcnm_status=res) LOG.info("Out partition cleared -noop- with service ip addr") return True
[ "def", "clear_dcnm_out_part", "(", "self", ",", "tenant_id", ",", "fw_dict", ",", "is_fw_virt", "=", "False", ")", ":", "res", "=", "fw_const", ".", "DCNM_OUT_PART_UPDDEL_SUCCESS", "self", ".", "update_fw_db_result", "(", "tenant_id", ",", "dcnm_status", "=", "r...
Clear DCNM out partition information. Clear the DCNM OUT partition service node IP address and update the result
[ "Clear", "DCNM", "out", "partition", "information", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L1444-L1453
train
38,108
openstack/networking-cisco
networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py
FabricBase.get_next_create_state
def get_next_create_state(self, state, ret): """Return the next create state from previous state. """ if ret: if state == fw_const.FABRIC_PREPARE_DONE_STATE: return state else: return state + 1 else: return state
python
def get_next_create_state(self, state, ret): """Return the next create state from previous state. """ if ret: if state == fw_const.FABRIC_PREPARE_DONE_STATE: return state else: return state + 1 else: return state
[ "def", "get_next_create_state", "(", "self", ",", "state", ",", "ret", ")", ":", "if", "ret", ":", "if", "state", "==", "fw_const", ".", "FABRIC_PREPARE_DONE_STATE", ":", "return", "state", "else", ":", "return", "state", "+", "1", "else", ":", "return", ...
Return the next create state from previous state.
[ "Return", "the", "next", "create", "state", "from", "previous", "state", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L1463-L1471
train
38,109
openstack/networking-cisco
networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py
FabricBase.get_next_del_state
def get_next_del_state(self, state, ret): """Return the next delete state from previous state. """ if ret: if state == fw_const.INIT_STATE: return state else: return state - 1 else: return state
python
def get_next_del_state(self, state, ret): """Return the next delete state from previous state. """ if ret: if state == fw_const.INIT_STATE: return state else: return state - 1 else: return state
[ "def", "get_next_del_state", "(", "self", ",", "state", ",", "ret", ")", ":", "if", "ret", ":", "if", "state", "==", "fw_const", ".", "INIT_STATE", ":", "return", "state", "else", ":", "return", "state", "-", "1", "else", ":", "return", "state" ]
Return the next delete state from previous state.
[ "Return", "the", "next", "delete", "state", "from", "previous", "state", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L1473-L1481
train
38,110
openstack/networking-cisco
networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py
FabricBase.get_next_state
def get_next_state(self, state, ret, oper): """Returns the next state for a create or delete operation. """ if oper == fw_const.FW_CR_OP: return self.get_next_create_state(state, ret) else: return self.get_next_del_state(state, ret)
python
def get_next_state(self, state, ret, oper): """Returns the next state for a create or delete operation. """ if oper == fw_const.FW_CR_OP: return self.get_next_create_state(state, ret) else: return self.get_next_del_state(state, ret)
[ "def", "get_next_state", "(", "self", ",", "state", ",", "ret", ",", "oper", ")", ":", "if", "oper", "==", "fw_const", ".", "FW_CR_OP", ":", "return", "self", ".", "get_next_create_state", "(", "state", ",", "ret", ")", "else", ":", "return", "self", "...
Returns the next state for a create or delete operation.
[ "Returns", "the", "next", "state", "for", "a", "create", "or", "delete", "operation", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L1483-L1488
train
38,111
openstack/networking-cisco
networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py
FabricBase.run_create_sm
def run_create_sm(self, tenant_id, fw_dict, is_fw_virt): """Runs the create State Machine. Goes through every state function until the end or when one state returns failure. """ ret = True serv_obj = self.get_service_obj(tenant_id) state = serv_obj.get_state() # Preserve the ordering of the next lines till while new_state = serv_obj.fixup_state(fw_const.FW_CR_OP, state) serv_obj.store_local_final_result(fw_const.RESULT_FW_CREATE_INIT) if state != new_state: state = new_state serv_obj.store_state(state) while ret: try: ret = self.fabric_fsm[state][0](tenant_id, fw_dict, is_fw_virt=is_fw_virt) except Exception as exc: LOG.error("Exception %(exc)s for state %(state)s", {'exc': str(exc), 'state': fw_const.fw_state_fn_dict.get(state)}) ret = False if ret: LOG.info("State %s return successfully", fw_const.fw_state_fn_dict.get(state)) state = self.get_next_state(state, ret, fw_const.FW_CR_OP) serv_obj.store_state(state) if state == fw_const.FABRIC_PREPARE_DONE_STATE: break if ret: serv_obj.store_local_final_result(fw_const.RESULT_FW_CREATE_DONE) return ret
python
def run_create_sm(self, tenant_id, fw_dict, is_fw_virt): """Runs the create State Machine. Goes through every state function until the end or when one state returns failure. """ ret = True serv_obj = self.get_service_obj(tenant_id) state = serv_obj.get_state() # Preserve the ordering of the next lines till while new_state = serv_obj.fixup_state(fw_const.FW_CR_OP, state) serv_obj.store_local_final_result(fw_const.RESULT_FW_CREATE_INIT) if state != new_state: state = new_state serv_obj.store_state(state) while ret: try: ret = self.fabric_fsm[state][0](tenant_id, fw_dict, is_fw_virt=is_fw_virt) except Exception as exc: LOG.error("Exception %(exc)s for state %(state)s", {'exc': str(exc), 'state': fw_const.fw_state_fn_dict.get(state)}) ret = False if ret: LOG.info("State %s return successfully", fw_const.fw_state_fn_dict.get(state)) state = self.get_next_state(state, ret, fw_const.FW_CR_OP) serv_obj.store_state(state) if state == fw_const.FABRIC_PREPARE_DONE_STATE: break if ret: serv_obj.store_local_final_result(fw_const.RESULT_FW_CREATE_DONE) return ret
[ "def", "run_create_sm", "(", "self", ",", "tenant_id", ",", "fw_dict", ",", "is_fw_virt", ")", ":", "ret", "=", "True", "serv_obj", "=", "self", ".", "get_service_obj", "(", "tenant_id", ")", "state", "=", "serv_obj", ".", "get_state", "(", ")", "# Preserv...
Runs the create State Machine. Goes through every state function until the end or when one state returns failure.
[ "Runs", "the", "create", "State", "Machine", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L1490-L1523
train
38,112
openstack/networking-cisco
networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py
FabricBase.run_delete_sm
def run_delete_sm(self, tenant_id, fw_dict, is_fw_virt): """Runs the delete State Machine. Goes through every state function until the end or when one state returns failure. """ # Read the current state from the DB ret = True serv_obj = self.get_service_obj(tenant_id) state = serv_obj.get_state() # Preserve the ordering of the next lines till while new_state = serv_obj.fixup_state(fw_const.FW_DEL_OP, state) serv_obj.store_local_final_result(fw_const.RESULT_FW_DELETE_INIT) if state != new_state: state = new_state serv_obj.store_state(state) while ret: try: ret = self.fabric_fsm[state][1](tenant_id, fw_dict, is_fw_virt=is_fw_virt) except Exception as exc: LOG.error("Exception %(exc)s for state %(state)s", {'exc': str(exc), 'state': fw_const.fw_state_fn_del_dict.get(state)}) ret = False if ret: LOG.info("State %s return successfully", fw_const.fw_state_fn_del_dict.get(state)) if state == fw_const.INIT_STATE: break state = self.get_next_state(state, ret, fw_const.FW_DEL_OP) serv_obj.store_state(state) return ret
python
def run_delete_sm(self, tenant_id, fw_dict, is_fw_virt): """Runs the delete State Machine. Goes through every state function until the end or when one state returns failure. """ # Read the current state from the DB ret = True serv_obj = self.get_service_obj(tenant_id) state = serv_obj.get_state() # Preserve the ordering of the next lines till while new_state = serv_obj.fixup_state(fw_const.FW_DEL_OP, state) serv_obj.store_local_final_result(fw_const.RESULT_FW_DELETE_INIT) if state != new_state: state = new_state serv_obj.store_state(state) while ret: try: ret = self.fabric_fsm[state][1](tenant_id, fw_dict, is_fw_virt=is_fw_virt) except Exception as exc: LOG.error("Exception %(exc)s for state %(state)s", {'exc': str(exc), 'state': fw_const.fw_state_fn_del_dict.get(state)}) ret = False if ret: LOG.info("State %s return successfully", fw_const.fw_state_fn_del_dict.get(state)) if state == fw_const.INIT_STATE: break state = self.get_next_state(state, ret, fw_const.FW_DEL_OP) serv_obj.store_state(state) return ret
[ "def", "run_delete_sm", "(", "self", ",", "tenant_id", ",", "fw_dict", ",", "is_fw_virt", ")", ":", "# Read the current state from the DB", "ret", "=", "True", "serv_obj", "=", "self", ".", "get_service_obj", "(", "tenant_id", ")", "state", "=", "serv_obj", ".",...
Runs the delete State Machine. Goes through every state function until the end or when one state returns failure.
[ "Runs", "the", "delete", "State", "Machine", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L1525-L1557
train
38,113
openstack/networking-cisco
networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py
FabricBase.get_key_state
def get_key_state(self, status, state_dict): """Returns the key associated with the dict. """ for key, val in state_dict.items(): if val == status: return key
python
def get_key_state(self, status, state_dict): """Returns the key associated with the dict. """ for key, val in state_dict.items(): if val == status: return key
[ "def", "get_key_state", "(", "self", ",", "status", ",", "state_dict", ")", ":", "for", "key", ",", "val", "in", "state_dict", ".", "items", "(", ")", ":", "if", "val", "==", "status", ":", "return", "key" ]
Returns the key associated with the dict.
[ "Returns", "the", "key", "associated", "with", "the", "dict", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L1559-L1563
train
38,114
openstack/networking-cisco
networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py
FabricBase.pop_fw_state
def pop_fw_state(self, compl_result, os_status, dcnm_status): """Populate the state information in the cache. Check if state information is embedded in result If not: a. It's still in Init state and no SM is called yet b. The SM has completely run c. Delete has started and before any SM is run, it restarted. """ res_list = compl_result.split('(') state_num = None if len(res_list) > 1: state_num = int(res_list[1].split(')')[0]) else: if res_list[0] == fw_const.RESULT_FW_CREATE_INIT: if os_status is None: state_num = fw_const.INIT_STATE elif res_list[0] == fw_const.RESULT_FW_CREATE_DONE: state_num = fw_const.FABRIC_PREPARE_DONE_STATE elif res_list[0] == fw_const.RESULT_FW_DELETE_INIT: if os_status == fw_const.OS_CREATE_SUCCESS and ( dcnm_status == fw_const.DCNM_CREATE_SUCCESS): state_num = fw_const.FABRIC_PREPARE_DONE_STATE return state_num
python
def pop_fw_state(self, compl_result, os_status, dcnm_status): """Populate the state information in the cache. Check if state information is embedded in result If not: a. It's still in Init state and no SM is called yet b. The SM has completely run c. Delete has started and before any SM is run, it restarted. """ res_list = compl_result.split('(') state_num = None if len(res_list) > 1: state_num = int(res_list[1].split(')')[0]) else: if res_list[0] == fw_const.RESULT_FW_CREATE_INIT: if os_status is None: state_num = fw_const.INIT_STATE elif res_list[0] == fw_const.RESULT_FW_CREATE_DONE: state_num = fw_const.FABRIC_PREPARE_DONE_STATE elif res_list[0] == fw_const.RESULT_FW_DELETE_INIT: if os_status == fw_const.OS_CREATE_SUCCESS and ( dcnm_status == fw_const.DCNM_CREATE_SUCCESS): state_num = fw_const.FABRIC_PREPARE_DONE_STATE return state_num
[ "def", "pop_fw_state", "(", "self", ",", "compl_result", ",", "os_status", ",", "dcnm_status", ")", ":", "res_list", "=", "compl_result", ".", "split", "(", "'('", ")", "state_num", "=", "None", "if", "len", "(", "res_list", ")", ">", "1", ":", "state_nu...
Populate the state information in the cache. Check if state information is embedded in result If not: a. It's still in Init state and no SM is called yet b. The SM has completely run c. Delete has started and before any SM is run, it restarted.
[ "Populate", "the", "state", "information", "in", "the", "cache", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L1565-L1588
train
38,115
openstack/networking-cisco
networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py
FabricBase.pop_fw_local
def pop_fw_local(self, tenant_id, net_id, direc, node_ip): """Populate the local cache. Read the Network DB and populate the local cache. Read the subnet from the Subnet DB, given the net_id and populate the cache. """ net = self.get_network(net_id) serv_obj = self.get_service_obj(tenant_id) serv_obj.update_fw_local_cache(net_id, direc, node_ip) if net is not None: net_dict = self.fill_dcnm_net_info(tenant_id, direc, net.vlan, net.segmentation_id) serv_obj.store_dcnm_net_dict(net_dict, direc) if direc == "in": subnet = self.service_in_ip.get_subnet_by_netid(net_id) else: subnet = self.service_out_ip.get_subnet_by_netid(net_id) if subnet is not None: subnet_dict = self.fill_dcnm_subnet_info( tenant_id, subnet, self.get_start_ip(subnet), self.get_end_ip(subnet), self.get_gateway(subnet), self.get_secondary_gateway(subnet), direc) serv_obj.store_dcnm_subnet_dict(subnet_dict, direc)
python
def pop_fw_local(self, tenant_id, net_id, direc, node_ip): """Populate the local cache. Read the Network DB and populate the local cache. Read the subnet from the Subnet DB, given the net_id and populate the cache. """ net = self.get_network(net_id) serv_obj = self.get_service_obj(tenant_id) serv_obj.update_fw_local_cache(net_id, direc, node_ip) if net is not None: net_dict = self.fill_dcnm_net_info(tenant_id, direc, net.vlan, net.segmentation_id) serv_obj.store_dcnm_net_dict(net_dict, direc) if direc == "in": subnet = self.service_in_ip.get_subnet_by_netid(net_id) else: subnet = self.service_out_ip.get_subnet_by_netid(net_id) if subnet is not None: subnet_dict = self.fill_dcnm_subnet_info( tenant_id, subnet, self.get_start_ip(subnet), self.get_end_ip(subnet), self.get_gateway(subnet), self.get_secondary_gateway(subnet), direc) serv_obj.store_dcnm_subnet_dict(subnet_dict, direc)
[ "def", "pop_fw_local", "(", "self", ",", "tenant_id", ",", "net_id", ",", "direc", ",", "node_ip", ")", ":", "net", "=", "self", ".", "get_network", "(", "net_id", ")", "serv_obj", "=", "self", ".", "get_service_obj", "(", "tenant_id", ")", "serv_obj", "...
Populate the local cache. Read the Network DB and populate the local cache. Read the subnet from the Subnet DB, given the net_id and populate the cache.
[ "Populate", "the", "local", "cache", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L1590-L1614
train
38,116
openstack/networking-cisco
networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py
FabricBase.populate_local_cache_tenant
def populate_local_cache_tenant(self, fw_id, fw_data): """Populate the cache for a given tenant. Calls routines to Populate the in and out information. Update the result information. Populate the state information. Populate the router information. """ tenant_id = fw_data.get('tenant_id') self.create_serv_obj(tenant_id) serv_obj = self.get_service_obj(tenant_id) serv_obj.create_fw_db(fw_id, fw_data.get('name'), tenant_id) self.pop_fw_local(tenant_id, fw_data.get('in_network_id'), "in", fw_data.get('in_service_node_ip')) self.pop_fw_local(tenant_id, fw_data.get('out_network_id'), "out", fw_data.get('out_service_node_ip')) serv_obj.update_fw_local_result_str(fw_data.get('os_status'), fw_data.get('dcnm_status'), fw_data.get('device_status')) compl_res = fw_data.get('result') result = compl_res.split('(')[0] serv_obj.store_local_final_result(result) state = self.pop_fw_state(compl_res, fw_data.get('os_status'), fw_data.get('dcnm_status')) if state is None: LOG.error("Unable to get state complete result %(res)s" " OS status %(os)s, dcnm status %(dcnm)s", {'res': compl_res, 'os': fw_data.get('os_status'), 'dcnm': fw_data.get('dcnm_status')}) serv_obj.store_state(state, popl_db=False) if state == fw_const.FABRIC_PREPARE_DONE_STATE: serv_obj.set_fabric_create(True) router_id = fw_data.get('router_id') rout_net_id = fw_data.get('router_net_id') rout_subnet_id = fw_data.get('router_subnet_id') # Result is already populated above, so pass None below. # And, the result passed should be a string serv_obj.update_fw_local_router(rout_net_id, rout_subnet_id, router_id, None)
python
def populate_local_cache_tenant(self, fw_id, fw_data): """Populate the cache for a given tenant. Calls routines to Populate the in and out information. Update the result information. Populate the state information. Populate the router information. """ tenant_id = fw_data.get('tenant_id') self.create_serv_obj(tenant_id) serv_obj = self.get_service_obj(tenant_id) serv_obj.create_fw_db(fw_id, fw_data.get('name'), tenant_id) self.pop_fw_local(tenant_id, fw_data.get('in_network_id'), "in", fw_data.get('in_service_node_ip')) self.pop_fw_local(tenant_id, fw_data.get('out_network_id'), "out", fw_data.get('out_service_node_ip')) serv_obj.update_fw_local_result_str(fw_data.get('os_status'), fw_data.get('dcnm_status'), fw_data.get('device_status')) compl_res = fw_data.get('result') result = compl_res.split('(')[0] serv_obj.store_local_final_result(result) state = self.pop_fw_state(compl_res, fw_data.get('os_status'), fw_data.get('dcnm_status')) if state is None: LOG.error("Unable to get state complete result %(res)s" " OS status %(os)s, dcnm status %(dcnm)s", {'res': compl_res, 'os': fw_data.get('os_status'), 'dcnm': fw_data.get('dcnm_status')}) serv_obj.store_state(state, popl_db=False) if state == fw_const.FABRIC_PREPARE_DONE_STATE: serv_obj.set_fabric_create(True) router_id = fw_data.get('router_id') rout_net_id = fw_data.get('router_net_id') rout_subnet_id = fw_data.get('router_subnet_id') # Result is already populated above, so pass None below. # And, the result passed should be a string serv_obj.update_fw_local_router(rout_net_id, rout_subnet_id, router_id, None)
[ "def", "populate_local_cache_tenant", "(", "self", ",", "fw_id", ",", "fw_data", ")", ":", "tenant_id", "=", "fw_data", ".", "get", "(", "'tenant_id'", ")", "self", ".", "create_serv_obj", "(", "tenant_id", ")", "serv_obj", "=", "self", ".", "get_service_obj",...
Populate the cache for a given tenant. Calls routines to Populate the in and out information. Update the result information. Populate the state information. Populate the router information.
[ "Populate", "the", "cache", "for", "a", "given", "tenant", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L1617-L1655
train
38,117
openstack/networking-cisco
networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py
FabricBase.populate_local_cache
def populate_local_cache(self): """Populate the local cache from DB. Read the entries from FW DB and Calls routines to populate the cache. """ fw_dict = self.get_all_fw_db() for fw_id in fw_dict: LOG.info("Populating cache for FW %s", fw_id) fw_data = fw_dict[fw_id] self.populate_local_cache_tenant(fw_id, fw_data)
python
def populate_local_cache(self): """Populate the local cache from DB. Read the entries from FW DB and Calls routines to populate the cache. """ fw_dict = self.get_all_fw_db() for fw_id in fw_dict: LOG.info("Populating cache for FW %s", fw_id) fw_data = fw_dict[fw_id] self.populate_local_cache_tenant(fw_id, fw_data)
[ "def", "populate_local_cache", "(", "self", ")", ":", "fw_dict", "=", "self", ".", "get_all_fw_db", "(", ")", "for", "fw_id", "in", "fw_dict", ":", "LOG", ".", "info", "(", "\"Populating cache for FW %s\"", ",", "fw_id", ")", "fw_data", "=", "fw_dict", "[", ...
Populate the local cache from DB. Read the entries from FW DB and Calls routines to populate the cache.
[ "Populate", "the", "local", "cache", "from", "DB", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L1657-L1666
train
38,118
openstack/networking-cisco
networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py
FabricBase.delete_os_dummy_rtr_nwk
def delete_os_dummy_rtr_nwk(self, rtr_id, net_id, subnet_id): """Delete the dummy interface to the router. """ subnet_lst = set() subnet_lst.add(subnet_id) ret = self.os_helper.delete_intf_router(None, None, rtr_id, subnet_lst) if not ret: return ret return self.os_helper.delete_network_all_subnets(net_id)
python
def delete_os_dummy_rtr_nwk(self, rtr_id, net_id, subnet_id): """Delete the dummy interface to the router. """ subnet_lst = set() subnet_lst.add(subnet_id) ret = self.os_helper.delete_intf_router(None, None, rtr_id, subnet_lst) if not ret: return ret return self.os_helper.delete_network_all_subnets(net_id)
[ "def", "delete_os_dummy_rtr_nwk", "(", "self", ",", "rtr_id", ",", "net_id", ",", "subnet_id", ")", ":", "subnet_lst", "=", "set", "(", ")", "subnet_lst", ".", "add", "(", "subnet_id", ")", "ret", "=", "self", ".", "os_helper", ".", "delete_intf_router", "...
Delete the dummy interface to the router.
[ "Delete", "the", "dummy", "interface", "to", "the", "router", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L1668-L1675
train
38,119
openstack/networking-cisco
networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py
FabricBase.delete_os_nwk_db
def delete_os_nwk_db(self, net_id, seg, vlan): """Delete the Openstack Network from the database. Release the segmentation ID, VLAN associated with the net. Delete the network given the partial name. Delete the entry from Network DB, given the net ID. Delete the entry from Firewall DB, given the net ID. Release the IN/OUT sug=bnets associated with the net. """ if seg is not None: self.service_segs.release_segmentation_id(seg) if vlan is not None: self.service_vlans.release_segmentation_id(vlan) self.os_helper.delete_network_all_subnets(net_id) # There's a chance that OS network got created but it's ID # was not put in DB # So, deleting networks in os that has part of the special # name self.os_helper.delete_network_subname(fw_const.IN_SERVICE_NWK) self.delete_network_db(net_id) self.clear_fw_entry_by_netid(net_id) self.service_in_ip.release_subnet_by_netid(net_id) self.service_out_ip.release_subnet_by_netid(net_id)
python
def delete_os_nwk_db(self, net_id, seg, vlan): """Delete the Openstack Network from the database. Release the segmentation ID, VLAN associated with the net. Delete the network given the partial name. Delete the entry from Network DB, given the net ID. Delete the entry from Firewall DB, given the net ID. Release the IN/OUT sug=bnets associated with the net. """ if seg is not None: self.service_segs.release_segmentation_id(seg) if vlan is not None: self.service_vlans.release_segmentation_id(vlan) self.os_helper.delete_network_all_subnets(net_id) # There's a chance that OS network got created but it's ID # was not put in DB # So, deleting networks in os that has part of the special # name self.os_helper.delete_network_subname(fw_const.IN_SERVICE_NWK) self.delete_network_db(net_id) self.clear_fw_entry_by_netid(net_id) self.service_in_ip.release_subnet_by_netid(net_id) self.service_out_ip.release_subnet_by_netid(net_id)
[ "def", "delete_os_nwk_db", "(", "self", ",", "net_id", ",", "seg", ",", "vlan", ")", ":", "if", "seg", "is", "not", "None", ":", "self", ".", "service_segs", ".", "release_segmentation_id", "(", "seg", ")", "if", "vlan", "is", "not", "None", ":", "self...
Delete the Openstack Network from the database. Release the segmentation ID, VLAN associated with the net. Delete the network given the partial name. Delete the entry from Network DB, given the net ID. Delete the entry from Firewall DB, given the net ID. Release the IN/OUT sug=bnets associated with the net.
[ "Delete", "the", "Openstack", "Network", "from", "the", "database", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L1677-L1699
train
38,120
openstack/networking-cisco
networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py
FabricBase.correct_db_restart
def correct_db_restart(self): """Ensure DB is consistent after unexpected restarts. """ LOG.info("Checking consistency of DB") # Any Segments allocated that's not in Network or FW DB, release it seg_netid_dict = self.service_segs.get_seg_netid_src(fw_const.FW_CONST) vlan_netid_dict = self.service_vlans.get_seg_netid_src( fw_const.FW_CONST) for netid in seg_netid_dict: net = self.get_network(netid) fw_net = self.get_fw_by_netid(netid) if not net or not fw_net: if netid in vlan_netid_dict: vlan_net = vlan_netid_dict[netid] else: vlan_net = None self.delete_os_nwk_db(netid, seg_netid_dict[netid], vlan_net) LOG.info("Allocated segment for net %s not in DB " "returning", net) return # Any VLANs allocated that's not in Network or FW DB, release it # For Virtual case, this list will be empty for netid in vlan_netid_dict: net = self.get_network(netid) fw_net = self.get_fw_by_netid(netid) if not net or not fw_net: if netid in seg_netid_dict: vlan_net = seg_netid_dict[netid] else: vlan_net = None self.delete_os_nwk_db(netid, vlan_net, vlan_netid_dict[netid]) LOG.info("Allocated vlan for net %s not in DB returning", net) return # Release all IP's from DB that has no NetID or SubnetID self.service_in_ip.release_subnet_no_netid() self.service_out_ip.release_subnet_no_netid() # It leaves out following possibilities not covered by above. # 1. Crash can happen just after creating FWID in DB (for init state) # 2. Crash can happen after 1 + IP address allocation # 3. Crash can happen after 2 + create OS network # IP address allocated will be freed as above. # Only OS network will remain for case 3. # Also, create that FW DB entry only if that FWID didn't exist. # Delete all dummy networks created for dummy router from OS if it's # ID is not in NetDB # Delete all dummy routers and its associated networks/subnetfrom OS # if it's ID is not in FWDB fw_dict = self.get_all_fw_db() for fw_id in fw_dict: rtr_nwk = fw_id[0:4] + fw_const.DUMMY_SERVICE_NWK + ( fw_id[len(fw_id) - 4:]) net_list = self.os_helper.get_network_by_name(rtr_nwk) # TODO(padkrish) Come back to finish this. Not sure of this. # The router interface should be deleted first and then the network # Try using show_router for net in net_list: # Check for if it's there in NetDB net_db_item = self.get_network(net.get('id')) if not net_db_item: self.os_helper.delete_network_all_subnets(net.get('id')) LOG.info("Router Network %s not in DB, returning", net.get('id')) return rtr_name = fw_id[0:4] + fw_const.DUMMY_SERVICE_RTR + ( fw_id[len(fw_id) - 4:]) rtr_list = self.os_helper.get_rtr_by_name(rtr_name) for rtr in rtr_list: fw_db_item = self.get_fw_by_rtrid(rtr.get('id')) if not fw_db_item: # There should be only one if not net_list: LOG.error("net_list len is 0, router net not " "found") return fw_type = fw_dict[fw_id].get('fw_type') if fw_type == fw_const.FW_TENANT_EDGE: rtr_net = net_list[0] rtr_subnet_lt = ( self.os_helper.get_subnets_for_net(rtr_net)) if rtr_subnet_lt is None: LOG.error("router subnet not found for " "net %s", rtr_net) return rtr_subnet_id = rtr_subnet_lt[0].get('id') LOG.info("Deleted dummy router network %s", rtr.get('id')) ret = self.delete_os_dummy_rtr_nwk(rtr.get('id'), rtr_net.get('id'), rtr_subnet_id) return ret LOG.info("Done Checking consistency of DB, no issues")
python
def correct_db_restart(self): """Ensure DB is consistent after unexpected restarts. """ LOG.info("Checking consistency of DB") # Any Segments allocated that's not in Network or FW DB, release it seg_netid_dict = self.service_segs.get_seg_netid_src(fw_const.FW_CONST) vlan_netid_dict = self.service_vlans.get_seg_netid_src( fw_const.FW_CONST) for netid in seg_netid_dict: net = self.get_network(netid) fw_net = self.get_fw_by_netid(netid) if not net or not fw_net: if netid in vlan_netid_dict: vlan_net = vlan_netid_dict[netid] else: vlan_net = None self.delete_os_nwk_db(netid, seg_netid_dict[netid], vlan_net) LOG.info("Allocated segment for net %s not in DB " "returning", net) return # Any VLANs allocated that's not in Network or FW DB, release it # For Virtual case, this list will be empty for netid in vlan_netid_dict: net = self.get_network(netid) fw_net = self.get_fw_by_netid(netid) if not net or not fw_net: if netid in seg_netid_dict: vlan_net = seg_netid_dict[netid] else: vlan_net = None self.delete_os_nwk_db(netid, vlan_net, vlan_netid_dict[netid]) LOG.info("Allocated vlan for net %s not in DB returning", net) return # Release all IP's from DB that has no NetID or SubnetID self.service_in_ip.release_subnet_no_netid() self.service_out_ip.release_subnet_no_netid() # It leaves out following possibilities not covered by above. # 1. Crash can happen just after creating FWID in DB (for init state) # 2. Crash can happen after 1 + IP address allocation # 3. Crash can happen after 2 + create OS network # IP address allocated will be freed as above. # Only OS network will remain for case 3. # Also, create that FW DB entry only if that FWID didn't exist. # Delete all dummy networks created for dummy router from OS if it's # ID is not in NetDB # Delete all dummy routers and its associated networks/subnetfrom OS # if it's ID is not in FWDB fw_dict = self.get_all_fw_db() for fw_id in fw_dict: rtr_nwk = fw_id[0:4] + fw_const.DUMMY_SERVICE_NWK + ( fw_id[len(fw_id) - 4:]) net_list = self.os_helper.get_network_by_name(rtr_nwk) # TODO(padkrish) Come back to finish this. Not sure of this. # The router interface should be deleted first and then the network # Try using show_router for net in net_list: # Check for if it's there in NetDB net_db_item = self.get_network(net.get('id')) if not net_db_item: self.os_helper.delete_network_all_subnets(net.get('id')) LOG.info("Router Network %s not in DB, returning", net.get('id')) return rtr_name = fw_id[0:4] + fw_const.DUMMY_SERVICE_RTR + ( fw_id[len(fw_id) - 4:]) rtr_list = self.os_helper.get_rtr_by_name(rtr_name) for rtr in rtr_list: fw_db_item = self.get_fw_by_rtrid(rtr.get('id')) if not fw_db_item: # There should be only one if not net_list: LOG.error("net_list len is 0, router net not " "found") return fw_type = fw_dict[fw_id].get('fw_type') if fw_type == fw_const.FW_TENANT_EDGE: rtr_net = net_list[0] rtr_subnet_lt = ( self.os_helper.get_subnets_for_net(rtr_net)) if rtr_subnet_lt is None: LOG.error("router subnet not found for " "net %s", rtr_net) return rtr_subnet_id = rtr_subnet_lt[0].get('id') LOG.info("Deleted dummy router network %s", rtr.get('id')) ret = self.delete_os_dummy_rtr_nwk(rtr.get('id'), rtr_net.get('id'), rtr_subnet_id) return ret LOG.info("Done Checking consistency of DB, no issues")
[ "def", "correct_db_restart", "(", "self", ")", ":", "LOG", ".", "info", "(", "\"Checking consistency of DB\"", ")", "# Any Segments allocated that's not in Network or FW DB, release it", "seg_netid_dict", "=", "self", ".", "service_segs", ".", "get_seg_netid_src", "(", "fw_...
Ensure DB is consistent after unexpected restarts.
[ "Ensure", "DB", "is", "consistent", "after", "unexpected", "restarts", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L1702-L1793
train
38,121
openstack/networking-cisco
networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py
FabricBase._prepare_fabric_fw_internal
def _prepare_fabric_fw_internal(self, tenant_id, fw_dict, is_fw_virt, result): """Internal routine to prepare the fabric. This creates an entry in FW DB and runs the SM. """ if not self.auto_nwk_create: LOG.info("Auto network creation disabled") return False try: tenant_name = fw_dict.get('tenant_name') fw_id = fw_dict.get('fw_id') fw_name = fw_dict.get('fw_name') # TODO(padkrish) More than 1 FW per tenant not supported. if tenant_id in self.service_attr and ( result == fw_const.RESULT_FW_CREATE_DONE): LOG.error("Fabric already prepared for tenant %(tenant)s," " %(name)s", {'tenant': tenant_id, 'name': tenant_name}) return True if tenant_id not in self.service_attr: self.create_serv_obj(tenant_id) self.service_attr[tenant_id].create_fw_db(fw_id, fw_name, tenant_id) ret = self.run_create_sm(tenant_id, fw_dict, is_fw_virt) if ret: LOG.info("SM create returned True for Tenant Name " "%(tenant)s FW %(fw)s", {'tenant': tenant_name, 'fw': fw_name}) self.service_attr[tenant_id].set_fabric_create(True) else: LOG.error("SM create returned False for Tenant Name " "%(tenant)s FW %(fw)s", {'tenant': tenant_name, 'fw': fw_name}) except Exception as exc: LOG.error("Exception raised in create fabric int %s", str(exc)) return False return ret
python
def _prepare_fabric_fw_internal(self, tenant_id, fw_dict, is_fw_virt, result): """Internal routine to prepare the fabric. This creates an entry in FW DB and runs the SM. """ if not self.auto_nwk_create: LOG.info("Auto network creation disabled") return False try: tenant_name = fw_dict.get('tenant_name') fw_id = fw_dict.get('fw_id') fw_name = fw_dict.get('fw_name') # TODO(padkrish) More than 1 FW per tenant not supported. if tenant_id in self.service_attr and ( result == fw_const.RESULT_FW_CREATE_DONE): LOG.error("Fabric already prepared for tenant %(tenant)s," " %(name)s", {'tenant': tenant_id, 'name': tenant_name}) return True if tenant_id not in self.service_attr: self.create_serv_obj(tenant_id) self.service_attr[tenant_id].create_fw_db(fw_id, fw_name, tenant_id) ret = self.run_create_sm(tenant_id, fw_dict, is_fw_virt) if ret: LOG.info("SM create returned True for Tenant Name " "%(tenant)s FW %(fw)s", {'tenant': tenant_name, 'fw': fw_name}) self.service_attr[tenant_id].set_fabric_create(True) else: LOG.error("SM create returned False for Tenant Name " "%(tenant)s FW %(fw)s", {'tenant': tenant_name, 'fw': fw_name}) except Exception as exc: LOG.error("Exception raised in create fabric int %s", str(exc)) return False return ret
[ "def", "_prepare_fabric_fw_internal", "(", "self", ",", "tenant_id", ",", "fw_dict", ",", "is_fw_virt", ",", "result", ")", ":", "if", "not", "self", ".", "auto_nwk_create", ":", "LOG", ".", "info", "(", "\"Auto network creation disabled\"", ")", "return", "Fals...
Internal routine to prepare the fabric. This creates an entry in FW DB and runs the SM.
[ "Internal", "routine", "to", "prepare", "the", "fabric", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L1799-L1837
train
38,122
openstack/networking-cisco
networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py
FabricBase.prepare_fabric_fw
def prepare_fabric_fw(self, tenant_id, fw_dict, is_fw_virt, result): """Top level routine to prepare the fabric. """ try: with self.mutex_lock: ret = self._prepare_fabric_fw_internal(tenant_id, fw_dict, is_fw_virt, result) except Exception as exc: LOG.error("Exception raised in create fabric %s", str(exc)) return False return ret
python
def prepare_fabric_fw(self, tenant_id, fw_dict, is_fw_virt, result): """Top level routine to prepare the fabric. """ try: with self.mutex_lock: ret = self._prepare_fabric_fw_internal(tenant_id, fw_dict, is_fw_virt, result) except Exception as exc: LOG.error("Exception raised in create fabric %s", str(exc)) return False return ret
[ "def", "prepare_fabric_fw", "(", "self", ",", "tenant_id", ",", "fw_dict", ",", "is_fw_virt", ",", "result", ")", ":", "try", ":", "with", "self", ".", "mutex_lock", ":", "ret", "=", "self", ".", "_prepare_fabric_fw_internal", "(", "tenant_id", ",", "fw_dict...
Top level routine to prepare the fabric.
[ "Top", "level", "routine", "to", "prepare", "the", "fabric", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L1839-L1848
train
38,123
openstack/networking-cisco
networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py
FabricBase.delete_fabric_fw_internal
def delete_fabric_fw_internal(self, tenant_id, fw_dict, is_fw_virt, result): """Internal routine to delete the fabric configuration. This runs the SM and deletes the entries from DB and local cache. """ if not self.auto_nwk_create: LOG.info("Auto network creation disabled") return False try: tenant_name = fw_dict.get('tenant_name') fw_name = fw_dict.get('fw_name') if tenant_id not in self.service_attr: LOG.error("Service obj not created for tenant %s", tenant_name) return False # A check for is_fabric_create is not needed since a delete # may be issued even when create is not completely done. # For example, some state such as create stuff in DCNM failed and # SM for create is in the process of retrying. A delete can be # issue at that time. If we have a check for is_fabric_create # then delete operation will not go through. if result == fw_const.RESULT_FW_DELETE_DONE: LOG.error("Fabric for tenant %s already deleted", tenant_id) return True ret = self.run_delete_sm(tenant_id, fw_dict, is_fw_virt) self.service_attr[tenant_id].set_fabric_create(False) if ret: LOG.info("Delete SM completed successfully for tenant" "%(tenant)s FW %(fw)s", {'tenant': tenant_name, 'fw': fw_name}) self.service_attr[tenant_id].destroy_local_fw_db() self.delete_serv_obj(tenant_id) else: LOG.error("Delete SM failed for tenant" "%(tenant)s FW %(fw)s", {'tenant': tenant_name, 'fw': fw_name}) # TODO(padkrish) Equivalent of create_fw_db for delete. except Exception as exc: LOG.error("Exception raised in delete fabric int %s", str(exc)) return False return ret
python
def delete_fabric_fw_internal(self, tenant_id, fw_dict, is_fw_virt, result): """Internal routine to delete the fabric configuration. This runs the SM and deletes the entries from DB and local cache. """ if not self.auto_nwk_create: LOG.info("Auto network creation disabled") return False try: tenant_name = fw_dict.get('tenant_name') fw_name = fw_dict.get('fw_name') if tenant_id not in self.service_attr: LOG.error("Service obj not created for tenant %s", tenant_name) return False # A check for is_fabric_create is not needed since a delete # may be issued even when create is not completely done. # For example, some state such as create stuff in DCNM failed and # SM for create is in the process of retrying. A delete can be # issue at that time. If we have a check for is_fabric_create # then delete operation will not go through. if result == fw_const.RESULT_FW_DELETE_DONE: LOG.error("Fabric for tenant %s already deleted", tenant_id) return True ret = self.run_delete_sm(tenant_id, fw_dict, is_fw_virt) self.service_attr[tenant_id].set_fabric_create(False) if ret: LOG.info("Delete SM completed successfully for tenant" "%(tenant)s FW %(fw)s", {'tenant': tenant_name, 'fw': fw_name}) self.service_attr[tenant_id].destroy_local_fw_db() self.delete_serv_obj(tenant_id) else: LOG.error("Delete SM failed for tenant" "%(tenant)s FW %(fw)s", {'tenant': tenant_name, 'fw': fw_name}) # TODO(padkrish) Equivalent of create_fw_db for delete. except Exception as exc: LOG.error("Exception raised in delete fabric int %s", str(exc)) return False return ret
[ "def", "delete_fabric_fw_internal", "(", "self", ",", "tenant_id", ",", "fw_dict", ",", "is_fw_virt", ",", "result", ")", ":", "if", "not", "self", ".", "auto_nwk_create", ":", "LOG", ".", "info", "(", "\"Auto network creation disabled\"", ")", "return", "False"...
Internal routine to delete the fabric configuration. This runs the SM and deletes the entries from DB and local cache.
[ "Internal", "routine", "to", "delete", "the", "fabric", "configuration", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L1850-L1893
train
38,124
openstack/networking-cisco
networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py
FabricBase.delete_fabric_fw
def delete_fabric_fw(self, tenant_id, fw_dict, is_fw_virt, result): """Top level routine to unconfigure the fabric. """ try: with self.mutex_lock: ret = self.delete_fabric_fw_internal(tenant_id, fw_dict, is_fw_virt, result) except Exception as exc: LOG.error("Exception raised in delete fabric %s", str(exc)) return False return ret
python
def delete_fabric_fw(self, tenant_id, fw_dict, is_fw_virt, result): """Top level routine to unconfigure the fabric. """ try: with self.mutex_lock: ret = self.delete_fabric_fw_internal(tenant_id, fw_dict, is_fw_virt, result) except Exception as exc: LOG.error("Exception raised in delete fabric %s", str(exc)) return False return ret
[ "def", "delete_fabric_fw", "(", "self", ",", "tenant_id", ",", "fw_dict", ",", "is_fw_virt", ",", "result", ")", ":", "try", ":", "with", "self", ".", "mutex_lock", ":", "ret", "=", "self", ".", "delete_fabric_fw_internal", "(", "tenant_id", ",", "fw_dict", ...
Top level routine to unconfigure the fabric.
[ "Top", "level", "routine", "to", "unconfigure", "the", "fabric", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L1895-L1904
train
38,125
openstack/networking-cisco
networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py
FabricBase.retry_failure_internal
def retry_failure_internal(self, tenant_id, tenant_name, fw_data, is_fw_virt, result): """Internal routine to retry the failed cases. """ if not self.auto_nwk_create: LOG.info("Auto network creation disabled") return False try: # TODO(padkrish) More than 1 FW per tenant not supported if tenant_id not in self.service_attr: LOG.error("Tenant Obj not created") return False if result == fw_const.RESULT_FW_CREATE_INIT: # A check for is_fabric_create is not done here. ret = self.run_create_sm(tenant_id, fw_data, is_fw_virt) else: if result == fw_const.RESULT_FW_DELETE_INIT: # A check for is_fabric_create is not done here. # Pls check the comment given in function # delete_fabric_fw_int ret = self.run_delete_sm(tenant_id, fw_data, is_fw_virt) else: LOG.error("Unknown state in retry") return False self.service_attr[tenant_id].set_fabric_create(ret) except Exception as exc: LOG.error("Exception raised in create fabric int %s", str(exc)) return False return ret
python
def retry_failure_internal(self, tenant_id, tenant_name, fw_data, is_fw_virt, result): """Internal routine to retry the failed cases. """ if not self.auto_nwk_create: LOG.info("Auto network creation disabled") return False try: # TODO(padkrish) More than 1 FW per tenant not supported if tenant_id not in self.service_attr: LOG.error("Tenant Obj not created") return False if result == fw_const.RESULT_FW_CREATE_INIT: # A check for is_fabric_create is not done here. ret = self.run_create_sm(tenant_id, fw_data, is_fw_virt) else: if result == fw_const.RESULT_FW_DELETE_INIT: # A check for is_fabric_create is not done here. # Pls check the comment given in function # delete_fabric_fw_int ret = self.run_delete_sm(tenant_id, fw_data, is_fw_virt) else: LOG.error("Unknown state in retry") return False self.service_attr[tenant_id].set_fabric_create(ret) except Exception as exc: LOG.error("Exception raised in create fabric int %s", str(exc)) return False return ret
[ "def", "retry_failure_internal", "(", "self", ",", "tenant_id", ",", "tenant_name", ",", "fw_data", ",", "is_fw_virt", ",", "result", ")", ":", "if", "not", "self", ".", "auto_nwk_create", ":", "LOG", ".", "info", "(", "\"Auto network creation disabled\"", ")", ...
Internal routine to retry the failed cases.
[ "Internal", "routine", "to", "retry", "the", "failed", "cases", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L1906-L1934
train
38,126
openstack/networking-cisco
networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py
FabricBase.retry_failure
def retry_failure(self, tenant_id, tenant_name, fw_data, is_fw_virt, result): """Top level retry failure routine. """ try: with self.mutex_lock: ret = self.retry_failure_internal(tenant_id, tenant_name, fw_data, is_fw_virt, result) except Exception as exc: LOG.error("Exception raised in create fabric %s", str(exc)) return False return ret
python
def retry_failure(self, tenant_id, tenant_name, fw_data, is_fw_virt, result): """Top level retry failure routine. """ try: with self.mutex_lock: ret = self.retry_failure_internal(tenant_id, tenant_name, fw_data, is_fw_virt, result) except Exception as exc: LOG.error("Exception raised in create fabric %s", str(exc)) return False return ret
[ "def", "retry_failure", "(", "self", ",", "tenant_id", ",", "tenant_name", ",", "fw_data", ",", "is_fw_virt", ",", "result", ")", ":", "try", ":", "with", "self", ".", "mutex_lock", ":", "ret", "=", "self", ".", "retry_failure_internal", "(", "tenant_id", ...
Top level retry failure routine.
[ "Top", "level", "retry", "failure", "routine", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/fabric_setup_base.py#L1936-L1946
train
38,127
openstack/networking-cisco
networking_cisco/plugins/cisco/device_manager/config.py
verify_resource_dict
def verify_resource_dict(res_dict, is_create, attr_info): """Verifies required attributes are in resource dictionary, res_dict. Also checking that an attribute is only specified if it is allowed for the given operation (create/update). Attribute with default values are considered to be optional. This function contains code taken from function 'prepare_request_body' in attributes.py. """ if ((bc.NEUTRON_VERSION >= bc.NEUTRON_NEWTON_VERSION) and 'tenant_id' in res_dict): res_dict['project_id'] = res_dict['tenant_id'] if is_create: # POST for attr, attr_vals in six.iteritems(attr_info): if attr_vals['allow_post']: if 'default' not in attr_vals and attr not in res_dict: msg = _("Failed to parse request. Required attribute '%s' " "not specified") % attr raise webob.exc.HTTPBadRequest(msg) res_dict[attr] = res_dict.get(attr, attr_vals.get('default')) else: if attr in res_dict: msg = _("Attribute '%s' not allowed in POST") % attr raise webob.exc.HTTPBadRequest(msg) else: # PUT for attr, attr_vals in six.iteritems(attr_info): if attr in res_dict and not attr_vals['allow_put']: msg = _("Cannot update read-only attribute %s") % attr raise webob.exc.HTTPBadRequest(msg) for attr, attr_vals in six.iteritems(attr_info): if (attr not in res_dict or res_dict[attr] is bc.constants.ATTR_NOT_SPECIFIED): continue # Convert values if necessary if 'convert_to' in attr_vals: res_dict[attr] = attr_vals['convert_to'](res_dict[attr]) # Check that configured values are correct if 'validate' not in attr_vals: continue for rule in attr_vals['validate']: _ensure_format(rule, attr, res_dict) res = bc.validators[rule](res_dict[attr], attr_vals['validate'][rule]) if res: msg_dict = dict(attr=attr, reason=res) msg = (_("Invalid input for %(attr)s. Reason: %(reason)s.") % msg_dict) raise webob.exc.HTTPBadRequest(msg) return res_dict
python
def verify_resource_dict(res_dict, is_create, attr_info): """Verifies required attributes are in resource dictionary, res_dict. Also checking that an attribute is only specified if it is allowed for the given operation (create/update). Attribute with default values are considered to be optional. This function contains code taken from function 'prepare_request_body' in attributes.py. """ if ((bc.NEUTRON_VERSION >= bc.NEUTRON_NEWTON_VERSION) and 'tenant_id' in res_dict): res_dict['project_id'] = res_dict['tenant_id'] if is_create: # POST for attr, attr_vals in six.iteritems(attr_info): if attr_vals['allow_post']: if 'default' not in attr_vals and attr not in res_dict: msg = _("Failed to parse request. Required attribute '%s' " "not specified") % attr raise webob.exc.HTTPBadRequest(msg) res_dict[attr] = res_dict.get(attr, attr_vals.get('default')) else: if attr in res_dict: msg = _("Attribute '%s' not allowed in POST") % attr raise webob.exc.HTTPBadRequest(msg) else: # PUT for attr, attr_vals in six.iteritems(attr_info): if attr in res_dict and not attr_vals['allow_put']: msg = _("Cannot update read-only attribute %s") % attr raise webob.exc.HTTPBadRequest(msg) for attr, attr_vals in six.iteritems(attr_info): if (attr not in res_dict or res_dict[attr] is bc.constants.ATTR_NOT_SPECIFIED): continue # Convert values if necessary if 'convert_to' in attr_vals: res_dict[attr] = attr_vals['convert_to'](res_dict[attr]) # Check that configured values are correct if 'validate' not in attr_vals: continue for rule in attr_vals['validate']: _ensure_format(rule, attr, res_dict) res = bc.validators[rule](res_dict[attr], attr_vals['validate'][rule]) if res: msg_dict = dict(attr=attr, reason=res) msg = (_("Invalid input for %(attr)s. Reason: %(reason)s.") % msg_dict) raise webob.exc.HTTPBadRequest(msg) return res_dict
[ "def", "verify_resource_dict", "(", "res_dict", ",", "is_create", ",", "attr_info", ")", ":", "if", "(", "(", "bc", ".", "NEUTRON_VERSION", ">=", "bc", ".", "NEUTRON_NEWTON_VERSION", ")", "and", "'tenant_id'", "in", "res_dict", ")", ":", "res_dict", "[", "'p...
Verifies required attributes are in resource dictionary, res_dict. Also checking that an attribute is only specified if it is allowed for the given operation (create/update). Attribute with default values are considered to be optional. This function contains code taken from function 'prepare_request_body' in attributes.py.
[ "Verifies", "required", "attributes", "are", "in", "resource", "dictionary", "res_dict", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/device_manager/config.py#L148-L199
train
38,128
openstack/networking-cisco
networking_cisco/plugins/cisco/device_manager/config.py
uuidify
def uuidify(val): """Takes an integer and transforms it to a UUID format. returns: UUID formatted version of input. """ if uuidutils.is_uuid_like(val): return val else: try: int_val = int(val, 16) except ValueError: with excutils.save_and_reraise_exception(): LOG.error("Invalid UUID format %s. Please provide an " "integer in decimal (0-9) or hex (0-9a-e) " "format", val) res = str(int_val) num = 12 - len(res) return "00000000-0000-0000-0000-" + "0" * num + res
python
def uuidify(val): """Takes an integer and transforms it to a UUID format. returns: UUID formatted version of input. """ if uuidutils.is_uuid_like(val): return val else: try: int_val = int(val, 16) except ValueError: with excutils.save_and_reraise_exception(): LOG.error("Invalid UUID format %s. Please provide an " "integer in decimal (0-9) or hex (0-9a-e) " "format", val) res = str(int_val) num = 12 - len(res) return "00000000-0000-0000-0000-" + "0" * num + res
[ "def", "uuidify", "(", "val", ")", ":", "if", "uuidutils", ".", "is_uuid_like", "(", "val", ")", ":", "return", "val", "else", ":", "try", ":", "int_val", "=", "int", "(", "val", ",", "16", ")", "except", "ValueError", ":", "with", "excutils", ".", ...
Takes an integer and transforms it to a UUID format. returns: UUID formatted version of input.
[ "Takes", "an", "integer", "and", "transforms", "it", "to", "a", "UUID", "format", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/device_manager/config.py#L202-L219
train
38,129
openstack/networking-cisco
networking_cisco/plugins/cisco/device_manager/config.py
_ensure_format
def _ensure_format(rule, attribute, res_dict): """Verifies that attribute in res_dict is properly formatted. Since, in the .ini-files, lists are specified as ':' separated text and UUID values can be plain integers we need to transform any such values into proper format. Empty strings are converted to None if validator specifies that None value is accepted. """ if rule == 'type:uuid' or (rule == 'type:uuid_or_none' and res_dict[attribute]): res_dict[attribute] = uuidify(res_dict[attribute]) elif rule == 'type:uuid_list': if not res_dict[attribute]: res_dict[attribute] = [] else: temp_list = res_dict[attribute].split(':') res_dict[attribute] = [] for item in temp_list: res_dict[attribute].append = uuidify(item) elif rule == 'type:string_or_none' and res_dict[attribute] == "": res_dict[attribute] = None
python
def _ensure_format(rule, attribute, res_dict): """Verifies that attribute in res_dict is properly formatted. Since, in the .ini-files, lists are specified as ':' separated text and UUID values can be plain integers we need to transform any such values into proper format. Empty strings are converted to None if validator specifies that None value is accepted. """ if rule == 'type:uuid' or (rule == 'type:uuid_or_none' and res_dict[attribute]): res_dict[attribute] = uuidify(res_dict[attribute]) elif rule == 'type:uuid_list': if not res_dict[attribute]: res_dict[attribute] = [] else: temp_list = res_dict[attribute].split(':') res_dict[attribute] = [] for item in temp_list: res_dict[attribute].append = uuidify(item) elif rule == 'type:string_or_none' and res_dict[attribute] == "": res_dict[attribute] = None
[ "def", "_ensure_format", "(", "rule", ",", "attribute", ",", "res_dict", ")", ":", "if", "rule", "==", "'type:uuid'", "or", "(", "rule", "==", "'type:uuid_or_none'", "and", "res_dict", "[", "attribute", "]", ")", ":", "res_dict", "[", "attribute", "]", "="...
Verifies that attribute in res_dict is properly formatted. Since, in the .ini-files, lists are specified as ':' separated text and UUID values can be plain integers we need to transform any such values into proper format. Empty strings are converted to None if validator specifies that None value is accepted.
[ "Verifies", "that", "attribute", "in", "res_dict", "is", "properly", "formatted", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/device_manager/config.py#L222-L242
train
38,130
openstack/networking-cisco
networking_cisco/plugins/cisco/device_manager/config.py
obtain_hosting_device_credentials_from_config
def obtain_hosting_device_credentials_from_config(): """Obtains credentials from config file and stores them in memory. To be called before hosting device templates defined in the config file are created. """ cred_dict = get_specific_config('cisco_hosting_device_credential') attr_info = { 'name': {'allow_post': True, 'allow_put': True, 'validate': {'type:string': None}, 'is_visible': True, 'default': ''}, 'description': {'allow_post': True, 'allow_put': True, 'validate': {'type:string': None}, 'is_visible': True, 'default': ''}, 'user_name': {'allow_post': True, 'allow_put': True, 'validate': {'type:string': None}, 'is_visible': True, 'default': ''}, 'password': {'allow_post': True, 'allow_put': True, 'validate': {'type:string': None}, 'is_visible': True, 'default': ''}, 'type': {'allow_post': True, 'allow_put': True, 'validate': {'type:string': None}, 'is_visible': True, 'default': ''}} credentials = {} for cred_uuid, kv_dict in cred_dict.items(): # ensure cred_uuid is properly formatted cred_uuid = uuidify(cred_uuid) verify_resource_dict(kv_dict, True, attr_info) credentials[cred_uuid] = kv_dict return credentials
python
def obtain_hosting_device_credentials_from_config(): """Obtains credentials from config file and stores them in memory. To be called before hosting device templates defined in the config file are created. """ cred_dict = get_specific_config('cisco_hosting_device_credential') attr_info = { 'name': {'allow_post': True, 'allow_put': True, 'validate': {'type:string': None}, 'is_visible': True, 'default': ''}, 'description': {'allow_post': True, 'allow_put': True, 'validate': {'type:string': None}, 'is_visible': True, 'default': ''}, 'user_name': {'allow_post': True, 'allow_put': True, 'validate': {'type:string': None}, 'is_visible': True, 'default': ''}, 'password': {'allow_post': True, 'allow_put': True, 'validate': {'type:string': None}, 'is_visible': True, 'default': ''}, 'type': {'allow_post': True, 'allow_put': True, 'validate': {'type:string': None}, 'is_visible': True, 'default': ''}} credentials = {} for cred_uuid, kv_dict in cred_dict.items(): # ensure cred_uuid is properly formatted cred_uuid = uuidify(cred_uuid) verify_resource_dict(kv_dict, True, attr_info) credentials[cred_uuid] = kv_dict return credentials
[ "def", "obtain_hosting_device_credentials_from_config", "(", ")", ":", "cred_dict", "=", "get_specific_config", "(", "'cisco_hosting_device_credential'", ")", "attr_info", "=", "{", "'name'", ":", "{", "'allow_post'", ":", "True", ",", "'allow_put'", ":", "True", ",",...
Obtains credentials from config file and stores them in memory. To be called before hosting device templates defined in the config file are created.
[ "Obtains", "credentials", "from", "config", "file", "and", "stores", "them", "in", "memory", ".", "To", "be", "called", "before", "hosting", "device", "templates", "defined", "in", "the", "config", "file", "are", "created", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/device_manager/config.py#L245-L273
train
38,131
openstack/networking-cisco
networking_cisco/plugins/cisco/extensions/routertype.py
RoutertypePluginBase.get_routertypes
def get_routertypes(self, context, filters=None, fields=None, sorts=None, limit=None, marker=None, page_reverse=False): """Lists defined router types.""" pass
python
def get_routertypes(self, context, filters=None, fields=None, sorts=None, limit=None, marker=None, page_reverse=False): """Lists defined router types.""" pass
[ "def", "get_routertypes", "(", "self", ",", "context", ",", "filters", "=", "None", ",", "fields", "=", "None", ",", "sorts", "=", "None", ",", "limit", "=", "None", ",", "marker", "=", "None", ",", "page_reverse", "=", "False", ")", ":", "pass" ]
Lists defined router types.
[ "Lists", "defined", "router", "types", "." ]
aa58a30aec25b86f9aa5952b0863045975debfa9
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/extensions/routertype.py#L213-L217
train
38,132
tophatmonocle/ims_lti_py
ims_lti_py/tool_provider.py
ToolProvider.has_role
def has_role(self, role): ''' Check whether the Launch Paramters set the role. ''' return self.roles and any([re.search(role, our_role, re.I) for our_role in self.roles])
python
def has_role(self, role): ''' Check whether the Launch Paramters set the role. ''' return self.roles and any([re.search(role, our_role, re.I) for our_role in self.roles])
[ "def", "has_role", "(", "self", ",", "role", ")", ":", "return", "self", ".", "roles", "and", "any", "(", "[", "re", ".", "search", "(", "role", ",", "our_role", ",", "re", ".", "I", ")", "for", "our_role", "in", "self", ".", "roles", "]", ")" ]
Check whether the Launch Paramters set the role.
[ "Check", "whether", "the", "Launch", "Paramters", "set", "the", "role", "." ]
979244d83c2e6420d2c1941f58e52f641c56ad12
https://github.com/tophatmonocle/ims_lti_py/blob/979244d83c2e6420d2c1941f58e52f641c56ad12/ims_lti_py/tool_provider.py#L57-L62
train
38,133
tophatmonocle/ims_lti_py
ims_lti_py/tool_provider.py
ToolProvider.username
def username(self, default=None): ''' Return the full, given, or family name if set. ''' if self.lis_person_name_given: return self.lis_person_name_given elif self.lis_person_name_family: return self.lis_person_name_family elif self.lis_person_name_full: return self.lis_person_name_full else: return default
python
def username(self, default=None): ''' Return the full, given, or family name if set. ''' if self.lis_person_name_given: return self.lis_person_name_given elif self.lis_person_name_family: return self.lis_person_name_family elif self.lis_person_name_full: return self.lis_person_name_full else: return default
[ "def", "username", "(", "self", ",", "default", "=", "None", ")", ":", "if", "self", ".", "lis_person_name_given", ":", "return", "self", ".", "lis_person_name_given", "elif", "self", ".", "lis_person_name_family", ":", "return", "self", ".", "lis_person_name_fa...
Return the full, given, or family name if set.
[ "Return", "the", "full", "given", "or", "family", "name", "if", "set", "." ]
979244d83c2e6420d2c1941f58e52f641c56ad12
https://github.com/tophatmonocle/ims_lti_py/blob/979244d83c2e6420d2c1941f58e52f641c56ad12/ims_lti_py/tool_provider.py#L96-L107
train
38,134
tophatmonocle/ims_lti_py
ims_lti_py/tool_provider.py
ToolProvider.build_return_url
def build_return_url(self): ''' If the Tool Consumer sent a return URL, add any set messages to the URL. ''' if not self.launch_presentation_return_url: return None lti_message_fields = ['lti_errormsg', 'lti_errorlog', 'lti_msg', 'lti_log'] messages = dict([(key, getattr(self, key)) for key in lti_message_fields if getattr(self, key, None)]) # Disassemble original return URL and reassemble with our options added original = urlsplit(self.launch_presentation_return_url) combined = messages.copy() combined.update(dict(parse_qsl(original.query))) combined_query = urlencode(combined) return urlunsplit(( original.scheme, original.netloc, original.path, combined_query, original.fragment ))
python
def build_return_url(self): ''' If the Tool Consumer sent a return URL, add any set messages to the URL. ''' if not self.launch_presentation_return_url: return None lti_message_fields = ['lti_errormsg', 'lti_errorlog', 'lti_msg', 'lti_log'] messages = dict([(key, getattr(self, key)) for key in lti_message_fields if getattr(self, key, None)]) # Disassemble original return URL and reassemble with our options added original = urlsplit(self.launch_presentation_return_url) combined = messages.copy() combined.update(dict(parse_qsl(original.query))) combined_query = urlencode(combined) return urlunsplit(( original.scheme, original.netloc, original.path, combined_query, original.fragment ))
[ "def", "build_return_url", "(", "self", ")", ":", "if", "not", "self", ".", "launch_presentation_return_url", ":", "return", "None", "lti_message_fields", "=", "[", "'lti_errormsg'", ",", "'lti_errorlog'", ",", "'lti_msg'", ",", "'lti_log'", "]", "messages", "=", ...
If the Tool Consumer sent a return URL, add any set messages to the URL.
[ "If", "the", "Tool", "Consumer", "sent", "a", "return", "URL", "add", "any", "set", "messages", "to", "the", "URL", "." ]
979244d83c2e6420d2c1941f58e52f641c56ad12
https://github.com/tophatmonocle/ims_lti_py/blob/979244d83c2e6420d2c1941f58e52f641c56ad12/ims_lti_py/tool_provider.py#L152-L181
train
38,135
tophatmonocle/ims_lti_py
ims_lti_py/tool_provider.py
DjangoToolProvider.success_redirect
def success_redirect(self, msg='', log=''): ''' Shortcut for redirecting Django view to LTI Consumer with messages ''' from django.shortcuts import redirect self.lti_msg = msg self.lti_log = log return redirect(self.build_return_url())
python
def success_redirect(self, msg='', log=''): ''' Shortcut for redirecting Django view to LTI Consumer with messages ''' from django.shortcuts import redirect self.lti_msg = msg self.lti_log = log return redirect(self.build_return_url())
[ "def", "success_redirect", "(", "self", ",", "msg", "=", "''", ",", "log", "=", "''", ")", ":", "from", "django", ".", "shortcuts", "import", "redirect", "self", ".", "lti_msg", "=", "msg", "self", ".", "lti_log", "=", "log", "return", "redirect", "(",...
Shortcut for redirecting Django view to LTI Consumer with messages
[ "Shortcut", "for", "redirecting", "Django", "view", "to", "LTI", "Consumer", "with", "messages" ]
979244d83c2e6420d2c1941f58e52f641c56ad12
https://github.com/tophatmonocle/ims_lti_py/blob/979244d83c2e6420d2c1941f58e52f641c56ad12/ims_lti_py/tool_provider.py#L201-L208
train
38,136
tophatmonocle/ims_lti_py
ims_lti_py/tool_provider.py
DjangoToolProvider.error_redirect
def error_redirect(self, errormsg='', errorlog=''): ''' Shortcut for redirecting Django view to LTI Consumer with errors ''' from django.shortcuts import redirect self.lti_errormsg = errormsg self.lti_errorlog = errorlog return redirect(self.build_return_url())
python
def error_redirect(self, errormsg='', errorlog=''): ''' Shortcut for redirecting Django view to LTI Consumer with errors ''' from django.shortcuts import redirect self.lti_errormsg = errormsg self.lti_errorlog = errorlog return redirect(self.build_return_url())
[ "def", "error_redirect", "(", "self", ",", "errormsg", "=", "''", ",", "errorlog", "=", "''", ")", ":", "from", "django", ".", "shortcuts", "import", "redirect", "self", ".", "lti_errormsg", "=", "errormsg", "self", ".", "lti_errorlog", "=", "errorlog", "r...
Shortcut for redirecting Django view to LTI Consumer with errors
[ "Shortcut", "for", "redirecting", "Django", "view", "to", "LTI", "Consumer", "with", "errors" ]
979244d83c2e6420d2c1941f58e52f641c56ad12
https://github.com/tophatmonocle/ims_lti_py/blob/979244d83c2e6420d2c1941f58e52f641c56ad12/ims_lti_py/tool_provider.py#L210-L217
train
38,137
Iotic-Labs/py-IoticAgent
src/IoticAgent/IOT/Client.py
Client._notify_thing_lid_change
def _notify_thing_lid_change(self, from_lid, to_lid): """Used by Thing instances to indicate that a rename operation has happened""" try: with self.__private_things: self.__private_things[to_lid] = self.__private_things.pop(from_lid) except KeyError: logger.warning('Thing %s renamed (to %s), but not in private lookup table', from_lid, to_lid) else: # renaming could happen before get_thing is called on the original try: with self.__new_things: self.__new_things[to_lid] = self.__new_things.pop(from_lid) except KeyError: pass
python
def _notify_thing_lid_change(self, from_lid, to_lid): """Used by Thing instances to indicate that a rename operation has happened""" try: with self.__private_things: self.__private_things[to_lid] = self.__private_things.pop(from_lid) except KeyError: logger.warning('Thing %s renamed (to %s), but not in private lookup table', from_lid, to_lid) else: # renaming could happen before get_thing is called on the original try: with self.__new_things: self.__new_things[to_lid] = self.__new_things.pop(from_lid) except KeyError: pass
[ "def", "_notify_thing_lid_change", "(", "self", ",", "from_lid", ",", "to_lid", ")", ":", "try", ":", "with", "self", ".", "__private_things", ":", "self", ".", "__private_things", "[", "to_lid", "]", "=", "self", ".", "__private_things", ".", "pop", "(", ...
Used by Thing instances to indicate that a rename operation has happened
[ "Used", "by", "Thing", "instances", "to", "indicate", "that", "a", "rename", "operation", "has", "happened" ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/IOT/Client.py#L235-L248
train
38,138
Iotic-Labs/py-IoticAgent
src/IoticAgent/IOT/Client.py
Client.register_catchall_feeddata
def register_catchall_feeddata(self, callback, callback_parsed=None): """ Registers a callback that is called for all feeddata your Thing receives `Example` #!python def feeddata_callback(data): print(data) ... client.register_catchall_feeddata(feeddata_callback) `callback` (required) the function name that you want to be called on receipt of new feed data `callback_parsed` (optional) (function reference) callback function to invoke on receipt of feed data. This is equivalent to `callback` except the dict includes the `parsed` key which holds the set of values in a [PointDataObject](./Point.m.html#IoticAgent.IOT.Point.PointDataObject) instance. If both `callback_parsed` and `callback` have been specified, the former takes precedence and `callback` is only called if the point data could not be parsed according to its current value description. `NOTE`: `callback_parsed` can only be used if `auto_encode_decode` is enabled for the client instance. More details on the contents of the `data` dictionary for feeds see: [follow()](./Thing.m.html#IoticAgent.IOT.Thing.Thing.follow) """ if callback_parsed: callback = self._get_parsed_feed_callback(callback_parsed, callback) return self.__client.register_callback_feeddata(callback)
python
def register_catchall_feeddata(self, callback, callback_parsed=None): """ Registers a callback that is called for all feeddata your Thing receives `Example` #!python def feeddata_callback(data): print(data) ... client.register_catchall_feeddata(feeddata_callback) `callback` (required) the function name that you want to be called on receipt of new feed data `callback_parsed` (optional) (function reference) callback function to invoke on receipt of feed data. This is equivalent to `callback` except the dict includes the `parsed` key which holds the set of values in a [PointDataObject](./Point.m.html#IoticAgent.IOT.Point.PointDataObject) instance. If both `callback_parsed` and `callback` have been specified, the former takes precedence and `callback` is only called if the point data could not be parsed according to its current value description. `NOTE`: `callback_parsed` can only be used if `auto_encode_decode` is enabled for the client instance. More details on the contents of the `data` dictionary for feeds see: [follow()](./Thing.m.html#IoticAgent.IOT.Thing.Thing.follow) """ if callback_parsed: callback = self._get_parsed_feed_callback(callback_parsed, callback) return self.__client.register_callback_feeddata(callback)
[ "def", "register_catchall_feeddata", "(", "self", ",", "callback", ",", "callback_parsed", "=", "None", ")", ":", "if", "callback_parsed", ":", "callback", "=", "self", ".", "_get_parsed_feed_callback", "(", "callback_parsed", ",", "callback", ")", "return", "self...
Registers a callback that is called for all feeddata your Thing receives `Example` #!python def feeddata_callback(data): print(data) ... client.register_catchall_feeddata(feeddata_callback) `callback` (required) the function name that you want to be called on receipt of new feed data `callback_parsed` (optional) (function reference) callback function to invoke on receipt of feed data. This is equivalent to `callback` except the dict includes the `parsed` key which holds the set of values in a [PointDataObject](./Point.m.html#IoticAgent.IOT.Point.PointDataObject) instance. If both `callback_parsed` and `callback` have been specified, the former takes precedence and `callback` is only called if the point data could not be parsed according to its current value description. `NOTE`: `callback_parsed` can only be used if `auto_encode_decode` is enabled for the client instance. More details on the contents of the `data` dictionary for feeds see: [follow()](./Thing.m.html#IoticAgent.IOT.Thing.Thing.follow)
[ "Registers", "a", "callback", "that", "is", "called", "for", "all", "feeddata", "your", "Thing", "receives" ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/IOT/Client.py#L256-L283
train
38,139
Iotic-Labs/py-IoticAgent
src/IoticAgent/IOT/Client.py
Client.register_catchall_controlreq
def register_catchall_controlreq(self, callback, callback_parsed=None): """ Registers a callback that is called for all control requests received by your Thing `Example` #!python def controlreq_callback(data): print(data) ... client.register_catchall_controlreq(controlreq_callback) `callback` (required) the function name that you want to be called on receipt of a new control request `callback_parsed` (optional) (function reference) callback function to invoke on receipt of a control ask/tell. This is equivalent to `callback` except the dict includes the `parsed` key which holds the set of values in a [PointDataObject](./Point.m.html#IoticAgent.IOT.Point.PointDataObject) instance. If both `callback_parsed` and `callback` have been specified, the former takes precedence and `callback` is only called if the point data could not be parsed according to its current value description. More details on the contents of the `data` dictionary for controls see: [create_control()](./Thing.m.html#IoticAgent.IOT.Thing.Thing.create_control) """ if callback_parsed: callback = self._get_parsed_control_callback(callback_parsed, callback) return self.__client.register_callback_controlreq(callback)
python
def register_catchall_controlreq(self, callback, callback_parsed=None): """ Registers a callback that is called for all control requests received by your Thing `Example` #!python def controlreq_callback(data): print(data) ... client.register_catchall_controlreq(controlreq_callback) `callback` (required) the function name that you want to be called on receipt of a new control request `callback_parsed` (optional) (function reference) callback function to invoke on receipt of a control ask/tell. This is equivalent to `callback` except the dict includes the `parsed` key which holds the set of values in a [PointDataObject](./Point.m.html#IoticAgent.IOT.Point.PointDataObject) instance. If both `callback_parsed` and `callback` have been specified, the former takes precedence and `callback` is only called if the point data could not be parsed according to its current value description. More details on the contents of the `data` dictionary for controls see: [create_control()](./Thing.m.html#IoticAgent.IOT.Thing.Thing.create_control) """ if callback_parsed: callback = self._get_parsed_control_callback(callback_parsed, callback) return self.__client.register_callback_controlreq(callback)
[ "def", "register_catchall_controlreq", "(", "self", ",", "callback", ",", "callback_parsed", "=", "None", ")", ":", "if", "callback_parsed", ":", "callback", "=", "self", ".", "_get_parsed_control_callback", "(", "callback_parsed", ",", "callback", ")", "return", ...
Registers a callback that is called for all control requests received by your Thing `Example` #!python def controlreq_callback(data): print(data) ... client.register_catchall_controlreq(controlreq_callback) `callback` (required) the function name that you want to be called on receipt of a new control request `callback_parsed` (optional) (function reference) callback function to invoke on receipt of a control ask/tell. This is equivalent to `callback` except the dict includes the `parsed` key which holds the set of values in a [PointDataObject](./Point.m.html#IoticAgent.IOT.Point.PointDataObject) instance. If both `callback_parsed` and `callback` have been specified, the former takes precedence and `callback` is only called if the point data could not be parsed according to its current value description. More details on the contents of the `data` dictionary for controls see: [create_control()](./Thing.m.html#IoticAgent.IOT.Thing.Thing.create_control)
[ "Registers", "a", "callback", "that", "is", "called", "for", "all", "control", "requests", "received", "by", "your", "Thing" ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/IOT/Client.py#L285-L311
train
38,140
Iotic-Labs/py-IoticAgent
src/IoticAgent/IOT/Client.py
Client.register_callback_duplicate
def register_callback_duplicate(self, func, serialised=True): """ Register a callback for resource creation but where the resource already exists in Iotic Space. In this case the existing reference is passed to you. If `serialised` is not set, the callbacks might arrive in a different order to they were requested. The payload passed to your callback is an OrderedDict with the following keys #!python r : R_ENTITY, R_FEED, etc # the type of existing resource lid : <name> # the local name of the # existing resource id : <GUID> # the global Id of the # existing resource epId : <GUID> # the global Id of your agent `Note` resource types are defined [here](../Core/Const.m.html) `Example` #!python def duplicated_callback(args): print(args) ... client.register_callback_created(duplicated_callback) This would print out something like the following on re-creation of an R_ENTITY #!python OrderedDict([(u'lid', u'new_thing1'), (u'r', 1), (u'epId', u'ffd47b75ea786f55c76e337cdc47665a'), (u'id', u'3f11df0a09588a6a1a9732e3837765f8')])) """ self.__client.register_callback_duplicate(partial(self.__callback_payload_only, func), serialised=serialised)
python
def register_callback_duplicate(self, func, serialised=True): """ Register a callback for resource creation but where the resource already exists in Iotic Space. In this case the existing reference is passed to you. If `serialised` is not set, the callbacks might arrive in a different order to they were requested. The payload passed to your callback is an OrderedDict with the following keys #!python r : R_ENTITY, R_FEED, etc # the type of existing resource lid : <name> # the local name of the # existing resource id : <GUID> # the global Id of the # existing resource epId : <GUID> # the global Id of your agent `Note` resource types are defined [here](../Core/Const.m.html) `Example` #!python def duplicated_callback(args): print(args) ... client.register_callback_created(duplicated_callback) This would print out something like the following on re-creation of an R_ENTITY #!python OrderedDict([(u'lid', u'new_thing1'), (u'r', 1), (u'epId', u'ffd47b75ea786f55c76e337cdc47665a'), (u'id', u'3f11df0a09588a6a1a9732e3837765f8')])) """ self.__client.register_callback_duplicate(partial(self.__callback_payload_only, func), serialised=serialised)
[ "def", "register_callback_duplicate", "(", "self", ",", "func", ",", "serialised", "=", "True", ")", ":", "self", ".", "__client", ".", "register_callback_duplicate", "(", "partial", "(", "self", ".", "__callback_payload_only", ",", "func", ")", ",", "serialised...
Register a callback for resource creation but where the resource already exists in Iotic Space. In this case the existing reference is passed to you. If `serialised` is not set, the callbacks might arrive in a different order to they were requested. The payload passed to your callback is an OrderedDict with the following keys #!python r : R_ENTITY, R_FEED, etc # the type of existing resource lid : <name> # the local name of the # existing resource id : <GUID> # the global Id of the # existing resource epId : <GUID> # the global Id of your agent `Note` resource types are defined [here](../Core/Const.m.html) `Example` #!python def duplicated_callback(args): print(args) ... client.register_callback_created(duplicated_callback) This would print out something like the following on re-creation of an R_ENTITY #!python OrderedDict([(u'lid', u'new_thing1'), (u'r', 1), (u'epId', u'ffd47b75ea786f55c76e337cdc47665a'), (u'id', u'3f11df0a09588a6a1a9732e3837765f8')]))
[ "Register", "a", "callback", "for", "resource", "creation", "but", "where", "the", "resource", "already", "exists", "in", "Iotic", "Space", ".", "In", "this", "case", "the", "existing", "reference", "is", "passed", "to", "you", ".", "If", "serialised", "is",...
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/IOT/Client.py#L383-L416
train
38,141
Iotic-Labs/py-IoticAgent
src/IoticAgent/IOT/Client.py
Client.register_callback_renamed
def register_callback_renamed(self, func, serialised=True): """ Register a callback for resource rename. This will be called when any resource is renamed within your agent. If `serialised` is not set, the callbacks might arrive in a different order to they were requested. The payload passed to your callback is an OrderedDict with the following keys #!python r : R_ENTITY, R_FEED, etc # the type of resource deleted lid : <name> # the new local name of the resource oldLid : <name> # the old local name of the resource id : <GUID> # the global Id of the resource `Note` resource types are defined [here](../Core/Const.m.html) `Example` #!python def renamed_callback(args): print(args) ... client.register_callback_renamed(renamed_callback) This would print out something like the following on renaming of an R_ENTITY #!python OrderedDict([(u'lid', u'new_name'), (u'r', 1), (u'oldLid', u'old_name'), (u'id', u'4448993b44738411de5fe2a6cf32d957')]) """ self.__client.register_callback_renamed(partial(self.__callback_payload_only, func), serialised=serialised)
python
def register_callback_renamed(self, func, serialised=True): """ Register a callback for resource rename. This will be called when any resource is renamed within your agent. If `serialised` is not set, the callbacks might arrive in a different order to they were requested. The payload passed to your callback is an OrderedDict with the following keys #!python r : R_ENTITY, R_FEED, etc # the type of resource deleted lid : <name> # the new local name of the resource oldLid : <name> # the old local name of the resource id : <GUID> # the global Id of the resource `Note` resource types are defined [here](../Core/Const.m.html) `Example` #!python def renamed_callback(args): print(args) ... client.register_callback_renamed(renamed_callback) This would print out something like the following on renaming of an R_ENTITY #!python OrderedDict([(u'lid', u'new_name'), (u'r', 1), (u'oldLid', u'old_name'), (u'id', u'4448993b44738411de5fe2a6cf32d957')]) """ self.__client.register_callback_renamed(partial(self.__callback_payload_only, func), serialised=serialised)
[ "def", "register_callback_renamed", "(", "self", ",", "func", ",", "serialised", "=", "True", ")", ":", "self", ".", "__client", ".", "register_callback_renamed", "(", "partial", "(", "self", ".", "__callback_payload_only", ",", "func", ")", ",", "serialised", ...
Register a callback for resource rename. This will be called when any resource is renamed within your agent. If `serialised` is not set, the callbacks might arrive in a different order to they were requested. The payload passed to your callback is an OrderedDict with the following keys #!python r : R_ENTITY, R_FEED, etc # the type of resource deleted lid : <name> # the new local name of the resource oldLid : <name> # the old local name of the resource id : <GUID> # the global Id of the resource `Note` resource types are defined [here](../Core/Const.m.html) `Example` #!python def renamed_callback(args): print(args) ... client.register_callback_renamed(renamed_callback) This would print out something like the following on renaming of an R_ENTITY #!python OrderedDict([(u'lid', u'new_name'), (u'r', 1), (u'oldLid', u'old_name'), (u'id', u'4448993b44738411de5fe2a6cf32d957')])
[ "Register", "a", "callback", "for", "resource", "rename", ".", "This", "will", "be", "called", "when", "any", "resource", "is", "renamed", "within", "your", "agent", ".", "If", "serialised", "is", "not", "set", "the", "callbacks", "might", "arrive", "in", ...
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/IOT/Client.py#L418-L451
train
38,142
Iotic-Labs/py-IoticAgent
src/IoticAgent/IOT/Client.py
Client.register_callback_deleted
def register_callback_deleted(self, func, serialised=True): """ Register a callback for resource deletion. This will be called when any resource is deleted within your agent. If `serialised` is not set, the callbacks might arrive in a different order to they were requested. The payload passed to your callback is an OrderedDict with the following keys #!python r : R_ENTITY, R_FEED, etc # the type of resource deleted lid : <name> # the local name of the resource id : <GUID> # the global Id of the resource `Note` resource types are defined [here](../Core/Const.m.html) `Example` #!python def deleted_callback(args): print(args) ... client.register_callback_deleted(deleted_callback) This would print out something like the following on deletion of an R_ENTITY #!python OrderedDict([(u'lid', u'old_thing1'), (u'r', 1), (u'id', u'315637813d801ec6f057c67728bf00c2')]) """ self.__client.register_callback_deleted(partial(self.__callback_payload_only, func), serialised=serialised)
python
def register_callback_deleted(self, func, serialised=True): """ Register a callback for resource deletion. This will be called when any resource is deleted within your agent. If `serialised` is not set, the callbacks might arrive in a different order to they were requested. The payload passed to your callback is an OrderedDict with the following keys #!python r : R_ENTITY, R_FEED, etc # the type of resource deleted lid : <name> # the local name of the resource id : <GUID> # the global Id of the resource `Note` resource types are defined [here](../Core/Const.m.html) `Example` #!python def deleted_callback(args): print(args) ... client.register_callback_deleted(deleted_callback) This would print out something like the following on deletion of an R_ENTITY #!python OrderedDict([(u'lid', u'old_thing1'), (u'r', 1), (u'id', u'315637813d801ec6f057c67728bf00c2')]) """ self.__client.register_callback_deleted(partial(self.__callback_payload_only, func), serialised=serialised)
[ "def", "register_callback_deleted", "(", "self", ",", "func", ",", "serialised", "=", "True", ")", ":", "self", ".", "__client", ".", "register_callback_deleted", "(", "partial", "(", "self", ".", "__callback_payload_only", ",", "func", ")", ",", "serialised", ...
Register a callback for resource deletion. This will be called when any resource is deleted within your agent. If `serialised` is not set, the callbacks might arrive in a different order to they were requested. The payload passed to your callback is an OrderedDict with the following keys #!python r : R_ENTITY, R_FEED, etc # the type of resource deleted lid : <name> # the local name of the resource id : <GUID> # the global Id of the resource `Note` resource types are defined [here](../Core/Const.m.html) `Example` #!python def deleted_callback(args): print(args) ... client.register_callback_deleted(deleted_callback) This would print out something like the following on deletion of an R_ENTITY #!python OrderedDict([(u'lid', u'old_thing1'), (u'r', 1), (u'id', u'315637813d801ec6f057c67728bf00c2')])
[ "Register", "a", "callback", "for", "resource", "deletion", ".", "This", "will", "be", "called", "when", "any", "resource", "is", "deleted", "within", "your", "agent", ".", "If", "serialised", "is", "not", "set", "the", "callbacks", "might", "arrive", "in", ...
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/IOT/Client.py#L453-L483
train
38,143
Iotic-Labs/py-IoticAgent
src/IoticAgent/IOT/Client.py
Client.register_callback_reassigned
def register_callback_reassigned(self, func, serialised=True): """ Register a callback for resource reassignment. This will be called when any resource is reassigned to or from your agent. If `serialised` is not set, the callbacks might arrive in a different order to they were requested. The payload passed to your callback is an OrderedDict with the following keys #!python r : R_ENTITY, R_FEED, etc # the type of resource reassigned lid : <name> # the local name of the resource epId : <GUID> # the global Id of the agent the # resource has been reassigned *to* id : <GUID> # the global Id of the resource `Note` resource types are defined [here](../Core/Const.m.html) `Note` You can check whether this is an assign "in" or "out" by comparing the epId with your current agent id, using the `IOT.Client.agent_id` property. If it's the same it's a reassign to you. `Example` #!python def reassigned_callback(args): print(args) ... client.register_callback_reassigned(reassigned_callback) This would print out something like the following on assignment of an R_ENTITY to #!python OrderedDict([(u'lid', u'moved_thing'), (u'r', 1), (u'epId', u'5a8d603ee757133d66d99875d0584c72'), (u'id', u'4448993b44738411de5fe2a6cf32d957')]) """ self.__client.register_callback_reassigned(partial(self.__callback_payload_only, func), serialised)
python
def register_callback_reassigned(self, func, serialised=True): """ Register a callback for resource reassignment. This will be called when any resource is reassigned to or from your agent. If `serialised` is not set, the callbacks might arrive in a different order to they were requested. The payload passed to your callback is an OrderedDict with the following keys #!python r : R_ENTITY, R_FEED, etc # the type of resource reassigned lid : <name> # the local name of the resource epId : <GUID> # the global Id of the agent the # resource has been reassigned *to* id : <GUID> # the global Id of the resource `Note` resource types are defined [here](../Core/Const.m.html) `Note` You can check whether this is an assign "in" or "out" by comparing the epId with your current agent id, using the `IOT.Client.agent_id` property. If it's the same it's a reassign to you. `Example` #!python def reassigned_callback(args): print(args) ... client.register_callback_reassigned(reassigned_callback) This would print out something like the following on assignment of an R_ENTITY to #!python OrderedDict([(u'lid', u'moved_thing'), (u'r', 1), (u'epId', u'5a8d603ee757133d66d99875d0584c72'), (u'id', u'4448993b44738411de5fe2a6cf32d957')]) """ self.__client.register_callback_reassigned(partial(self.__callback_payload_only, func), serialised)
[ "def", "register_callback_reassigned", "(", "self", ",", "func", ",", "serialised", "=", "True", ")", ":", "self", ".", "__client", ".", "register_callback_reassigned", "(", "partial", "(", "self", ".", "__callback_payload_only", ",", "func", ")", ",", "serialis...
Register a callback for resource reassignment. This will be called when any resource is reassigned to or from your agent. If `serialised` is not set, the callbacks might arrive in a different order to they were requested. The payload passed to your callback is an OrderedDict with the following keys #!python r : R_ENTITY, R_FEED, etc # the type of resource reassigned lid : <name> # the local name of the resource epId : <GUID> # the global Id of the agent the # resource has been reassigned *to* id : <GUID> # the global Id of the resource `Note` resource types are defined [here](../Core/Const.m.html) `Note` You can check whether this is an assign "in" or "out" by comparing the epId with your current agent id, using the `IOT.Client.agent_id` property. If it's the same it's a reassign to you. `Example` #!python def reassigned_callback(args): print(args) ... client.register_callback_reassigned(reassigned_callback) This would print out something like the following on assignment of an R_ENTITY to #!python OrderedDict([(u'lid', u'moved_thing'), (u'r', 1), (u'epId', u'5a8d603ee757133d66d99875d0584c72'), (u'id', u'4448993b44738411de5fe2a6cf32d957')])
[ "Register", "a", "callback", "for", "resource", "reassignment", ".", "This", "will", "be", "called", "when", "any", "resource", "is", "reassigned", "to", "or", "from", "your", "agent", ".", "If", "serialised", "is", "not", "set", "the", "callbacks", "might",...
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/IOT/Client.py#L485-L521
train
38,144
Iotic-Labs/py-IoticAgent
src/IoticAgent/IOT/Client.py
Client.simulate_feeddata
def simulate_feeddata(self, feedid, data, mime=None, time=None): """Simulate the last feeddata received for given feedid Calls the registered callback for the feed with the last recieved feed data. Allows you to test your code without having to wait for the remote thing to share again. `feedid` (required) (string) local id of your Feed `data` (optional) (as applicable) The data you want to use to simulate the arrival of remote feed data `mime` (optional) (string) The mime type of your data. See also: [share()](./Point.m.html#IoticAgent.IOT.Point.Feed.share) `time` (optional) (datetime) UTC timestamp for share. See also: [share()](./Point.m.html#IoticAgent.IOT.Point.Feed.share) """ self.__client.simulate_feeddata(feedid, data, mime, time)
python
def simulate_feeddata(self, feedid, data, mime=None, time=None): """Simulate the last feeddata received for given feedid Calls the registered callback for the feed with the last recieved feed data. Allows you to test your code without having to wait for the remote thing to share again. `feedid` (required) (string) local id of your Feed `data` (optional) (as applicable) The data you want to use to simulate the arrival of remote feed data `mime` (optional) (string) The mime type of your data. See also: [share()](./Point.m.html#IoticAgent.IOT.Point.Feed.share) `time` (optional) (datetime) UTC timestamp for share. See also: [share()](./Point.m.html#IoticAgent.IOT.Point.Feed.share) """ self.__client.simulate_feeddata(feedid, data, mime, time)
[ "def", "simulate_feeddata", "(", "self", ",", "feedid", ",", "data", ",", "mime", "=", "None", ",", "time", "=", "None", ")", ":", "self", ".", "__client", ".", "simulate_feeddata", "(", "feedid", ",", "data", ",", "mime", ",", "time", ")" ]
Simulate the last feeddata received for given feedid Calls the registered callback for the feed with the last recieved feed data. Allows you to test your code without having to wait for the remote thing to share again. `feedid` (required) (string) local id of your Feed `data` (optional) (as applicable) The data you want to use to simulate the arrival of remote feed data `mime` (optional) (string) The mime type of your data. See also: [share()](./Point.m.html#IoticAgent.IOT.Point.Feed.share) `time` (optional) (datetime) UTC timestamp for share. See also: [share()](./Point.m.html#IoticAgent.IOT.Point.Feed.share)
[ "Simulate", "the", "last", "feeddata", "received", "for", "given", "feedid", "Calls", "the", "registered", "callback", "for", "the", "feed", "with", "the", "last", "recieved", "feed", "data", ".", "Allows", "you", "to", "test", "your", "code", "without", "ha...
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/IOT/Client.py#L543-L558
train
38,145
Iotic-Labs/py-IoticAgent
src/IoticAgent/IOT/Client.py
Client.confirm_tell
def confirm_tell(self, data, success): """Confirm that you've done as you were told. Call this from your control callback to confirm action. Used when you are advertising a control and you want to tell the remote requestor that you have done what they asked you to. `Example:` this is a minimal example to show the idea. Note - no Exception handling and ugly use of globals #!python client = None def controlreq_cb(args): global client # the client object you connected with # perform your action with the data they sent success = do_control_action(args['data']) if args['confirm']: # you've been asked to confirm client.confirm_tell(args, success) # else, if you do not confirm_tell() this causes a timeout at the requestor's end. client = IOT.Client(config='test.ini') thing = client.create_thing('test321') control = thing.create_control('control', controlreq_cb) Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `data` (mandatory) (dictionary) The `"args"` dictionary that your callback was called with `success` (mandatory) (boolean) Whether or not the action you have been asked to do has been sucessful. More details on the contents of the `data` dictionary for controls see: [create_control()](./Thing.m.html#IoticAgent.IOT.Thing.Thing.create_control) """ logger.info("confirm_tell(success=%s) [lid=\"%s\",pid=\"%s\"]", success, data[P_ENTITY_LID], data[P_LID]) evt = self._request_point_confirm_tell(R_CONTROL, data[P_ENTITY_LID], data[P_LID], success, data['requestId']) self._wait_and_except_if_failed(evt)
python
def confirm_tell(self, data, success): """Confirm that you've done as you were told. Call this from your control callback to confirm action. Used when you are advertising a control and you want to tell the remote requestor that you have done what they asked you to. `Example:` this is a minimal example to show the idea. Note - no Exception handling and ugly use of globals #!python client = None def controlreq_cb(args): global client # the client object you connected with # perform your action with the data they sent success = do_control_action(args['data']) if args['confirm']: # you've been asked to confirm client.confirm_tell(args, success) # else, if you do not confirm_tell() this causes a timeout at the requestor's end. client = IOT.Client(config='test.ini') thing = client.create_thing('test321') control = thing.create_control('control', controlreq_cb) Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `data` (mandatory) (dictionary) The `"args"` dictionary that your callback was called with `success` (mandatory) (boolean) Whether or not the action you have been asked to do has been sucessful. More details on the contents of the `data` dictionary for controls see: [create_control()](./Thing.m.html#IoticAgent.IOT.Thing.Thing.create_control) """ logger.info("confirm_tell(success=%s) [lid=\"%s\",pid=\"%s\"]", success, data[P_ENTITY_LID], data[P_LID]) evt = self._request_point_confirm_tell(R_CONTROL, data[P_ENTITY_LID], data[P_LID], success, data['requestId']) self._wait_and_except_if_failed(evt)
[ "def", "confirm_tell", "(", "self", ",", "data", ",", "success", ")", ":", "logger", ".", "info", "(", "\"confirm_tell(success=%s) [lid=\\\"%s\\\",pid=\\\"%s\\\"]\"", ",", "success", ",", "data", "[", "P_ENTITY_LID", "]", ",", "data", "[", "P_LID", "]", ")", "...
Confirm that you've done as you were told. Call this from your control callback to confirm action. Used when you are advertising a control and you want to tell the remote requestor that you have done what they asked you to. `Example:` this is a minimal example to show the idea. Note - no Exception handling and ugly use of globals #!python client = None def controlreq_cb(args): global client # the client object you connected with # perform your action with the data they sent success = do_control_action(args['data']) if args['confirm']: # you've been asked to confirm client.confirm_tell(args, success) # else, if you do not confirm_tell() this causes a timeout at the requestor's end. client = IOT.Client(config='test.ini') thing = client.create_thing('test321') control = thing.create_control('control', controlreq_cb) Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `data` (mandatory) (dictionary) The `"args"` dictionary that your callback was called with `success` (mandatory) (boolean) Whether or not the action you have been asked to do has been sucessful. More details on the contents of the `data` dictionary for controls see: [create_control()](./Thing.m.html#IoticAgent.IOT.Thing.Thing.create_control)
[ "Confirm", "that", "you", "ve", "done", "as", "you", "were", "told", ".", "Call", "this", "from", "your", "control", "callback", "to", "confirm", "action", ".", "Used", "when", "you", "are", "advertising", "a", "control", "and", "you", "want", "to", "tel...
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/IOT/Client.py#L564-L604
train
38,146
Iotic-Labs/py-IoticAgent
src/IoticAgent/IOT/Client.py
Client.save_config
def save_config(self): """Save the config, update the seqnum & default language """ self.__config.set('agent', 'seqnum', self.__client.get_seqnum()) self.__config.set('agent', 'lang', self.__client.default_lang) self.__config.save()
python
def save_config(self): """Save the config, update the seqnum & default language """ self.__config.set('agent', 'seqnum', self.__client.get_seqnum()) self.__config.set('agent', 'lang', self.__client.default_lang) self.__config.save()
[ "def", "save_config", "(", "self", ")", ":", "self", ".", "__config", ".", "set", "(", "'agent'", ",", "'seqnum'", ",", "self", ".", "__client", ".", "get_seqnum", "(", ")", ")", "self", ".", "__config", ".", "set", "(", "'agent'", ",", "'lang'", ","...
Save the config, update the seqnum & default language
[ "Save", "the", "config", "update", "the", "seqnum", "&", "default", "language" ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/IOT/Client.py#L606-L611
train
38,147
Iotic-Labs/py-IoticAgent
src/IoticAgent/IOT/Client.py
Client._get_point_data_handler_for
def _get_point_data_handler_for(self, point): """Used by point instances and data callbacks""" with self.__point_data_handlers: try: return self.__point_data_handlers[point] except KeyError: return self.__point_data_handlers.setdefault(point, PointDataObjectHandler(point, self))
python
def _get_point_data_handler_for(self, point): """Used by point instances and data callbacks""" with self.__point_data_handlers: try: return self.__point_data_handlers[point] except KeyError: return self.__point_data_handlers.setdefault(point, PointDataObjectHandler(point, self))
[ "def", "_get_point_data_handler_for", "(", "self", ",", "point", ")", ":", "with", "self", ".", "__point_data_handlers", ":", "try", ":", "return", "self", ".", "__point_data_handlers", "[", "point", "]", "except", "KeyError", ":", "return", "self", ".", "__po...
Used by point instances and data callbacks
[ "Used", "by", "point", "instances", "and", "data", "callbacks" ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/IOT/Client.py#L621-L627
train
38,148
Iotic-Labs/py-IoticAgent
src/IoticAgent/IOT/Client.py
Client._wait_and_except_if_failed
def _wait_and_except_if_failed(self, event, timeout=None): """Combines waiting for event and call to `_except_if_failed`. If timeout is not specified the configured sync_timeout is used. """ event.wait(timeout or self.__sync_timeout) self._except_if_failed(event)
python
def _wait_and_except_if_failed(self, event, timeout=None): """Combines waiting for event and call to `_except_if_failed`. If timeout is not specified the configured sync_timeout is used. """ event.wait(timeout or self.__sync_timeout) self._except_if_failed(event)
[ "def", "_wait_and_except_if_failed", "(", "self", ",", "event", ",", "timeout", "=", "None", ")", ":", "event", ".", "wait", "(", "timeout", "or", "self", ".", "__sync_timeout", ")", "self", ".", "_except_if_failed", "(", "event", ")" ]
Combines waiting for event and call to `_except_if_failed`. If timeout is not specified the configured sync_timeout is used.
[ "Combines", "waiting", "for", "event", "and", "call", "to", "_except_if_failed", ".", "If", "timeout", "is", "not", "specified", "the", "configured", "sync_timeout", "is", "used", "." ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/IOT/Client.py#L661-L666
train
38,149
Iotic-Labs/py-IoticAgent
src/IoticAgent/IOT/Client.py
Client._except_if_failed
def _except_if_failed(cls, event): """Raises an IOTException from the given event if it was not successful. Assumes timeout success flag on event has not been set yet.""" if event.success is None: raise IOTSyncTimeout('Requested timed out', event) if not event.success: msg = "Request failed, unknown error" if isinstance(event.payload, Mapping): if P_MESSAGE in event.payload: msg = event.payload[P_MESSAGE] try: exc_class = cls.__exception_mapping[event.payload[P_CODE]] except KeyError: pass else: raise exc_class(msg, event) raise IOTException(msg, event)
python
def _except_if_failed(cls, event): """Raises an IOTException from the given event if it was not successful. Assumes timeout success flag on event has not been set yet.""" if event.success is None: raise IOTSyncTimeout('Requested timed out', event) if not event.success: msg = "Request failed, unknown error" if isinstance(event.payload, Mapping): if P_MESSAGE in event.payload: msg = event.payload[P_MESSAGE] try: exc_class = cls.__exception_mapping[event.payload[P_CODE]] except KeyError: pass else: raise exc_class(msg, event) raise IOTException(msg, event)
[ "def", "_except_if_failed", "(", "cls", ",", "event", ")", ":", "if", "event", ".", "success", "is", "None", ":", "raise", "IOTSyncTimeout", "(", "'Requested timed out'", ",", "event", ")", "if", "not", "event", ".", "success", ":", "msg", "=", "\"Request ...
Raises an IOTException from the given event if it was not successful. Assumes timeout success flag on event has not been set yet.
[ "Raises", "an", "IOTException", "from", "the", "given", "event", "if", "it", "was", "not", "successful", ".", "Assumes", "timeout", "success", "flag", "on", "event", "has", "not", "been", "set", "yet", "." ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/IOT/Client.py#L669-L686
train
38,150
Iotic-Labs/py-IoticAgent
src/IoticAgent/IOT/Client.py
Client.list
def list(self, all_my_agents=False, limit=500, offset=0): """List `all` the things created by this client on this or all your agents Returns QAPI list function payload Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `all_my_agents` (optional) (boolean) If `False` limit search to just this agent, if `True` return list of things belonging to all agents you own. `limit` (optional) (integer) Return this many Point details `offset` (optional) (integer) Return Point details starting at this offset """ logger.info("list(all_my_agents=%s, limit=%s, offset=%s)", all_my_agents, limit, offset) if all_my_agents: evt = self._request_entity_list_all(limit=limit, offset=offset) else: evt = self._request_entity_list(limit=limit, offset=offset) self._wait_and_except_if_failed(evt) return evt.payload['entities']
python
def list(self, all_my_agents=False, limit=500, offset=0): """List `all` the things created by this client on this or all your agents Returns QAPI list function payload Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `all_my_agents` (optional) (boolean) If `False` limit search to just this agent, if `True` return list of things belonging to all agents you own. `limit` (optional) (integer) Return this many Point details `offset` (optional) (integer) Return Point details starting at this offset """ logger.info("list(all_my_agents=%s, limit=%s, offset=%s)", all_my_agents, limit, offset) if all_my_agents: evt = self._request_entity_list_all(limit=limit, offset=offset) else: evt = self._request_entity_list(limit=limit, offset=offset) self._wait_and_except_if_failed(evt) return evt.payload['entities']
[ "def", "list", "(", "self", ",", "all_my_agents", "=", "False", ",", "limit", "=", "500", ",", "offset", "=", "0", ")", ":", "logger", ".", "info", "(", "\"list(all_my_agents=%s, limit=%s, offset=%s)\"", ",", "all_my_agents", ",", "limit", ",", "offset", ")"...
List `all` the things created by this client on this or all your agents Returns QAPI list function payload Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `all_my_agents` (optional) (boolean) If `False` limit search to just this agent, if `True` return list of things belonging to all agents you own. `limit` (optional) (integer) Return this many Point details `offset` (optional) (integer) Return Point details starting at this offset
[ "List", "all", "the", "things", "created", "by", "this", "client", "on", "this", "or", "all", "your", "agents" ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/IOT/Client.py#L688-L710
train
38,151
Iotic-Labs/py-IoticAgent
src/IoticAgent/IOT/Client.py
Client.get_thing
def get_thing(self, lid): """Get the details of a newly created Thing. This only applies to asynchronous creation of Things and the new Thing instance can only be retrieved once. Returns a [Thing](Thing.m.html#IoticAgent.IOT.Thing.Thing) object, which corresponds to the Thing with the given local id (nickname) Raises `KeyError` if the Thing has not been newly created (or has already been retrieved by a previous call) `lid` (required) (string) local identifier of your Thing. """ with self.__new_things: try: return self.__new_things.pop(lid) except KeyError as ex: raise_from(KeyError('Thing %s not know as new' % lid), ex)
python
def get_thing(self, lid): """Get the details of a newly created Thing. This only applies to asynchronous creation of Things and the new Thing instance can only be retrieved once. Returns a [Thing](Thing.m.html#IoticAgent.IOT.Thing.Thing) object, which corresponds to the Thing with the given local id (nickname) Raises `KeyError` if the Thing has not been newly created (or has already been retrieved by a previous call) `lid` (required) (string) local identifier of your Thing. """ with self.__new_things: try: return self.__new_things.pop(lid) except KeyError as ex: raise_from(KeyError('Thing %s not know as new' % lid), ex)
[ "def", "get_thing", "(", "self", ",", "lid", ")", ":", "with", "self", ".", "__new_things", ":", "try", ":", "return", "self", ".", "__new_things", ".", "pop", "(", "lid", ")", "except", "KeyError", "as", "ex", ":", "raise_from", "(", "KeyError", "(", ...
Get the details of a newly created Thing. This only applies to asynchronous creation of Things and the new Thing instance can only be retrieved once. Returns a [Thing](Thing.m.html#IoticAgent.IOT.Thing.Thing) object, which corresponds to the Thing with the given local id (nickname) Raises `KeyError` if the Thing has not been newly created (or has already been retrieved by a previous call) `lid` (required) (string) local identifier of your Thing.
[ "Get", "the", "details", "of", "a", "newly", "created", "Thing", ".", "This", "only", "applies", "to", "asynchronous", "creation", "of", "Things", "and", "the", "new", "Thing", "instance", "can", "only", "be", "retrieved", "once", "." ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/IOT/Client.py#L712-L727
train
38,152
Iotic-Labs/py-IoticAgent
src/IoticAgent/IOT/Client.py
Client.delete_thing
def delete_thing(self, lid): """Delete a Thing Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `lid` (required) (string) local identifier of the Thing you want to delete """ logger.info("delete_thing(lid=\"%s\")", lid) evt = self.delete_thing_async(lid) self._wait_and_except_if_failed(evt)
python
def delete_thing(self, lid): """Delete a Thing Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `lid` (required) (string) local identifier of the Thing you want to delete """ logger.info("delete_thing(lid=\"%s\")", lid) evt = self.delete_thing_async(lid) self._wait_and_except_if_failed(evt)
[ "def", "delete_thing", "(", "self", ",", "lid", ")", ":", "logger", ".", "info", "(", "\"delete_thing(lid=\\\"%s\\\")\"", ",", "lid", ")", "evt", "=", "self", ".", "delete_thing_async", "(", "lid", ")", "self", ".", "_wait_and_except_if_failed", "(", "evt", ...
Delete a Thing Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem between you and the infrastructure `lid` (required) (string) local identifier of the Thing you want to delete
[ "Delete", "a", "Thing" ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/IOT/Client.py#L756-L769
train
38,153
tophatmonocle/ims_lti_py
ims_lti_py/outcome_request.py
OutcomeRequest.from_post_request
def from_post_request(post_request): ''' Convenience method for creating a new OutcomeRequest from a request object. post_request is assumed to be a Django HttpRequest object ''' request = OutcomeRequest() request.post_request = post_request request.process_xml(post_request.data) return request
python
def from_post_request(post_request): ''' Convenience method for creating a new OutcomeRequest from a request object. post_request is assumed to be a Django HttpRequest object ''' request = OutcomeRequest() request.post_request = post_request request.process_xml(post_request.data) return request
[ "def", "from_post_request", "(", "post_request", ")", ":", "request", "=", "OutcomeRequest", "(", ")", "request", ".", "post_request", "=", "post_request", "request", ".", "process_xml", "(", "post_request", ".", "data", ")", "return", "request" ]
Convenience method for creating a new OutcomeRequest from a request object. post_request is assumed to be a Django HttpRequest object
[ "Convenience", "method", "for", "creating", "a", "new", "OutcomeRequest", "from", "a", "request", "object", "." ]
979244d83c2e6420d2c1941f58e52f641c56ad12
https://github.com/tophatmonocle/ims_lti_py/blob/979244d83c2e6420d2c1941f58e52f641c56ad12/ims_lti_py/outcome_request.py#L48-L58
train
38,154
tophatmonocle/ims_lti_py
ims_lti_py/outcome_request.py
OutcomeRequest.post_outcome_request
def post_outcome_request(self): ''' POST an OAuth signed request to the Tool Consumer. ''' if not self.has_required_attributes(): raise InvalidLTIConfigError( 'OutcomeRequest does not have all required attributes') consumer = oauth2.Consumer(key=self.consumer_key, secret=self.consumer_secret) client = oauth2.Client(consumer) # monkey_patch_headers ensures that Authorization # header is NOT lower cased monkey_patch_headers = True monkey_patch_function = None if monkey_patch_headers: import httplib2 http = httplib2.Http normalize = http._normalize_headers def my_normalize(self, headers): print("My Normalize", headers) ret = normalize(self, headers) if 'authorization' in ret: ret['Authorization'] = ret.pop('authorization') print("My Normalize", ret) return ret http._normalize_headers = my_normalize monkey_patch_function = normalize response, content = client.request( self.lis_outcome_service_url, 'POST', body=self.generate_request_xml(), headers={'Content-Type': 'application/xml'}) if monkey_patch_headers and monkey_patch_function: import httplib2 http = httplib2.Http http._normalize_headers = monkey_patch_function self.outcome_response = OutcomeResponse.from_post_response(response, content) return self.outcome_response
python
def post_outcome_request(self): ''' POST an OAuth signed request to the Tool Consumer. ''' if not self.has_required_attributes(): raise InvalidLTIConfigError( 'OutcomeRequest does not have all required attributes') consumer = oauth2.Consumer(key=self.consumer_key, secret=self.consumer_secret) client = oauth2.Client(consumer) # monkey_patch_headers ensures that Authorization # header is NOT lower cased monkey_patch_headers = True monkey_patch_function = None if monkey_patch_headers: import httplib2 http = httplib2.Http normalize = http._normalize_headers def my_normalize(self, headers): print("My Normalize", headers) ret = normalize(self, headers) if 'authorization' in ret: ret['Authorization'] = ret.pop('authorization') print("My Normalize", ret) return ret http._normalize_headers = my_normalize monkey_patch_function = normalize response, content = client.request( self.lis_outcome_service_url, 'POST', body=self.generate_request_xml(), headers={'Content-Type': 'application/xml'}) if monkey_patch_headers and monkey_patch_function: import httplib2 http = httplib2.Http http._normalize_headers = monkey_patch_function self.outcome_response = OutcomeResponse.from_post_response(response, content) return self.outcome_response
[ "def", "post_outcome_request", "(", "self", ")", ":", "if", "not", "self", ".", "has_required_attributes", "(", ")", ":", "raise", "InvalidLTIConfigError", "(", "'OutcomeRequest does not have all required attributes'", ")", "consumer", "=", "oauth2", ".", "Consumer", ...
POST an OAuth signed request to the Tool Consumer.
[ "POST", "an", "OAuth", "signed", "request", "to", "the", "Tool", "Consumer", "." ]
979244d83c2e6420d2c1941f58e52f641c56ad12
https://github.com/tophatmonocle/ims_lti_py/blob/979244d83c2e6420d2c1941f58e52f641c56ad12/ims_lti_py/outcome_request.py#L124-L169
train
38,155
tophatmonocle/ims_lti_py
ims_lti_py/outcome_request.py
OutcomeRequest.process_xml
def process_xml(self, xml): ''' Parse Outcome Request data from XML. ''' root = objectify.fromstring(xml) self.message_identifier = str( root.imsx_POXHeader.imsx_POXRequestHeaderInfo. imsx_messageIdentifier) try: result = root.imsx_POXBody.replaceResultRequest self.operation = REPLACE_REQUEST # Get result sourced id from resultRecord self.lis_result_sourcedid = result.resultRecord.\ sourcedGUID.sourcedId self.score = str(result.resultRecord.result. resultScore.textString) except: pass try: result = root.imsx_POXBody.deleteResultRequest self.operation = DELETE_REQUEST # Get result sourced id from resultRecord self.lis_result_sourcedid = result.resultRecord.\ sourcedGUID.sourcedId except: pass try: result = root.imsx_POXBody.readResultRequest self.operation = READ_REQUEST # Get result sourced id from resultRecord self.lis_result_sourcedid = result.resultRecord.\ sourcedGUID.sourcedId except: pass
python
def process_xml(self, xml): ''' Parse Outcome Request data from XML. ''' root = objectify.fromstring(xml) self.message_identifier = str( root.imsx_POXHeader.imsx_POXRequestHeaderInfo. imsx_messageIdentifier) try: result = root.imsx_POXBody.replaceResultRequest self.operation = REPLACE_REQUEST # Get result sourced id from resultRecord self.lis_result_sourcedid = result.resultRecord.\ sourcedGUID.sourcedId self.score = str(result.resultRecord.result. resultScore.textString) except: pass try: result = root.imsx_POXBody.deleteResultRequest self.operation = DELETE_REQUEST # Get result sourced id from resultRecord self.lis_result_sourcedid = result.resultRecord.\ sourcedGUID.sourcedId except: pass try: result = root.imsx_POXBody.readResultRequest self.operation = READ_REQUEST # Get result sourced id from resultRecord self.lis_result_sourcedid = result.resultRecord.\ sourcedGUID.sourcedId except: pass
[ "def", "process_xml", "(", "self", ",", "xml", ")", ":", "root", "=", "objectify", ".", "fromstring", "(", "xml", ")", "self", ".", "message_identifier", "=", "str", "(", "root", ".", "imsx_POXHeader", ".", "imsx_POXRequestHeaderInfo", ".", "imsx_messageIdenti...
Parse Outcome Request data from XML.
[ "Parse", "Outcome", "Request", "data", "from", "XML", "." ]
979244d83c2e6420d2c1941f58e52f641c56ad12
https://github.com/tophatmonocle/ims_lti_py/blob/979244d83c2e6420d2c1941f58e52f641c56ad12/ims_lti_py/outcome_request.py#L171-L206
train
38,156
Iotic-Labs/py-IoticAgent
src/IoticAgent/IOT/Config.py
Config.setup_logging
def setup_logging(self): """Setup logging module based on known modules in the config file """ logging.getLogger('amqp').setLevel(str_to_logging(self.get('logging', 'amqp'))) logging.getLogger('rdflib').setLevel(str_to_logging(self.get('logging', 'rdflib')))
python
def setup_logging(self): """Setup logging module based on known modules in the config file """ logging.getLogger('amqp').setLevel(str_to_logging(self.get('logging', 'amqp'))) logging.getLogger('rdflib').setLevel(str_to_logging(self.get('logging', 'rdflib')))
[ "def", "setup_logging", "(", "self", ")", ":", "logging", ".", "getLogger", "(", "'amqp'", ")", ".", "setLevel", "(", "str_to_logging", "(", "self", ".", "get", "(", "'logging'", ",", "'amqp'", ")", ")", ")", "logging", ".", "getLogger", "(", "'rdflib'",...
Setup logging module based on known modules in the config file
[ "Setup", "logging", "module", "based", "on", "known", "modules", "in", "the", "config", "file" ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/IOT/Config.py#L158-L162
train
38,157
Iotic-Labs/py-IoticAgent
src/IoticAgent/IOT/Config.py
Config.save
def save(self, filename=None): """Write config to file.""" if self.__fname is None and filename is None: raise ValueError('Config loaded from string, no filename specified') conf = self.__config cpa = dict_to_cp(conf) with open(self.__fname if filename is None else filename, 'w') as f: cpa.write(f)
python
def save(self, filename=None): """Write config to file.""" if self.__fname is None and filename is None: raise ValueError('Config loaded from string, no filename specified') conf = self.__config cpa = dict_to_cp(conf) with open(self.__fname if filename is None else filename, 'w') as f: cpa.write(f)
[ "def", "save", "(", "self", ",", "filename", "=", "None", ")", ":", "if", "self", ".", "__fname", "is", "None", "and", "filename", "is", "None", ":", "raise", "ValueError", "(", "'Config loaded from string, no filename specified'", ")", "conf", "=", "self", ...
Write config to file.
[ "Write", "config", "to", "file", "." ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/IOT/Config.py#L164-L171
train
38,158
Iotic-Labs/py-IoticAgent
src/IoticAgent/IOT/Config.py
Config.get
def get(self, section, val): """Get a setting or the default `Returns` The current value of the setting `val` or the default, or `None` if not found `section` (mandatory) (string) the section name in the config E.g. `"agent"` `val` (mandatory) (string) the section name in the config E.g. `"host"` """ val = val.lower() if section in self.__config: if val in self.__config[section]: # logger.debug('get config %s %s = %s', section, val, self.__config[section][val]) return self.__config[section][val] if section in self.__defaults: if val in self.__defaults[section]: # logger.debug('get defaults %s %s = %s', section, val, self.__defaults[section][val]) return self.__defaults[section][val] return None
python
def get(self, section, val): """Get a setting or the default `Returns` The current value of the setting `val` or the default, or `None` if not found `section` (mandatory) (string) the section name in the config E.g. `"agent"` `val` (mandatory) (string) the section name in the config E.g. `"host"` """ val = val.lower() if section in self.__config: if val in self.__config[section]: # logger.debug('get config %s %s = %s', section, val, self.__config[section][val]) return self.__config[section][val] if section in self.__defaults: if val in self.__defaults[section]: # logger.debug('get defaults %s %s = %s', section, val, self.__defaults[section][val]) return self.__defaults[section][val] return None
[ "def", "get", "(", "self", ",", "section", ",", "val", ")", ":", "val", "=", "val", ".", "lower", "(", ")", "if", "section", "in", "self", ".", "__config", ":", "if", "val", "in", "self", ".", "__config", "[", "section", "]", ":", "# logger.debug('...
Get a setting or the default `Returns` The current value of the setting `val` or the default, or `None` if not found `section` (mandatory) (string) the section name in the config E.g. `"agent"` `val` (mandatory) (string) the section name in the config E.g. `"host"`
[ "Get", "a", "setting", "or", "the", "default" ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/IOT/Config.py#L173-L191
train
38,159
Iotic-Labs/py-IoticAgent
src/IoticAgent/IOT/Config.py
Config.set
def set(self, section, val, data): """Add a setting to the config `section` (mandatory) (string) the section name in the config E.g. `"agent"` `val` (mandatory) (string) the section name in the config E.g. `"host"` `data` (mandatory) (as appropriate) the new value for the `val` """ val = val.lower() if section in self.__config: # logger.debug('set %s %s = %s', section, val, data) self.__config[section][val] = data
python
def set(self, section, val, data): """Add a setting to the config `section` (mandatory) (string) the section name in the config E.g. `"agent"` `val` (mandatory) (string) the section name in the config E.g. `"host"` `data` (mandatory) (as appropriate) the new value for the `val` """ val = val.lower() if section in self.__config: # logger.debug('set %s %s = %s', section, val, data) self.__config[section][val] = data
[ "def", "set", "(", "self", ",", "section", ",", "val", ",", "data", ")", ":", "val", "=", "val", ".", "lower", "(", ")", "if", "section", "in", "self", ".", "__config", ":", "# logger.debug('set %s %s = %s', section, val, data)", "self", ".", "__config", "...
Add a setting to the config `section` (mandatory) (string) the section name in the config E.g. `"agent"` `val` (mandatory) (string) the section name in the config E.g. `"host"` `data` (mandatory) (as appropriate) the new value for the `val`
[ "Add", "a", "setting", "to", "the", "config" ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/IOT/Config.py#L193-L205
train
38,160
Iotic-Labs/py-IoticAgent
src/IoticAgent/IOT/Config.py
Config.update
def update(self, section, val, data): """Add a setting to the config, but if same as default or None then no action. This saves the .save writing the defaults `section` (mandatory) (string) the section name in the config E.g. `"agent"` `val` (mandatory) (string) the section name in the config E.g. `"host"` `data` (mandatory) (as appropriate) the new value for the `val` """ k = self.get(section, val) # logger.debug('update %s %s from: %s to: %s', section, val, k, data) if data is not None and k != data: self.set(section, val, data)
python
def update(self, section, val, data): """Add a setting to the config, but if same as default or None then no action. This saves the .save writing the defaults `section` (mandatory) (string) the section name in the config E.g. `"agent"` `val` (mandatory) (string) the section name in the config E.g. `"host"` `data` (mandatory) (as appropriate) the new value for the `val` """ k = self.get(section, val) # logger.debug('update %s %s from: %s to: %s', section, val, k, data) if data is not None and k != data: self.set(section, val, data)
[ "def", "update", "(", "self", ",", "section", ",", "val", ",", "data", ")", ":", "k", "=", "self", ".", "get", "(", "section", ",", "val", ")", "# logger.debug('update %s %s from: %s to: %s', section, val, k, data)", "if", "data", "is", "not", "None", "and", ...
Add a setting to the config, but if same as default or None then no action. This saves the .save writing the defaults `section` (mandatory) (string) the section name in the config E.g. `"agent"` `val` (mandatory) (string) the section name in the config E.g. `"host"` `data` (mandatory) (as appropriate) the new value for the `val`
[ "Add", "a", "setting", "to", "the", "config", "but", "if", "same", "as", "default", "or", "None", "then", "no", "action", ".", "This", "saves", "the", ".", "save", "writing", "the", "defaults" ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/IOT/Config.py#L207-L220
train
38,161
Iotic-Labs/py-IoticAgent
src/IoticAgent/IOT/ThingMeta.py
ThingMeta.get_location
def get_location(self): """Gets the current geo location of your Thing Returns tuple of `(lat, lon)` in `float` or `(None, None)` if location is not set for this Thing """ lat = None lon = None # note: always picks from first triple for _, _, o in self._graph.triples((None, GEO_NS.lat, None)): lat = float(o) break for _, _, o in self._graph.triples((None, GEO_NS.long, None)): lon = float(o) break return lat, lon
python
def get_location(self): """Gets the current geo location of your Thing Returns tuple of `(lat, lon)` in `float` or `(None, None)` if location is not set for this Thing """ lat = None lon = None # note: always picks from first triple for _, _, o in self._graph.triples((None, GEO_NS.lat, None)): lat = float(o) break for _, _, o in self._graph.triples((None, GEO_NS.long, None)): lon = float(o) break return lat, lon
[ "def", "get_location", "(", "self", ")", ":", "lat", "=", "None", "lon", "=", "None", "# note: always picks from first triple", "for", "_", ",", "_", ",", "o", "in", "self", ".", "_graph", ".", "triples", "(", "(", "None", ",", "GEO_NS", ".", "lat", ",...
Gets the current geo location of your Thing Returns tuple of `(lat, lon)` in `float` or `(None, None)` if location is not set for this Thing
[ "Gets", "the", "current", "geo", "location", "of", "your", "Thing" ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/IOT/ThingMeta.py#L48-L63
train
38,162
Iotic-Labs/py-IoticAgent
src/IoticAgent/Core/AmqpLink.py
AmqpLink.start
def start(self): """start connection threads, blocks until started """ if not (self.__recv_thread or self.__send_thread): self.__end.clear() self.__send_ready.clear() self.__recv_ready.clear() timeout = self.__socket_timeout + 1 ignore_exc = self.__startup_ignore_exc self.__send_exc_clear() self.__recv_exc_clear() # start & await send thread success (unless timeout reached or an exception has occured) self.__send_thread = Thread(target=self.__send_run, name='amqplink_send') self.__send_thread.start() start_time = monotonic() success = False while not (success or (not ignore_exc and self.__send_exc) or monotonic() - start_time > timeout): success = self.__send_ready.wait(.25) if success: # start & await receiver thread success self.__recv_thread = Thread(target=self.__recv_run, name='amqplink_recv') self.__recv_thread.start() start_time = monotonic() success = False while not (success or (not ignore_exc and self.__recv_exc) or monotonic() - start_time >= timeout): success = self.__recv_ready.wait(.25) # handler either thread's failure if not success: logger.warning("AmqpLink Failed to start. Giving up.") self.stop() if self.__recv_exc: # prioritise receive thread since this can get access-denied whereas send does not (until sending) raise_from(LinkException('Receive thread failure'), self.__recv_exc) elif self.__send_exc: raise_from(LinkException('Send thread failure'), self.__send_exc) else: raise LinkException('Unknown link failure (timeout reached)') else: raise LinkException('amqplink already started')
python
def start(self): """start connection threads, blocks until started """ if not (self.__recv_thread or self.__send_thread): self.__end.clear() self.__send_ready.clear() self.__recv_ready.clear() timeout = self.__socket_timeout + 1 ignore_exc = self.__startup_ignore_exc self.__send_exc_clear() self.__recv_exc_clear() # start & await send thread success (unless timeout reached or an exception has occured) self.__send_thread = Thread(target=self.__send_run, name='amqplink_send') self.__send_thread.start() start_time = monotonic() success = False while not (success or (not ignore_exc and self.__send_exc) or monotonic() - start_time > timeout): success = self.__send_ready.wait(.25) if success: # start & await receiver thread success self.__recv_thread = Thread(target=self.__recv_run, name='amqplink_recv') self.__recv_thread.start() start_time = monotonic() success = False while not (success or (not ignore_exc and self.__recv_exc) or monotonic() - start_time >= timeout): success = self.__recv_ready.wait(.25) # handler either thread's failure if not success: logger.warning("AmqpLink Failed to start. Giving up.") self.stop() if self.__recv_exc: # prioritise receive thread since this can get access-denied whereas send does not (until sending) raise_from(LinkException('Receive thread failure'), self.__recv_exc) elif self.__send_exc: raise_from(LinkException('Send thread failure'), self.__send_exc) else: raise LinkException('Unknown link failure (timeout reached)') else: raise LinkException('amqplink already started')
[ "def", "start", "(", "self", ")", ":", "if", "not", "(", "self", ".", "__recv_thread", "or", "self", ".", "__send_thread", ")", ":", "self", ".", "__end", ".", "clear", "(", ")", "self", ".", "__send_ready", ".", "clear", "(", ")", "self", ".", "__...
start connection threads, blocks until started
[ "start", "connection", "threads", "blocks", "until", "started" ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/Core/AmqpLink.py#L120-L162
train
38,163
Iotic-Labs/py-IoticAgent
src/IoticAgent/Core/AmqpLink.py
AmqpLink.is_alive
def is_alive(self): """Helper function to show if send & recv Threads are running """ if self.__send_ready.is_set() and self.__recv_ready.is_set(): if self.__send_thread is not None and self.__recv_thread is not None: return self.__send_thread.is_alive() and self.__recv_thread.is_alive() return False
python
def is_alive(self): """Helper function to show if send & recv Threads are running """ if self.__send_ready.is_set() and self.__recv_ready.is_set(): if self.__send_thread is not None and self.__recv_thread is not None: return self.__send_thread.is_alive() and self.__recv_thread.is_alive() return False
[ "def", "is_alive", "(", "self", ")", ":", "if", "self", ".", "__send_ready", ".", "is_set", "(", ")", "and", "self", ".", "__recv_ready", ".", "is_set", "(", ")", ":", "if", "self", ".", "__send_thread", "is", "not", "None", "and", "self", ".", "__re...
Helper function to show if send & recv Threads are running
[ "Helper", "function", "to", "show", "if", "send", "&", "recv", "Threads", "are", "running" ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/Core/AmqpLink.py#L164-L170
train
38,164
Iotic-Labs/py-IoticAgent
src/IoticAgent/Core/AmqpLink.py
AmqpLink.stop
def stop(self): """disconnect, blocks until stopped """ self.__end.set() if self.__recv_thread: self.__recv_thread.join() self.__recv_thread = None if self.__send_thread: self.__send_thread.join() self.__send_thread = None
python
def stop(self): """disconnect, blocks until stopped """ self.__end.set() if self.__recv_thread: self.__recv_thread.join() self.__recv_thread = None if self.__send_thread: self.__send_thread.join() self.__send_thread = None
[ "def", "stop", "(", "self", ")", ":", "self", ".", "__end", ".", "set", "(", ")", "if", "self", ".", "__recv_thread", ":", "self", ".", "__recv_thread", ".", "join", "(", ")", "self", ".", "__recv_thread", "=", "None", "if", "self", ".", "__send_thre...
disconnect, blocks until stopped
[ "disconnect", "blocks", "until", "stopped" ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/Core/AmqpLink.py#L172-L181
train
38,165
Iotic-Labs/py-IoticAgent
src/IoticAgent/Core/AmqpLink.py
AmqpLink.__get_ssl_context
def __get_ssl_context(cls, sslca=None): """Make an SSLConext for this Python version using public or sslca """ if ((version_info[0] == 2 and (version_info[1] >= 7 and version_info[2] >= 5)) or (version_info[0] == 3 and version_info[1] >= 4)): logger.debug('SSL method for 2.7.5+ / 3.4+') # pylint: disable=no-name-in-module from ssl import SSLContext, PROTOCOL_TLSv1_2, CERT_REQUIRED, OP_NO_COMPRESSION ctx = SSLContext(PROTOCOL_TLSv1_2) ctx.set_ciphers('HIGH:!SSLv3:!TLSv1:!aNULL:@STRENGTH') # see CRIME security exploit ctx.options |= OP_NO_COMPRESSION # the following options are used to verify the identity of the broker if sslca: ctx.load_verify_locations(sslca) ctx.verify_mode = CERT_REQUIRED ctx.check_hostname = False else: # Verify public certifcates if sslca is None (default) from ssl import Purpose # pylint: disable=no-name-in-module ctx.load_default_certs(purpose=Purpose.SERVER_AUTH) ctx.verify_mode = CERT_REQUIRED ctx.check_hostname = True elif version_info[0] == 3 and version_info[1] < 4: logger.debug('Using SSL method for 3.2+, < 3.4') # pylint: disable=no-name-in-module from ssl import SSLContext, CERT_REQUIRED, PROTOCOL_SSLv23, OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_TLSv1 ctx = SSLContext(PROTOCOL_SSLv23) ctx.options |= (OP_NO_SSLv2 | OP_NO_SSLv3 | OP_NO_TLSv1) ctx.set_ciphers('HIGH:!SSLv3:!TLSv1:!aNULL:@STRENGTH') # the following options are used to verify the identity of the broker if sslca: ctx.load_verify_locations(sslca) ctx.verify_mode = CERT_REQUIRED else: # Verify public certifcates if sslca is None (default) ctx.set_default_verify_paths() ctx.verify_mode = CERT_REQUIRED else: raise Exception("Unsupported Python version %s" % '.'.join(str(item) for item in version_info[:3])) return ctx
python
def __get_ssl_context(cls, sslca=None): """Make an SSLConext for this Python version using public or sslca """ if ((version_info[0] == 2 and (version_info[1] >= 7 and version_info[2] >= 5)) or (version_info[0] == 3 and version_info[1] >= 4)): logger.debug('SSL method for 2.7.5+ / 3.4+') # pylint: disable=no-name-in-module from ssl import SSLContext, PROTOCOL_TLSv1_2, CERT_REQUIRED, OP_NO_COMPRESSION ctx = SSLContext(PROTOCOL_TLSv1_2) ctx.set_ciphers('HIGH:!SSLv3:!TLSv1:!aNULL:@STRENGTH') # see CRIME security exploit ctx.options |= OP_NO_COMPRESSION # the following options are used to verify the identity of the broker if sslca: ctx.load_verify_locations(sslca) ctx.verify_mode = CERT_REQUIRED ctx.check_hostname = False else: # Verify public certifcates if sslca is None (default) from ssl import Purpose # pylint: disable=no-name-in-module ctx.load_default_certs(purpose=Purpose.SERVER_AUTH) ctx.verify_mode = CERT_REQUIRED ctx.check_hostname = True elif version_info[0] == 3 and version_info[1] < 4: logger.debug('Using SSL method for 3.2+, < 3.4') # pylint: disable=no-name-in-module from ssl import SSLContext, CERT_REQUIRED, PROTOCOL_SSLv23, OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_TLSv1 ctx = SSLContext(PROTOCOL_SSLv23) ctx.options |= (OP_NO_SSLv2 | OP_NO_SSLv3 | OP_NO_TLSv1) ctx.set_ciphers('HIGH:!SSLv3:!TLSv1:!aNULL:@STRENGTH') # the following options are used to verify the identity of the broker if sslca: ctx.load_verify_locations(sslca) ctx.verify_mode = CERT_REQUIRED else: # Verify public certifcates if sslca is None (default) ctx.set_default_verify_paths() ctx.verify_mode = CERT_REQUIRED else: raise Exception("Unsupported Python version %s" % '.'.join(str(item) for item in version_info[:3])) return ctx
[ "def", "__get_ssl_context", "(", "cls", ",", "sslca", "=", "None", ")", ":", "if", "(", "(", "version_info", "[", "0", "]", "==", "2", "and", "(", "version_info", "[", "1", "]", ">=", "7", "and", "version_info", "[", "2", "]", ">=", "5", ")", ")"...
Make an SSLConext for this Python version using public or sslca
[ "Make", "an", "SSLConext", "for", "this", "Python", "version", "using", "public", "or", "sslca" ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/Core/AmqpLink.py#L216-L259
train
38,166
Iotic-Labs/py-IoticAgent
src/IoticAgent/Core/AmqpLink.py
AmqpLink.__recv_cb
def __recv_cb(self, msg): """Calls user-provided callback and marks message for Ack regardless of success """ try: self.__msg_callback(msg) except: logger.exception("AmqpLink.__recv_cb exception calling msg_callback") finally: # only works if all messages handled in series self.__last_id = msg.delivery_tag self.__unacked += 1
python
def __recv_cb(self, msg): """Calls user-provided callback and marks message for Ack regardless of success """ try: self.__msg_callback(msg) except: logger.exception("AmqpLink.__recv_cb exception calling msg_callback") finally: # only works if all messages handled in series self.__last_id = msg.delivery_tag self.__unacked += 1
[ "def", "__recv_cb", "(", "self", ",", "msg", ")", ":", "try", ":", "self", ".", "__msg_callback", "(", "msg", ")", "except", ":", "logger", ".", "exception", "(", "\"AmqpLink.__recv_cb exception calling msg_callback\"", ")", "finally", ":", "# only works if all me...
Calls user-provided callback and marks message for Ack regardless of success
[ "Calls", "user", "-", "provided", "callback", "and", "marks", "message", "for", "Ack", "regardless", "of", "success" ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/Core/AmqpLink.py#L275-L285
train
38,167
Iotic-Labs/py-IoticAgent
src/IoticAgent/Core/AmqpLink.py
AmqpLink.__send_run
def __send_run(self): """Send request thread """ while not self.__end.is_set(): try: with Connection(userid=self.__prefix + self.__epid, password=self.__passwd, virtual_host=self.__vhost, heartbeat=self.__heartbeat, connect_timeout=self.__socket_timeout, operation_timeout=self.__socket_timeout, ssl=self.__get_ssl_context(self.__sslca), host=self.__host) as conn,\ conn.channel(auto_encode_decode=False) as channel: self.__send_channel = channel self.__send_exc_clear(log_if_exc_set='reconnected') self.__send_ready.set() try: self.__send_ready_callback(self.__send_exc_time) while not self.__end.is_set(): with self.__send_lock: try: # deal with any incoming messages (AMQP protocol only, not QAPI) conn.drain_events(0) except (BlockingIOError, SocketTimeout): pass conn.heartbeat_tick() # idle self.__end.wait(.25) finally: # locked so can make sure another call to send() is not made whilst shutting down with self.__send_lock: self.__send_ready.clear() except exceptions.AccessRefused: self.__send_log_set_exc_and_wait('Access Refused (Credentials already in use?)') except exceptions.ConnectionForced: self.__send_log_set_exc_and_wait('Disconnected by broker (ConnectionForced)') except SocketTimeout: self.__send_log_set_exc_and_wait('SocketTimeout exception. wrong credentials, vhost or prefix?') except SSLError: self.__send_log_set_exc_and_wait('ssl.SSLError Bad Certificate?') except (exceptions.AMQPError, SocketError): self.__send_log_set_exc_and_wait('amqp/transport failure, sleeping before retry') except: self.__send_log_set_exc_and_wait('unexpected failure, exiting', wait_seconds=0) break logger.debug('finished')
python
def __send_run(self): """Send request thread """ while not self.__end.is_set(): try: with Connection(userid=self.__prefix + self.__epid, password=self.__passwd, virtual_host=self.__vhost, heartbeat=self.__heartbeat, connect_timeout=self.__socket_timeout, operation_timeout=self.__socket_timeout, ssl=self.__get_ssl_context(self.__sslca), host=self.__host) as conn,\ conn.channel(auto_encode_decode=False) as channel: self.__send_channel = channel self.__send_exc_clear(log_if_exc_set='reconnected') self.__send_ready.set() try: self.__send_ready_callback(self.__send_exc_time) while not self.__end.is_set(): with self.__send_lock: try: # deal with any incoming messages (AMQP protocol only, not QAPI) conn.drain_events(0) except (BlockingIOError, SocketTimeout): pass conn.heartbeat_tick() # idle self.__end.wait(.25) finally: # locked so can make sure another call to send() is not made whilst shutting down with self.__send_lock: self.__send_ready.clear() except exceptions.AccessRefused: self.__send_log_set_exc_and_wait('Access Refused (Credentials already in use?)') except exceptions.ConnectionForced: self.__send_log_set_exc_and_wait('Disconnected by broker (ConnectionForced)') except SocketTimeout: self.__send_log_set_exc_and_wait('SocketTimeout exception. wrong credentials, vhost or prefix?') except SSLError: self.__send_log_set_exc_and_wait('ssl.SSLError Bad Certificate?') except (exceptions.AMQPError, SocketError): self.__send_log_set_exc_and_wait('amqp/transport failure, sleeping before retry') except: self.__send_log_set_exc_and_wait('unexpected failure, exiting', wait_seconds=0) break logger.debug('finished')
[ "def", "__send_run", "(", "self", ")", ":", "while", "not", "self", ".", "__end", ".", "is_set", "(", ")", ":", "try", ":", "with", "Connection", "(", "userid", "=", "self", ".", "__prefix", "+", "self", ".", "__epid", ",", "password", "=", "self", ...
Send request thread
[ "Send", "request", "thread" ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/Core/AmqpLink.py#L374-L423
train
38,168
Iotic-Labs/py-IoticAgent
src/IoticAgent/Core/AmqpLink.py
AmqpLink.__send_log_set_exc_and_wait
def __send_log_set_exc_and_wait(self, msg, level=None, wait_seconds=CONN_RETRY_DELAY_SECONDS): """To be called in exception context only. msg - message to log level - logging level. If not specified, ERROR unless it is a repeated failure in which case DEBUG. If specified, the given level will always be used. wait_seconds - how long to pause for (so retry is not triggered immediately) """ logger.log( ((logging.DEBUG if self.__send_exc else logging.ERROR) if level is None else level), msg, exc_info=DEBUG_ENABLED ) self.__send_exc_time = monotonic() self.__send_exc = exc_info()[1] self.__end.wait(wait_seconds)
python
def __send_log_set_exc_and_wait(self, msg, level=None, wait_seconds=CONN_RETRY_DELAY_SECONDS): """To be called in exception context only. msg - message to log level - logging level. If not specified, ERROR unless it is a repeated failure in which case DEBUG. If specified, the given level will always be used. wait_seconds - how long to pause for (so retry is not triggered immediately) """ logger.log( ((logging.DEBUG if self.__send_exc else logging.ERROR) if level is None else level), msg, exc_info=DEBUG_ENABLED ) self.__send_exc_time = monotonic() self.__send_exc = exc_info()[1] self.__end.wait(wait_seconds)
[ "def", "__send_log_set_exc_and_wait", "(", "self", ",", "msg", ",", "level", "=", "None", ",", "wait_seconds", "=", "CONN_RETRY_DELAY_SECONDS", ")", ":", "logger", ".", "log", "(", "(", "(", "logging", ".", "DEBUG", "if", "self", ".", "__send_exc", "else", ...
To be called in exception context only. msg - message to log level - logging level. If not specified, ERROR unless it is a repeated failure in which case DEBUG. If specified, the given level will always be used. wait_seconds - how long to pause for (so retry is not triggered immediately)
[ "To", "be", "called", "in", "exception", "context", "only", "." ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/Core/AmqpLink.py#L425-L440
train
38,169
Iotic-Labs/py-IoticAgent
src/IoticAgent/Core/AmqpLink.py
AmqpLink.__send_exc_clear
def __send_exc_clear(self, log_if_exc_set=None): """Clear send exception and time. If exception was previously was set, optionally log log_if_exc_set at INFO level. """ if not (log_if_exc_set is None or self.__send_exc is None): logger.info(log_if_exc_set) self.__send_exc_time = None self.__send_exc = None
python
def __send_exc_clear(self, log_if_exc_set=None): """Clear send exception and time. If exception was previously was set, optionally log log_if_exc_set at INFO level. """ if not (log_if_exc_set is None or self.__send_exc is None): logger.info(log_if_exc_set) self.__send_exc_time = None self.__send_exc = None
[ "def", "__send_exc_clear", "(", "self", ",", "log_if_exc_set", "=", "None", ")", ":", "if", "not", "(", "log_if_exc_set", "is", "None", "or", "self", ".", "__send_exc", "is", "None", ")", ":", "logger", ".", "info", "(", "log_if_exc_set", ")", "self", "....
Clear send exception and time. If exception was previously was set, optionally log log_if_exc_set at INFO level.
[ "Clear", "send", "exception", "and", "time", ".", "If", "exception", "was", "previously", "was", "set", "optionally", "log", "log_if_exc_set", "at", "INFO", "level", "." ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/Core/AmqpLink.py#L442-L449
train
38,170
Iotic-Labs/py-IoticAgent
src/IoticAgent/Core/Mime.py
expand_idx_mimetype
def expand_idx_mimetype(type_): """Returns long equivalent of type_, if available, otherwise type_ itself. Does not raise exceptions""" if isinstance(type_, unicode_type): match = __IDX_PATTERN.match(type_) return __IDX_MAPPING.get(match.group(1), type_) if match else type_ else: return type_
python
def expand_idx_mimetype(type_): """Returns long equivalent of type_, if available, otherwise type_ itself. Does not raise exceptions""" if isinstance(type_, unicode_type): match = __IDX_PATTERN.match(type_) return __IDX_MAPPING.get(match.group(1), type_) if match else type_ else: return type_
[ "def", "expand_idx_mimetype", "(", "type_", ")", ":", "if", "isinstance", "(", "type_", ",", "unicode_type", ")", ":", "match", "=", "__IDX_PATTERN", ".", "match", "(", "type_", ")", "return", "__IDX_MAPPING", ".", "get", "(", "match", ".", "group", "(", ...
Returns long equivalent of type_, if available, otherwise type_ itself. Does not raise exceptions
[ "Returns", "long", "equivalent", "of", "type_", "if", "available", "otherwise", "type_", "itself", ".", "Does", "not", "raise", "exceptions" ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/Core/Mime.py#L73-L79
train
38,171
Iotic-Labs/py-IoticAgent
src/IoticAgent/Core/Client.py
Client.restore_event
def restore_event(self, requestId): """restore an event based on the requestId. For example if the user app had to shutdown with pending requests. The user can rebuild the Events they were waiting for based on the requestId(s). """ with self.__requests: if requestId not in self.__requests: self.__requests[requestId] = RequestEvent(requestId) return True return False
python
def restore_event(self, requestId): """restore an event based on the requestId. For example if the user app had to shutdown with pending requests. The user can rebuild the Events they were waiting for based on the requestId(s). """ with self.__requests: if requestId not in self.__requests: self.__requests[requestId] = RequestEvent(requestId) return True return False
[ "def", "restore_event", "(", "self", ",", "requestId", ")", ":", "with", "self", ".", "__requests", ":", "if", "requestId", "not", "in", "self", ".", "__requests", ":", "self", ".", "__requests", "[", "requestId", "]", "=", "RequestEvent", "(", "requestId"...
restore an event based on the requestId. For example if the user app had to shutdown with pending requests. The user can rebuild the Events they were waiting for based on the requestId(s).
[ "restore", "an", "event", "based", "on", "the", "requestId", "." ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/Core/Client.py#L286-L296
train
38,172
Iotic-Labs/py-IoticAgent
src/IoticAgent/Core/Client.py
Client.simulate_feeddata
def simulate_feeddata(self, feedid, data, mime=None, time=None): """Send feed data""" # Separate public method since internal one does not require parameter checks feedid = Validation.guid_check_convert(feedid) mime = Validation.mime_check_convert(mime, allow_none=True) Validation.datetime_check_convert(time, allow_none=True, to_iso8601=False) self.__simulate_feeddata(feedid, data, mime, datetime.utcnow() if time is None else time)
python
def simulate_feeddata(self, feedid, data, mime=None, time=None): """Send feed data""" # Separate public method since internal one does not require parameter checks feedid = Validation.guid_check_convert(feedid) mime = Validation.mime_check_convert(mime, allow_none=True) Validation.datetime_check_convert(time, allow_none=True, to_iso8601=False) self.__simulate_feeddata(feedid, data, mime, datetime.utcnow() if time is None else time)
[ "def", "simulate_feeddata", "(", "self", ",", "feedid", ",", "data", ",", "mime", "=", "None", ",", "time", "=", "None", ")", ":", "# Separate public method since internal one does not require parameter checks", "feedid", "=", "Validation", ".", "guid_check_convert", ...
Send feed data
[ "Send", "feed", "data" ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/Core/Client.py#L393-L399
train
38,173
Iotic-Labs/py-IoticAgent
src/IoticAgent/Core/Client.py
Client.stop
def stop(self): """Stop the Client, disconnect from queue """ if self.__end.is_set(): return self.__end.set() self.__send_retry_requests_timer.cancel() self.__threadpool.stop() self.__crud_threadpool.stop() self.__amqplink.stop() self.__network_retry_thread.join() # Clear out remaining pending requests with self.__requests: shutdown = LinkShutdownException('Client stopped') for req in self.__requests.values(): req.exception = shutdown req._set() self.__clear_references(req, remove_request=False) if self.__requests: logger.warning('%d unfinished request(s) discarded', len(self.__requests)) self.__requests.clear() # self.__network_retry_thread = None self.__network_retry_queue = None self.__container_params = None
python
def stop(self): """Stop the Client, disconnect from queue """ if self.__end.is_set(): return self.__end.set() self.__send_retry_requests_timer.cancel() self.__threadpool.stop() self.__crud_threadpool.stop() self.__amqplink.stop() self.__network_retry_thread.join() # Clear out remaining pending requests with self.__requests: shutdown = LinkShutdownException('Client stopped') for req in self.__requests.values(): req.exception = shutdown req._set() self.__clear_references(req, remove_request=False) if self.__requests: logger.warning('%d unfinished request(s) discarded', len(self.__requests)) self.__requests.clear() # self.__network_retry_thread = None self.__network_retry_queue = None self.__container_params = None
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "__end", ".", "is_set", "(", ")", ":", "return", "self", ".", "__end", ".", "set", "(", ")", "self", ".", "__send_retry_requests_timer", ".", "cancel", "(", ")", "self", ".", "__threadpool", "....
Stop the Client, disconnect from queue
[ "Stop", "the", "Client", "disconnect", "from", "queue" ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/Core/Client.py#L516-L540
train
38,174
Iotic-Labs/py-IoticAgent
src/IoticAgent/Core/Client.py
Client._request
def _request(self, resource, rtype, action=None, payload=None, offset=None, limit=None, requestId=None, is_crud=False): """_request amqp queue publish helper return: RequestEvent object or None for failed to publish """ end = self.__end if end.is_set(): raise LinkShutdownException('Client stopped') rng = None if offset is not None and limit is not None: Validation.limit_offset_check(limit, offset) rng = "%d/%d" % (offset, limit) with self.__requests: if requestId is None: requestId = self.__new_request_id() elif requestId in self.__requests: raise ValueError('requestId %s already in use' % requestId) inner_msg = self.__make_innermsg(resource, rtype, requestId, action, payload, rng) self.__requests[requestId] = ret = RequestEvent(requestId, inner_msg, is_crud=is_crud) # if not self.__retry_enqueue(PreparedMessage(inner_msg, requestId)): raise LinkShutdownException('Client stopping') return ret
python
def _request(self, resource, rtype, action=None, payload=None, offset=None, limit=None, requestId=None, is_crud=False): """_request amqp queue publish helper return: RequestEvent object or None for failed to publish """ end = self.__end if end.is_set(): raise LinkShutdownException('Client stopped') rng = None if offset is not None and limit is not None: Validation.limit_offset_check(limit, offset) rng = "%d/%d" % (offset, limit) with self.__requests: if requestId is None: requestId = self.__new_request_id() elif requestId in self.__requests: raise ValueError('requestId %s already in use' % requestId) inner_msg = self.__make_innermsg(resource, rtype, requestId, action, payload, rng) self.__requests[requestId] = ret = RequestEvent(requestId, inner_msg, is_crud=is_crud) # if not self.__retry_enqueue(PreparedMessage(inner_msg, requestId)): raise LinkShutdownException('Client stopping') return ret
[ "def", "_request", "(", "self", ",", "resource", ",", "rtype", ",", "action", "=", "None", ",", "payload", "=", "None", ",", "offset", "=", "None", ",", "limit", "=", "None", ",", "requestId", "=", "None", ",", "is_crud", "=", "False", ")", ":", "e...
_request amqp queue publish helper return: RequestEvent object or None for failed to publish
[ "_request", "amqp", "queue", "publish", "helper" ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/Core/Client.py#L577-L601
train
38,175
Iotic-Labs/py-IoticAgent
src/IoticAgent/Core/Client.py
Client.__bytes_to_share_data
def __bytes_to_share_data(self, payload): """Attempt to auto-decode data""" rbytes = payload[P_DATA] mime = payload[P_MIME] if mime is None or not self.__auto_encode_decode: return rbytes, mime mime = expand_idx_mimetype(mime).lower() try: if mime == 'application/ubjson': return ubjloadb(rbytes), None elif mime == 'text/plain; charset=utf8': return rbytes.decode('utf-8'), None else: return rbytes, mime except: logger.warning('auto-decode failed, returning bytes', exc_info=DEBUG_ENABLED) return rbytes, mime
python
def __bytes_to_share_data(self, payload): """Attempt to auto-decode data""" rbytes = payload[P_DATA] mime = payload[P_MIME] if mime is None or not self.__auto_encode_decode: return rbytes, mime mime = expand_idx_mimetype(mime).lower() try: if mime == 'application/ubjson': return ubjloadb(rbytes), None elif mime == 'text/plain; charset=utf8': return rbytes.decode('utf-8'), None else: return rbytes, mime except: logger.warning('auto-decode failed, returning bytes', exc_info=DEBUG_ENABLED) return rbytes, mime
[ "def", "__bytes_to_share_data", "(", "self", ",", "payload", ")", ":", "rbytes", "=", "payload", "[", "P_DATA", "]", "mime", "=", "payload", "[", "P_MIME", "]", "if", "mime", "is", "None", "or", "not", "self", ".", "__auto_encode_decode", ":", "return", ...
Attempt to auto-decode data
[ "Attempt", "to", "auto", "-", "decode", "data" ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/Core/Client.py#L960-L977
train
38,176
Iotic-Labs/py-IoticAgent
src/IoticAgent/Core/Client.py
Client.__make_hash
def __make_hash(cls, innermsg, token, seqnum): """return the hash for this innermsg, token, seqnum return digest bytes """ hobj = hmacNew(token, digestmod=hashfunc) hobj.update(innermsg) hobj.update(cls.__byte_packer(seqnum)) return hobj.digest()
python
def __make_hash(cls, innermsg, token, seqnum): """return the hash for this innermsg, token, seqnum return digest bytes """ hobj = hmacNew(token, digestmod=hashfunc) hobj.update(innermsg) hobj.update(cls.__byte_packer(seqnum)) return hobj.digest()
[ "def", "__make_hash", "(", "cls", ",", "innermsg", ",", "token", ",", "seqnum", ")", ":", "hobj", "=", "hmacNew", "(", "token", ",", "digestmod", "=", "hashfunc", ")", "hobj", ".", "update", "(", "innermsg", ")", "hobj", ".", "update", "(", "cls", "....
return the hash for this innermsg, token, seqnum return digest bytes
[ "return", "the", "hash", "for", "this", "innermsg", "token", "seqnum", "return", "digest", "bytes" ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/Core/Client.py#L1069-L1076
train
38,177
Iotic-Labs/py-IoticAgent
src/IoticAgent/Core/Client.py
Client.__request_mark_sent
def __request_mark_sent(self, requestId): """Set send time & clear exception from request if set, ignoring non-existent requests""" with self.__requests: try: req = self.__requests[requestId] except KeyError: # request might have had a response already have been removed by receiving thread pass else: req.exception = None req._send_time = monotonic()
python
def __request_mark_sent(self, requestId): """Set send time & clear exception from request if set, ignoring non-existent requests""" with self.__requests: try: req = self.__requests[requestId] except KeyError: # request might have had a response already have been removed by receiving thread pass else: req.exception = None req._send_time = monotonic()
[ "def", "__request_mark_sent", "(", "self", ",", "requestId", ")", ":", "with", "self", ".", "__requests", ":", "try", ":", "req", "=", "self", ".", "__requests", "[", "requestId", "]", "except", "KeyError", ":", "# request might have had a response already have be...
Set send time & clear exception from request if set, ignoring non-existent requests
[ "Set", "send", "time", "&", "clear", "exception", "from", "request", "if", "set", "ignoring", "non", "-", "existent", "requests" ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/Core/Client.py#L1117-L1127
train
38,178
Iotic-Labs/py-IoticAgent
src/IoticAgent/Core/Client.py
Client.__fire_callback
def __fire_callback(self, type_, *args, **kwargs): """Returns True if at least one callback was called""" called = False plain_submit = self.__threadpool.submit with self.__callbacks: submit = self.__crud_threadpool.submit if type_ in _CB_CRUD_TYPES else plain_submit for func, serialised_if_crud in self.__callbacks[type_]: called = True # allow CRUD callbacks to not be serialised if requested (submit if serialised_if_crud else plain_submit)(func, *args, **kwargs) return called
python
def __fire_callback(self, type_, *args, **kwargs): """Returns True if at least one callback was called""" called = False plain_submit = self.__threadpool.submit with self.__callbacks: submit = self.__crud_threadpool.submit if type_ in _CB_CRUD_TYPES else plain_submit for func, serialised_if_crud in self.__callbacks[type_]: called = True # allow CRUD callbacks to not be serialised if requested (submit if serialised_if_crud else plain_submit)(func, *args, **kwargs) return called
[ "def", "__fire_callback", "(", "self", ",", "type_", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "called", "=", "False", "plain_submit", "=", "self", ".", "__threadpool", ".", "submit", "with", "self", ".", "__callbacks", ":", "submit", "=", "...
Returns True if at least one callback was called
[ "Returns", "True", "if", "at", "least", "one", "callback", "was", "called" ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/Core/Client.py#L1225-L1235
train
38,179
Iotic-Labs/py-IoticAgent
src/IoticAgent/Core/Client.py
Client.__handle_known_solicited
def __handle_known_solicited(self, msg): """returns True if message has been handled as a solicited response""" with self.__requests: try: req = self.__requests[msg[M_CLIENTREF]] except KeyError: return False if self.__handle_low_seq_resend(msg, req): return True perform_cb = finish = False if msg[M_TYPE] not in _RSP_NO_REF: self.__update_existing(msg, req) # Finalise request if applicable (not marked as finished here so can perform callback first below) if msg[M_TYPE] in _RSP_TYPE_FINISH: finish = True # Exception - DUPLICATED also should produce callback perform_cb = (msg[M_TYPE] == E_DUPLICATED) elif msg[M_TYPE] not in _RSP_TYPE_ONGOING: perform_cb = True else: logger.warning('Reference unexpected for request %s of type %s', msg[M_CLIENTREF], msg[M_TYPE]) # outside lock to avoid deadlock if callbacks try to perform request-related functions if perform_cb: self.__perform_unsolicited_callbacks(msg) # mark request as finished if finish: req.success = msg[M_TYPE] in _RSP_TYPE_SUCCESS req.payload = msg[M_PAYLOAD] self.__clear_references(req) # Serialise completion of CRUD requests (together with CREATED, DELETED, etc. messages) if req.is_crud: self.__crud_threadpool.submit(req._set) else: req._set() return True
python
def __handle_known_solicited(self, msg): """returns True if message has been handled as a solicited response""" with self.__requests: try: req = self.__requests[msg[M_CLIENTREF]] except KeyError: return False if self.__handle_low_seq_resend(msg, req): return True perform_cb = finish = False if msg[M_TYPE] not in _RSP_NO_REF: self.__update_existing(msg, req) # Finalise request if applicable (not marked as finished here so can perform callback first below) if msg[M_TYPE] in _RSP_TYPE_FINISH: finish = True # Exception - DUPLICATED also should produce callback perform_cb = (msg[M_TYPE] == E_DUPLICATED) elif msg[M_TYPE] not in _RSP_TYPE_ONGOING: perform_cb = True else: logger.warning('Reference unexpected for request %s of type %s', msg[M_CLIENTREF], msg[M_TYPE]) # outside lock to avoid deadlock if callbacks try to perform request-related functions if perform_cb: self.__perform_unsolicited_callbacks(msg) # mark request as finished if finish: req.success = msg[M_TYPE] in _RSP_TYPE_SUCCESS req.payload = msg[M_PAYLOAD] self.__clear_references(req) # Serialise completion of CRUD requests (together with CREATED, DELETED, etc. messages) if req.is_crud: self.__crud_threadpool.submit(req._set) else: req._set() return True
[ "def", "__handle_known_solicited", "(", "self", ",", "msg", ")", ":", "with", "self", ".", "__requests", ":", "try", ":", "req", "=", "self", ".", "__requests", "[", "msg", "[", "M_CLIENTREF", "]", "]", "except", "KeyError", ":", "return", "False", "if",...
returns True if message has been handled as a solicited response
[ "returns", "True", "if", "message", "has", "been", "handled", "as", "a", "solicited", "response" ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/Core/Client.py#L1358-L1398
train
38,180
Iotic-Labs/py-IoticAgent
src/IoticAgent/Core/Client.py
Client.__clear_references
def __clear_references(self, request, remove_request=True): """Remove any internal references to the given request""" # remove request itself if remove_request: with self.__requests: self.__requests.pop(request.id_) # remove request type specific references if not request.success: with self.__pending_subs: self.__pending_subs.pop(request.id_, None) with self.__pending_controls: self.__pending_controls.pop(request.id_, None)
python
def __clear_references(self, request, remove_request=True): """Remove any internal references to the given request""" # remove request itself if remove_request: with self.__requests: self.__requests.pop(request.id_) # remove request type specific references if not request.success: with self.__pending_subs: self.__pending_subs.pop(request.id_, None) with self.__pending_controls: self.__pending_controls.pop(request.id_, None)
[ "def", "__clear_references", "(", "self", ",", "request", ",", "remove_request", "=", "True", ")", ":", "# remove request itself", "if", "remove_request", ":", "with", "self", ".", "__requests", ":", "self", ".", "__requests", ".", "pop", "(", "request", ".", ...
Remove any internal references to the given request
[ "Remove", "any", "internal", "references", "to", "the", "given", "request" ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/Core/Client.py#L1400-L1411
train
38,181
Iotic-Labs/py-IoticAgent
src/IoticAgent/Core/Client.py
Client.__perform_unsolicited_callbacks
def __perform_unsolicited_callbacks(self, msg): """Callbacks for which a client reference is either optional or does not apply at all""" type_ = msg[M_TYPE] payload = msg[M_PAYLOAD] # callbacks for responses which might be unsolicited (e.g. created or deleted) if type_ in _RSP_PAYLOAD_CB_MAPPING: self.__fire_callback(_RSP_PAYLOAD_CB_MAPPING[type_], msg) # Perform callbacks for feed data elif type_ == E_FEEDDATA: self.__simulate_feeddata(payload[P_FEED_ID], *self.__decode_data_time(payload)) # Perform callbacks for unsolicited subscriber message elif type_ == E_SUBSCRIBED: self.__fire_callback(_CB_SUBSCRIPTION, payload) else: logger.error('Unexpected message type for unsolicited callback %s', type_)
python
def __perform_unsolicited_callbacks(self, msg): """Callbacks for which a client reference is either optional or does not apply at all""" type_ = msg[M_TYPE] payload = msg[M_PAYLOAD] # callbacks for responses which might be unsolicited (e.g. created or deleted) if type_ in _RSP_PAYLOAD_CB_MAPPING: self.__fire_callback(_RSP_PAYLOAD_CB_MAPPING[type_], msg) # Perform callbacks for feed data elif type_ == E_FEEDDATA: self.__simulate_feeddata(payload[P_FEED_ID], *self.__decode_data_time(payload)) # Perform callbacks for unsolicited subscriber message elif type_ == E_SUBSCRIBED: self.__fire_callback(_CB_SUBSCRIPTION, payload) else: logger.error('Unexpected message type for unsolicited callback %s', type_)
[ "def", "__perform_unsolicited_callbacks", "(", "self", ",", "msg", ")", ":", "type_", "=", "msg", "[", "M_TYPE", "]", "payload", "=", "msg", "[", "M_PAYLOAD", "]", "# callbacks for responses which might be unsolicited (e.g. created or deleted)", "if", "type_", "in", "...
Callbacks for which a client reference is either optional or does not apply at all
[ "Callbacks", "for", "which", "a", "client", "reference", "is", "either", "optional", "or", "does", "not", "apply", "at", "all" ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/Core/Client.py#L1471-L1489
train
38,182
tophatmonocle/ims_lti_py
ims_lti_py/launch_params.py
LaunchParamsMixin.roles
def roles(self, roles_list): ''' Set the roles for the current launch. Full list of roles can be found here: http://www.imsglobal.org/LTI/v1p1/ltiIMGv1p1.html#_Toc319560479 LIS roles include: * Student * Faculty * Member * Learner * Instructor * Mentor * Staff * Alumni * ProspectiveStudent * Guest * Other * Administrator * Observer * None ''' if roles_list and isinstance(roles_list, list): self.roles = [].extend(roles_list) elif roles_list and isinstance(roles_list, basestring): self.roles = [role.lower() for role in roles_list.split(',')]
python
def roles(self, roles_list): ''' Set the roles for the current launch. Full list of roles can be found here: http://www.imsglobal.org/LTI/v1p1/ltiIMGv1p1.html#_Toc319560479 LIS roles include: * Student * Faculty * Member * Learner * Instructor * Mentor * Staff * Alumni * ProspectiveStudent * Guest * Other * Administrator * Observer * None ''' if roles_list and isinstance(roles_list, list): self.roles = [].extend(roles_list) elif roles_list and isinstance(roles_list, basestring): self.roles = [role.lower() for role in roles_list.split(',')]
[ "def", "roles", "(", "self", ",", "roles_list", ")", ":", "if", "roles_list", "and", "isinstance", "(", "roles_list", ",", "list", ")", ":", "self", ".", "roles", "=", "[", "]", ".", "extend", "(", "roles_list", ")", "elif", "roles_list", "and", "isins...
Set the roles for the current launch. Full list of roles can be found here: http://www.imsglobal.org/LTI/v1p1/ltiIMGv1p1.html#_Toc319560479 LIS roles include: * Student * Faculty * Member * Learner * Instructor * Mentor * Staff * Alumni * ProspectiveStudent * Guest * Other * Administrator * Observer * None
[ "Set", "the", "roles", "for", "the", "current", "launch", "." ]
979244d83c2e6420d2c1941f58e52f641c56ad12
https://github.com/tophatmonocle/ims_lti_py/blob/979244d83c2e6420d2c1941f58e52f641c56ad12/ims_lti_py/launch_params.py#L71-L97
train
38,183
tophatmonocle/ims_lti_py
ims_lti_py/launch_params.py
LaunchParamsMixin.process_params
def process_params(self, params): ''' Populates the launch data from a dictionary. Only cares about keys in the LAUNCH_DATA_PARAMETERS list, or that start with 'custom_' or 'ext_'. ''' for key, val in params.items(): if key in LAUNCH_DATA_PARAMETERS and val != 'None': if key == 'roles': if isinstance(val, list): # If it's already a list, no need to parse self.roles = list(val) else: # If it's a ',' delimited string, split self.roles = val.split(',') else: setattr(self, key, touni(val)) elif 'custom_' in key: self.custom_params[key] = touni(val) elif 'ext_' in key: self.ext_params[key] = touni(val)
python
def process_params(self, params): ''' Populates the launch data from a dictionary. Only cares about keys in the LAUNCH_DATA_PARAMETERS list, or that start with 'custom_' or 'ext_'. ''' for key, val in params.items(): if key in LAUNCH_DATA_PARAMETERS and val != 'None': if key == 'roles': if isinstance(val, list): # If it's already a list, no need to parse self.roles = list(val) else: # If it's a ',' delimited string, split self.roles = val.split(',') else: setattr(self, key, touni(val)) elif 'custom_' in key: self.custom_params[key] = touni(val) elif 'ext_' in key: self.ext_params[key] = touni(val)
[ "def", "process_params", "(", "self", ",", "params", ")", ":", "for", "key", ",", "val", "in", "params", ".", "items", "(", ")", ":", "if", "key", "in", "LAUNCH_DATA_PARAMETERS", "and", "val", "!=", "'None'", ":", "if", "key", "==", "'roles'", ":", "...
Populates the launch data from a dictionary. Only cares about keys in the LAUNCH_DATA_PARAMETERS list, or that start with 'custom_' or 'ext_'.
[ "Populates", "the", "launch", "data", "from", "a", "dictionary", ".", "Only", "cares", "about", "keys", "in", "the", "LAUNCH_DATA_PARAMETERS", "list", "or", "that", "start", "with", "custom_", "or", "ext_", "." ]
979244d83c2e6420d2c1941f58e52f641c56ad12
https://github.com/tophatmonocle/ims_lti_py/blob/979244d83c2e6420d2c1941f58e52f641c56ad12/ims_lti_py/launch_params.py#L99-L119
train
38,184
Iotic-Labs/py-IoticAgent
src/IoticAgent/ThingRunner.py
ThingRunner.run
def run(self, background=False): """Runs `on_startup`, `main` and `on_shutdown`, blocking until finished, unless background is set.""" if self.__bgthread: raise Exception('run has already been called (since last stop)') self.__shutdown.clear() if background: self.__bgthread = Thread(target=self.__run, name=('bg_' + self.__client.agent_id)) self.__bgthread.daemon = True self.__bgthread.start() else: self.__run()
python
def run(self, background=False): """Runs `on_startup`, `main` and `on_shutdown`, blocking until finished, unless background is set.""" if self.__bgthread: raise Exception('run has already been called (since last stop)') self.__shutdown.clear() if background: self.__bgthread = Thread(target=self.__run, name=('bg_' + self.__client.agent_id)) self.__bgthread.daemon = True self.__bgthread.start() else: self.__run()
[ "def", "run", "(", "self", ",", "background", "=", "False", ")", ":", "if", "self", ".", "__bgthread", ":", "raise", "Exception", "(", "'run has already been called (since last stop)'", ")", "self", ".", "__shutdown", ".", "clear", "(", ")", "if", "background"...
Runs `on_startup`, `main` and `on_shutdown`, blocking until finished, unless background is set.
[ "Runs", "on_startup", "main", "and", "on_shutdown", "blocking", "until", "finished", "unless", "background", "is", "set", "." ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/ThingRunner.py#L73-L83
train
38,185
edx/edx-django-utils
edx_django_utils/monitoring/middleware.py
MonitoringCustomMetricsMiddleware._batch_report
def _batch_report(cls, request): """ Report the collected custom metrics to New Relic. """ if not newrelic: return metrics_cache = cls._get_metrics_cache() try: newrelic.agent.add_custom_parameter('user_id', request.user.id) except AttributeError: pass for key, value in metrics_cache.data.items(): newrelic.agent.add_custom_parameter(key, value)
python
def _batch_report(cls, request): """ Report the collected custom metrics to New Relic. """ if not newrelic: return metrics_cache = cls._get_metrics_cache() try: newrelic.agent.add_custom_parameter('user_id', request.user.id) except AttributeError: pass for key, value in metrics_cache.data.items(): newrelic.agent.add_custom_parameter(key, value)
[ "def", "_batch_report", "(", "cls", ",", "request", ")", ":", "if", "not", "newrelic", ":", "return", "metrics_cache", "=", "cls", ".", "_get_metrics_cache", "(", ")", "try", ":", "newrelic", ".", "agent", ".", "add_custom_parameter", "(", "'user_id'", ",", ...
Report the collected custom metrics to New Relic.
[ "Report", "the", "collected", "custom", "metrics", "to", "New", "Relic", "." ]
16cb4ac617e53c572bf68ccd19d24afeff1ca769
https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/monitoring/middleware.py#L66-L78
train
38,186
edx/edx-django-utils
edx_django_utils/monitoring/middleware.py
MonitoringMemoryMiddleware.process_request
def process_request(self, request): """ Store memory data to log later. """ if self._is_enabled(): self._cache.set(self.guid_key, six.text_type(uuid4())) log_prefix = self._log_prefix(u"Before", request) self._cache.set(self.memory_data_key, self._memory_data(log_prefix))
python
def process_request(self, request): """ Store memory data to log later. """ if self._is_enabled(): self._cache.set(self.guid_key, six.text_type(uuid4())) log_prefix = self._log_prefix(u"Before", request) self._cache.set(self.memory_data_key, self._memory_data(log_prefix))
[ "def", "process_request", "(", "self", ",", "request", ")", ":", "if", "self", ".", "_is_enabled", "(", ")", ":", "self", ".", "_cache", ".", "set", "(", "self", ".", "guid_key", ",", "six", ".", "text_type", "(", "uuid4", "(", ")", ")", ")", "log_...
Store memory data to log later.
[ "Store", "memory", "data", "to", "log", "later", "." ]
16cb4ac617e53c572bf68ccd19d24afeff1ca769
https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/monitoring/middleware.py#L115-L122
train
38,187
edx/edx-django-utils
edx_django_utils/monitoring/middleware.py
MonitoringMemoryMiddleware.process_response
def process_response(self, request, response): """ Logs memory data after processing response. """ if self._is_enabled(): log_prefix = self._log_prefix(u"After", request) new_memory_data = self._memory_data(log_prefix) log_prefix = self._log_prefix(u"Diff", request) cached_memory_data_response = self._cache.get_cached_response(self.memory_data_key) old_memory_data = cached_memory_data_response.get_value_or_default(None) self._log_diff_memory_data(log_prefix, new_memory_data, old_memory_data) return response
python
def process_response(self, request, response): """ Logs memory data after processing response. """ if self._is_enabled(): log_prefix = self._log_prefix(u"After", request) new_memory_data = self._memory_data(log_prefix) log_prefix = self._log_prefix(u"Diff", request) cached_memory_data_response = self._cache.get_cached_response(self.memory_data_key) old_memory_data = cached_memory_data_response.get_value_or_default(None) self._log_diff_memory_data(log_prefix, new_memory_data, old_memory_data) return response
[ "def", "process_response", "(", "self", ",", "request", ",", "response", ")", ":", "if", "self", ".", "_is_enabled", "(", ")", ":", "log_prefix", "=", "self", ".", "_log_prefix", "(", "u\"After\"", ",", "request", ")", "new_memory_data", "=", "self", ".", ...
Logs memory data after processing response.
[ "Logs", "memory", "data", "after", "processing", "response", "." ]
16cb4ac617e53c572bf68ccd19d24afeff1ca769
https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/monitoring/middleware.py#L124-L136
train
38,188
edx/edx-django-utils
edx_django_utils/monitoring/middleware.py
MonitoringMemoryMiddleware._log_prefix
def _log_prefix(self, prefix, request): """ Returns a formatted prefix for logging for the given request. """ # After a celery task runs, the request cache is cleared. So if celery # tasks are running synchronously (CELERY_ALWAYS _EAGER), "guid_key" # will no longer be in the request cache when process_response executes. cached_guid_response = self._cache.get_cached_response(self.guid_key) cached_guid = cached_guid_response.get_value_or_default(u"without_guid") return u"{} request '{} {} {}'".format(prefix, request.method, request.path, cached_guid)
python
def _log_prefix(self, prefix, request): """ Returns a formatted prefix for logging for the given request. """ # After a celery task runs, the request cache is cleared. So if celery # tasks are running synchronously (CELERY_ALWAYS _EAGER), "guid_key" # will no longer be in the request cache when process_response executes. cached_guid_response = self._cache.get_cached_response(self.guid_key) cached_guid = cached_guid_response.get_value_or_default(u"without_guid") return u"{} request '{} {} {}'".format(prefix, request.method, request.path, cached_guid)
[ "def", "_log_prefix", "(", "self", ",", "prefix", ",", "request", ")", ":", "# After a celery task runs, the request cache is cleared. So if celery", "# tasks are running synchronously (CELERY_ALWAYS _EAGER), \"guid_key\"", "# will no longer be in the request cache when process_response exec...
Returns a formatted prefix for logging for the given request.
[ "Returns", "a", "formatted", "prefix", "for", "logging", "for", "the", "given", "request", "." ]
16cb4ac617e53c572bf68ccd19d24afeff1ca769
https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/monitoring/middleware.py#L145-L154
train
38,189
edx/edx-django-utils
edx_django_utils/monitoring/middleware.py
MonitoringMemoryMiddleware._memory_data
def _memory_data(self, log_prefix): """ Returns a dict with information for current memory utilization. Uses log_prefix in log statements. """ machine_data = psutil.virtual_memory() process = psutil.Process() process_data = { 'memory_info': process.get_memory_info(), 'ext_memory_info': process.get_ext_memory_info(), 'memory_percent': process.get_memory_percent(), 'cpu_percent': process.get_cpu_percent(), } log.info(u"%s Machine memory usage: %s; Process memory usage: %s", log_prefix, machine_data, process_data) return { 'machine_data': machine_data, 'process_data': process_data, }
python
def _memory_data(self, log_prefix): """ Returns a dict with information for current memory utilization. Uses log_prefix in log statements. """ machine_data = psutil.virtual_memory() process = psutil.Process() process_data = { 'memory_info': process.get_memory_info(), 'ext_memory_info': process.get_ext_memory_info(), 'memory_percent': process.get_memory_percent(), 'cpu_percent': process.get_cpu_percent(), } log.info(u"%s Machine memory usage: %s; Process memory usage: %s", log_prefix, machine_data, process_data) return { 'machine_data': machine_data, 'process_data': process_data, }
[ "def", "_memory_data", "(", "self", ",", "log_prefix", ")", ":", "machine_data", "=", "psutil", ".", "virtual_memory", "(", ")", "process", "=", "psutil", ".", "Process", "(", ")", "process_data", "=", "{", "'memory_info'", ":", "process", ".", "get_memory_i...
Returns a dict with information for current memory utilization. Uses log_prefix in log statements.
[ "Returns", "a", "dict", "with", "information", "for", "current", "memory", "utilization", ".", "Uses", "log_prefix", "in", "log", "statements", "." ]
16cb4ac617e53c572bf68ccd19d24afeff1ca769
https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/monitoring/middleware.py#L156-L175
train
38,190
edx/edx-django-utils
edx_django_utils/monitoring/middleware.py
MonitoringMemoryMiddleware._log_diff_memory_data
def _log_diff_memory_data(self, prefix, new_memory_data, old_memory_data): """ Computes and logs the difference in memory utilization between the given old and new memory data. """ def _vmem_used(memory_data): return memory_data['machine_data'].used def _process_mem_percent(memory_data): return memory_data['process_data']['memory_percent'] def _process_rss(memory_data): return memory_data['process_data']['memory_info'].rss def _process_vms(memory_data): return memory_data['process_data']['memory_info'].vms if new_memory_data and old_memory_data: log.info( u"%s Diff Vmem used: %s, Diff percent memory: %s, Diff rss: %s, Diff vms: %s", prefix, _vmem_used(new_memory_data) - _vmem_used(old_memory_data), _process_mem_percent(new_memory_data) - _process_mem_percent(old_memory_data), _process_rss(new_memory_data) - _process_rss(old_memory_data), _process_vms(new_memory_data) - _process_vms(old_memory_data), )
python
def _log_diff_memory_data(self, prefix, new_memory_data, old_memory_data): """ Computes and logs the difference in memory utilization between the given old and new memory data. """ def _vmem_used(memory_data): return memory_data['machine_data'].used def _process_mem_percent(memory_data): return memory_data['process_data']['memory_percent'] def _process_rss(memory_data): return memory_data['process_data']['memory_info'].rss def _process_vms(memory_data): return memory_data['process_data']['memory_info'].vms if new_memory_data and old_memory_data: log.info( u"%s Diff Vmem used: %s, Diff percent memory: %s, Diff rss: %s, Diff vms: %s", prefix, _vmem_used(new_memory_data) - _vmem_used(old_memory_data), _process_mem_percent(new_memory_data) - _process_mem_percent(old_memory_data), _process_rss(new_memory_data) - _process_rss(old_memory_data), _process_vms(new_memory_data) - _process_vms(old_memory_data), )
[ "def", "_log_diff_memory_data", "(", "self", ",", "prefix", ",", "new_memory_data", ",", "old_memory_data", ")", ":", "def", "_vmem_used", "(", "memory_data", ")", ":", "return", "memory_data", "[", "'machine_data'", "]", ".", "used", "def", "_process_mem_percent"...
Computes and logs the difference in memory utilization between the given old and new memory data.
[ "Computes", "and", "logs", "the", "difference", "in", "memory", "utilization", "between", "the", "given", "old", "and", "new", "memory", "data", "." ]
16cb4ac617e53c572bf68ccd19d24afeff1ca769
https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/monitoring/middleware.py#L177-L202
train
38,191
edx/edx-django-utils
edx_django_utils/cache/utils.py
TieredCache.set_all_tiers
def set_all_tiers(key, value, django_cache_timeout=DEFAULT_TIMEOUT): """ Caches the value for the provided key in both the request cache and the django cache. Args: key (string) value (object) django_cache_timeout (int): (Optional) Timeout used to determine if and for how long to cache in the django cache. A timeout of 0 will skip the django cache. If timeout is provided, use that timeout for the key; otherwise use the default cache timeout. """ DEFAULT_REQUEST_CACHE.set(key, value) django_cache.set(key, value, django_cache_timeout)
python
def set_all_tiers(key, value, django_cache_timeout=DEFAULT_TIMEOUT): """ Caches the value for the provided key in both the request cache and the django cache. Args: key (string) value (object) django_cache_timeout (int): (Optional) Timeout used to determine if and for how long to cache in the django cache. A timeout of 0 will skip the django cache. If timeout is provided, use that timeout for the key; otherwise use the default cache timeout. """ DEFAULT_REQUEST_CACHE.set(key, value) django_cache.set(key, value, django_cache_timeout)
[ "def", "set_all_tiers", "(", "key", ",", "value", ",", "django_cache_timeout", "=", "DEFAULT_TIMEOUT", ")", ":", "DEFAULT_REQUEST_CACHE", ".", "set", "(", "key", ",", "value", ")", "django_cache", ".", "set", "(", "key", ",", "value", ",", "django_cache_timeou...
Caches the value for the provided key in both the request cache and the django cache. Args: key (string) value (object) django_cache_timeout (int): (Optional) Timeout used to determine if and for how long to cache in the django cache. A timeout of 0 will skip the django cache. If timeout is provided, use that timeout for the key; otherwise use the default cache timeout.
[ "Caches", "the", "value", "for", "the", "provided", "key", "in", "both", "the", "request", "cache", "and", "the", "django", "cache", "." ]
16cb4ac617e53c572bf68ccd19d24afeff1ca769
https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/cache/utils.py#L172-L187
train
38,192
edx/edx-django-utils
edx_django_utils/cache/utils.py
TieredCache._get_cached_response_from_django_cache
def _get_cached_response_from_django_cache(key): """ Retrieves a CachedResponse for the given key from the django cache. If the request was set to force cache misses, then this will always return a cache miss response. Args: key (string) Returns: A CachedResponse with is_found status and value. """ if TieredCache._should_force_django_cache_miss(): return CachedResponse(is_found=False, key=key, value=None) cached_value = django_cache.get(key, _CACHE_MISS) is_found = cached_value is not _CACHE_MISS return CachedResponse(is_found, key, cached_value)
python
def _get_cached_response_from_django_cache(key): """ Retrieves a CachedResponse for the given key from the django cache. If the request was set to force cache misses, then this will always return a cache miss response. Args: key (string) Returns: A CachedResponse with is_found status and value. """ if TieredCache._should_force_django_cache_miss(): return CachedResponse(is_found=False, key=key, value=None) cached_value = django_cache.get(key, _CACHE_MISS) is_found = cached_value is not _CACHE_MISS return CachedResponse(is_found, key, cached_value)
[ "def", "_get_cached_response_from_django_cache", "(", "key", ")", ":", "if", "TieredCache", ".", "_should_force_django_cache_miss", "(", ")", ":", "return", "CachedResponse", "(", "is_found", "=", "False", ",", "key", "=", "key", ",", "value", "=", "None", ")", ...
Retrieves a CachedResponse for the given key from the django cache. If the request was set to force cache misses, then this will always return a cache miss response. Args: key (string) Returns: A CachedResponse with is_found status and value.
[ "Retrieves", "a", "CachedResponse", "for", "the", "given", "key", "from", "the", "django", "cache", "." ]
16cb4ac617e53c572bf68ccd19d24afeff1ca769
https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/cache/utils.py#L218-L237
train
38,193
edx/edx-django-utils
edx_django_utils/cache/utils.py
TieredCache._set_request_cache_if_django_cache_hit
def _set_request_cache_if_django_cache_hit(key, django_cached_response): """ Sets the value in the request cache if the django cached response was a hit. Args: key (string) django_cached_response (CachedResponse) """ if django_cached_response.is_found: DEFAULT_REQUEST_CACHE.set(key, django_cached_response.value)
python
def _set_request_cache_if_django_cache_hit(key, django_cached_response): """ Sets the value in the request cache if the django cached response was a hit. Args: key (string) django_cached_response (CachedResponse) """ if django_cached_response.is_found: DEFAULT_REQUEST_CACHE.set(key, django_cached_response.value)
[ "def", "_set_request_cache_if_django_cache_hit", "(", "key", ",", "django_cached_response", ")", ":", "if", "django_cached_response", ".", "is_found", ":", "DEFAULT_REQUEST_CACHE", ".", "set", "(", "key", ",", "django_cached_response", ".", "value", ")" ]
Sets the value in the request cache if the django cached response was a hit. Args: key (string) django_cached_response (CachedResponse)
[ "Sets", "the", "value", "in", "the", "request", "cache", "if", "the", "django", "cached", "response", "was", "a", "hit", "." ]
16cb4ac617e53c572bf68ccd19d24afeff1ca769
https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/cache/utils.py#L240-L250
train
38,194
edx/edx-django-utils
edx_django_utils/cache/utils.py
TieredCache._get_and_set_force_cache_miss
def _get_and_set_force_cache_miss(request): """ Gets value for request query parameter FORCE_CACHE_MISS and sets it in the default request cache. This functionality is only available for staff. Example: http://clobert.com/api/v1/resource?force_cache_miss=true """ if not (request.user and request.user.is_active and request.user.is_staff): force_cache_miss = False else: force_cache_miss = request.GET.get(FORCE_CACHE_MISS_PARAM, 'false').lower() == 'true' DEFAULT_REQUEST_CACHE.set(SHOULD_FORCE_CACHE_MISS_KEY, force_cache_miss)
python
def _get_and_set_force_cache_miss(request): """ Gets value for request query parameter FORCE_CACHE_MISS and sets it in the default request cache. This functionality is only available for staff. Example: http://clobert.com/api/v1/resource?force_cache_miss=true """ if not (request.user and request.user.is_active and request.user.is_staff): force_cache_miss = False else: force_cache_miss = request.GET.get(FORCE_CACHE_MISS_PARAM, 'false').lower() == 'true' DEFAULT_REQUEST_CACHE.set(SHOULD_FORCE_CACHE_MISS_KEY, force_cache_miss)
[ "def", "_get_and_set_force_cache_miss", "(", "request", ")", ":", "if", "not", "(", "request", ".", "user", "and", "request", ".", "user", ".", "is_active", "and", "request", ".", "user", ".", "is_staff", ")", ":", "force_cache_miss", "=", "False", "else", ...
Gets value for request query parameter FORCE_CACHE_MISS and sets it in the default request cache. This functionality is only available for staff. Example: http://clobert.com/api/v1/resource?force_cache_miss=true
[ "Gets", "value", "for", "request", "query", "parameter", "FORCE_CACHE_MISS", "and", "sets", "it", "in", "the", "default", "request", "cache", "." ]
16cb4ac617e53c572bf68ccd19d24afeff1ca769
https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/cache/utils.py#L253-L268
train
38,195
edx/edx-django-utils
edx_django_utils/cache/utils.py
TieredCache._should_force_django_cache_miss
def _should_force_django_cache_miss(cls): """ Returns True if the tiered cache should force a cache miss for the django cache, and False otherwise. """ cached_response = DEFAULT_REQUEST_CACHE.get_cached_response(SHOULD_FORCE_CACHE_MISS_KEY) return False if not cached_response.is_found else cached_response.value
python
def _should_force_django_cache_miss(cls): """ Returns True if the tiered cache should force a cache miss for the django cache, and False otherwise. """ cached_response = DEFAULT_REQUEST_CACHE.get_cached_response(SHOULD_FORCE_CACHE_MISS_KEY) return False if not cached_response.is_found else cached_response.value
[ "def", "_should_force_django_cache_miss", "(", "cls", ")", ":", "cached_response", "=", "DEFAULT_REQUEST_CACHE", ".", "get_cached_response", "(", "SHOULD_FORCE_CACHE_MISS_KEY", ")", "return", "False", "if", "not", "cached_response", ".", "is_found", "else", "cached_respon...
Returns True if the tiered cache should force a cache miss for the django cache, and False otherwise.
[ "Returns", "True", "if", "the", "tiered", "cache", "should", "force", "a", "cache", "miss", "for", "the", "django", "cache", "and", "False", "otherwise", "." ]
16cb4ac617e53c572bf68ccd19d24afeff1ca769
https://github.com/edx/edx-django-utils/blob/16cb4ac617e53c572bf68ccd19d24afeff1ca769/edx_django_utils/cache/utils.py#L271-L278
train
38,196
Iotic-Labs/py-IoticAgent
src/IoticAgent/Core/Validation.py
Validation.check_convert_string
def check_convert_string(obj, name=None, no_leading_trailing_whitespace=True, no_whitespace=False, no_newline=True, whole_word=False, min_len=1, max_len=0): """Ensures the provided object can be interpreted as a unicode string, optionally with additional restrictions imposed. By default this means a non-zero length string which does not begin or end in whitespace.""" if not name: name = 'Argument' obj = ensure_unicode(obj, name=name) if no_whitespace: if _PATTERN_WHITESPACE.match(obj): raise ValueError('%s cannot contain whitespace' % name) elif no_leading_trailing_whitespace and _PATTERN_LEAD_TRAIL_WHITESPACE.match(obj): raise ValueError('%s contains leading/trailing whitespace' % name) if (min_len and len(obj) < min_len) or (max_len and len(obj) > max_len): raise ValueError('%s too short/long (%d/%d)' % (name, min_len, max_len)) if whole_word: if not _PATTERN_WORD.match(obj): raise ValueError('%s can only contain alphanumeric (unicode) characters, numbers and the underscore' % name) # whole words cannot contain newline so additional check not required elif no_newline and '\n' in obj: raise ValueError('%s cannot contain line breaks' % name) return obj
python
def check_convert_string(obj, name=None, no_leading_trailing_whitespace=True, no_whitespace=False, no_newline=True, whole_word=False, min_len=1, max_len=0): """Ensures the provided object can be interpreted as a unicode string, optionally with additional restrictions imposed. By default this means a non-zero length string which does not begin or end in whitespace.""" if not name: name = 'Argument' obj = ensure_unicode(obj, name=name) if no_whitespace: if _PATTERN_WHITESPACE.match(obj): raise ValueError('%s cannot contain whitespace' % name) elif no_leading_trailing_whitespace and _PATTERN_LEAD_TRAIL_WHITESPACE.match(obj): raise ValueError('%s contains leading/trailing whitespace' % name) if (min_len and len(obj) < min_len) or (max_len and len(obj) > max_len): raise ValueError('%s too short/long (%d/%d)' % (name, min_len, max_len)) if whole_word: if not _PATTERN_WORD.match(obj): raise ValueError('%s can only contain alphanumeric (unicode) characters, numbers and the underscore' % name) # whole words cannot contain newline so additional check not required elif no_newline and '\n' in obj: raise ValueError('%s cannot contain line breaks' % name) return obj
[ "def", "check_convert_string", "(", "obj", ",", "name", "=", "None", ",", "no_leading_trailing_whitespace", "=", "True", ",", "no_whitespace", "=", "False", ",", "no_newline", "=", "True", ",", "whole_word", "=", "False", ",", "min_len", "=", "1", ",", "max_...
Ensures the provided object can be interpreted as a unicode string, optionally with additional restrictions imposed. By default this means a non-zero length string which does not begin or end in whitespace.
[ "Ensures", "the", "provided", "object", "can", "be", "interpreted", "as", "a", "unicode", "string", "optionally", "with", "additional", "restrictions", "imposed", ".", "By", "default", "this", "means", "a", "non", "-", "zero", "length", "string", "which", "doe...
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/Core/Validation.py#L66-L93
train
38,197
Iotic-Labs/py-IoticAgent
src/IoticAgent/Core/Validation.py
Validation.__valid_url
def __valid_url(cls, url): """Expects input to already be a valid string""" bits = urlparse(url) return ((bits.scheme == "http" or bits.scheme == "https") and _PATTERN_URL_PART.match(bits.netloc) and _PATTERN_URL_PART.match(bits.path))
python
def __valid_url(cls, url): """Expects input to already be a valid string""" bits = urlparse(url) return ((bits.scheme == "http" or bits.scheme == "https") and _PATTERN_URL_PART.match(bits.netloc) and _PATTERN_URL_PART.match(bits.path))
[ "def", "__valid_url", "(", "cls", ",", "url", ")", ":", "bits", "=", "urlparse", "(", "url", ")", "return", "(", "(", "bits", ".", "scheme", "==", "\"http\"", "or", "bits", ".", "scheme", "==", "\"https\"", ")", "and", "_PATTERN_URL_PART", ".", "match"...
Expects input to already be a valid string
[ "Expects", "input", "to", "already", "be", "a", "valid", "string" ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/Core/Validation.py#L231-L236
train
38,198
Iotic-Labs/py-IoticAgent
src/IoticAgent/Core/Validation.py
Validation.location_check
def location_check(lat, lon): """For use by Core client wrappers""" if not (isinstance(lat, number_types) and -90 <= lat <= 90): raise ValueError("Latitude: '{latitude}' invalid".format(latitude=lat)) if not (isinstance(lon, number_types) and -180 <= lon <= 180): raise ValueError("Longitude: '{longitude}' invalid".format(longitude=lon))
python
def location_check(lat, lon): """For use by Core client wrappers""" if not (isinstance(lat, number_types) and -90 <= lat <= 90): raise ValueError("Latitude: '{latitude}' invalid".format(latitude=lat)) if not (isinstance(lon, number_types) and -180 <= lon <= 180): raise ValueError("Longitude: '{longitude}' invalid".format(longitude=lon))
[ "def", "location_check", "(", "lat", ",", "lon", ")", ":", "if", "not", "(", "isinstance", "(", "lat", ",", "number_types", ")", "and", "-", "90", "<=", "lat", "<=", "90", ")", ":", "raise", "ValueError", "(", "\"Latitude: '{latitude}' invalid\"", ".", "...
For use by Core client wrappers
[ "For", "use", "by", "Core", "client", "wrappers" ]
893e8582ad1dacfe32dfc0ee89452bbd6f57d28d
https://github.com/Iotic-Labs/py-IoticAgent/blob/893e8582ad1dacfe32dfc0ee89452bbd6f57d28d/src/IoticAgent/Core/Validation.py#L239-L245
train
38,199