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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
bitcraze/crazyflie-lib-python | cflib/crazyflie/param.py | Param._check_if_all_updated | def _check_if_all_updated(self):
"""Check if all parameters from the TOC has at least been fetched
once"""
for g in self.toc.toc:
if g not in self.values:
return False
for n in self.toc.toc[g]:
if n not in self.values[g]:
return False
return True | python | def _check_if_all_updated(self):
"""Check if all parameters from the TOC has at least been fetched
once"""
for g in self.toc.toc:
if g not in self.values:
return False
for n in self.toc.toc[g]:
if n not in self.values[g]:
return False
return True | [
"def",
"_check_if_all_updated",
"(",
"self",
")",
":",
"for",
"g",
"in",
"self",
".",
"toc",
".",
"toc",
":",
"if",
"g",
"not",
"in",
"self",
".",
"values",
":",
"return",
"False",
"for",
"n",
"in",
"self",
".",
"toc",
".",
"toc",
"[",
"g",
"]",
... | Check if all parameters from the TOC has at least been fetched
once | [
"Check",
"if",
"all",
"parameters",
"from",
"the",
"TOC",
"has",
"at",
"least",
"been",
"fetched",
"once"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/param.py#L152-L162 | train | 228,400 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/param.py | Param._param_updated | def _param_updated(self, pk):
"""Callback with data for an updated parameter"""
if self._useV2:
var_id = struct.unpack('<H', pk.data[:2])[0]
else:
var_id = pk.data[0]
element = self.toc.get_element_by_id(var_id)
if element:
if self._useV2:
s = struct.unpack(element.pytype, pk.data[2:])[0]
else:
s = struct.unpack(element.pytype, pk.data[1:])[0]
s = s.__str__()
complete_name = '%s.%s' % (element.group, element.name)
# Save the value for synchronous access
if element.group not in self.values:
self.values[element.group] = {}
self.values[element.group][element.name] = s
logger.debug('Updated parameter [%s]' % complete_name)
if complete_name in self.param_update_callbacks:
self.param_update_callbacks[complete_name].call(
complete_name, s)
if element.group in self.group_update_callbacks:
self.group_update_callbacks[element.group].call(
complete_name, s)
self.all_update_callback.call(complete_name, s)
# Once all the parameters are updated call the
# callback for "everything updated" (after all the param
# updated callbacks)
if self._check_if_all_updated() and not self.is_updated:
self.is_updated = True
self.all_updated.call()
else:
logger.debug('Variable id [%d] not found in TOC', var_id) | python | def _param_updated(self, pk):
"""Callback with data for an updated parameter"""
if self._useV2:
var_id = struct.unpack('<H', pk.data[:2])[0]
else:
var_id = pk.data[0]
element = self.toc.get_element_by_id(var_id)
if element:
if self._useV2:
s = struct.unpack(element.pytype, pk.data[2:])[0]
else:
s = struct.unpack(element.pytype, pk.data[1:])[0]
s = s.__str__()
complete_name = '%s.%s' % (element.group, element.name)
# Save the value for synchronous access
if element.group not in self.values:
self.values[element.group] = {}
self.values[element.group][element.name] = s
logger.debug('Updated parameter [%s]' % complete_name)
if complete_name in self.param_update_callbacks:
self.param_update_callbacks[complete_name].call(
complete_name, s)
if element.group in self.group_update_callbacks:
self.group_update_callbacks[element.group].call(
complete_name, s)
self.all_update_callback.call(complete_name, s)
# Once all the parameters are updated call the
# callback for "everything updated" (after all the param
# updated callbacks)
if self._check_if_all_updated() and not self.is_updated:
self.is_updated = True
self.all_updated.call()
else:
logger.debug('Variable id [%d] not found in TOC', var_id) | [
"def",
"_param_updated",
"(",
"self",
",",
"pk",
")",
":",
"if",
"self",
".",
"_useV2",
":",
"var_id",
"=",
"struct",
".",
"unpack",
"(",
"'<H'",
",",
"pk",
".",
"data",
"[",
":",
"2",
"]",
")",
"[",
"0",
"]",
"else",
":",
"var_id",
"=",
"pk",
... | Callback with data for an updated parameter | [
"Callback",
"with",
"data",
"for",
"an",
"updated",
"parameter"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/param.py#L164-L200 | train | 228,401 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/param.py | Param.remove_update_callback | def remove_update_callback(self, group, name=None, cb=None):
"""Remove the supplied callback for a group or a group.name"""
if not cb:
return
if not name:
if group in self.group_update_callbacks:
self.group_update_callbacks[group].remove_callback(cb)
else:
paramname = '{}.{}'.format(group, name)
if paramname in self.param_update_callbacks:
self.param_update_callbacks[paramname].remove_callback(cb) | python | def remove_update_callback(self, group, name=None, cb=None):
"""Remove the supplied callback for a group or a group.name"""
if not cb:
return
if not name:
if group in self.group_update_callbacks:
self.group_update_callbacks[group].remove_callback(cb)
else:
paramname = '{}.{}'.format(group, name)
if paramname in self.param_update_callbacks:
self.param_update_callbacks[paramname].remove_callback(cb) | [
"def",
"remove_update_callback",
"(",
"self",
",",
"group",
",",
"name",
"=",
"None",
",",
"cb",
"=",
"None",
")",
":",
"if",
"not",
"cb",
":",
"return",
"if",
"not",
"name",
":",
"if",
"group",
"in",
"self",
".",
"group_update_callbacks",
":",
"self",... | Remove the supplied callback for a group or a group.name | [
"Remove",
"the",
"supplied",
"callback",
"for",
"a",
"group",
"or",
"a",
"group",
".",
"name"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/param.py#L202-L213 | train | 228,402 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/param.py | Param.add_update_callback | def add_update_callback(self, group=None, name=None, cb=None):
"""
Add a callback for a specific parameter name. This callback will be
executed when a new value is read from the Crazyflie.
"""
if not group and not name:
self.all_update_callback.add_callback(cb)
elif not name:
if group not in self.group_update_callbacks:
self.group_update_callbacks[group] = Caller()
self.group_update_callbacks[group].add_callback(cb)
else:
paramname = '{}.{}'.format(group, name)
if paramname not in self.param_update_callbacks:
self.param_update_callbacks[paramname] = Caller()
self.param_update_callbacks[paramname].add_callback(cb) | python | def add_update_callback(self, group=None, name=None, cb=None):
"""
Add a callback for a specific parameter name. This callback will be
executed when a new value is read from the Crazyflie.
"""
if not group and not name:
self.all_update_callback.add_callback(cb)
elif not name:
if group not in self.group_update_callbacks:
self.group_update_callbacks[group] = Caller()
self.group_update_callbacks[group].add_callback(cb)
else:
paramname = '{}.{}'.format(group, name)
if paramname not in self.param_update_callbacks:
self.param_update_callbacks[paramname] = Caller()
self.param_update_callbacks[paramname].add_callback(cb) | [
"def",
"add_update_callback",
"(",
"self",
",",
"group",
"=",
"None",
",",
"name",
"=",
"None",
",",
"cb",
"=",
"None",
")",
":",
"if",
"not",
"group",
"and",
"not",
"name",
":",
"self",
".",
"all_update_callback",
".",
"add_callback",
"(",
"cb",
")",
... | Add a callback for a specific parameter name. This callback will be
executed when a new value is read from the Crazyflie. | [
"Add",
"a",
"callback",
"for",
"a",
"specific",
"parameter",
"name",
".",
"This",
"callback",
"will",
"be",
"executed",
"when",
"a",
"new",
"value",
"is",
"read",
"from",
"the",
"Crazyflie",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/param.py#L215-L230 | train | 228,403 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/param.py | Param.refresh_toc | def refresh_toc(self, refresh_done_callback, toc_cache):
"""
Initiate a refresh of the parameter TOC.
"""
self._useV2 = self.cf.platform.get_protocol_version() >= 4
toc_fetcher = TocFetcher(self.cf, ParamTocElement,
CRTPPort.PARAM, self.toc,
refresh_done_callback, toc_cache)
toc_fetcher.start() | python | def refresh_toc(self, refresh_done_callback, toc_cache):
"""
Initiate a refresh of the parameter TOC.
"""
self._useV2 = self.cf.platform.get_protocol_version() >= 4
toc_fetcher = TocFetcher(self.cf, ParamTocElement,
CRTPPort.PARAM, self.toc,
refresh_done_callback, toc_cache)
toc_fetcher.start() | [
"def",
"refresh_toc",
"(",
"self",
",",
"refresh_done_callback",
",",
"toc_cache",
")",
":",
"self",
".",
"_useV2",
"=",
"self",
".",
"cf",
".",
"platform",
".",
"get_protocol_version",
"(",
")",
">=",
"4",
"toc_fetcher",
"=",
"TocFetcher",
"(",
"self",
".... | Initiate a refresh of the parameter TOC. | [
"Initiate",
"a",
"refresh",
"of",
"the",
"parameter",
"TOC",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/param.py#L232-L240 | train | 228,404 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/param.py | Param._disconnected | def _disconnected(self, uri):
"""Disconnected callback from Crazyflie API"""
self.param_updater.close()
self.is_updated = False
# Clear all values from the previous Crazyflie
self.toc = Toc()
self.values = {} | python | def _disconnected(self, uri):
"""Disconnected callback from Crazyflie API"""
self.param_updater.close()
self.is_updated = False
# Clear all values from the previous Crazyflie
self.toc = Toc()
self.values = {} | [
"def",
"_disconnected",
"(",
"self",
",",
"uri",
")",
":",
"self",
".",
"param_updater",
".",
"close",
"(",
")",
"self",
".",
"is_updated",
"=",
"False",
"# Clear all values from the previous Crazyflie",
"self",
".",
"toc",
"=",
"Toc",
"(",
")",
"self",
".",... | Disconnected callback from Crazyflie API | [
"Disconnected",
"callback",
"from",
"Crazyflie",
"API"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/param.py#L242-L248 | train | 228,405 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/param.py | Param.request_param_update | def request_param_update(self, complete_name):
"""
Request an update of the value for the supplied parameter.
"""
self.param_updater.request_param_update(
self.toc.get_element_id(complete_name)) | python | def request_param_update(self, complete_name):
"""
Request an update of the value for the supplied parameter.
"""
self.param_updater.request_param_update(
self.toc.get_element_id(complete_name)) | [
"def",
"request_param_update",
"(",
"self",
",",
"complete_name",
")",
":",
"self",
".",
"param_updater",
".",
"request_param_update",
"(",
"self",
".",
"toc",
".",
"get_element_id",
"(",
"complete_name",
")",
")"
] | Request an update of the value for the supplied parameter. | [
"Request",
"an",
"update",
"of",
"the",
"value",
"for",
"the",
"supplied",
"parameter",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/param.py#L250-L255 | train | 228,406 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/param.py | Param.set_value | def set_value(self, complete_name, value):
"""
Set the value for the supplied parameter.
"""
element = self.toc.get_element_by_complete_name(complete_name)
if not element:
logger.warning("Cannot set value for [%s], it's not in the TOC!",
complete_name)
raise KeyError('{} not in param TOC'.format(complete_name))
elif element.access == ParamTocElement.RO_ACCESS:
logger.debug('[%s] is read only, no trying to set value',
complete_name)
raise AttributeError('{} is read-only!'.format(complete_name))
else:
varid = element.ident
pk = CRTPPacket()
pk.set_header(CRTPPort.PARAM, WRITE_CHANNEL)
if self._useV2:
pk.data = struct.pack('<H', varid)
else:
pk.data = struct.pack('<B', varid)
try:
value_nr = eval(value)
except TypeError:
value_nr = value
pk.data += struct.pack(element.pytype, value_nr)
self.param_updater.request_param_setvalue(pk) | python | def set_value(self, complete_name, value):
"""
Set the value for the supplied parameter.
"""
element = self.toc.get_element_by_complete_name(complete_name)
if not element:
logger.warning("Cannot set value for [%s], it's not in the TOC!",
complete_name)
raise KeyError('{} not in param TOC'.format(complete_name))
elif element.access == ParamTocElement.RO_ACCESS:
logger.debug('[%s] is read only, no trying to set value',
complete_name)
raise AttributeError('{} is read-only!'.format(complete_name))
else:
varid = element.ident
pk = CRTPPacket()
pk.set_header(CRTPPort.PARAM, WRITE_CHANNEL)
if self._useV2:
pk.data = struct.pack('<H', varid)
else:
pk.data = struct.pack('<B', varid)
try:
value_nr = eval(value)
except TypeError:
value_nr = value
pk.data += struct.pack(element.pytype, value_nr)
self.param_updater.request_param_setvalue(pk) | [
"def",
"set_value",
"(",
"self",
",",
"complete_name",
",",
"value",
")",
":",
"element",
"=",
"self",
".",
"toc",
".",
"get_element_by_complete_name",
"(",
"complete_name",
")",
"if",
"not",
"element",
":",
"logger",
".",
"warning",
"(",
"\"Cannot set value f... | Set the value for the supplied parameter. | [
"Set",
"the",
"value",
"for",
"the",
"supplied",
"parameter",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/param.py#L257-L286 | train | 228,407 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/param.py | _ParamUpdater._new_packet_cb | def _new_packet_cb(self, pk):
"""Callback for newly arrived packets"""
if pk.channel == READ_CHANNEL or pk.channel == WRITE_CHANNEL:
if self._useV2:
var_id = struct.unpack('<H', pk.data[:2])[0]
if pk.channel == READ_CHANNEL:
pk.data = pk.data[:2] + pk.data[3:]
else:
var_id = pk.data[0]
if (pk.channel != TOC_CHANNEL and self._req_param == var_id and
pk is not None):
self.updated_callback(pk)
self._req_param = -1
try:
self.wait_lock.release()
except Exception:
pass | python | def _new_packet_cb(self, pk):
"""Callback for newly arrived packets"""
if pk.channel == READ_CHANNEL or pk.channel == WRITE_CHANNEL:
if self._useV2:
var_id = struct.unpack('<H', pk.data[:2])[0]
if pk.channel == READ_CHANNEL:
pk.data = pk.data[:2] + pk.data[3:]
else:
var_id = pk.data[0]
if (pk.channel != TOC_CHANNEL and self._req_param == var_id and
pk is not None):
self.updated_callback(pk)
self._req_param = -1
try:
self.wait_lock.release()
except Exception:
pass | [
"def",
"_new_packet_cb",
"(",
"self",
",",
"pk",
")",
":",
"if",
"pk",
".",
"channel",
"==",
"READ_CHANNEL",
"or",
"pk",
".",
"channel",
"==",
"WRITE_CHANNEL",
":",
"if",
"self",
".",
"_useV2",
":",
"var_id",
"=",
"struct",
".",
"unpack",
"(",
"'<H'",
... | Callback for newly arrived packets | [
"Callback",
"for",
"newly",
"arrived",
"packets"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/param.py#L322-L338 | train | 228,408 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/param.py | _ParamUpdater.request_param_update | def request_param_update(self, var_id):
"""Place a param update request on the queue"""
self._useV2 = self.cf.platform.get_protocol_version() >= 4
pk = CRTPPacket()
pk.set_header(CRTPPort.PARAM, READ_CHANNEL)
if self._useV2:
pk.data = struct.pack('<H', var_id)
else:
pk.data = struct.pack('<B', var_id)
logger.debug('Requesting request to update param [%d]', var_id)
self.request_queue.put(pk) | python | def request_param_update(self, var_id):
"""Place a param update request on the queue"""
self._useV2 = self.cf.platform.get_protocol_version() >= 4
pk = CRTPPacket()
pk.set_header(CRTPPort.PARAM, READ_CHANNEL)
if self._useV2:
pk.data = struct.pack('<H', var_id)
else:
pk.data = struct.pack('<B', var_id)
logger.debug('Requesting request to update param [%d]', var_id)
self.request_queue.put(pk) | [
"def",
"request_param_update",
"(",
"self",
",",
"var_id",
")",
":",
"self",
".",
"_useV2",
"=",
"self",
".",
"cf",
".",
"platform",
".",
"get_protocol_version",
"(",
")",
">=",
"4",
"pk",
"=",
"CRTPPacket",
"(",
")",
"pk",
".",
"set_header",
"(",
"CRT... | Place a param update request on the queue | [
"Place",
"a",
"param",
"update",
"request",
"on",
"the",
"queue"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/param.py#L340-L350 | train | 228,409 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/toc.py | Toc.add_element | def add_element(self, element):
"""Add a new TocElement to the TOC container."""
try:
self.toc[element.group][element.name] = element
except KeyError:
self.toc[element.group] = {}
self.toc[element.group][element.name] = element | python | def add_element(self, element):
"""Add a new TocElement to the TOC container."""
try:
self.toc[element.group][element.name] = element
except KeyError:
self.toc[element.group] = {}
self.toc[element.group][element.name] = element | [
"def",
"add_element",
"(",
"self",
",",
"element",
")",
":",
"try",
":",
"self",
".",
"toc",
"[",
"element",
".",
"group",
"]",
"[",
"element",
".",
"name",
"]",
"=",
"element",
"except",
"KeyError",
":",
"self",
".",
"toc",
"[",
"element",
".",
"g... | Add a new TocElement to the TOC container. | [
"Add",
"a",
"new",
"TocElement",
"to",
"the",
"TOC",
"container",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/toc.py#L65-L71 | train | 228,410 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/toc.py | Toc.get_element_id | def get_element_id(self, complete_name):
"""Get the TocElement element id-number of the element with the
supplied name."""
[group, name] = complete_name.split('.')
element = self.get_element(group, name)
if element:
return element.ident
else:
logger.warning('Unable to find variable [%s]', complete_name)
return None | python | def get_element_id(self, complete_name):
"""Get the TocElement element id-number of the element with the
supplied name."""
[group, name] = complete_name.split('.')
element = self.get_element(group, name)
if element:
return element.ident
else:
logger.warning('Unable to find variable [%s]', complete_name)
return None | [
"def",
"get_element_id",
"(",
"self",
",",
"complete_name",
")",
":",
"[",
"group",
",",
"name",
"]",
"=",
"complete_name",
".",
"split",
"(",
"'.'",
")",
"element",
"=",
"self",
".",
"get_element",
"(",
"group",
",",
"name",
")",
"if",
"element",
":",... | Get the TocElement element id-number of the element with the
supplied name. | [
"Get",
"the",
"TocElement",
"element",
"id",
"-",
"number",
"of",
"the",
"element",
"with",
"the",
"supplied",
"name",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/toc.py#L82-L91 | train | 228,411 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/toc.py | Toc.get_element_by_id | def get_element_by_id(self, ident):
"""Get a TocElement element identified by index number from the
container."""
for group in list(self.toc.keys()):
for name in list(self.toc[group].keys()):
if self.toc[group][name].ident == ident:
return self.toc[group][name]
return None | python | def get_element_by_id(self, ident):
"""Get a TocElement element identified by index number from the
container."""
for group in list(self.toc.keys()):
for name in list(self.toc[group].keys()):
if self.toc[group][name].ident == ident:
return self.toc[group][name]
return None | [
"def",
"get_element_by_id",
"(",
"self",
",",
"ident",
")",
":",
"for",
"group",
"in",
"list",
"(",
"self",
".",
"toc",
".",
"keys",
"(",
")",
")",
":",
"for",
"name",
"in",
"list",
"(",
"self",
".",
"toc",
"[",
"group",
"]",
".",
"keys",
"(",
... | Get a TocElement element identified by index number from the
container. | [
"Get",
"a",
"TocElement",
"element",
"identified",
"by",
"index",
"number",
"from",
"the",
"container",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/toc.py#L101-L108 | train | 228,412 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/toc.py | TocFetcher.start | def start(self):
"""Initiate fetching of the TOC."""
self._useV2 = self.cf.platform.get_protocol_version() >= 4
logger.debug('[%d]: Using V2 protocol: %d', self.port, self._useV2)
logger.debug('[%d]: Start fetching...', self.port)
# Register callback in this class for the port
self.cf.add_port_callback(self.port, self._new_packet_cb)
# Request the TOC CRC
self.state = GET_TOC_INFO
pk = CRTPPacket()
pk.set_header(self.port, TOC_CHANNEL)
if self._useV2:
pk.data = (CMD_TOC_INFO_V2,)
self.cf.send_packet(pk, expected_reply=(CMD_TOC_INFO_V2,))
else:
pk.data = (CMD_TOC_INFO,)
self.cf.send_packet(pk, expected_reply=(CMD_TOC_INFO,)) | python | def start(self):
"""Initiate fetching of the TOC."""
self._useV2 = self.cf.platform.get_protocol_version() >= 4
logger.debug('[%d]: Using V2 protocol: %d', self.port, self._useV2)
logger.debug('[%d]: Start fetching...', self.port)
# Register callback in this class for the port
self.cf.add_port_callback(self.port, self._new_packet_cb)
# Request the TOC CRC
self.state = GET_TOC_INFO
pk = CRTPPacket()
pk.set_header(self.port, TOC_CHANNEL)
if self._useV2:
pk.data = (CMD_TOC_INFO_V2,)
self.cf.send_packet(pk, expected_reply=(CMD_TOC_INFO_V2,))
else:
pk.data = (CMD_TOC_INFO,)
self.cf.send_packet(pk, expected_reply=(CMD_TOC_INFO,)) | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"_useV2",
"=",
"self",
".",
"cf",
".",
"platform",
".",
"get_protocol_version",
"(",
")",
">=",
"4",
"logger",
".",
"debug",
"(",
"'[%d]: Using V2 protocol: %d'",
",",
"self",
".",
"port",
",",
"self",
... | Initiate fetching of the TOC. | [
"Initiate",
"fetching",
"of",
"the",
"TOC",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/toc.py#L128-L147 | train | 228,413 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/toc.py | TocFetcher._toc_fetch_finished | def _toc_fetch_finished(self):
"""Callback for when the TOC fetching is finished"""
self.cf.remove_port_callback(self.port, self._new_packet_cb)
logger.debug('[%d]: Done!', self.port)
self.finished_callback() | python | def _toc_fetch_finished(self):
"""Callback for when the TOC fetching is finished"""
self.cf.remove_port_callback(self.port, self._new_packet_cb)
logger.debug('[%d]: Done!', self.port)
self.finished_callback() | [
"def",
"_toc_fetch_finished",
"(",
"self",
")",
":",
"self",
".",
"cf",
".",
"remove_port_callback",
"(",
"self",
".",
"port",
",",
"self",
".",
"_new_packet_cb",
")",
"logger",
".",
"debug",
"(",
"'[%d]: Done!'",
",",
"self",
".",
"port",
")",
"self",
"... | Callback for when the TOC fetching is finished | [
"Callback",
"for",
"when",
"the",
"TOC",
"fetching",
"is",
"finished"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/toc.py#L149-L153 | train | 228,414 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/toc.py | TocFetcher._new_packet_cb | def _new_packet_cb(self, packet):
"""Handle a newly arrived packet"""
chan = packet.channel
if (chan != 0):
return
payload = packet.data[1:]
if (self.state == GET_TOC_INFO):
if self._useV2:
[self.nbr_of_items, self._crc] = struct.unpack(
'<HI', payload[:6])
else:
[self.nbr_of_items, self._crc] = struct.unpack(
'<BI', payload[:5])
logger.debug('[%d]: Got TOC CRC, %d items and crc=0x%08X',
self.port, self.nbr_of_items, self._crc)
cache_data = self._toc_cache.fetch(self._crc)
if (cache_data):
self.toc.toc = cache_data
logger.info('TOC for port [%s] found in cache' % self.port)
self._toc_fetch_finished()
else:
self.state = GET_TOC_ELEMENT
self.requested_index = 0
self._request_toc_element(self.requested_index)
elif (self.state == GET_TOC_ELEMENT):
# Always add new element, but only request new if it's not the
# last one.
if self._useV2:
ident = struct.unpack('<H', payload[:2])[0]
else:
ident = payload[0]
if ident != self.requested_index:
return
if self._useV2:
self.toc.add_element(self.element_class(ident, payload[2:]))
else:
self.toc.add_element(self.element_class(ident, payload[1:]))
logger.debug('Added element [%s]', ident)
if (self.requested_index < (self.nbr_of_items - 1)):
logger.debug('[%d]: More variables, requesting index %d',
self.port, self.requested_index + 1)
self.requested_index = self.requested_index + 1
self._request_toc_element(self.requested_index)
else: # No more variables in TOC
self._toc_cache.insert(self._crc, self.toc.toc)
self._toc_fetch_finished() | python | def _new_packet_cb(self, packet):
"""Handle a newly arrived packet"""
chan = packet.channel
if (chan != 0):
return
payload = packet.data[1:]
if (self.state == GET_TOC_INFO):
if self._useV2:
[self.nbr_of_items, self._crc] = struct.unpack(
'<HI', payload[:6])
else:
[self.nbr_of_items, self._crc] = struct.unpack(
'<BI', payload[:5])
logger.debug('[%d]: Got TOC CRC, %d items and crc=0x%08X',
self.port, self.nbr_of_items, self._crc)
cache_data = self._toc_cache.fetch(self._crc)
if (cache_data):
self.toc.toc = cache_data
logger.info('TOC for port [%s] found in cache' % self.port)
self._toc_fetch_finished()
else:
self.state = GET_TOC_ELEMENT
self.requested_index = 0
self._request_toc_element(self.requested_index)
elif (self.state == GET_TOC_ELEMENT):
# Always add new element, but only request new if it's not the
# last one.
if self._useV2:
ident = struct.unpack('<H', payload[:2])[0]
else:
ident = payload[0]
if ident != self.requested_index:
return
if self._useV2:
self.toc.add_element(self.element_class(ident, payload[2:]))
else:
self.toc.add_element(self.element_class(ident, payload[1:]))
logger.debug('Added element [%s]', ident)
if (self.requested_index < (self.nbr_of_items - 1)):
logger.debug('[%d]: More variables, requesting index %d',
self.port, self.requested_index + 1)
self.requested_index = self.requested_index + 1
self._request_toc_element(self.requested_index)
else: # No more variables in TOC
self._toc_cache.insert(self._crc, self.toc.toc)
self._toc_fetch_finished() | [
"def",
"_new_packet_cb",
"(",
"self",
",",
"packet",
")",
":",
"chan",
"=",
"packet",
".",
"channel",
"if",
"(",
"chan",
"!=",
"0",
")",
":",
"return",
"payload",
"=",
"packet",
".",
"data",
"[",
"1",
":",
"]",
"if",
"(",
"self",
".",
"state",
"=... | Handle a newly arrived packet | [
"Handle",
"a",
"newly",
"arrived",
"packet"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/toc.py#L155-L204 | train | 228,415 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/toc.py | TocFetcher._request_toc_element | def _request_toc_element(self, index):
"""Request information about a specific item in the TOC"""
logger.debug('Requesting index %d on port %d', index, self.port)
pk = CRTPPacket()
if self._useV2:
pk.set_header(self.port, TOC_CHANNEL)
pk.data = (CMD_TOC_ITEM_V2, index & 0x0ff, (index >> 8) & 0x0ff)
self.cf.send_packet(pk, expected_reply=(
CMD_TOC_ITEM_V2, index & 0x0ff, (index >> 8) & 0x0ff))
else:
pk.set_header(self.port, TOC_CHANNEL)
pk.data = (CMD_TOC_ELEMENT, index)
self.cf.send_packet(pk, expected_reply=(CMD_TOC_ELEMENT, index)) | python | def _request_toc_element(self, index):
"""Request information about a specific item in the TOC"""
logger.debug('Requesting index %d on port %d', index, self.port)
pk = CRTPPacket()
if self._useV2:
pk.set_header(self.port, TOC_CHANNEL)
pk.data = (CMD_TOC_ITEM_V2, index & 0x0ff, (index >> 8) & 0x0ff)
self.cf.send_packet(pk, expected_reply=(
CMD_TOC_ITEM_V2, index & 0x0ff, (index >> 8) & 0x0ff))
else:
pk.set_header(self.port, TOC_CHANNEL)
pk.data = (CMD_TOC_ELEMENT, index)
self.cf.send_packet(pk, expected_reply=(CMD_TOC_ELEMENT, index)) | [
"def",
"_request_toc_element",
"(",
"self",
",",
"index",
")",
":",
"logger",
".",
"debug",
"(",
"'Requesting index %d on port %d'",
",",
"index",
",",
"self",
".",
"port",
")",
"pk",
"=",
"CRTPPacket",
"(",
")",
"if",
"self",
".",
"_useV2",
":",
"pk",
"... | Request information about a specific item in the TOC | [
"Request",
"information",
"about",
"a",
"specific",
"item",
"in",
"the",
"TOC"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/toc.py#L206-L218 | train | 228,416 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/__init__.py | Crazyflie._start_connection_setup | def _start_connection_setup(self):
"""Start the connection setup by refreshing the TOCs"""
logger.info('We are connected[%s], request connection setup',
self.link_uri)
self.platform.fetch_platform_informations(self._platform_info_fetched) | python | def _start_connection_setup(self):
"""Start the connection setup by refreshing the TOCs"""
logger.info('We are connected[%s], request connection setup',
self.link_uri)
self.platform.fetch_platform_informations(self._platform_info_fetched) | [
"def",
"_start_connection_setup",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'We are connected[%s], request connection setup'",
",",
"self",
".",
"link_uri",
")",
"self",
".",
"platform",
".",
"fetch_platform_informations",
"(",
"self",
".",
"_platform_info_f... | Start the connection setup by refreshing the TOCs | [
"Start",
"the",
"connection",
"setup",
"by",
"refreshing",
"the",
"TOCs"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/__init__.py#L156-L160 | train | 228,417 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/__init__.py | Crazyflie._param_toc_updated_cb | def _param_toc_updated_cb(self):
"""Called when the param TOC has been fully updated"""
logger.info('Param TOC finished updating')
self.connected_ts = datetime.datetime.now()
self.connected.call(self.link_uri)
# Trigger the update for all the parameters
self.param.request_update_of_all_params() | python | def _param_toc_updated_cb(self):
"""Called when the param TOC has been fully updated"""
logger.info('Param TOC finished updating')
self.connected_ts = datetime.datetime.now()
self.connected.call(self.link_uri)
# Trigger the update for all the parameters
self.param.request_update_of_all_params() | [
"def",
"_param_toc_updated_cb",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'Param TOC finished updating'",
")",
"self",
".",
"connected_ts",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"self",
".",
"connected",
".",
"call",
"(",
"self",
... | Called when the param TOC has been fully updated | [
"Called",
"when",
"the",
"param",
"TOC",
"has",
"been",
"fully",
"updated"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/__init__.py#L165-L171 | train | 228,418 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/__init__.py | Crazyflie._mems_updated_cb | def _mems_updated_cb(self):
"""Called when the memories have been identified"""
logger.info('Memories finished updating')
self.param.refresh_toc(self._param_toc_updated_cb, self._toc_cache) | python | def _mems_updated_cb(self):
"""Called when the memories have been identified"""
logger.info('Memories finished updating')
self.param.refresh_toc(self._param_toc_updated_cb, self._toc_cache) | [
"def",
"_mems_updated_cb",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'Memories finished updating'",
")",
"self",
".",
"param",
".",
"refresh_toc",
"(",
"self",
".",
"_param_toc_updated_cb",
",",
"self",
".",
"_toc_cache",
")"
] | Called when the memories have been identified | [
"Called",
"when",
"the",
"memories",
"have",
"been",
"identified"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/__init__.py#L173-L176 | train | 228,419 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/__init__.py | Crazyflie._link_error_cb | def _link_error_cb(self, errmsg):
"""Called from the link driver when there's an error"""
logger.warning('Got link error callback [%s] in state [%s]',
errmsg, self.state)
if (self.link is not None):
self.link.close()
self.link = None
if (self.state == State.INITIALIZED):
self.connection_failed.call(self.link_uri, errmsg)
if (self.state == State.CONNECTED or
self.state == State.SETUP_FINISHED):
self.disconnected.call(self.link_uri)
self.connection_lost.call(self.link_uri, errmsg)
self.state = State.DISCONNECTED | python | def _link_error_cb(self, errmsg):
"""Called from the link driver when there's an error"""
logger.warning('Got link error callback [%s] in state [%s]',
errmsg, self.state)
if (self.link is not None):
self.link.close()
self.link = None
if (self.state == State.INITIALIZED):
self.connection_failed.call(self.link_uri, errmsg)
if (self.state == State.CONNECTED or
self.state == State.SETUP_FINISHED):
self.disconnected.call(self.link_uri)
self.connection_lost.call(self.link_uri, errmsg)
self.state = State.DISCONNECTED | [
"def",
"_link_error_cb",
"(",
"self",
",",
"errmsg",
")",
":",
"logger",
".",
"warning",
"(",
"'Got link error callback [%s] in state [%s]'",
",",
"errmsg",
",",
"self",
".",
"state",
")",
"if",
"(",
"self",
".",
"link",
"is",
"not",
"None",
")",
":",
"sel... | Called from the link driver when there's an error | [
"Called",
"from",
"the",
"link",
"driver",
"when",
"there",
"s",
"an",
"error"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/__init__.py#L183-L196 | train | 228,420 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/__init__.py | Crazyflie._check_for_initial_packet_cb | def _check_for_initial_packet_cb(self, data):
"""
Called when first packet arrives from Crazyflie.
This is used to determine if we are connected to something that is
answering.
"""
self.state = State.CONNECTED
self.link_established.call(self.link_uri)
self.packet_received.remove_callback(self._check_for_initial_packet_cb) | python | def _check_for_initial_packet_cb(self, data):
"""
Called when first packet arrives from Crazyflie.
This is used to determine if we are connected to something that is
answering.
"""
self.state = State.CONNECTED
self.link_established.call(self.link_uri)
self.packet_received.remove_callback(self._check_for_initial_packet_cb) | [
"def",
"_check_for_initial_packet_cb",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"state",
"=",
"State",
".",
"CONNECTED",
"self",
".",
"link_established",
".",
"call",
"(",
"self",
".",
"link_uri",
")",
"self",
".",
"packet_received",
".",
"remove_cal... | Called when first packet arrives from Crazyflie.
This is used to determine if we are connected to something that is
answering. | [
"Called",
"when",
"first",
"packet",
"arrives",
"from",
"Crazyflie",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/__init__.py#L202-L211 | train | 228,421 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/__init__.py | Crazyflie.close_link | def close_link(self):
"""Close the communication link."""
logger.info('Closing link')
if (self.link is not None):
self.commander.send_setpoint(0, 0, 0, 0)
if (self.link is not None):
self.link.close()
self.link = None
self._answer_patterns = {}
self.disconnected.call(self.link_uri) | python | def close_link(self):
"""Close the communication link."""
logger.info('Closing link')
if (self.link is not None):
self.commander.send_setpoint(0, 0, 0, 0)
if (self.link is not None):
self.link.close()
self.link = None
self._answer_patterns = {}
self.disconnected.call(self.link_uri) | [
"def",
"close_link",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'Closing link'",
")",
"if",
"(",
"self",
".",
"link",
"is",
"not",
"None",
")",
":",
"self",
".",
"commander",
".",
"send_setpoint",
"(",
"0",
",",
"0",
",",
"0",
",",
"0",
... | Close the communication link. | [
"Close",
"the",
"communication",
"link",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/__init__.py#L251-L260 | train | 228,422 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/__init__.py | Crazyflie._no_answer_do_retry | def _no_answer_do_retry(self, pk, pattern):
"""Resend packets that we have not gotten answers to"""
logger.info('Resending for pattern %s', pattern)
# Set the timer to None before trying to send again
self.send_packet(pk, expected_reply=pattern, resend=True) | python | def _no_answer_do_retry(self, pk, pattern):
"""Resend packets that we have not gotten answers to"""
logger.info('Resending for pattern %s', pattern)
# Set the timer to None before trying to send again
self.send_packet(pk, expected_reply=pattern, resend=True) | [
"def",
"_no_answer_do_retry",
"(",
"self",
",",
"pk",
",",
"pattern",
")",
":",
"logger",
".",
"info",
"(",
"'Resending for pattern %s'",
",",
"pattern",
")",
"# Set the timer to None before trying to send again",
"self",
".",
"send_packet",
"(",
"pk",
",",
"expecte... | Resend packets that we have not gotten answers to | [
"Resend",
"packets",
"that",
"we",
"have",
"not",
"gotten",
"answers",
"to"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/__init__.py#L275-L279 | train | 228,423 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/__init__.py | Crazyflie._check_for_answers | def _check_for_answers(self, pk):
"""
Callback called for every packet received to check if we are
waiting for an answer on this port. If so, then cancel the retry
timer.
"""
longest_match = ()
if len(self._answer_patterns) > 0:
data = (pk.header,) + tuple(pk.data)
for p in list(self._answer_patterns.keys()):
logger.debug('Looking for pattern match on %s vs %s', p, data)
if len(p) <= len(data):
if p == data[0:len(p)]:
match = data[0:len(p)]
if len(match) >= len(longest_match):
logger.debug('Found new longest match %s', match)
longest_match = match
if len(longest_match) > 0:
self._answer_patterns[longest_match].cancel()
del self._answer_patterns[longest_match] | python | def _check_for_answers(self, pk):
"""
Callback called for every packet received to check if we are
waiting for an answer on this port. If so, then cancel the retry
timer.
"""
longest_match = ()
if len(self._answer_patterns) > 0:
data = (pk.header,) + tuple(pk.data)
for p in list(self._answer_patterns.keys()):
logger.debug('Looking for pattern match on %s vs %s', p, data)
if len(p) <= len(data):
if p == data[0:len(p)]:
match = data[0:len(p)]
if len(match) >= len(longest_match):
logger.debug('Found new longest match %s', match)
longest_match = match
if len(longest_match) > 0:
self._answer_patterns[longest_match].cancel()
del self._answer_patterns[longest_match] | [
"def",
"_check_for_answers",
"(",
"self",
",",
"pk",
")",
":",
"longest_match",
"=",
"(",
")",
"if",
"len",
"(",
"self",
".",
"_answer_patterns",
")",
">",
"0",
":",
"data",
"=",
"(",
"pk",
".",
"header",
",",
")",
"+",
"tuple",
"(",
"pk",
".",
"... | Callback called for every packet received to check if we are
waiting for an answer on this port. If so, then cancel the retry
timer. | [
"Callback",
"called",
"for",
"every",
"packet",
"received",
"to",
"check",
"if",
"we",
"are",
"waiting",
"for",
"an",
"answer",
"on",
"this",
"port",
".",
"If",
"so",
"then",
"cancel",
"the",
"retry",
"timer",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/__init__.py#L281-L300 | train | 228,424 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/__init__.py | Crazyflie.send_packet | def send_packet(self, pk, expected_reply=(), resend=False, timeout=0.2):
"""
Send a packet through the link interface.
pk -- Packet to send
expect_answer -- True if a packet from the Crazyflie is expected to
be sent back, otherwise false
"""
self._send_lock.acquire()
if self.link is not None:
if len(expected_reply) > 0 and not resend and \
self.link.needs_resending:
pattern = (pk.header,) + expected_reply
logger.debug(
'Sending packet and expecting the %s pattern back',
pattern)
new_timer = Timer(timeout,
lambda: self._no_answer_do_retry(pk,
pattern))
self._answer_patterns[pattern] = new_timer
new_timer.start()
elif resend:
# Check if we have gotten an answer, if not try again
pattern = expected_reply
if pattern in self._answer_patterns:
logger.debug('We want to resend and the pattern is there')
if self._answer_patterns[pattern]:
new_timer = Timer(timeout,
lambda:
self._no_answer_do_retry(
pk, pattern))
self._answer_patterns[pattern] = new_timer
new_timer.start()
else:
logger.debug('Resend requested, but no pattern found: %s',
self._answer_patterns)
self.link.send_packet(pk)
self.packet_sent.call(pk)
self._send_lock.release() | python | def send_packet(self, pk, expected_reply=(), resend=False, timeout=0.2):
"""
Send a packet through the link interface.
pk -- Packet to send
expect_answer -- True if a packet from the Crazyflie is expected to
be sent back, otherwise false
"""
self._send_lock.acquire()
if self.link is not None:
if len(expected_reply) > 0 and not resend and \
self.link.needs_resending:
pattern = (pk.header,) + expected_reply
logger.debug(
'Sending packet and expecting the %s pattern back',
pattern)
new_timer = Timer(timeout,
lambda: self._no_answer_do_retry(pk,
pattern))
self._answer_patterns[pattern] = new_timer
new_timer.start()
elif resend:
# Check if we have gotten an answer, if not try again
pattern = expected_reply
if pattern in self._answer_patterns:
logger.debug('We want to resend and the pattern is there')
if self._answer_patterns[pattern]:
new_timer = Timer(timeout,
lambda:
self._no_answer_do_retry(
pk, pattern))
self._answer_patterns[pattern] = new_timer
new_timer.start()
else:
logger.debug('Resend requested, but no pattern found: %s',
self._answer_patterns)
self.link.send_packet(pk)
self.packet_sent.call(pk)
self._send_lock.release() | [
"def",
"send_packet",
"(",
"self",
",",
"pk",
",",
"expected_reply",
"=",
"(",
")",
",",
"resend",
"=",
"False",
",",
"timeout",
"=",
"0.2",
")",
":",
"self",
".",
"_send_lock",
".",
"acquire",
"(",
")",
"if",
"self",
".",
"link",
"is",
"not",
"Non... | Send a packet through the link interface.
pk -- Packet to send
expect_answer -- True if a packet from the Crazyflie is expected to
be sent back, otherwise false | [
"Send",
"a",
"packet",
"through",
"the",
"link",
"interface",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/__init__.py#L302-L341 | train | 228,425 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/__init__.py | _IncomingPacketHandler.add_port_callback | def add_port_callback(self, port, cb):
"""Add a callback for data that comes on a specific port"""
logger.debug('Adding callback on port [%d] to [%s]', port, cb)
self.add_header_callback(cb, port, 0, 0xff, 0x0) | python | def add_port_callback(self, port, cb):
"""Add a callback for data that comes on a specific port"""
logger.debug('Adding callback on port [%d] to [%s]', port, cb)
self.add_header_callback(cb, port, 0, 0xff, 0x0) | [
"def",
"add_port_callback",
"(",
"self",
",",
"port",
",",
"cb",
")",
":",
"logger",
".",
"debug",
"(",
"'Adding callback on port [%d] to [%s]'",
",",
"port",
",",
"cb",
")",
"self",
".",
"add_header_callback",
"(",
"cb",
",",
"port",
",",
"0",
",",
"0xff"... | Add a callback for data that comes on a specific port | [
"Add",
"a",
"callback",
"for",
"data",
"that",
"comes",
"on",
"a",
"specific",
"port"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/__init__.py#L356-L359 | train | 228,426 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/__init__.py | _IncomingPacketHandler.remove_port_callback | def remove_port_callback(self, port, cb):
"""Remove a callback for data that comes on a specific port"""
logger.debug('Removing callback on port [%d] to [%s]', port, cb)
for port_callback in self.cb:
if port_callback.port == port and port_callback.callback == cb:
self.cb.remove(port_callback) | python | def remove_port_callback(self, port, cb):
"""Remove a callback for data that comes on a specific port"""
logger.debug('Removing callback on port [%d] to [%s]', port, cb)
for port_callback in self.cb:
if port_callback.port == port and port_callback.callback == cb:
self.cb.remove(port_callback) | [
"def",
"remove_port_callback",
"(",
"self",
",",
"port",
",",
"cb",
")",
":",
"logger",
".",
"debug",
"(",
"'Removing callback on port [%d] to [%s]'",
",",
"port",
",",
"cb",
")",
"for",
"port_callback",
"in",
"self",
".",
"cb",
":",
"if",
"port_callback",
"... | Remove a callback for data that comes on a specific port | [
"Remove",
"a",
"callback",
"for",
"data",
"that",
"comes",
"on",
"a",
"specific",
"port"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/__init__.py#L361-L366 | train | 228,427 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/log.py | LogConfig.add_variable | def add_variable(self, name, fetch_as=None):
"""Add a new variable to the configuration.
name - Complete name of the variable in the form group.name
fetch_as - String representation of the type the variable should be
fetched as (i.e uint8_t, float, FP16, etc)
If no fetch_as type is supplied, then the stored as type will be used
(i.e the type of the fetched variable is the same as it's stored in the
Crazyflie)."""
if fetch_as:
self.variables.append(LogVariable(name, fetch_as))
else:
# We cannot determine the default type until we have connected. So
# save the name and we will add these once we are connected.
self.default_fetch_as.append(name) | python | def add_variable(self, name, fetch_as=None):
"""Add a new variable to the configuration.
name - Complete name of the variable in the form group.name
fetch_as - String representation of the type the variable should be
fetched as (i.e uint8_t, float, FP16, etc)
If no fetch_as type is supplied, then the stored as type will be used
(i.e the type of the fetched variable is the same as it's stored in the
Crazyflie)."""
if fetch_as:
self.variables.append(LogVariable(name, fetch_as))
else:
# We cannot determine the default type until we have connected. So
# save the name and we will add these once we are connected.
self.default_fetch_as.append(name) | [
"def",
"add_variable",
"(",
"self",
",",
"name",
",",
"fetch_as",
"=",
"None",
")",
":",
"if",
"fetch_as",
":",
"self",
".",
"variables",
".",
"append",
"(",
"LogVariable",
"(",
"name",
",",
"fetch_as",
")",
")",
"else",
":",
"# We cannot determine the def... | Add a new variable to the configuration.
name - Complete name of the variable in the form group.name
fetch_as - String representation of the type the variable should be
fetched as (i.e uint8_t, float, FP16, etc)
If no fetch_as type is supplied, then the stored as type will be used
(i.e the type of the fetched variable is the same as it's stored in the
Crazyflie). | [
"Add",
"a",
"new",
"variable",
"to",
"the",
"configuration",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/log.py#L171-L186 | train | 228,428 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/log.py | LogConfig.add_memory | def add_memory(self, name, fetch_as, stored_as, address):
"""Add a raw memory position to log.
name - Arbitrary name of the variable
fetch_as - String representation of the type of the data the memory
should be fetch as (i.e uint8_t, float, FP16)
stored_as - String representation of the type the data is stored as
in the Crazyflie
address - The address of the data
"""
self.variables.append(LogVariable(name, fetch_as, LogVariable.MEM_TYPE,
stored_as, address)) | python | def add_memory(self, name, fetch_as, stored_as, address):
"""Add a raw memory position to log.
name - Arbitrary name of the variable
fetch_as - String representation of the type of the data the memory
should be fetch as (i.e uint8_t, float, FP16)
stored_as - String representation of the type the data is stored as
in the Crazyflie
address - The address of the data
"""
self.variables.append(LogVariable(name, fetch_as, LogVariable.MEM_TYPE,
stored_as, address)) | [
"def",
"add_memory",
"(",
"self",
",",
"name",
",",
"fetch_as",
",",
"stored_as",
",",
"address",
")",
":",
"self",
".",
"variables",
".",
"append",
"(",
"LogVariable",
"(",
"name",
",",
"fetch_as",
",",
"LogVariable",
".",
"MEM_TYPE",
",",
"stored_as",
... | Add a raw memory position to log.
name - Arbitrary name of the variable
fetch_as - String representation of the type of the data the memory
should be fetch as (i.e uint8_t, float, FP16)
stored_as - String representation of the type the data is stored as
in the Crazyflie
address - The address of the data | [
"Add",
"a",
"raw",
"memory",
"position",
"to",
"log",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/log.py#L188-L199 | train | 228,429 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/log.py | LogConfig.create | def create(self):
"""Save the log configuration in the Crazyflie"""
pk = CRTPPacket()
pk.set_header(5, CHAN_SETTINGS)
if self.useV2:
pk.data = (CMD_CREATE_BLOCK_V2, self.id)
else:
pk.data = (CMD_CREATE_BLOCK, self.id)
for var in self.variables:
if (var.is_toc_variable() is False): # Memory location
logger.debug('Logging to raw memory %d, 0x%04X',
var.get_storage_and_fetch_byte(), var.address)
pk.data.append(struct.pack('<B',
var.get_storage_and_fetch_byte()))
pk.data.append(struct.pack('<I', var.address))
else: # Item in TOC
logger.debug('Adding %s with id=%d and type=0x%02X',
var.name,
self.cf.log.toc.get_element_id(
var.name), var.get_storage_and_fetch_byte())
pk.data.append(var.get_storage_and_fetch_byte())
if self.useV2:
ident = self.cf.log.toc.get_element_id(var.name)
pk.data.append(ident & 0x0ff)
pk.data.append((ident >> 8) & 0x0ff)
else:
pk.data.append(self.cf.log.toc.get_element_id(var.name))
logger.debug('Adding log block id {}'.format(self.id))
if self.useV2:
self.cf.send_packet(pk, expected_reply=(
CMD_CREATE_BLOCK_V2, self.id))
else:
self.cf.send_packet(pk, expected_reply=(CMD_CREATE_BLOCK, self.id)) | python | def create(self):
"""Save the log configuration in the Crazyflie"""
pk = CRTPPacket()
pk.set_header(5, CHAN_SETTINGS)
if self.useV2:
pk.data = (CMD_CREATE_BLOCK_V2, self.id)
else:
pk.data = (CMD_CREATE_BLOCK, self.id)
for var in self.variables:
if (var.is_toc_variable() is False): # Memory location
logger.debug('Logging to raw memory %d, 0x%04X',
var.get_storage_and_fetch_byte(), var.address)
pk.data.append(struct.pack('<B',
var.get_storage_and_fetch_byte()))
pk.data.append(struct.pack('<I', var.address))
else: # Item in TOC
logger.debug('Adding %s with id=%d and type=0x%02X',
var.name,
self.cf.log.toc.get_element_id(
var.name), var.get_storage_and_fetch_byte())
pk.data.append(var.get_storage_and_fetch_byte())
if self.useV2:
ident = self.cf.log.toc.get_element_id(var.name)
pk.data.append(ident & 0x0ff)
pk.data.append((ident >> 8) & 0x0ff)
else:
pk.data.append(self.cf.log.toc.get_element_id(var.name))
logger.debug('Adding log block id {}'.format(self.id))
if self.useV2:
self.cf.send_packet(pk, expected_reply=(
CMD_CREATE_BLOCK_V2, self.id))
else:
self.cf.send_packet(pk, expected_reply=(CMD_CREATE_BLOCK, self.id)) | [
"def",
"create",
"(",
"self",
")",
":",
"pk",
"=",
"CRTPPacket",
"(",
")",
"pk",
".",
"set_header",
"(",
"5",
",",
"CHAN_SETTINGS",
")",
"if",
"self",
".",
"useV2",
":",
"pk",
".",
"data",
"=",
"(",
"CMD_CREATE_BLOCK_V2",
",",
"self",
".",
"id",
")... | Save the log configuration in the Crazyflie | [
"Save",
"the",
"log",
"configuration",
"in",
"the",
"Crazyflie"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/log.py#L220-L252 | train | 228,430 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/log.py | LogConfig.start | def start(self):
"""Start the logging for this entry"""
if (self.cf.link is not None):
if (self._added is False):
self.create()
logger.debug('First time block is started, add block')
else:
logger.debug('Block already registered, starting logging'
' for id=%d', self.id)
pk = CRTPPacket()
pk.set_header(5, CHAN_SETTINGS)
pk.data = (CMD_START_LOGGING, self.id, self.period)
self.cf.send_packet(pk, expected_reply=(
CMD_START_LOGGING, self.id)) | python | def start(self):
"""Start the logging for this entry"""
if (self.cf.link is not None):
if (self._added is False):
self.create()
logger.debug('First time block is started, add block')
else:
logger.debug('Block already registered, starting logging'
' for id=%d', self.id)
pk = CRTPPacket()
pk.set_header(5, CHAN_SETTINGS)
pk.data = (CMD_START_LOGGING, self.id, self.period)
self.cf.send_packet(pk, expected_reply=(
CMD_START_LOGGING, self.id)) | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"cf",
".",
"link",
"is",
"not",
"None",
")",
":",
"if",
"(",
"self",
".",
"_added",
"is",
"False",
")",
":",
"self",
".",
"create",
"(",
")",
"logger",
".",
"debug",
"(",
"'First ti... | Start the logging for this entry | [
"Start",
"the",
"logging",
"for",
"this",
"entry"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/log.py#L254-L267 | train | 228,431 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/log.py | LogConfig.stop | def stop(self):
"""Stop the logging for this entry"""
if (self.cf.link is not None):
if (self.id is None):
logger.warning('Stopping block, but no block registered')
else:
logger.debug('Sending stop logging for block id=%d', self.id)
pk = CRTPPacket()
pk.set_header(5, CHAN_SETTINGS)
pk.data = (CMD_STOP_LOGGING, self.id)
self.cf.send_packet(
pk, expected_reply=(CMD_STOP_LOGGING, self.id)) | python | def stop(self):
"""Stop the logging for this entry"""
if (self.cf.link is not None):
if (self.id is None):
logger.warning('Stopping block, but no block registered')
else:
logger.debug('Sending stop logging for block id=%d', self.id)
pk = CRTPPacket()
pk.set_header(5, CHAN_SETTINGS)
pk.data = (CMD_STOP_LOGGING, self.id)
self.cf.send_packet(
pk, expected_reply=(CMD_STOP_LOGGING, self.id)) | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"cf",
".",
"link",
"is",
"not",
"None",
")",
":",
"if",
"(",
"self",
".",
"id",
"is",
"None",
")",
":",
"logger",
".",
"warning",
"(",
"'Stopping block, but no block registered'",
")",
"el... | Stop the logging for this entry | [
"Stop",
"the",
"logging",
"for",
"this",
"entry"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/log.py#L269-L280 | train | 228,432 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/log.py | LogConfig.delete | def delete(self):
"""Delete this entry in the Crazyflie"""
if (self.cf.link is not None):
if (self.id is None):
logger.warning('Delete block, but no block registered')
else:
logger.debug('LogEntry: Sending delete logging for block id=%d'
% self.id)
pk = CRTPPacket()
pk.set_header(5, CHAN_SETTINGS)
pk.data = (CMD_DELETE_BLOCK, self.id)
self.cf.send_packet(
pk, expected_reply=(CMD_DELETE_BLOCK, self.id)) | python | def delete(self):
"""Delete this entry in the Crazyflie"""
if (self.cf.link is not None):
if (self.id is None):
logger.warning('Delete block, but no block registered')
else:
logger.debug('LogEntry: Sending delete logging for block id=%d'
% self.id)
pk = CRTPPacket()
pk.set_header(5, CHAN_SETTINGS)
pk.data = (CMD_DELETE_BLOCK, self.id)
self.cf.send_packet(
pk, expected_reply=(CMD_DELETE_BLOCK, self.id)) | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"cf",
".",
"link",
"is",
"not",
"None",
")",
":",
"if",
"(",
"self",
".",
"id",
"is",
"None",
")",
":",
"logger",
".",
"warning",
"(",
"'Delete block, but no block registered'",
")",
"el... | Delete this entry in the Crazyflie | [
"Delete",
"this",
"entry",
"in",
"the",
"Crazyflie"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/log.py#L282-L294 | train | 228,433 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/log.py | LogConfig.unpack_log_data | def unpack_log_data(self, log_data, timestamp):
"""Unpack received logging data so it represent real values according
to the configuration in the entry"""
ret_data = {}
data_index = 0
for var in self.variables:
size = LogTocElement.get_size_from_id(var.fetch_as)
name = var.name
unpackstring = LogTocElement.get_unpack_string_from_id(
var.fetch_as)
value = struct.unpack(
unpackstring, log_data[data_index:data_index + size])[0]
data_index += size
ret_data[name] = value
self.data_received_cb.call(timestamp, ret_data, self) | python | def unpack_log_data(self, log_data, timestamp):
"""Unpack received logging data so it represent real values according
to the configuration in the entry"""
ret_data = {}
data_index = 0
for var in self.variables:
size = LogTocElement.get_size_from_id(var.fetch_as)
name = var.name
unpackstring = LogTocElement.get_unpack_string_from_id(
var.fetch_as)
value = struct.unpack(
unpackstring, log_data[data_index:data_index + size])[0]
data_index += size
ret_data[name] = value
self.data_received_cb.call(timestamp, ret_data, self) | [
"def",
"unpack_log_data",
"(",
"self",
",",
"log_data",
",",
"timestamp",
")",
":",
"ret_data",
"=",
"{",
"}",
"data_index",
"=",
"0",
"for",
"var",
"in",
"self",
".",
"variables",
":",
"size",
"=",
"LogTocElement",
".",
"get_size_from_id",
"(",
"var",
"... | Unpack received logging data so it represent real values according
to the configuration in the entry | [
"Unpack",
"received",
"logging",
"data",
"so",
"it",
"represent",
"real",
"values",
"according",
"to",
"the",
"configuration",
"in",
"the",
"entry"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/log.py#L296-L310 | train | 228,434 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/log.py | LogTocElement.get_id_from_cstring | def get_id_from_cstring(name):
"""Return variable type id given the C-storage name"""
for key in list(LogTocElement.types.keys()):
if (LogTocElement.types[key][0] == name):
return key
raise KeyError('Type [%s] not found in LogTocElement.types!' % name) | python | def get_id_from_cstring(name):
"""Return variable type id given the C-storage name"""
for key in list(LogTocElement.types.keys()):
if (LogTocElement.types[key][0] == name):
return key
raise KeyError('Type [%s] not found in LogTocElement.types!' % name) | [
"def",
"get_id_from_cstring",
"(",
"name",
")",
":",
"for",
"key",
"in",
"list",
"(",
"LogTocElement",
".",
"types",
".",
"keys",
"(",
")",
")",
":",
"if",
"(",
"LogTocElement",
".",
"types",
"[",
"key",
"]",
"[",
"0",
"]",
"==",
"name",
")",
":",
... | Return variable type id given the C-storage name | [
"Return",
"variable",
"type",
"id",
"given",
"the",
"C",
"-",
"storage",
"name"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/log.py#L325-L330 | train | 228,435 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/log.py | Log.add_config | def add_config(self, logconf):
"""Add a log configuration to the logging framework.
When doing this the contents of the log configuration will be validated
and listeners for new log configurations will be notified. When
validating the configuration the variables are checked against the TOC
to see that they actually exist. If they don't then the configuration
cannot be used. Since a valid TOC is required, a Crazyflie has to be
connected when calling this method, otherwise it will fail."""
if not self.cf.link:
logger.error('Cannot add configs without being connected to a '
'Crazyflie!')
return
# If the log configuration contains variables that we added without
# type (i.e we want the stored as type for fetching as well) then
# resolve this now and add them to the block again.
for name in logconf.default_fetch_as:
var = self.toc.get_element_by_complete_name(name)
if not var:
logger.warning(
'%s not in TOC, this block cannot be used!', name)
logconf.valid = False
raise KeyError('Variable {} not in TOC'.format(name))
# Now that we know what type this variable has, add it to the log
# config again with the correct type
logconf.add_variable(name, var.ctype)
# Now check that all the added variables are in the TOC and that
# the total size constraint of a data packet with logging data is
# not
size = 0
for var in logconf.variables:
size += LogTocElement.get_size_from_id(var.fetch_as)
# Check that we are able to find the variable in the TOC so
# we can return error already now and not when the config is sent
if var.is_toc_variable():
if (self.toc.get_element_by_complete_name(var.name) is None):
logger.warning(
'Log: %s not in TOC, this block cannot be used!',
var.name)
logconf.valid = False
raise KeyError('Variable {} not in TOC'.format(var.name))
if (size <= MAX_LOG_DATA_PACKET_SIZE and
(logconf.period > 0 and logconf.period < 0xFF)):
logconf.valid = True
logconf.cf = self.cf
logconf.id = self._config_id_counter
logconf.useV2 = self._useV2
self._config_id_counter = (self._config_id_counter + 1) % 255
self.log_blocks.append(logconf)
self.block_added_cb.call(logconf)
else:
logconf.valid = False
raise AttributeError(
'The log configuration is too large or has an invalid '
'parameter') | python | def add_config(self, logconf):
"""Add a log configuration to the logging framework.
When doing this the contents of the log configuration will be validated
and listeners for new log configurations will be notified. When
validating the configuration the variables are checked against the TOC
to see that they actually exist. If they don't then the configuration
cannot be used. Since a valid TOC is required, a Crazyflie has to be
connected when calling this method, otherwise it will fail."""
if not self.cf.link:
logger.error('Cannot add configs without being connected to a '
'Crazyflie!')
return
# If the log configuration contains variables that we added without
# type (i.e we want the stored as type for fetching as well) then
# resolve this now and add them to the block again.
for name in logconf.default_fetch_as:
var = self.toc.get_element_by_complete_name(name)
if not var:
logger.warning(
'%s not in TOC, this block cannot be used!', name)
logconf.valid = False
raise KeyError('Variable {} not in TOC'.format(name))
# Now that we know what type this variable has, add it to the log
# config again with the correct type
logconf.add_variable(name, var.ctype)
# Now check that all the added variables are in the TOC and that
# the total size constraint of a data packet with logging data is
# not
size = 0
for var in logconf.variables:
size += LogTocElement.get_size_from_id(var.fetch_as)
# Check that we are able to find the variable in the TOC so
# we can return error already now and not when the config is sent
if var.is_toc_variable():
if (self.toc.get_element_by_complete_name(var.name) is None):
logger.warning(
'Log: %s not in TOC, this block cannot be used!',
var.name)
logconf.valid = False
raise KeyError('Variable {} not in TOC'.format(var.name))
if (size <= MAX_LOG_DATA_PACKET_SIZE and
(logconf.period > 0 and logconf.period < 0xFF)):
logconf.valid = True
logconf.cf = self.cf
logconf.id = self._config_id_counter
logconf.useV2 = self._useV2
self._config_id_counter = (self._config_id_counter + 1) % 255
self.log_blocks.append(logconf)
self.block_added_cb.call(logconf)
else:
logconf.valid = False
raise AttributeError(
'The log configuration is too large or has an invalid '
'parameter') | [
"def",
"add_config",
"(",
"self",
",",
"logconf",
")",
":",
"if",
"not",
"self",
".",
"cf",
".",
"link",
":",
"logger",
".",
"error",
"(",
"'Cannot add configs without being connected to a '",
"'Crazyflie!'",
")",
"return",
"# If the log configuration contains variabl... | Add a log configuration to the logging framework.
When doing this the contents of the log configuration will be validated
and listeners for new log configurations will be notified. When
validating the configuration the variables are checked against the TOC
to see that they actually exist. If they don't then the configuration
cannot be used. Since a valid TOC is required, a Crazyflie has to be
connected when calling this method, otherwise it will fail. | [
"Add",
"a",
"log",
"configuration",
"to",
"the",
"logging",
"framework",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/log.py#L410-L468 | train | 228,436 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/log.py | Log.refresh_toc | def refresh_toc(self, refresh_done_callback, toc_cache):
"""Start refreshing the table of loggale variables"""
self._useV2 = self.cf.platform.get_protocol_version() >= 4
self._toc_cache = toc_cache
self._refresh_callback = refresh_done_callback
self.toc = None
pk = CRTPPacket()
pk.set_header(CRTPPort.LOGGING, CHAN_SETTINGS)
pk.data = (CMD_RESET_LOGGING,)
self.cf.send_packet(pk, expected_reply=(CMD_RESET_LOGGING,)) | python | def refresh_toc(self, refresh_done_callback, toc_cache):
"""Start refreshing the table of loggale variables"""
self._useV2 = self.cf.platform.get_protocol_version() >= 4
self._toc_cache = toc_cache
self._refresh_callback = refresh_done_callback
self.toc = None
pk = CRTPPacket()
pk.set_header(CRTPPort.LOGGING, CHAN_SETTINGS)
pk.data = (CMD_RESET_LOGGING,)
self.cf.send_packet(pk, expected_reply=(CMD_RESET_LOGGING,)) | [
"def",
"refresh_toc",
"(",
"self",
",",
"refresh_done_callback",
",",
"toc_cache",
")",
":",
"self",
".",
"_useV2",
"=",
"self",
".",
"cf",
".",
"platform",
".",
"get_protocol_version",
"(",
")",
">=",
"4",
"self",
".",
"_toc_cache",
"=",
"toc_cache",
"sel... | Start refreshing the table of loggale variables | [
"Start",
"refreshing",
"the",
"table",
"of",
"loggale",
"variables"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/log.py#L470-L482 | train | 228,437 |
bitcraze/crazyflie-lib-python | cflib/crtp/__init__.py | init_drivers | def init_drivers(enable_debug_driver=False):
"""Initialize all the drivers."""
for driver in DRIVERS:
try:
if driver != DebugDriver or enable_debug_driver:
CLASSES.append(driver)
except Exception: # pylint: disable=W0703
continue | python | def init_drivers(enable_debug_driver=False):
"""Initialize all the drivers."""
for driver in DRIVERS:
try:
if driver != DebugDriver or enable_debug_driver:
CLASSES.append(driver)
except Exception: # pylint: disable=W0703
continue | [
"def",
"init_drivers",
"(",
"enable_debug_driver",
"=",
"False",
")",
":",
"for",
"driver",
"in",
"DRIVERS",
":",
"try",
":",
"if",
"driver",
"!=",
"DebugDriver",
"or",
"enable_debug_driver",
":",
"CLASSES",
".",
"append",
"(",
"driver",
")",
"except",
"Exce... | Initialize all the drivers. | [
"Initialize",
"all",
"the",
"drivers",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crtp/__init__.py#L47-L54 | train | 228,438 |
bitcraze/crazyflie-lib-python | cflib/crtp/__init__.py | scan_interfaces | def scan_interfaces(address=None):
""" Scan all the interfaces for available Crazyflies """
available = []
found = []
for driverClass in CLASSES:
try:
logger.debug('Scanning: %s', driverClass)
instance = driverClass()
found = instance.scan_interface(address)
available += found
except Exception:
raise
return available | python | def scan_interfaces(address=None):
""" Scan all the interfaces for available Crazyflies """
available = []
found = []
for driverClass in CLASSES:
try:
logger.debug('Scanning: %s', driverClass)
instance = driverClass()
found = instance.scan_interface(address)
available += found
except Exception:
raise
return available | [
"def",
"scan_interfaces",
"(",
"address",
"=",
"None",
")",
":",
"available",
"=",
"[",
"]",
"found",
"=",
"[",
"]",
"for",
"driverClass",
"in",
"CLASSES",
":",
"try",
":",
"logger",
".",
"debug",
"(",
"'Scanning: %s'",
",",
"driverClass",
")",
"instance... | Scan all the interfaces for available Crazyflies | [
"Scan",
"all",
"the",
"interfaces",
"for",
"available",
"Crazyflies"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crtp/__init__.py#L57-L69 | train | 228,439 |
bitcraze/crazyflie-lib-python | cflib/crtp/__init__.py | get_interfaces_status | def get_interfaces_status():
"""Get the status of all the interfaces"""
status = {}
for driverClass in CLASSES:
try:
instance = driverClass()
status[instance.get_name()] = instance.get_status()
except Exception:
raise
return status | python | def get_interfaces_status():
"""Get the status of all the interfaces"""
status = {}
for driverClass in CLASSES:
try:
instance = driverClass()
status[instance.get_name()] = instance.get_status()
except Exception:
raise
return status | [
"def",
"get_interfaces_status",
"(",
")",
":",
"status",
"=",
"{",
"}",
"for",
"driverClass",
"in",
"CLASSES",
":",
"try",
":",
"instance",
"=",
"driverClass",
"(",
")",
"status",
"[",
"instance",
".",
"get_name",
"(",
")",
"]",
"=",
"instance",
".",
"... | Get the status of all the interfaces | [
"Get",
"the",
"status",
"of",
"all",
"the",
"interfaces"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crtp/__init__.py#L72-L81 | train | 228,440 |
bitcraze/crazyflie-lib-python | cflib/crtp/__init__.py | get_link_driver | def get_link_driver(uri, link_quality_callback=None, link_error_callback=None):
"""Return the link driver for the given URI. Returns None if no driver
was found for the URI or the URI was not well formatted for the matching
driver."""
for driverClass in CLASSES:
try:
instance = driverClass()
instance.connect(uri, link_quality_callback, link_error_callback)
return instance
except WrongUriType:
continue
return None | python | def get_link_driver(uri, link_quality_callback=None, link_error_callback=None):
"""Return the link driver for the given URI. Returns None if no driver
was found for the URI or the URI was not well formatted for the matching
driver."""
for driverClass in CLASSES:
try:
instance = driverClass()
instance.connect(uri, link_quality_callback, link_error_callback)
return instance
except WrongUriType:
continue
return None | [
"def",
"get_link_driver",
"(",
"uri",
",",
"link_quality_callback",
"=",
"None",
",",
"link_error_callback",
"=",
"None",
")",
":",
"for",
"driverClass",
"in",
"CLASSES",
":",
"try",
":",
"instance",
"=",
"driverClass",
"(",
")",
"instance",
".",
"connect",
... | Return the link driver for the given URI. Returns None if no driver
was found for the URI or the URI was not well formatted for the matching
driver. | [
"Return",
"the",
"link",
"driver",
"for",
"the",
"given",
"URI",
".",
"Returns",
"None",
"if",
"no",
"driver",
"was",
"found",
"for",
"the",
"URI",
"or",
"the",
"URI",
"was",
"not",
"well",
"formatted",
"for",
"the",
"matching",
"driver",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crtp/__init__.py#L84-L96 | train | 228,441 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/localization.py | Localization.send_short_lpp_packet | def send_short_lpp_packet(self, dest_id, data):
"""
Send ultra-wide-band LPP packet to dest_id
"""
pk = CRTPPacket()
pk.port = CRTPPort.LOCALIZATION
pk.channel = self.GENERIC_CH
pk.data = struct.pack('<BB', self.LPS_SHORT_LPP_PACKET, dest_id) + data
self._cf.send_packet(pk) | python | def send_short_lpp_packet(self, dest_id, data):
"""
Send ultra-wide-band LPP packet to dest_id
"""
pk = CRTPPacket()
pk.port = CRTPPort.LOCALIZATION
pk.channel = self.GENERIC_CH
pk.data = struct.pack('<BB', self.LPS_SHORT_LPP_PACKET, dest_id) + data
self._cf.send_packet(pk) | [
"def",
"send_short_lpp_packet",
"(",
"self",
",",
"dest_id",
",",
"data",
")",
":",
"pk",
"=",
"CRTPPacket",
"(",
")",
"pk",
".",
"port",
"=",
"CRTPPort",
".",
"LOCALIZATION",
"pk",
".",
"channel",
"=",
"self",
".",
"GENERIC_CH",
"pk",
".",
"data",
"="... | Send ultra-wide-band LPP packet to dest_id | [
"Send",
"ultra",
"-",
"wide",
"-",
"band",
"LPP",
"packet",
"to",
"dest_id"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/localization.py#L113-L122 | train | 228,442 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/commander.py | Commander.send_velocity_world_setpoint | def send_velocity_world_setpoint(self, vx, vy, vz, yawrate):
"""
Send Velocity in the world frame of reference setpoint.
vx, vy, vz are in m/s
yawrate is in degrees/s
"""
pk = CRTPPacket()
pk.port = CRTPPort.COMMANDER_GENERIC
pk.data = struct.pack('<Bffff', TYPE_VELOCITY_WORLD,
vx, vy, vz, yawrate)
self._cf.send_packet(pk) | python | def send_velocity_world_setpoint(self, vx, vy, vz, yawrate):
"""
Send Velocity in the world frame of reference setpoint.
vx, vy, vz are in m/s
yawrate is in degrees/s
"""
pk = CRTPPacket()
pk.port = CRTPPort.COMMANDER_GENERIC
pk.data = struct.pack('<Bffff', TYPE_VELOCITY_WORLD,
vx, vy, vz, yawrate)
self._cf.send_packet(pk) | [
"def",
"send_velocity_world_setpoint",
"(",
"self",
",",
"vx",
",",
"vy",
",",
"vz",
",",
"yawrate",
")",
":",
"pk",
"=",
"CRTPPacket",
"(",
")",
"pk",
".",
"port",
"=",
"CRTPPort",
".",
"COMMANDER_GENERIC",
"pk",
".",
"data",
"=",
"struct",
".",
"pack... | Send Velocity in the world frame of reference setpoint.
vx, vy, vz are in m/s
yawrate is in degrees/s | [
"Send",
"Velocity",
"in",
"the",
"world",
"frame",
"of",
"reference",
"setpoint",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/commander.py#L92-L103 | train | 228,443 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/commander.py | Commander.send_position_setpoint | def send_position_setpoint(self, x, y, z, yaw):
"""
Control mode where the position is sent as absolute x,y,z coordinate in
meter and the yaw is the absolute orientation.
x and y are in m
yaw is in degrees
"""
pk = CRTPPacket()
pk.port = CRTPPort.COMMANDER_GENERIC
pk.data = struct.pack('<Bffff', TYPE_POSITION,
x, y, z, yaw)
self._cf.send_packet(pk) | python | def send_position_setpoint(self, x, y, z, yaw):
"""
Control mode where the position is sent as absolute x,y,z coordinate in
meter and the yaw is the absolute orientation.
x and y are in m
yaw is in degrees
"""
pk = CRTPPacket()
pk.port = CRTPPort.COMMANDER_GENERIC
pk.data = struct.pack('<Bffff', TYPE_POSITION,
x, y, z, yaw)
self._cf.send_packet(pk) | [
"def",
"send_position_setpoint",
"(",
"self",
",",
"x",
",",
"y",
",",
"z",
",",
"yaw",
")",
":",
"pk",
"=",
"CRTPPacket",
"(",
")",
"pk",
".",
"port",
"=",
"CRTPPort",
".",
"COMMANDER_GENERIC",
"pk",
".",
"data",
"=",
"struct",
".",
"pack",
"(",
"... | Control mode where the position is sent as absolute x,y,z coordinate in
meter and the yaw is the absolute orientation.
x and y are in m
yaw is in degrees | [
"Control",
"mode",
"where",
"the",
"position",
"is",
"sent",
"as",
"absolute",
"x",
"y",
"z",
"coordinate",
"in",
"meter",
"and",
"the",
"yaw",
"is",
"the",
"absolute",
"orientation",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/commander.py#L132-L144 | train | 228,444 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/mem.py | MemoryElement.type_to_string | def type_to_string(t):
"""Get string representation of memory type"""
if t == MemoryElement.TYPE_I2C:
return 'I2C'
if t == MemoryElement.TYPE_1W:
return '1-wire'
if t == MemoryElement.TYPE_DRIVER_LED:
return 'LED driver'
if t == MemoryElement.TYPE_LOCO:
return 'Loco Positioning'
if t == MemoryElement.TYPE_TRAJ:
return 'Trajectory'
if t == MemoryElement.TYPE_LOCO2:
return 'Loco Positioning 2'
return 'Unknown' | python | def type_to_string(t):
"""Get string representation of memory type"""
if t == MemoryElement.TYPE_I2C:
return 'I2C'
if t == MemoryElement.TYPE_1W:
return '1-wire'
if t == MemoryElement.TYPE_DRIVER_LED:
return 'LED driver'
if t == MemoryElement.TYPE_LOCO:
return 'Loco Positioning'
if t == MemoryElement.TYPE_TRAJ:
return 'Trajectory'
if t == MemoryElement.TYPE_LOCO2:
return 'Loco Positioning 2'
return 'Unknown' | [
"def",
"type_to_string",
"(",
"t",
")",
":",
"if",
"t",
"==",
"MemoryElement",
".",
"TYPE_I2C",
":",
"return",
"'I2C'",
"if",
"t",
"==",
"MemoryElement",
".",
"TYPE_1W",
":",
"return",
"'1-wire'",
"if",
"t",
"==",
"MemoryElement",
".",
"TYPE_DRIVER_LED",
"... | Get string representation of memory type | [
"Get",
"string",
"representation",
"of",
"memory",
"type"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/mem.py#L86-L100 | train | 228,445 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/mem.py | LEDDriverMemory.write_data | def write_data(self, write_finished_cb):
"""Write the saved LED-ring data to the Crazyflie"""
self._write_finished_cb = write_finished_cb
data = bytearray()
for led in self.leds:
# In order to fit all the LEDs in one radio packet RGB565 is used
# to compress the colors. The calculations below converts 3 bytes
# RGB into 2 bytes RGB565. Then shifts the value of each color to
# LSB, applies the intensity and shifts them back for correct
# alignment on 2 bytes.
R5 = ((int)((((int(led.r) & 0xFF) * 249 + 1014) >> 11) & 0x1F) *
led.intensity / 100)
G6 = ((int)((((int(led.g) & 0xFF) * 253 + 505) >> 10) & 0x3F) *
led.intensity / 100)
B5 = ((int)((((int(led.b) & 0xFF) * 249 + 1014) >> 11) & 0x1F) *
led.intensity / 100)
tmp = (int(R5) << 11) | (int(G6) << 5) | (int(B5) << 0)
data += bytearray((tmp >> 8, tmp & 0xFF))
self.mem_handler.write(self, 0x00, data, flush_queue=True) | python | def write_data(self, write_finished_cb):
"""Write the saved LED-ring data to the Crazyflie"""
self._write_finished_cb = write_finished_cb
data = bytearray()
for led in self.leds:
# In order to fit all the LEDs in one radio packet RGB565 is used
# to compress the colors. The calculations below converts 3 bytes
# RGB into 2 bytes RGB565. Then shifts the value of each color to
# LSB, applies the intensity and shifts them back for correct
# alignment on 2 bytes.
R5 = ((int)((((int(led.r) & 0xFF) * 249 + 1014) >> 11) & 0x1F) *
led.intensity / 100)
G6 = ((int)((((int(led.g) & 0xFF) * 253 + 505) >> 10) & 0x3F) *
led.intensity / 100)
B5 = ((int)((((int(led.b) & 0xFF) * 249 + 1014) >> 11) & 0x1F) *
led.intensity / 100)
tmp = (int(R5) << 11) | (int(G6) << 5) | (int(B5) << 0)
data += bytearray((tmp >> 8, tmp & 0xFF))
self.mem_handler.write(self, 0x00, data, flush_queue=True) | [
"def",
"write_data",
"(",
"self",
",",
"write_finished_cb",
")",
":",
"self",
".",
"_write_finished_cb",
"=",
"write_finished_cb",
"data",
"=",
"bytearray",
"(",
")",
"for",
"led",
"in",
"self",
".",
"leds",
":",
"# In order to fit all the LEDs in one radio packet R... | Write the saved LED-ring data to the Crazyflie | [
"Write",
"the",
"saved",
"LED",
"-",
"ring",
"data",
"to",
"the",
"Crazyflie"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/mem.py#L151-L169 | train | 228,446 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/mem.py | OWElement._parse_and_check_elements | def _parse_and_check_elements(self, data):
"""
Parse and check the CRC and length of the elements part of the memory
"""
crc = data[-1]
test_crc = crc32(data[:-1]) & 0x0ff
elem_data = data[2:-1]
if test_crc == crc:
while len(elem_data) > 0:
(eid, elen) = struct.unpack('BB', elem_data[:2])
self.elements[self.element_mapping[eid]] = \
elem_data[2:2 + elen].decode('ISO-8859-1')
elem_data = elem_data[2 + elen:]
return True
return False | python | def _parse_and_check_elements(self, data):
"""
Parse and check the CRC and length of the elements part of the memory
"""
crc = data[-1]
test_crc = crc32(data[:-1]) & 0x0ff
elem_data = data[2:-1]
if test_crc == crc:
while len(elem_data) > 0:
(eid, elen) = struct.unpack('BB', elem_data[:2])
self.elements[self.element_mapping[eid]] = \
elem_data[2:2 + elen].decode('ISO-8859-1')
elem_data = elem_data[2 + elen:]
return True
return False | [
"def",
"_parse_and_check_elements",
"(",
"self",
",",
"data",
")",
":",
"crc",
"=",
"data",
"[",
"-",
"1",
"]",
"test_crc",
"=",
"crc32",
"(",
"data",
"[",
":",
"-",
"1",
"]",
")",
"&",
"0x0ff",
"elem_data",
"=",
"data",
"[",
"2",
":",
"-",
"1",
... | Parse and check the CRC and length of the elements part of the memory | [
"Parse",
"and",
"check",
"the",
"CRC",
"and",
"length",
"of",
"the",
"elements",
"part",
"of",
"the",
"memory"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/mem.py#L347-L361 | train | 228,447 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/mem.py | OWElement._parse_and_check_header | def _parse_and_check_header(self, data):
"""Parse and check the CRC of the header part of the memory"""
(start, self.pins, self.vid, self.pid, crc) = struct.unpack('<BIBBB',
data)
test_crc = crc32(data[:-1]) & 0x0ff
if start == 0xEB and crc == test_crc:
return True
return False | python | def _parse_and_check_header(self, data):
"""Parse and check the CRC of the header part of the memory"""
(start, self.pins, self.vid, self.pid, crc) = struct.unpack('<BIBBB',
data)
test_crc = crc32(data[:-1]) & 0x0ff
if start == 0xEB and crc == test_crc:
return True
return False | [
"def",
"_parse_and_check_header",
"(",
"self",
",",
"data",
")",
":",
"(",
"start",
",",
"self",
".",
"pins",
",",
"self",
".",
"vid",
",",
"self",
".",
"pid",
",",
"crc",
")",
"=",
"struct",
".",
"unpack",
"(",
"'<BIBBB'",
",",
"data",
")",
"test_... | Parse and check the CRC of the header part of the memory | [
"Parse",
"and",
"check",
"the",
"CRC",
"of",
"the",
"header",
"part",
"of",
"the",
"memory"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/mem.py#L412-L419 | train | 228,448 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/mem.py | LocoMemory2.update_id_list | def update_id_list(self, update_ids_finished_cb):
"""Request an update of the id list"""
if not self._update_ids_finished_cb:
self._update_ids_finished_cb = update_ids_finished_cb
self.anchor_ids = []
self.active_anchor_ids = []
self.anchor_data = {}
self.nr_of_anchors = 0
self.ids_valid = False
self.data_valid = False
logger.debug('Updating ids of memory {}'.format(self.id))
# Start reading the header
self.mem_handler.read(self, LocoMemory2.ADR_ID_LIST,
LocoMemory2.ID_LIST_LEN) | python | def update_id_list(self, update_ids_finished_cb):
"""Request an update of the id list"""
if not self._update_ids_finished_cb:
self._update_ids_finished_cb = update_ids_finished_cb
self.anchor_ids = []
self.active_anchor_ids = []
self.anchor_data = {}
self.nr_of_anchors = 0
self.ids_valid = False
self.data_valid = False
logger.debug('Updating ids of memory {}'.format(self.id))
# Start reading the header
self.mem_handler.read(self, LocoMemory2.ADR_ID_LIST,
LocoMemory2.ID_LIST_LEN) | [
"def",
"update_id_list",
"(",
"self",
",",
"update_ids_finished_cb",
")",
":",
"if",
"not",
"self",
".",
"_update_ids_finished_cb",
":",
"self",
".",
"_update_ids_finished_cb",
"=",
"update_ids_finished_cb",
"self",
".",
"anchor_ids",
"=",
"[",
"]",
"self",
".",
... | Request an update of the id list | [
"Request",
"an",
"update",
"of",
"the",
"id",
"list"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/mem.py#L572-L588 | train | 228,449 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/mem.py | LocoMemory2.update_active_id_list | def update_active_id_list(self, update_active_ids_finished_cb):
"""Request an update of the active id list"""
if not self._update_active_ids_finished_cb:
self._update_active_ids_finished_cb = update_active_ids_finished_cb
self.active_anchor_ids = []
self.active_ids_valid = False
logger.debug('Updating active ids of memory {}'.format(self.id))
# Start reading the header
self.mem_handler.read(self, LocoMemory2.ADR_ACTIVE_ID_LIST,
LocoMemory2.ID_LIST_LEN) | python | def update_active_id_list(self, update_active_ids_finished_cb):
"""Request an update of the active id list"""
if not self._update_active_ids_finished_cb:
self._update_active_ids_finished_cb = update_active_ids_finished_cb
self.active_anchor_ids = []
self.active_ids_valid = False
logger.debug('Updating active ids of memory {}'.format(self.id))
# Start reading the header
self.mem_handler.read(self, LocoMemory2.ADR_ACTIVE_ID_LIST,
LocoMemory2.ID_LIST_LEN) | [
"def",
"update_active_id_list",
"(",
"self",
",",
"update_active_ids_finished_cb",
")",
":",
"if",
"not",
"self",
".",
"_update_active_ids_finished_cb",
":",
"self",
".",
"_update_active_ids_finished_cb",
"=",
"update_active_ids_finished_cb",
"self",
".",
"active_anchor_ids... | Request an update of the active id list | [
"Request",
"an",
"update",
"of",
"the",
"active",
"id",
"list"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/mem.py#L590-L602 | train | 228,450 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/mem.py | LocoMemory2.update_data | def update_data(self, update_data_finished_cb):
"""Request an update of the anchor data"""
if not self._update_data_finished_cb and self.nr_of_anchors > 0:
self._update_data_finished_cb = update_data_finished_cb
self.anchor_data = {}
self.data_valid = False
self._nr_of_anchors_to_fetch = self.nr_of_anchors
logger.debug('Updating anchor data of memory {}'.format(self.id))
# Start reading the first anchor
self._currently_fetching_index = 0
self._request_page(self.anchor_ids[self._currently_fetching_index]) | python | def update_data(self, update_data_finished_cb):
"""Request an update of the anchor data"""
if not self._update_data_finished_cb and self.nr_of_anchors > 0:
self._update_data_finished_cb = update_data_finished_cb
self.anchor_data = {}
self.data_valid = False
self._nr_of_anchors_to_fetch = self.nr_of_anchors
logger.debug('Updating anchor data of memory {}'.format(self.id))
# Start reading the first anchor
self._currently_fetching_index = 0
self._request_page(self.anchor_ids[self._currently_fetching_index]) | [
"def",
"update_data",
"(",
"self",
",",
"update_data_finished_cb",
")",
":",
"if",
"not",
"self",
".",
"_update_data_finished_cb",
"and",
"self",
".",
"nr_of_anchors",
">",
"0",
":",
"self",
".",
"_update_data_finished_cb",
"=",
"update_data_finished_cb",
"self",
... | Request an update of the anchor data | [
"Request",
"an",
"update",
"of",
"the",
"anchor",
"data"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/mem.py#L604-L617 | train | 228,451 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/mem.py | TrajectoryMemory.write_data | def write_data(self, write_finished_cb):
"""Write trajectory data to the Crazyflie"""
self._write_finished_cb = write_finished_cb
data = bytearray()
for poly4D in self.poly4Ds:
data += struct.pack('<ffffffff', *poly4D.x.values)
data += struct.pack('<ffffffff', *poly4D.y.values)
data += struct.pack('<ffffffff', *poly4D.z.values)
data += struct.pack('<ffffffff', *poly4D.yaw.values)
data += struct.pack('<f', poly4D.duration)
self.mem_handler.write(self, 0x00, data, flush_queue=True) | python | def write_data(self, write_finished_cb):
"""Write trajectory data to the Crazyflie"""
self._write_finished_cb = write_finished_cb
data = bytearray()
for poly4D in self.poly4Ds:
data += struct.pack('<ffffffff', *poly4D.x.values)
data += struct.pack('<ffffffff', *poly4D.y.values)
data += struct.pack('<ffffffff', *poly4D.z.values)
data += struct.pack('<ffffffff', *poly4D.yaw.values)
data += struct.pack('<f', poly4D.duration)
self.mem_handler.write(self, 0x00, data, flush_queue=True) | [
"def",
"write_data",
"(",
"self",
",",
"write_finished_cb",
")",
":",
"self",
".",
"_write_finished_cb",
"=",
"write_finished_cb",
"data",
"=",
"bytearray",
"(",
")",
"for",
"poly4D",
"in",
"self",
".",
"poly4Ds",
":",
"data",
"+=",
"struct",
".",
"pack",
... | Write trajectory data to the Crazyflie | [
"Write",
"trajectory",
"data",
"to",
"the",
"Crazyflie"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/mem.py#L690-L702 | train | 228,452 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/mem.py | Memory.get_mem | def get_mem(self, id):
"""Fetch the memory with the supplied id"""
for m in self.mems:
if m.id == id:
return m
return None | python | def get_mem(self, id):
"""Fetch the memory with the supplied id"""
for m in self.mems:
if m.id == id:
return m
return None | [
"def",
"get_mem",
"(",
"self",
",",
"id",
")",
":",
"for",
"m",
"in",
"self",
".",
"mems",
":",
"if",
"m",
".",
"id",
"==",
"id",
":",
"return",
"m",
"return",
"None"
] | Fetch the memory with the supplied id | [
"Fetch",
"the",
"memory",
"with",
"the",
"supplied",
"id"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/mem.py#L911-L917 | train | 228,453 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/mem.py | Memory.get_mems | def get_mems(self, type):
"""Fetch all the memories of the supplied type"""
ret = ()
for m in self.mems:
if m.type == type:
ret += (m,)
return ret | python | def get_mems(self, type):
"""Fetch all the memories of the supplied type"""
ret = ()
for m in self.mems:
if m.type == type:
ret += (m,)
return ret | [
"def",
"get_mems",
"(",
"self",
",",
"type",
")",
":",
"ret",
"=",
"(",
")",
"for",
"m",
"in",
"self",
".",
"mems",
":",
"if",
"m",
".",
"type",
"==",
"type",
":",
"ret",
"+=",
"(",
"m",
",",
")",
"return",
"ret"
] | Fetch all the memories of the supplied type | [
"Fetch",
"all",
"the",
"memories",
"of",
"the",
"supplied",
"type"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/mem.py#L919-L926 | train | 228,454 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/mem.py | Memory.write | def write(self, memory, addr, data, flush_queue=False):
"""Write the specified data to the given memory at the given address"""
wreq = _WriteRequest(memory, addr, data, self.cf)
if memory.id not in self._write_requests:
self._write_requests[memory.id] = []
# Workaround until we secure the uplink and change messages for
# mems to non-blocking
self._write_requests_lock.acquire()
if flush_queue:
self._write_requests[memory.id] = self._write_requests[
memory.id][:1]
self._write_requests[memory.id].insert(len(self._write_requests), wreq)
if len(self._write_requests[memory.id]) == 1:
wreq.start()
self._write_requests_lock.release()
return True | python | def write(self, memory, addr, data, flush_queue=False):
"""Write the specified data to the given memory at the given address"""
wreq = _WriteRequest(memory, addr, data, self.cf)
if memory.id not in self._write_requests:
self._write_requests[memory.id] = []
# Workaround until we secure the uplink and change messages for
# mems to non-blocking
self._write_requests_lock.acquire()
if flush_queue:
self._write_requests[memory.id] = self._write_requests[
memory.id][:1]
self._write_requests[memory.id].insert(len(self._write_requests), wreq)
if len(self._write_requests[memory.id]) == 1:
wreq.start()
self._write_requests_lock.release()
return True | [
"def",
"write",
"(",
"self",
",",
"memory",
",",
"addr",
",",
"data",
",",
"flush_queue",
"=",
"False",
")",
":",
"wreq",
"=",
"_WriteRequest",
"(",
"memory",
",",
"addr",
",",
"data",
",",
"self",
".",
"cf",
")",
"if",
"memory",
".",
"id",
"not",
... | Write the specified data to the given memory at the given address | [
"Write",
"the",
"specified",
"data",
"to",
"the",
"given",
"memory",
"at",
"the",
"given",
"address"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/mem.py#L936-L953 | train | 228,455 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/mem.py | Memory.read | def read(self, memory, addr, length):
"""
Read the specified amount of bytes from the given memory at the given
address
"""
if memory.id in self._read_requests:
logger.warning('There is already a read operation ongoing for '
'memory id {}'.format(memory.id))
return False
rreq = _ReadRequest(memory, addr, length, self.cf)
self._read_requests[memory.id] = rreq
rreq.start()
return True | python | def read(self, memory, addr, length):
"""
Read the specified amount of bytes from the given memory at the given
address
"""
if memory.id in self._read_requests:
logger.warning('There is already a read operation ongoing for '
'memory id {}'.format(memory.id))
return False
rreq = _ReadRequest(memory, addr, length, self.cf)
self._read_requests[memory.id] = rreq
rreq.start()
return True | [
"def",
"read",
"(",
"self",
",",
"memory",
",",
"addr",
",",
"length",
")",
":",
"if",
"memory",
".",
"id",
"in",
"self",
".",
"_read_requests",
":",
"logger",
".",
"warning",
"(",
"'There is already a read operation ongoing for '",
"'memory id {}'",
".",
"for... | Read the specified amount of bytes from the given memory at the given
address | [
"Read",
"the",
"specified",
"amount",
"of",
"bytes",
"from",
"the",
"given",
"memory",
"at",
"the",
"given",
"address"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/mem.py#L955-L970 | train | 228,456 |
bitcraze/crazyflie-lib-python | cflib/crazyflie/mem.py | Memory.refresh | def refresh(self, refresh_done_callback):
"""Start fetching all the detected memories"""
self._refresh_callback = refresh_done_callback
self._fetch_id = 0
for m in self.mems:
try:
self.mem_read_cb.remove_callback(m.new_data)
m.disconnect()
except Exception as e:
logger.info(
'Error when removing memory after update: {}'.format(e))
self.mems = []
self.nbr_of_mems = 0
self._getting_count = False
logger.debug('Requesting number of memories')
pk = CRTPPacket()
pk.set_header(CRTPPort.MEM, CHAN_INFO)
pk.data = (CMD_INFO_NBR,)
self.cf.send_packet(pk, expected_reply=(CMD_INFO_NBR,)) | python | def refresh(self, refresh_done_callback):
"""Start fetching all the detected memories"""
self._refresh_callback = refresh_done_callback
self._fetch_id = 0
for m in self.mems:
try:
self.mem_read_cb.remove_callback(m.new_data)
m.disconnect()
except Exception as e:
logger.info(
'Error when removing memory after update: {}'.format(e))
self.mems = []
self.nbr_of_mems = 0
self._getting_count = False
logger.debug('Requesting number of memories')
pk = CRTPPacket()
pk.set_header(CRTPPort.MEM, CHAN_INFO)
pk.data = (CMD_INFO_NBR,)
self.cf.send_packet(pk, expected_reply=(CMD_INFO_NBR,)) | [
"def",
"refresh",
"(",
"self",
",",
"refresh_done_callback",
")",
":",
"self",
".",
"_refresh_callback",
"=",
"refresh_done_callback",
"self",
".",
"_fetch_id",
"=",
"0",
"for",
"m",
"in",
"self",
".",
"mems",
":",
"try",
":",
"self",
".",
"mem_read_cb",
"... | Start fetching all the detected memories | [
"Start",
"fetching",
"all",
"the",
"detected",
"memories"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crazyflie/mem.py#L972-L992 | train | 228,457 |
bitcraze/crazyflie-lib-python | cflib/bootloader/cloader.py | Cloader.reset_to_bootloader1 | def reset_to_bootloader1(self, cpu_id):
""" Reset to the bootloader
The parameter cpuid shall correspond to the device to reset.
Return true if the reset has been done and the contact with the
bootloader is established.
"""
# Send an echo request and wait for the answer
# Mainly aim to bypass a bug of the crazyflie firmware that prevents
# reset before normal CRTP communication
pk = CRTPPacket()
pk.port = CRTPPort.LINKCTRL
pk.data = (1, 2, 3) + cpu_id
self.link.send_packet(pk)
pk = None
while True:
pk = self.link.receive_packet(2)
if not pk:
return False
if pk.port == CRTPPort.LINKCTRL:
break
# Send the reset to bootloader request
pk = CRTPPacket()
pk.set_header(0xFF, 0xFF)
pk.data = (0xFF, 0xFE) + cpu_id
self.link.send_packet(pk)
# Wait to ack the reset ...
pk = None
while True:
pk = self.link.receive_packet(2)
if not pk:
return False
if pk.port == 0xFF and tuple(pk.data) == (0xFF, 0xFE) + cpu_id:
pk.data = (0xFF, 0xF0) + cpu_id
self.link.send_packet(pk)
break
time.sleep(0.1)
self.link.close()
self.link = cflib.crtp.get_link_driver(self.clink_address)
# time.sleep(0.1)
return self._update_info() | python | def reset_to_bootloader1(self, cpu_id):
""" Reset to the bootloader
The parameter cpuid shall correspond to the device to reset.
Return true if the reset has been done and the contact with the
bootloader is established.
"""
# Send an echo request and wait for the answer
# Mainly aim to bypass a bug of the crazyflie firmware that prevents
# reset before normal CRTP communication
pk = CRTPPacket()
pk.port = CRTPPort.LINKCTRL
pk.data = (1, 2, 3) + cpu_id
self.link.send_packet(pk)
pk = None
while True:
pk = self.link.receive_packet(2)
if not pk:
return False
if pk.port == CRTPPort.LINKCTRL:
break
# Send the reset to bootloader request
pk = CRTPPacket()
pk.set_header(0xFF, 0xFF)
pk.data = (0xFF, 0xFE) + cpu_id
self.link.send_packet(pk)
# Wait to ack the reset ...
pk = None
while True:
pk = self.link.receive_packet(2)
if not pk:
return False
if pk.port == 0xFF and tuple(pk.data) == (0xFF, 0xFE) + cpu_id:
pk.data = (0xFF, 0xF0) + cpu_id
self.link.send_packet(pk)
break
time.sleep(0.1)
self.link.close()
self.link = cflib.crtp.get_link_driver(self.clink_address)
# time.sleep(0.1)
return self._update_info() | [
"def",
"reset_to_bootloader1",
"(",
"self",
",",
"cpu_id",
")",
":",
"# Send an echo request and wait for the answer",
"# Mainly aim to bypass a bug of the crazyflie firmware that prevents",
"# reset before normal CRTP communication",
"pk",
"=",
"CRTPPacket",
"(",
")",
"pk",
".",
... | Reset to the bootloader
The parameter cpuid shall correspond to the device to reset.
Return true if the reset has been done and the contact with the
bootloader is established. | [
"Reset",
"to",
"the",
"bootloader",
"The",
"parameter",
"cpuid",
"shall",
"correspond",
"to",
"the",
"device",
"to",
"reset",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/bootloader/cloader.py#L137-L184 | train | 228,458 |
bitcraze/crazyflie-lib-python | cflib/bootloader/cloader.py | Cloader.reset_to_firmware | def reset_to_firmware(self, target_id):
""" Reset to firmware
The parameter cpuid shall correspond to the device to reset.
Return true if the reset has been done
"""
# The fake CPU ID is legacy from the Crazyflie 1.0
# In order to reset the CPU id had to be sent, but this
# was removed before launching it. But the length check is
# still in the bootloader. So to work around this bug so
# some extra data needs to be sent.
fake_cpu_id = (1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12)
# Send the reset to bootloader request
pk = CRTPPacket()
pk.set_header(0xFF, 0xFF)
pk.data = (target_id, 0xFF) + fake_cpu_id
self.link.send_packet(pk)
# Wait to ack the reset ...
pk = None
while True:
pk = self.link.receive_packet(2)
if not pk:
return False
if (pk.header == 0xFF and struct.unpack(
'B' * len(pk.data), pk.data)[:2] == (target_id, 0xFF)):
# Difference in CF1 and CF2 (CPU ID)
if target_id == 0xFE:
pk.data = (target_id, 0xF0, 0x01)
else:
pk.data = (target_id, 0xF0) + fake_cpu_id
self.link.send_packet(pk)
break
time.sleep(0.1) | python | def reset_to_firmware(self, target_id):
""" Reset to firmware
The parameter cpuid shall correspond to the device to reset.
Return true if the reset has been done
"""
# The fake CPU ID is legacy from the Crazyflie 1.0
# In order to reset the CPU id had to be sent, but this
# was removed before launching it. But the length check is
# still in the bootloader. So to work around this bug so
# some extra data needs to be sent.
fake_cpu_id = (1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12)
# Send the reset to bootloader request
pk = CRTPPacket()
pk.set_header(0xFF, 0xFF)
pk.data = (target_id, 0xFF) + fake_cpu_id
self.link.send_packet(pk)
# Wait to ack the reset ...
pk = None
while True:
pk = self.link.receive_packet(2)
if not pk:
return False
if (pk.header == 0xFF and struct.unpack(
'B' * len(pk.data), pk.data)[:2] == (target_id, 0xFF)):
# Difference in CF1 and CF2 (CPU ID)
if target_id == 0xFE:
pk.data = (target_id, 0xF0, 0x01)
else:
pk.data = (target_id, 0xF0) + fake_cpu_id
self.link.send_packet(pk)
break
time.sleep(0.1) | [
"def",
"reset_to_firmware",
"(",
"self",
",",
"target_id",
")",
":",
"# The fake CPU ID is legacy from the Crazyflie 1.0",
"# In order to reset the CPU id had to be sent, but this",
"# was removed before launching it. But the length check is",
"# still in the bootloader. So to work around this... | Reset to firmware
The parameter cpuid shall correspond to the device to reset.
Return true if the reset has been done | [
"Reset",
"to",
"firmware",
"The",
"parameter",
"cpuid",
"shall",
"correspond",
"to",
"the",
"device",
"to",
"reset",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/bootloader/cloader.py#L186-L221 | train | 228,459 |
bitcraze/crazyflie-lib-python | cflib/bootloader/cloader.py | Cloader.check_link_and_get_info | def check_link_and_get_info(self, target_id=0xFF):
"""Try to get a connection with the bootloader by requesting info
5 times. This let roughly 10 seconds to boot the copter ..."""
for _ in range(0, 5):
if self._update_info(target_id):
if self._in_boot_cb:
self._in_boot_cb.call(True, self.targets[
target_id].protocol_version)
if self._info_cb:
self._info_cb.call(self.targets[target_id])
return True
return False | python | def check_link_and_get_info(self, target_id=0xFF):
"""Try to get a connection with the bootloader by requesting info
5 times. This let roughly 10 seconds to boot the copter ..."""
for _ in range(0, 5):
if self._update_info(target_id):
if self._in_boot_cb:
self._in_boot_cb.call(True, self.targets[
target_id].protocol_version)
if self._info_cb:
self._info_cb.call(self.targets[target_id])
return True
return False | [
"def",
"check_link_and_get_info",
"(",
"self",
",",
"target_id",
"=",
"0xFF",
")",
":",
"for",
"_",
"in",
"range",
"(",
"0",
",",
"5",
")",
":",
"if",
"self",
".",
"_update_info",
"(",
"target_id",
")",
":",
"if",
"self",
".",
"_in_boot_cb",
":",
"se... | Try to get a connection with the bootloader by requesting info
5 times. This let roughly 10 seconds to boot the copter ... | [
"Try",
"to",
"get",
"a",
"connection",
"with",
"the",
"bootloader",
"by",
"requesting",
"info",
"5",
"times",
".",
"This",
"let",
"roughly",
"10",
"seconds",
"to",
"boot",
"the",
"copter",
"..."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/bootloader/cloader.py#L231-L242 | train | 228,460 |
bitcraze/crazyflie-lib-python | cflib/bootloader/cloader.py | Cloader._update_info | def _update_info(self, target_id):
""" Call the command getInfo and fill up the information received in
the fields of the object
"""
# Call getInfo ...
pk = CRTPPacket()
pk.set_header(0xFF, 0xFF)
pk.data = (target_id, 0x10)
self.link.send_packet(pk)
# Wait for the answer
pk = self.link.receive_packet(2)
if (pk and pk.header == 0xFF and struct.unpack('<BB', pk.data[0:2]) ==
(target_id, 0x10)):
tab = struct.unpack('BBHHHH', pk.data[0:10])
cpuid = struct.unpack('B' * 12, pk.data[10:22])
if target_id not in self.targets:
self.targets[target_id] = Target(target_id)
self.targets[target_id].addr = target_id
if len(pk.data) > 22:
self.targets[target_id].protocol_version = pk.datat[22]
self.protocol_version = pk.datat[22]
self.targets[target_id].page_size = tab[2]
self.targets[target_id].buffer_pages = tab[3]
self.targets[target_id].flash_pages = tab[4]
self.targets[target_id].start_page = tab[5]
self.targets[target_id].cpuid = '%02X' % cpuid[0]
for i in cpuid[1:]:
self.targets[target_id].cpuid += ':%02X' % i
if (self.protocol_version == 0x10 and
target_id == TargetTypes.STM32):
self._update_mapping(target_id)
return True
return False | python | def _update_info(self, target_id):
""" Call the command getInfo and fill up the information received in
the fields of the object
"""
# Call getInfo ...
pk = CRTPPacket()
pk.set_header(0xFF, 0xFF)
pk.data = (target_id, 0x10)
self.link.send_packet(pk)
# Wait for the answer
pk = self.link.receive_packet(2)
if (pk and pk.header == 0xFF and struct.unpack('<BB', pk.data[0:2]) ==
(target_id, 0x10)):
tab = struct.unpack('BBHHHH', pk.data[0:10])
cpuid = struct.unpack('B' * 12, pk.data[10:22])
if target_id not in self.targets:
self.targets[target_id] = Target(target_id)
self.targets[target_id].addr = target_id
if len(pk.data) > 22:
self.targets[target_id].protocol_version = pk.datat[22]
self.protocol_version = pk.datat[22]
self.targets[target_id].page_size = tab[2]
self.targets[target_id].buffer_pages = tab[3]
self.targets[target_id].flash_pages = tab[4]
self.targets[target_id].start_page = tab[5]
self.targets[target_id].cpuid = '%02X' % cpuid[0]
for i in cpuid[1:]:
self.targets[target_id].cpuid += ':%02X' % i
if (self.protocol_version == 0x10 and
target_id == TargetTypes.STM32):
self._update_mapping(target_id)
return True
return False | [
"def",
"_update_info",
"(",
"self",
",",
"target_id",
")",
":",
"# Call getInfo ...",
"pk",
"=",
"CRTPPacket",
"(",
")",
"pk",
".",
"set_header",
"(",
"0xFF",
",",
"0xFF",
")",
"pk",
".",
"data",
"=",
"(",
"target_id",
",",
"0x10",
")",
"self",
".",
... | Call the command getInfo and fill up the information received in
the fields of the object | [
"Call",
"the",
"command",
"getInfo",
"and",
"fill",
"up",
"the",
"information",
"received",
"in",
"the",
"fields",
"of",
"the",
"object"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/bootloader/cloader.py#L251-L289 | train | 228,461 |
bitcraze/crazyflie-lib-python | cflib/bootloader/cloader.py | Cloader.upload_buffer | def upload_buffer(self, target_id, page, address, buff):
"""Upload data into a buffer on the Crazyflie"""
# print len(buff)
count = 0
pk = CRTPPacket()
pk.set_header(0xFF, 0xFF)
pk.data = struct.pack('=BBHH', target_id, 0x14, page, address)
for i in range(0, len(buff)):
pk.data.append(buff[i])
count += 1
if count > 24:
self.link.send_packet(pk)
count = 0
pk = CRTPPacket()
pk.set_header(0xFF, 0xFF)
pk.data = struct.pack('=BBHH', target_id, 0x14, page,
i + address + 1)
self.link.send_packet(pk) | python | def upload_buffer(self, target_id, page, address, buff):
"""Upload data into a buffer on the Crazyflie"""
# print len(buff)
count = 0
pk = CRTPPacket()
pk.set_header(0xFF, 0xFF)
pk.data = struct.pack('=BBHH', target_id, 0x14, page, address)
for i in range(0, len(buff)):
pk.data.append(buff[i])
count += 1
if count > 24:
self.link.send_packet(pk)
count = 0
pk = CRTPPacket()
pk.set_header(0xFF, 0xFF)
pk.data = struct.pack('=BBHH', target_id, 0x14, page,
i + address + 1)
self.link.send_packet(pk) | [
"def",
"upload_buffer",
"(",
"self",
",",
"target_id",
",",
"page",
",",
"address",
",",
"buff",
")",
":",
"# print len(buff)",
"count",
"=",
"0",
"pk",
"=",
"CRTPPacket",
"(",
")",
"pk",
".",
"set_header",
"(",
"0xFF",
",",
"0xFF",
")",
"pk",
".",
"... | Upload data into a buffer on the Crazyflie | [
"Upload",
"data",
"into",
"a",
"buffer",
"on",
"the",
"Crazyflie"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/bootloader/cloader.py#L313-L334 | train | 228,462 |
bitcraze/crazyflie-lib-python | cflib/bootloader/cloader.py | Cloader.read_flash | def read_flash(self, addr=0xFF, page=0x00):
"""Read back a flash page from the Crazyflie and return it"""
buff = bytearray()
page_size = self.targets[addr].page_size
for i in range(0, int(math.ceil(page_size / 25.0))):
pk = None
retry_counter = 5
while ((not pk or pk.header != 0xFF or
struct.unpack('<BB', pk.data[0:2]) != (addr, 0x1C)) and
retry_counter >= 0):
pk = CRTPPacket()
pk.set_header(0xFF, 0xFF)
pk.data = struct.pack('<BBHH', addr, 0x1C, page, (i * 25))
self.link.send_packet(pk)
pk = self.link.receive_packet(1)
retry_counter -= 1
if (retry_counter < 0):
return None
else:
buff += pk.data[6:]
# For some reason we get one byte extra here...
return buff[0:page_size] | python | def read_flash(self, addr=0xFF, page=0x00):
"""Read back a flash page from the Crazyflie and return it"""
buff = bytearray()
page_size = self.targets[addr].page_size
for i in range(0, int(math.ceil(page_size / 25.0))):
pk = None
retry_counter = 5
while ((not pk or pk.header != 0xFF or
struct.unpack('<BB', pk.data[0:2]) != (addr, 0x1C)) and
retry_counter >= 0):
pk = CRTPPacket()
pk.set_header(0xFF, 0xFF)
pk.data = struct.pack('<BBHH', addr, 0x1C, page, (i * 25))
self.link.send_packet(pk)
pk = self.link.receive_packet(1)
retry_counter -= 1
if (retry_counter < 0):
return None
else:
buff += pk.data[6:]
# For some reason we get one byte extra here...
return buff[0:page_size] | [
"def",
"read_flash",
"(",
"self",
",",
"addr",
"=",
"0xFF",
",",
"page",
"=",
"0x00",
")",
":",
"buff",
"=",
"bytearray",
"(",
")",
"page_size",
"=",
"self",
".",
"targets",
"[",
"addr",
"]",
".",
"page_size",
"for",
"i",
"in",
"range",
"(",
"0",
... | Read back a flash page from the Crazyflie and return it | [
"Read",
"back",
"a",
"flash",
"page",
"from",
"the",
"Crazyflie",
"and",
"return",
"it"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/bootloader/cloader.py#L336-L361 | train | 228,463 |
bitcraze/crazyflie-lib-python | cflib/bootloader/cloader.py | Cloader.write_flash | def write_flash(self, addr, page_buffer, target_page, page_count):
"""Initiate flashing of data in the buffer to flash."""
# print "Write page", flashPage
# print "Writing page [%d] and [%d] forward" % (flashPage, nPage)
pk = None
# Flushing downlink ...
pk = self.link.receive_packet(0)
while pk is not None:
pk = self.link.receive_packet(0)
retry_counter = 5
# print "Flasing to 0x{:X}".format(addr)
while ((not pk or pk.header != 0xFF or
struct.unpack('<BB', pk.data[0:2]) != (addr, 0x18)) and
retry_counter >= 0):
pk = CRTPPacket()
pk.set_header(0xFF, 0xFF)
pk.data = struct.pack('<BBHHH', addr, 0x18, page_buffer,
target_page, page_count)
self.link.send_packet(pk)
pk = self.link.receive_packet(1)
retry_counter -= 1
if retry_counter < 0:
self.error_code = -1
return False
self.error_code = pk.data[3]
return pk.data[2] == 1 | python | def write_flash(self, addr, page_buffer, target_page, page_count):
"""Initiate flashing of data in the buffer to flash."""
# print "Write page", flashPage
# print "Writing page [%d] and [%d] forward" % (flashPage, nPage)
pk = None
# Flushing downlink ...
pk = self.link.receive_packet(0)
while pk is not None:
pk = self.link.receive_packet(0)
retry_counter = 5
# print "Flasing to 0x{:X}".format(addr)
while ((not pk or pk.header != 0xFF or
struct.unpack('<BB', pk.data[0:2]) != (addr, 0x18)) and
retry_counter >= 0):
pk = CRTPPacket()
pk.set_header(0xFF, 0xFF)
pk.data = struct.pack('<BBHHH', addr, 0x18, page_buffer,
target_page, page_count)
self.link.send_packet(pk)
pk = self.link.receive_packet(1)
retry_counter -= 1
if retry_counter < 0:
self.error_code = -1
return False
self.error_code = pk.data[3]
return pk.data[2] == 1 | [
"def",
"write_flash",
"(",
"self",
",",
"addr",
",",
"page_buffer",
",",
"target_page",
",",
"page_count",
")",
":",
"# print \"Write page\", flashPage",
"# print \"Writing page [%d] and [%d] forward\" % (flashPage, nPage)",
"pk",
"=",
"None",
"# Flushing downlink ...",
"pk",... | Initiate flashing of data in the buffer to flash. | [
"Initiate",
"flashing",
"of",
"data",
"in",
"the",
"buffer",
"to",
"flash",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/bootloader/cloader.py#L363-L393 | train | 228,464 |
bitcraze/crazyflie-lib-python | cflib/bootloader/cloader.py | Cloader.decode_cpu_id | def decode_cpu_id(self, cpuid):
"""Decode the CPU id into a string"""
ret = ()
for i in cpuid.split(':'):
ret += (eval('0x' + i),)
return ret | python | def decode_cpu_id(self, cpuid):
"""Decode the CPU id into a string"""
ret = ()
for i in cpuid.split(':'):
ret += (eval('0x' + i),)
return ret | [
"def",
"decode_cpu_id",
"(",
"self",
",",
"cpuid",
")",
":",
"ret",
"=",
"(",
")",
"for",
"i",
"in",
"cpuid",
".",
"split",
"(",
"':'",
")",
":",
"ret",
"+=",
"(",
"eval",
"(",
"'0x'",
"+",
"i",
")",
",",
")",
"return",
"ret"
] | Decode the CPU id into a string | [
"Decode",
"the",
"CPU",
"id",
"into",
"a",
"string"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/bootloader/cloader.py#L395-L401 | train | 228,465 |
bitcraze/crazyflie-lib-python | cflib/crtp/crtpstack.py | CRTPPacket.set_header | def set_header(self, port, channel):
"""
Set the port and channel for this packet.
"""
self._port = port
self.channel = channel
self._update_header() | python | def set_header(self, port, channel):
"""
Set the port and channel for this packet.
"""
self._port = port
self.channel = channel
self._update_header() | [
"def",
"set_header",
"(",
"self",
",",
"port",
",",
"channel",
")",
":",
"self",
".",
"_port",
"=",
"port",
"self",
".",
"channel",
"=",
"channel",
"self",
".",
"_update_header",
"(",
")"
] | Set the port and channel for this packet. | [
"Set",
"the",
"port",
"and",
"channel",
"for",
"this",
"packet",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crtp/crtpstack.py#L99-L105 | train | 228,466 |
bitcraze/crazyflie-lib-python | cflib/crtp/crtpstack.py | CRTPPacket._set_data | def _set_data(self, data):
"""Set the packet data"""
if type(data) == bytearray:
self._data = data
elif type(data) == str:
if sys.version_info < (3,):
self._data = bytearray(data)
else:
self._data = bytearray(data.encode('ISO-8859-1'))
elif type(data) == list or type(data) == tuple:
self._data = bytearray(data)
elif sys.version_info >= (3,) and type(data) == bytes:
self._data = bytearray(data)
else:
raise Exception('Data must be bytearray, string, list or tuple,'
' not {}'.format(type(data))) | python | def _set_data(self, data):
"""Set the packet data"""
if type(data) == bytearray:
self._data = data
elif type(data) == str:
if sys.version_info < (3,):
self._data = bytearray(data)
else:
self._data = bytearray(data.encode('ISO-8859-1'))
elif type(data) == list or type(data) == tuple:
self._data = bytearray(data)
elif sys.version_info >= (3,) and type(data) == bytes:
self._data = bytearray(data)
else:
raise Exception('Data must be bytearray, string, list or tuple,'
' not {}'.format(type(data))) | [
"def",
"_set_data",
"(",
"self",
",",
"data",
")",
":",
"if",
"type",
"(",
"data",
")",
"==",
"bytearray",
":",
"self",
".",
"_data",
"=",
"data",
"elif",
"type",
"(",
"data",
")",
"==",
"str",
":",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3"... | Set the packet data | [
"Set",
"the",
"packet",
"data"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crtp/crtpstack.py#L119-L134 | train | 228,467 |
bitcraze/crazyflie-lib-python | cflib/positioning/motion_commander.py | MotionCommander.take_off | def take_off(self, height=None, velocity=VELOCITY):
"""
Takes off, that is starts the motors, goes straigt up and hovers.
Do not call this function if you use the with keyword. Take off is
done automatically when the context is created.
:param height: the height (meters) to hover at. None uses the default
height set when constructed.
:param velocity: the velocity (meters/second) when taking off
:return:
"""
if self._is_flying:
raise Exception('Already flying')
if not self._cf.is_connected():
raise Exception('Crazyflie is not connected')
self._is_flying = True
self._reset_position_estimator()
self._thread = _SetPointThread(self._cf)
self._thread.start()
if height is None:
height = self.default_height
self.up(height, velocity) | python | def take_off(self, height=None, velocity=VELOCITY):
"""
Takes off, that is starts the motors, goes straigt up and hovers.
Do not call this function if you use the with keyword. Take off is
done automatically when the context is created.
:param height: the height (meters) to hover at. None uses the default
height set when constructed.
:param velocity: the velocity (meters/second) when taking off
:return:
"""
if self._is_flying:
raise Exception('Already flying')
if not self._cf.is_connected():
raise Exception('Crazyflie is not connected')
self._is_flying = True
self._reset_position_estimator()
self._thread = _SetPointThread(self._cf)
self._thread.start()
if height is None:
height = self.default_height
self.up(height, velocity) | [
"def",
"take_off",
"(",
"self",
",",
"height",
"=",
"None",
",",
"velocity",
"=",
"VELOCITY",
")",
":",
"if",
"self",
".",
"_is_flying",
":",
"raise",
"Exception",
"(",
"'Already flying'",
")",
"if",
"not",
"self",
".",
"_cf",
".",
"is_connected",
"(",
... | Takes off, that is starts the motors, goes straigt up and hovers.
Do not call this function if you use the with keyword. Take off is
done automatically when the context is created.
:param height: the height (meters) to hover at. None uses the default
height set when constructed.
:param velocity: the velocity (meters/second) when taking off
:return: | [
"Takes",
"off",
"that",
"is",
"starts",
"the",
"motors",
"goes",
"straigt",
"up",
"and",
"hovers",
".",
"Do",
"not",
"call",
"this",
"function",
"if",
"you",
"use",
"the",
"with",
"keyword",
".",
"Take",
"off",
"is",
"done",
"automatically",
"when",
"the... | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/positioning/motion_commander.py#L81-L107 | train | 228,468 |
bitcraze/crazyflie-lib-python | cflib/positioning/motion_commander.py | MotionCommander.turn_left | def turn_left(self, angle_degrees, rate=RATE):
"""
Turn to the left, staying on the spot
:param angle_degrees: How far to turn (degrees)
:param rate: The trurning speed (degrees/second)
:return:
"""
flight_time = angle_degrees / rate
self.start_turn_left(rate)
time.sleep(flight_time)
self.stop() | python | def turn_left(self, angle_degrees, rate=RATE):
"""
Turn to the left, staying on the spot
:param angle_degrees: How far to turn (degrees)
:param rate: The trurning speed (degrees/second)
:return:
"""
flight_time = angle_degrees / rate
self.start_turn_left(rate)
time.sleep(flight_time)
self.stop() | [
"def",
"turn_left",
"(",
"self",
",",
"angle_degrees",
",",
"rate",
"=",
"RATE",
")",
":",
"flight_time",
"=",
"angle_degrees",
"/",
"rate",
"self",
".",
"start_turn_left",
"(",
"rate",
")",
"time",
".",
"sleep",
"(",
"flight_time",
")",
"self",
".",
"st... | Turn to the left, staying on the spot
:param angle_degrees: How far to turn (degrees)
:param rate: The trurning speed (degrees/second)
:return: | [
"Turn",
"to",
"the",
"left",
"staying",
"on",
"the",
"spot"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/positioning/motion_commander.py#L195-L207 | train | 228,469 |
bitcraze/crazyflie-lib-python | cflib/positioning/motion_commander.py | MotionCommander.turn_right | def turn_right(self, angle_degrees, rate=RATE):
"""
Turn to the right, staying on the spot
:param angle_degrees: How far to turn (degrees)
:param rate: The trurning speed (degrees/second)
:return:
"""
flight_time = angle_degrees / rate
self.start_turn_right(rate)
time.sleep(flight_time)
self.stop() | python | def turn_right(self, angle_degrees, rate=RATE):
"""
Turn to the right, staying on the spot
:param angle_degrees: How far to turn (degrees)
:param rate: The trurning speed (degrees/second)
:return:
"""
flight_time = angle_degrees / rate
self.start_turn_right(rate)
time.sleep(flight_time)
self.stop() | [
"def",
"turn_right",
"(",
"self",
",",
"angle_degrees",
",",
"rate",
"=",
"RATE",
")",
":",
"flight_time",
"=",
"angle_degrees",
"/",
"rate",
"self",
".",
"start_turn_right",
"(",
"rate",
")",
"time",
".",
"sleep",
"(",
"flight_time",
")",
"self",
".",
"... | Turn to the right, staying on the spot
:param angle_degrees: How far to turn (degrees)
:param rate: The trurning speed (degrees/second)
:return: | [
"Turn",
"to",
"the",
"right",
"staying",
"on",
"the",
"spot"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/positioning/motion_commander.py#L209-L221 | train | 228,470 |
bitcraze/crazyflie-lib-python | cflib/positioning/motion_commander.py | MotionCommander.circle_left | def circle_left(self, radius_m, velocity=VELOCITY, angle_degrees=360.0):
"""
Go in circle, counter clock wise
:param radius_m: The radius of the circle (meters)
:param velocity: The velocity along the circle (meters/second)
:param angle_degrees: How far to go in the circle (degrees)
:return:
"""
distance = 2 * radius_m * math.pi * angle_degrees / 360.0
flight_time = distance / velocity
self.start_circle_left(radius_m, velocity)
time.sleep(flight_time)
self.stop() | python | def circle_left(self, radius_m, velocity=VELOCITY, angle_degrees=360.0):
"""
Go in circle, counter clock wise
:param radius_m: The radius of the circle (meters)
:param velocity: The velocity along the circle (meters/second)
:param angle_degrees: How far to go in the circle (degrees)
:return:
"""
distance = 2 * radius_m * math.pi * angle_degrees / 360.0
flight_time = distance / velocity
self.start_circle_left(radius_m, velocity)
time.sleep(flight_time)
self.stop() | [
"def",
"circle_left",
"(",
"self",
",",
"radius_m",
",",
"velocity",
"=",
"VELOCITY",
",",
"angle_degrees",
"=",
"360.0",
")",
":",
"distance",
"=",
"2",
"*",
"radius_m",
"*",
"math",
".",
"pi",
"*",
"angle_degrees",
"/",
"360.0",
"flight_time",
"=",
"di... | Go in circle, counter clock wise
:param radius_m: The radius of the circle (meters)
:param velocity: The velocity along the circle (meters/second)
:param angle_degrees: How far to go in the circle (degrees)
:return: | [
"Go",
"in",
"circle",
"counter",
"clock",
"wise"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/positioning/motion_commander.py#L223-L237 | train | 228,471 |
bitcraze/crazyflie-lib-python | cflib/positioning/motion_commander.py | MotionCommander.circle_right | def circle_right(self, radius_m, velocity=VELOCITY, angle_degrees=360.0):
"""
Go in circle, clock wise
:param radius_m: The radius of the circle (meters)
:param velocity: The velocity along the circle (meters/second)
:param angle_degrees: How far to go in the circle (degrees)
:return:
"""
distance = 2 * radius_m * math.pi * angle_degrees / 360.0
flight_time = distance / velocity
self.start_circle_right(radius_m, velocity)
time.sleep(flight_time)
self.stop() | python | def circle_right(self, radius_m, velocity=VELOCITY, angle_degrees=360.0):
"""
Go in circle, clock wise
:param radius_m: The radius of the circle (meters)
:param velocity: The velocity along the circle (meters/second)
:param angle_degrees: How far to go in the circle (degrees)
:return:
"""
distance = 2 * radius_m * math.pi * angle_degrees / 360.0
flight_time = distance / velocity
self.start_circle_right(radius_m, velocity)
time.sleep(flight_time)
self.stop() | [
"def",
"circle_right",
"(",
"self",
",",
"radius_m",
",",
"velocity",
"=",
"VELOCITY",
",",
"angle_degrees",
"=",
"360.0",
")",
":",
"distance",
"=",
"2",
"*",
"radius_m",
"*",
"math",
".",
"pi",
"*",
"angle_degrees",
"/",
"360.0",
"flight_time",
"=",
"d... | Go in circle, clock wise
:param radius_m: The radius of the circle (meters)
:param velocity: The velocity along the circle (meters/second)
:param angle_degrees: How far to go in the circle (degrees)
:return: | [
"Go",
"in",
"circle",
"clock",
"wise"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/positioning/motion_commander.py#L239-L253 | train | 228,472 |
bitcraze/crazyflie-lib-python | cflib/positioning/motion_commander.py | MotionCommander.start_circle_left | def start_circle_left(self, radius_m, velocity=VELOCITY):
"""
Start a circular motion to the left. This function returns immediately.
:param radius_m: The radius of the circle (meters)
:param velocity: The velocity of the motion (meters/second)
:return:
"""
circumference = 2 * radius_m * math.pi
rate = 360.0 * velocity / circumference
self._set_vel_setpoint(velocity, 0.0, 0.0, -rate) | python | def start_circle_left(self, radius_m, velocity=VELOCITY):
"""
Start a circular motion to the left. This function returns immediately.
:param radius_m: The radius of the circle (meters)
:param velocity: The velocity of the motion (meters/second)
:return:
"""
circumference = 2 * radius_m * math.pi
rate = 360.0 * velocity / circumference
self._set_vel_setpoint(velocity, 0.0, 0.0, -rate) | [
"def",
"start_circle_left",
"(",
"self",
",",
"radius_m",
",",
"velocity",
"=",
"VELOCITY",
")",
":",
"circumference",
"=",
"2",
"*",
"radius_m",
"*",
"math",
".",
"pi",
"rate",
"=",
"360.0",
"*",
"velocity",
"/",
"circumference",
"self",
".",
"_set_vel_se... | Start a circular motion to the left. This function returns immediately.
:param radius_m: The radius of the circle (meters)
:param velocity: The velocity of the motion (meters/second)
:return: | [
"Start",
"a",
"circular",
"motion",
"to",
"the",
"left",
".",
"This",
"function",
"returns",
"immediately",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/positioning/motion_commander.py#L364-L375 | train | 228,473 |
bitcraze/crazyflie-lib-python | cflib/positioning/motion_commander.py | MotionCommander.start_linear_motion | def start_linear_motion(self, velocity_x_m, velocity_y_m, velocity_z_m):
"""
Start a linear motion. This function returns immediately.
positive X is forward
positive Y is left
positive Z is up
:param velocity_x_m: The velocity along the X-axis (meters/second)
:param velocity_y_m: The velocity along the Y-axis (meters/second)
:param velocity_z_m: The velocity along the Z-axis (meters/second)
:return:
"""
self._set_vel_setpoint(
velocity_x_m, velocity_y_m, velocity_z_m, 0.0) | python | def start_linear_motion(self, velocity_x_m, velocity_y_m, velocity_z_m):
"""
Start a linear motion. This function returns immediately.
positive X is forward
positive Y is left
positive Z is up
:param velocity_x_m: The velocity along the X-axis (meters/second)
:param velocity_y_m: The velocity along the Y-axis (meters/second)
:param velocity_z_m: The velocity along the Z-axis (meters/second)
:return:
"""
self._set_vel_setpoint(
velocity_x_m, velocity_y_m, velocity_z_m, 0.0) | [
"def",
"start_linear_motion",
"(",
"self",
",",
"velocity_x_m",
",",
"velocity_y_m",
",",
"velocity_z_m",
")",
":",
"self",
".",
"_set_vel_setpoint",
"(",
"velocity_x_m",
",",
"velocity_y_m",
",",
"velocity_z_m",
",",
"0.0",
")"
] | Start a linear motion. This function returns immediately.
positive X is forward
positive Y is left
positive Z is up
:param velocity_x_m: The velocity along the X-axis (meters/second)
:param velocity_y_m: The velocity along the Y-axis (meters/second)
:param velocity_z_m: The velocity along the Z-axis (meters/second)
:return: | [
"Start",
"a",
"linear",
"motion",
".",
"This",
"function",
"returns",
"immediately",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/positioning/motion_commander.py#L390-L404 | train | 228,474 |
bitcraze/crazyflie-lib-python | cflib/positioning/motion_commander.py | _SetPointThread.set_vel_setpoint | def set_vel_setpoint(self, velocity_x, velocity_y, velocity_z, rate_yaw):
"""Set the velocity setpoint to use for the future motion"""
self._queue.put((velocity_x, velocity_y, velocity_z, rate_yaw)) | python | def set_vel_setpoint(self, velocity_x, velocity_y, velocity_z, rate_yaw):
"""Set the velocity setpoint to use for the future motion"""
self._queue.put((velocity_x, velocity_y, velocity_z, rate_yaw)) | [
"def",
"set_vel_setpoint",
"(",
"self",
",",
"velocity_x",
",",
"velocity_y",
",",
"velocity_z",
",",
"rate_yaw",
")",
":",
"self",
".",
"_queue",
".",
"put",
"(",
"(",
"velocity_x",
",",
"velocity_y",
",",
"velocity_z",
",",
"rate_yaw",
")",
")"
] | Set the velocity setpoint to use for the future motion | [
"Set",
"the",
"velocity",
"setpoint",
"to",
"use",
"for",
"the",
"future",
"motion"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/positioning/motion_commander.py#L446-L448 | train | 228,475 |
bitcraze/crazyflie-lib-python | examples/basicparam.py | ParamExample._param_callback | def _param_callback(self, name, value):
"""Generic callback registered for all the groups"""
print('{0}: {1}'.format(name, value))
# Remove each parameter from the list and close the link when
# all are fetched
self._param_check_list.remove(name)
if len(self._param_check_list) == 0:
print('Have fetched all parameter values.')
# First remove all the group callbacks
for g in self._param_groups:
self._cf.param.remove_update_callback(group=g,
cb=self._param_callback)
# Create a new random value [0.00,1.00] for pid_attitude.pitch_kd
# and set it
pkd = random.random()
print('')
print('Write: pid_attitude.pitch_kd={:.2f}'.format(pkd))
self._cf.param.add_update_callback(group='pid_attitude',
name='pitch_kd',
cb=self._a_pitch_kd_callback)
# When setting a value the parameter is automatically read back
# and the registered callbacks will get the updated value
self._cf.param.set_value('pid_attitude.pitch_kd',
'{:.2f}'.format(pkd)) | python | def _param_callback(self, name, value):
"""Generic callback registered for all the groups"""
print('{0}: {1}'.format(name, value))
# Remove each parameter from the list and close the link when
# all are fetched
self._param_check_list.remove(name)
if len(self._param_check_list) == 0:
print('Have fetched all parameter values.')
# First remove all the group callbacks
for g in self._param_groups:
self._cf.param.remove_update_callback(group=g,
cb=self._param_callback)
# Create a new random value [0.00,1.00] for pid_attitude.pitch_kd
# and set it
pkd = random.random()
print('')
print('Write: pid_attitude.pitch_kd={:.2f}'.format(pkd))
self._cf.param.add_update_callback(group='pid_attitude',
name='pitch_kd',
cb=self._a_pitch_kd_callback)
# When setting a value the parameter is automatically read back
# and the registered callbacks will get the updated value
self._cf.param.set_value('pid_attitude.pitch_kd',
'{:.2f}'.format(pkd)) | [
"def",
"_param_callback",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"print",
"(",
"'{0}: {1}'",
".",
"format",
"(",
"name",
",",
"value",
")",
")",
"# Remove each parameter from the list and close the link when",
"# all are fetched",
"self",
".",
"_param_che... | Generic callback registered for all the groups | [
"Generic",
"callback",
"registered",
"for",
"all",
"the",
"groups"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/examples/basicparam.py#L99-L125 | train | 228,476 |
bitcraze/crazyflie-lib-python | examples/basicparam.py | ParamExample._a_pitch_kd_callback | def _a_pitch_kd_callback(self, name, value):
"""Callback for pid_attitude.pitch_kd"""
print('Readback: {0}={1}'.format(name, value))
# End the example by closing the link (will cause the app to quit)
self._cf.close_link() | python | def _a_pitch_kd_callback(self, name, value):
"""Callback for pid_attitude.pitch_kd"""
print('Readback: {0}={1}'.format(name, value))
# End the example by closing the link (will cause the app to quit)
self._cf.close_link() | [
"def",
"_a_pitch_kd_callback",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"print",
"(",
"'Readback: {0}={1}'",
".",
"format",
"(",
"name",
",",
"value",
")",
")",
"# End the example by closing the link (will cause the app to quit)",
"self",
".",
"_cf",
".",
... | Callback for pid_attitude.pitch_kd | [
"Callback",
"for",
"pid_attitude",
".",
"pitch_kd"
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/examples/basicparam.py#L127-L132 | train | 228,477 |
bitcraze/crazyflie-lib-python | cflib/crtp/radiodriver.py | RadioDriver._scan_radio_channels | def _scan_radio_channels(self, cradio, start=0, stop=125):
""" Scan for Crazyflies between the supplied channels. """
return list(cradio.scan_channels(start, stop, (0xff,))) | python | def _scan_radio_channels(self, cradio, start=0, stop=125):
""" Scan for Crazyflies between the supplied channels. """
return list(cradio.scan_channels(start, stop, (0xff,))) | [
"def",
"_scan_radio_channels",
"(",
"self",
",",
"cradio",
",",
"start",
"=",
"0",
",",
"stop",
"=",
"125",
")",
":",
"return",
"list",
"(",
"cradio",
".",
"scan_channels",
"(",
"start",
",",
"stop",
",",
"(",
"0xff",
",",
")",
")",
")"
] | Scan for Crazyflies between the supplied channels. | [
"Scan",
"for",
"Crazyflies",
"between",
"the",
"supplied",
"channels",
"."
] | f6ebb4eb315bbe6e02db518936ac17fb615b2af8 | https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crtp/radiodriver.py#L290-L292 | train | 228,478 |
googleapis/google-auth-library-python-oauthlib | google_auth_oauthlib/tool/__main__.py | main | def main(client_secrets, scope, save, credentials, headless):
"""Command-line tool for obtaining authorization and credentials from a user.
This tool uses the OAuth 2.0 Authorization Code grant as described
in section 1.3.1 of RFC6749:
https://tools.ietf.org/html/rfc6749#section-1.3.1
This tool is intended for assist developers in obtaining credentials
for testing applications where it may not be possible or easy to run a
complete OAuth 2.0 authorization flow, especially in the case of code
samples or embedded devices without input / display capabilities.
This is not intended for production use where a combination of
companion and on-device applications should complete the OAuth 2.0
authorization flow to get authorization from the users.
"""
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
client_secrets,
scopes=scope
)
if not headless:
creds = flow.run_local_server()
else:
creds = flow.run_console()
creds_data = {
'token': creds.token,
'refresh_token': creds.refresh_token,
'token_uri': creds.token_uri,
'client_id': creds.client_id,
'client_secret': creds.client_secret,
'scopes': creds.scopes
}
if save:
del creds_data['token']
config_path = os.path.dirname(credentials)
if config_path and not os.path.isdir(config_path):
os.makedirs(config_path)
with open(credentials, 'w') as outfile:
json.dump(creds_data, outfile)
click.echo('credentials saved: %s' % credentials)
else:
click.echo(json.dumps(creds_data)) | python | def main(client_secrets, scope, save, credentials, headless):
"""Command-line tool for obtaining authorization and credentials from a user.
This tool uses the OAuth 2.0 Authorization Code grant as described
in section 1.3.1 of RFC6749:
https://tools.ietf.org/html/rfc6749#section-1.3.1
This tool is intended for assist developers in obtaining credentials
for testing applications where it may not be possible or easy to run a
complete OAuth 2.0 authorization flow, especially in the case of code
samples or embedded devices without input / display capabilities.
This is not intended for production use where a combination of
companion and on-device applications should complete the OAuth 2.0
authorization flow to get authorization from the users.
"""
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
client_secrets,
scopes=scope
)
if not headless:
creds = flow.run_local_server()
else:
creds = flow.run_console()
creds_data = {
'token': creds.token,
'refresh_token': creds.refresh_token,
'token_uri': creds.token_uri,
'client_id': creds.client_id,
'client_secret': creds.client_secret,
'scopes': creds.scopes
}
if save:
del creds_data['token']
config_path = os.path.dirname(credentials)
if config_path and not os.path.isdir(config_path):
os.makedirs(config_path)
with open(credentials, 'w') as outfile:
json.dump(creds_data, outfile)
click.echo('credentials saved: %s' % credentials)
else:
click.echo(json.dumps(creds_data)) | [
"def",
"main",
"(",
"client_secrets",
",",
"scope",
",",
"save",
",",
"credentials",
",",
"headless",
")",
":",
"flow",
"=",
"google_auth_oauthlib",
".",
"flow",
".",
"InstalledAppFlow",
".",
"from_client_secrets_file",
"(",
"client_secrets",
",",
"scopes",
"=",... | Command-line tool for obtaining authorization and credentials from a user.
This tool uses the OAuth 2.0 Authorization Code grant as described
in section 1.3.1 of RFC6749:
https://tools.ietf.org/html/rfc6749#section-1.3.1
This tool is intended for assist developers in obtaining credentials
for testing applications where it may not be possible or easy to run a
complete OAuth 2.0 authorization flow, especially in the case of code
samples or embedded devices without input / display capabilities.
This is not intended for production use where a combination of
companion and on-device applications should complete the OAuth 2.0
authorization flow to get authorization from the users. | [
"Command",
"-",
"line",
"tool",
"for",
"obtaining",
"authorization",
"and",
"credentials",
"from",
"a",
"user",
"."
] | ba826565994cf20c073d79f534036747fdef2041 | https://github.com/googleapis/google-auth-library-python-oauthlib/blob/ba826565994cf20c073d79f534036747fdef2041/google_auth_oauthlib/tool/__main__.py#L80-L130 | train | 228,479 |
googleapis/google-auth-library-python-oauthlib | google_auth_oauthlib/flow.py | Flow.authorization_url | def authorization_url(self, **kwargs):
"""Generates an authorization URL.
This is the first step in the OAuth 2.0 Authorization Flow. The user's
browser should be redirected to the returned URL.
This method calls
:meth:`requests_oauthlib.OAuth2Session.authorization_url`
and specifies the client configuration's authorization URI (usually
Google's authorization server) and specifies that "offline" access is
desired. This is required in order to obtain a refresh token.
Args:
kwargs: Additional arguments passed through to
:meth:`requests_oauthlib.OAuth2Session.authorization_url`
Returns:
Tuple[str, str]: The generated authorization URL and state. The
user must visit the URL to complete the flow. The state is used
when completing the flow to verify that the request originated
from your application. If your application is using a different
:class:`Flow` instance to obtain the token, you will need to
specify the ``state`` when constructing the :class:`Flow`.
"""
kwargs.setdefault('access_type', 'offline')
url, state = self.oauth2session.authorization_url(
self.client_config['auth_uri'], **kwargs)
return url, state | python | def authorization_url(self, **kwargs):
"""Generates an authorization URL.
This is the first step in the OAuth 2.0 Authorization Flow. The user's
browser should be redirected to the returned URL.
This method calls
:meth:`requests_oauthlib.OAuth2Session.authorization_url`
and specifies the client configuration's authorization URI (usually
Google's authorization server) and specifies that "offline" access is
desired. This is required in order to obtain a refresh token.
Args:
kwargs: Additional arguments passed through to
:meth:`requests_oauthlib.OAuth2Session.authorization_url`
Returns:
Tuple[str, str]: The generated authorization URL and state. The
user must visit the URL to complete the flow. The state is used
when completing the flow to verify that the request originated
from your application. If your application is using a different
:class:`Flow` instance to obtain the token, you will need to
specify the ``state`` when constructing the :class:`Flow`.
"""
kwargs.setdefault('access_type', 'offline')
url, state = self.oauth2session.authorization_url(
self.client_config['auth_uri'], **kwargs)
return url, state | [
"def",
"authorization_url",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'access_type'",
",",
"'offline'",
")",
"url",
",",
"state",
"=",
"self",
".",
"oauth2session",
".",
"authorization_url",
"(",
"self",
".",
"clien... | Generates an authorization URL.
This is the first step in the OAuth 2.0 Authorization Flow. The user's
browser should be redirected to the returned URL.
This method calls
:meth:`requests_oauthlib.OAuth2Session.authorization_url`
and specifies the client configuration's authorization URI (usually
Google's authorization server) and specifies that "offline" access is
desired. This is required in order to obtain a refresh token.
Args:
kwargs: Additional arguments passed through to
:meth:`requests_oauthlib.OAuth2Session.authorization_url`
Returns:
Tuple[str, str]: The generated authorization URL and state. The
user must visit the URL to complete the flow. The state is used
when completing the flow to verify that the request originated
from your application. If your application is using a different
:class:`Flow` instance to obtain the token, you will need to
specify the ``state`` when constructing the :class:`Flow`. | [
"Generates",
"an",
"authorization",
"URL",
"."
] | ba826565994cf20c073d79f534036747fdef2041 | https://github.com/googleapis/google-auth-library-python-oauthlib/blob/ba826565994cf20c073d79f534036747fdef2041/google_auth_oauthlib/flow.py#L186-L214 | train | 228,480 |
googleapis/google-auth-library-python-oauthlib | google_auth_oauthlib/flow.py | Flow.fetch_token | def fetch_token(self, **kwargs):
"""Completes the Authorization Flow and obtains an access token.
This is the final step in the OAuth 2.0 Authorization Flow. This is
called after the user consents.
This method calls
:meth:`requests_oauthlib.OAuth2Session.fetch_token`
and specifies the client configuration's token URI (usually Google's
token server).
Args:
kwargs: Arguments passed through to
:meth:`requests_oauthlib.OAuth2Session.fetch_token`. At least
one of ``code`` or ``authorization_response`` must be
specified.
Returns:
Mapping[str, str]: The obtained tokens. Typically, you will not use
return value of this function and instead and use
:meth:`credentials` to obtain a
:class:`~google.auth.credentials.Credentials` instance.
"""
kwargs.setdefault('client_secret', self.client_config['client_secret'])
return self.oauth2session.fetch_token(
self.client_config['token_uri'], **kwargs) | python | def fetch_token(self, **kwargs):
"""Completes the Authorization Flow and obtains an access token.
This is the final step in the OAuth 2.0 Authorization Flow. This is
called after the user consents.
This method calls
:meth:`requests_oauthlib.OAuth2Session.fetch_token`
and specifies the client configuration's token URI (usually Google's
token server).
Args:
kwargs: Arguments passed through to
:meth:`requests_oauthlib.OAuth2Session.fetch_token`. At least
one of ``code`` or ``authorization_response`` must be
specified.
Returns:
Mapping[str, str]: The obtained tokens. Typically, you will not use
return value of this function and instead and use
:meth:`credentials` to obtain a
:class:`~google.auth.credentials.Credentials` instance.
"""
kwargs.setdefault('client_secret', self.client_config['client_secret'])
return self.oauth2session.fetch_token(
self.client_config['token_uri'], **kwargs) | [
"def",
"fetch_token",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'client_secret'",
",",
"self",
".",
"client_config",
"[",
"'client_secret'",
"]",
")",
"return",
"self",
".",
"oauth2session",
".",
"fetch_token",
"(",
... | Completes the Authorization Flow and obtains an access token.
This is the final step in the OAuth 2.0 Authorization Flow. This is
called after the user consents.
This method calls
:meth:`requests_oauthlib.OAuth2Session.fetch_token`
and specifies the client configuration's token URI (usually Google's
token server).
Args:
kwargs: Arguments passed through to
:meth:`requests_oauthlib.OAuth2Session.fetch_token`. At least
one of ``code`` or ``authorization_response`` must be
specified.
Returns:
Mapping[str, str]: The obtained tokens. Typically, you will not use
return value of this function and instead and use
:meth:`credentials` to obtain a
:class:`~google.auth.credentials.Credentials` instance. | [
"Completes",
"the",
"Authorization",
"Flow",
"and",
"obtains",
"an",
"access",
"token",
"."
] | ba826565994cf20c073d79f534036747fdef2041 | https://github.com/googleapis/google-auth-library-python-oauthlib/blob/ba826565994cf20c073d79f534036747fdef2041/google_auth_oauthlib/flow.py#L216-L241 | train | 228,481 |
googleapis/google-auth-library-python-oauthlib | google_auth_oauthlib/flow.py | InstalledAppFlow.run_console | def run_console(
self,
authorization_prompt_message=_DEFAULT_AUTH_PROMPT_MESSAGE,
authorization_code_message=_DEFAULT_AUTH_CODE_MESSAGE,
**kwargs):
"""Run the flow using the console strategy.
The console strategy instructs the user to open the authorization URL
in their browser. Once the authorization is complete the authorization
server will give the user a code. The user then must copy & paste this
code into the application. The code is then exchanged for a token.
Args:
authorization_prompt_message (str): The message to display to tell
the user to navigate to the authorization URL.
authorization_code_message (str): The message to display when
prompting the user for the authorization code.
kwargs: Additional keyword arguments passed through to
:meth:`authorization_url`.
Returns:
google.oauth2.credentials.Credentials: The OAuth 2.0 credentials
for the user.
"""
kwargs.setdefault('prompt', 'consent')
self.redirect_uri = self._OOB_REDIRECT_URI
auth_url, _ = self.authorization_url(**kwargs)
print(authorization_prompt_message.format(url=auth_url))
code = input(authorization_code_message)
self.fetch_token(code=code)
return self.credentials | python | def run_console(
self,
authorization_prompt_message=_DEFAULT_AUTH_PROMPT_MESSAGE,
authorization_code_message=_DEFAULT_AUTH_CODE_MESSAGE,
**kwargs):
"""Run the flow using the console strategy.
The console strategy instructs the user to open the authorization URL
in their browser. Once the authorization is complete the authorization
server will give the user a code. The user then must copy & paste this
code into the application. The code is then exchanged for a token.
Args:
authorization_prompt_message (str): The message to display to tell
the user to navigate to the authorization URL.
authorization_code_message (str): The message to display when
prompting the user for the authorization code.
kwargs: Additional keyword arguments passed through to
:meth:`authorization_url`.
Returns:
google.oauth2.credentials.Credentials: The OAuth 2.0 credentials
for the user.
"""
kwargs.setdefault('prompt', 'consent')
self.redirect_uri = self._OOB_REDIRECT_URI
auth_url, _ = self.authorization_url(**kwargs)
print(authorization_prompt_message.format(url=auth_url))
code = input(authorization_code_message)
self.fetch_token(code=code)
return self.credentials | [
"def",
"run_console",
"(",
"self",
",",
"authorization_prompt_message",
"=",
"_DEFAULT_AUTH_PROMPT_MESSAGE",
",",
"authorization_code_message",
"=",
"_DEFAULT_AUTH_CODE_MESSAGE",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'prompt'",
",",
"'c... | Run the flow using the console strategy.
The console strategy instructs the user to open the authorization URL
in their browser. Once the authorization is complete the authorization
server will give the user a code. The user then must copy & paste this
code into the application. The code is then exchanged for a token.
Args:
authorization_prompt_message (str): The message to display to tell
the user to navigate to the authorization URL.
authorization_code_message (str): The message to display when
prompting the user for the authorization code.
kwargs: Additional keyword arguments passed through to
:meth:`authorization_url`.
Returns:
google.oauth2.credentials.Credentials: The OAuth 2.0 credentials
for the user. | [
"Run",
"the",
"flow",
"using",
"the",
"console",
"strategy",
"."
] | ba826565994cf20c073d79f534036747fdef2041 | https://github.com/googleapis/google-auth-library-python-oauthlib/blob/ba826565994cf20c073d79f534036747fdef2041/google_auth_oauthlib/flow.py#L330-L366 | train | 228,482 |
googleapis/google-auth-library-python-oauthlib | google_auth_oauthlib/flow.py | InstalledAppFlow.run_local_server | def run_local_server(
self, host='localhost', port=8080,
authorization_prompt_message=_DEFAULT_AUTH_PROMPT_MESSAGE,
success_message=_DEFAULT_WEB_SUCCESS_MESSAGE,
open_browser=True,
**kwargs):
"""Run the flow using the server strategy.
The server strategy instructs the user to open the authorization URL in
their browser and will attempt to automatically open the URL for them.
It will start a local web server to listen for the authorization
response. Once authorization is complete the authorization server will
redirect the user's browser to the local web server. The web server
will get the authorization code from the response and shutdown. The
code is then exchanged for a token.
Args:
host (str): The hostname for the local redirect server. This will
be served over http, not https.
port (int): The port for the local redirect server.
authorization_prompt_message (str): The message to display to tell
the user to navigate to the authorization URL.
success_message (str): The message to display in the web browser
the authorization flow is complete.
open_browser (bool): Whether or not to open the authorization URL
in the user's browser.
kwargs: Additional keyword arguments passed through to
:meth:`authorization_url`.
Returns:
google.oauth2.credentials.Credentials: The OAuth 2.0 credentials
for the user.
"""
self.redirect_uri = 'http://{}:{}/'.format(host, port)
auth_url, _ = self.authorization_url(**kwargs)
wsgi_app = _RedirectWSGIApp(success_message)
local_server = wsgiref.simple_server.make_server(
host, port, wsgi_app, handler_class=_WSGIRequestHandler)
if open_browser:
webbrowser.open(auth_url, new=1, autoraise=True)
print(authorization_prompt_message.format(url=auth_url))
local_server.handle_request()
# Note: using https here because oauthlib is very picky that
# OAuth 2.0 should only occur over https.
authorization_response = wsgi_app.last_request_uri.replace(
'http', 'https')
self.fetch_token(authorization_response=authorization_response)
return self.credentials | python | def run_local_server(
self, host='localhost', port=8080,
authorization_prompt_message=_DEFAULT_AUTH_PROMPT_MESSAGE,
success_message=_DEFAULT_WEB_SUCCESS_MESSAGE,
open_browser=True,
**kwargs):
"""Run the flow using the server strategy.
The server strategy instructs the user to open the authorization URL in
their browser and will attempt to automatically open the URL for them.
It will start a local web server to listen for the authorization
response. Once authorization is complete the authorization server will
redirect the user's browser to the local web server. The web server
will get the authorization code from the response and shutdown. The
code is then exchanged for a token.
Args:
host (str): The hostname for the local redirect server. This will
be served over http, not https.
port (int): The port for the local redirect server.
authorization_prompt_message (str): The message to display to tell
the user to navigate to the authorization URL.
success_message (str): The message to display in the web browser
the authorization flow is complete.
open_browser (bool): Whether or not to open the authorization URL
in the user's browser.
kwargs: Additional keyword arguments passed through to
:meth:`authorization_url`.
Returns:
google.oauth2.credentials.Credentials: The OAuth 2.0 credentials
for the user.
"""
self.redirect_uri = 'http://{}:{}/'.format(host, port)
auth_url, _ = self.authorization_url(**kwargs)
wsgi_app = _RedirectWSGIApp(success_message)
local_server = wsgiref.simple_server.make_server(
host, port, wsgi_app, handler_class=_WSGIRequestHandler)
if open_browser:
webbrowser.open(auth_url, new=1, autoraise=True)
print(authorization_prompt_message.format(url=auth_url))
local_server.handle_request()
# Note: using https here because oauthlib is very picky that
# OAuth 2.0 should only occur over https.
authorization_response = wsgi_app.last_request_uri.replace(
'http', 'https')
self.fetch_token(authorization_response=authorization_response)
return self.credentials | [
"def",
"run_local_server",
"(",
"self",
",",
"host",
"=",
"'localhost'",
",",
"port",
"=",
"8080",
",",
"authorization_prompt_message",
"=",
"_DEFAULT_AUTH_PROMPT_MESSAGE",
",",
"success_message",
"=",
"_DEFAULT_WEB_SUCCESS_MESSAGE",
",",
"open_browser",
"=",
"True",
... | Run the flow using the server strategy.
The server strategy instructs the user to open the authorization URL in
their browser and will attempt to automatically open the URL for them.
It will start a local web server to listen for the authorization
response. Once authorization is complete the authorization server will
redirect the user's browser to the local web server. The web server
will get the authorization code from the response and shutdown. The
code is then exchanged for a token.
Args:
host (str): The hostname for the local redirect server. This will
be served over http, not https.
port (int): The port for the local redirect server.
authorization_prompt_message (str): The message to display to tell
the user to navigate to the authorization URL.
success_message (str): The message to display in the web browser
the authorization flow is complete.
open_browser (bool): Whether or not to open the authorization URL
in the user's browser.
kwargs: Additional keyword arguments passed through to
:meth:`authorization_url`.
Returns:
google.oauth2.credentials.Credentials: The OAuth 2.0 credentials
for the user. | [
"Run",
"the",
"flow",
"using",
"the",
"server",
"strategy",
"."
] | ba826565994cf20c073d79f534036747fdef2041 | https://github.com/googleapis/google-auth-library-python-oauthlib/blob/ba826565994cf20c073d79f534036747fdef2041/google_auth_oauthlib/flow.py#L368-L422 | train | 228,483 |
PyFilesystem/pyfilesystem2 | fs/opener/registry.py | Registry.install | def install(self, opener):
# type: (Union[Type[Opener], Opener, Callable[[], Opener]]) -> None
"""Install an opener.
Arguments:
opener (`Opener`): an `Opener` instance, or a callable that
returns an opener instance.
Note:
May be used as a class decorator. For example::
registry = Registry()
@registry.install
class ArchiveOpener(Opener):
protocols = ['zip', 'tar']
"""
_opener = opener if isinstance(opener, Opener) else opener()
assert isinstance(_opener, Opener), "Opener instance required"
assert _opener.protocols, "must list one or more protocols"
for protocol in _opener.protocols:
self._protocols[protocol] = _opener
return opener | python | def install(self, opener):
# type: (Union[Type[Opener], Opener, Callable[[], Opener]]) -> None
"""Install an opener.
Arguments:
opener (`Opener`): an `Opener` instance, or a callable that
returns an opener instance.
Note:
May be used as a class decorator. For example::
registry = Registry()
@registry.install
class ArchiveOpener(Opener):
protocols = ['zip', 'tar']
"""
_opener = opener if isinstance(opener, Opener) else opener()
assert isinstance(_opener, Opener), "Opener instance required"
assert _opener.protocols, "must list one or more protocols"
for protocol in _opener.protocols:
self._protocols[protocol] = _opener
return opener | [
"def",
"install",
"(",
"self",
",",
"opener",
")",
":",
"# type: (Union[Type[Opener], Opener, Callable[[], Opener]]) -> None",
"_opener",
"=",
"opener",
"if",
"isinstance",
"(",
"opener",
",",
"Opener",
")",
"else",
"opener",
"(",
")",
"assert",
"isinstance",
"(",
... | Install an opener.
Arguments:
opener (`Opener`): an `Opener` instance, or a callable that
returns an opener instance.
Note:
May be used as a class decorator. For example::
registry = Registry()
@registry.install
class ArchiveOpener(Opener):
protocols = ['zip', 'tar'] | [
"Install",
"an",
"opener",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/opener/registry.py#L59-L79 | train | 228,484 |
PyFilesystem/pyfilesystem2 | fs/opener/registry.py | Registry.get_opener | def get_opener(self, protocol):
# type: (Text) -> Opener
"""Get the opener class associated to a given protocol.
Arguments:
protocol (str): A filesystem protocol.
Returns:
Opener: an opener instance.
Raises:
~fs.opener.errors.UnsupportedProtocol: If no opener
could be found for the given protocol.
EntryPointLoadingError: If the returned entry point
is not an `Opener` subclass or could not be loaded
successfully.
"""
protocol = protocol or self.default_opener
if self.load_extern:
entry_point = next(
pkg_resources.iter_entry_points("fs.opener", protocol), None
)
else:
entry_point = None
# If not entry point was loaded from the extensions, try looking
# into the registered protocols
if entry_point is None:
if protocol in self._protocols:
opener_instance = self._protocols[protocol]
else:
raise UnsupportedProtocol(
"protocol '{}' is not supported".format(protocol)
)
# If an entry point was found in an extension, attempt to load it
else:
try:
opener = entry_point.load()
except Exception as exception:
raise EntryPointError(
"could not load entry point; {}".format(exception)
)
if not issubclass(opener, Opener):
raise EntryPointError("entry point did not return an opener")
try:
opener_instance = opener()
except Exception as exception:
raise EntryPointError(
"could not instantiate opener; {}".format(exception)
)
return opener_instance | python | def get_opener(self, protocol):
# type: (Text) -> Opener
"""Get the opener class associated to a given protocol.
Arguments:
protocol (str): A filesystem protocol.
Returns:
Opener: an opener instance.
Raises:
~fs.opener.errors.UnsupportedProtocol: If no opener
could be found for the given protocol.
EntryPointLoadingError: If the returned entry point
is not an `Opener` subclass or could not be loaded
successfully.
"""
protocol = protocol or self.default_opener
if self.load_extern:
entry_point = next(
pkg_resources.iter_entry_points("fs.opener", protocol), None
)
else:
entry_point = None
# If not entry point was loaded from the extensions, try looking
# into the registered protocols
if entry_point is None:
if protocol in self._protocols:
opener_instance = self._protocols[protocol]
else:
raise UnsupportedProtocol(
"protocol '{}' is not supported".format(protocol)
)
# If an entry point was found in an extension, attempt to load it
else:
try:
opener = entry_point.load()
except Exception as exception:
raise EntryPointError(
"could not load entry point; {}".format(exception)
)
if not issubclass(opener, Opener):
raise EntryPointError("entry point did not return an opener")
try:
opener_instance = opener()
except Exception as exception:
raise EntryPointError(
"could not instantiate opener; {}".format(exception)
)
return opener_instance | [
"def",
"get_opener",
"(",
"self",
",",
"protocol",
")",
":",
"# type: (Text) -> Opener",
"protocol",
"=",
"protocol",
"or",
"self",
".",
"default_opener",
"if",
"self",
".",
"load_extern",
":",
"entry_point",
"=",
"next",
"(",
"pkg_resources",
".",
"iter_entry_p... | Get the opener class associated to a given protocol.
Arguments:
protocol (str): A filesystem protocol.
Returns:
Opener: an opener instance.
Raises:
~fs.opener.errors.UnsupportedProtocol: If no opener
could be found for the given protocol.
EntryPointLoadingError: If the returned entry point
is not an `Opener` subclass or could not be loaded
successfully. | [
"Get",
"the",
"opener",
"class",
"associated",
"to",
"a",
"given",
"protocol",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/opener/registry.py#L96-L151 | train | 228,485 |
PyFilesystem/pyfilesystem2 | fs/opener/registry.py | Registry.open | def open(
self,
fs_url, # type: Text
writeable=True, # type: bool
create=False, # type: bool
cwd=".", # type: Text
default_protocol="osfs", # type: Text
):
# type: (...) -> Tuple[FS, Text]
"""Open a filesystem from a FS URL.
Returns a tuple of a filesystem object and a path. If there is
no path in the FS URL, the path value will be `None`.
Arguments:
fs_url (str): A filesystem URL.
writeable (bool, optional): `True` if the filesystem must be
writeable.
create (bool, optional): `True` if the filesystem should be
created if it does not exist.
cwd (str): The current working directory.
Returns:
(FS, str): a tuple of ``(<filesystem>, <path from url>)``
"""
if "://" not in fs_url:
# URL may just be a path
fs_url = "{}://{}".format(default_protocol, fs_url)
parse_result = parse_fs_url(fs_url)
protocol = parse_result.protocol
open_path = parse_result.path
opener = self.get_opener(protocol)
open_fs = opener.open_fs(fs_url, parse_result, writeable, create, cwd)
return open_fs, open_path | python | def open(
self,
fs_url, # type: Text
writeable=True, # type: bool
create=False, # type: bool
cwd=".", # type: Text
default_protocol="osfs", # type: Text
):
# type: (...) -> Tuple[FS, Text]
"""Open a filesystem from a FS URL.
Returns a tuple of a filesystem object and a path. If there is
no path in the FS URL, the path value will be `None`.
Arguments:
fs_url (str): A filesystem URL.
writeable (bool, optional): `True` if the filesystem must be
writeable.
create (bool, optional): `True` if the filesystem should be
created if it does not exist.
cwd (str): The current working directory.
Returns:
(FS, str): a tuple of ``(<filesystem>, <path from url>)``
"""
if "://" not in fs_url:
# URL may just be a path
fs_url = "{}://{}".format(default_protocol, fs_url)
parse_result = parse_fs_url(fs_url)
protocol = parse_result.protocol
open_path = parse_result.path
opener = self.get_opener(protocol)
open_fs = opener.open_fs(fs_url, parse_result, writeable, create, cwd)
return open_fs, open_path | [
"def",
"open",
"(",
"self",
",",
"fs_url",
",",
"# type: Text",
"writeable",
"=",
"True",
",",
"# type: bool",
"create",
"=",
"False",
",",
"# type: bool",
"cwd",
"=",
"\".\"",
",",
"# type: Text",
"default_protocol",
"=",
"\"osfs\"",
",",
"# type: Text",
")",... | Open a filesystem from a FS URL.
Returns a tuple of a filesystem object and a path. If there is
no path in the FS URL, the path value will be `None`.
Arguments:
fs_url (str): A filesystem URL.
writeable (bool, optional): `True` if the filesystem must be
writeable.
create (bool, optional): `True` if the filesystem should be
created if it does not exist.
cwd (str): The current working directory.
Returns:
(FS, str): a tuple of ``(<filesystem>, <path from url>)`` | [
"Open",
"a",
"filesystem",
"from",
"a",
"FS",
"URL",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/opener/registry.py#L153-L190 | train | 228,486 |
PyFilesystem/pyfilesystem2 | fs/opener/registry.py | Registry.manage_fs | def manage_fs(
self,
fs_url, # type: Union[FS, Text]
create=False, # type: bool
writeable=False, # type: bool
cwd=".", # type: Text
):
# type: (...) -> Iterator[FS]
"""Get a context manager to open and close a filesystem.
Arguments:
fs_url (FS or str): A filesystem instance or a FS URL.
create (bool, optional): If `True`, then create the filesystem if
it doesn't already exist.
writeable (bool, optional): If `True`, then the filesystem
must be writeable.
cwd (str): The current working directory, if opening a
`~fs.osfs.OSFS`.
Sometimes it is convenient to be able to pass either a FS object
*or* an FS URL to a function. This context manager handles the
required logic for that.
Example:
>>> def print_ls(list_fs):
... '''List a directory.'''
... with manage_fs(list_fs) as fs:
... print(' '.join(fs.listdir()))
This function may be used in two ways. You may either pass
a ``str``, as follows::
>>> print_list('zip://projects.zip')
Or, an filesystem instance::
>>> from fs.osfs import OSFS
>>> projects_fs = OSFS('~/')
>>> print_list(projects_fs)
"""
from ..base import FS
if isinstance(fs_url, FS):
yield fs_url
else:
_fs = self.open_fs(fs_url, create=create, writeable=writeable, cwd=cwd)
try:
yield _fs
except:
raise
finally:
_fs.close() | python | def manage_fs(
self,
fs_url, # type: Union[FS, Text]
create=False, # type: bool
writeable=False, # type: bool
cwd=".", # type: Text
):
# type: (...) -> Iterator[FS]
"""Get a context manager to open and close a filesystem.
Arguments:
fs_url (FS or str): A filesystem instance or a FS URL.
create (bool, optional): If `True`, then create the filesystem if
it doesn't already exist.
writeable (bool, optional): If `True`, then the filesystem
must be writeable.
cwd (str): The current working directory, if opening a
`~fs.osfs.OSFS`.
Sometimes it is convenient to be able to pass either a FS object
*or* an FS URL to a function. This context manager handles the
required logic for that.
Example:
>>> def print_ls(list_fs):
... '''List a directory.'''
... with manage_fs(list_fs) as fs:
... print(' '.join(fs.listdir()))
This function may be used in two ways. You may either pass
a ``str``, as follows::
>>> print_list('zip://projects.zip')
Or, an filesystem instance::
>>> from fs.osfs import OSFS
>>> projects_fs = OSFS('~/')
>>> print_list(projects_fs)
"""
from ..base import FS
if isinstance(fs_url, FS):
yield fs_url
else:
_fs = self.open_fs(fs_url, create=create, writeable=writeable, cwd=cwd)
try:
yield _fs
except:
raise
finally:
_fs.close() | [
"def",
"manage_fs",
"(",
"self",
",",
"fs_url",
",",
"# type: Union[FS, Text]",
"create",
"=",
"False",
",",
"# type: bool",
"writeable",
"=",
"False",
",",
"# type: bool",
"cwd",
"=",
"\".\"",
",",
"# type: Text",
")",
":",
"# type: (...) -> Iterator[FS]",
"from"... | Get a context manager to open and close a filesystem.
Arguments:
fs_url (FS or str): A filesystem instance or a FS URL.
create (bool, optional): If `True`, then create the filesystem if
it doesn't already exist.
writeable (bool, optional): If `True`, then the filesystem
must be writeable.
cwd (str): The current working directory, if opening a
`~fs.osfs.OSFS`.
Sometimes it is convenient to be able to pass either a FS object
*or* an FS URL to a function. This context manager handles the
required logic for that.
Example:
>>> def print_ls(list_fs):
... '''List a directory.'''
... with manage_fs(list_fs) as fs:
... print(' '.join(fs.listdir()))
This function may be used in two ways. You may either pass
a ``str``, as follows::
>>> print_list('zip://projects.zip')
Or, an filesystem instance::
>>> from fs.osfs import OSFS
>>> projects_fs = OSFS('~/')
>>> print_list(projects_fs) | [
"Get",
"a",
"context",
"manager",
"to",
"open",
"and",
"close",
"a",
"filesystem",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/opener/registry.py#L233-L285 | train | 228,487 |
PyFilesystem/pyfilesystem2 | fs/copy.py | copy_fs | def copy_fs(
src_fs, # type: Union[FS, Text]
dst_fs, # type: Union[FS, Text]
walker=None, # type: Optional[Walker]
on_copy=None, # type: Optional[_OnCopy]
workers=0, # type: int
):
# type: (...) -> None
"""Copy the contents of one filesystem to another.
Arguments:
src_fs (FS or str): Source filesystem (URL or instance).
dst_fs (FS or str): Destination filesystem (URL or instance).
walker (~fs.walk.Walker, optional): A walker object that will be
used to scan for files in ``src_fs``. Set this if you only want
to consider a sub-set of the resources in ``src_fs``.
on_copy (callable): A function callback called after a single file copy
is executed. Expected signature is ``(src_fs, src_path, dst_fs,
dst_path)``.
workers (int): Use `worker` threads to copy data, or ``0`` (default) for
a single-threaded copy.
"""
return copy_dir(
src_fs, "/", dst_fs, "/", walker=walker, on_copy=on_copy, workers=workers
) | python | def copy_fs(
src_fs, # type: Union[FS, Text]
dst_fs, # type: Union[FS, Text]
walker=None, # type: Optional[Walker]
on_copy=None, # type: Optional[_OnCopy]
workers=0, # type: int
):
# type: (...) -> None
"""Copy the contents of one filesystem to another.
Arguments:
src_fs (FS or str): Source filesystem (URL or instance).
dst_fs (FS or str): Destination filesystem (URL or instance).
walker (~fs.walk.Walker, optional): A walker object that will be
used to scan for files in ``src_fs``. Set this if you only want
to consider a sub-set of the resources in ``src_fs``.
on_copy (callable): A function callback called after a single file copy
is executed. Expected signature is ``(src_fs, src_path, dst_fs,
dst_path)``.
workers (int): Use `worker` threads to copy data, or ``0`` (default) for
a single-threaded copy.
"""
return copy_dir(
src_fs, "/", dst_fs, "/", walker=walker, on_copy=on_copy, workers=workers
) | [
"def",
"copy_fs",
"(",
"src_fs",
",",
"# type: Union[FS, Text]",
"dst_fs",
",",
"# type: Union[FS, Text]",
"walker",
"=",
"None",
",",
"# type: Optional[Walker]",
"on_copy",
"=",
"None",
",",
"# type: Optional[_OnCopy]",
"workers",
"=",
"0",
",",
"# type: int",
")",
... | Copy the contents of one filesystem to another.
Arguments:
src_fs (FS or str): Source filesystem (URL or instance).
dst_fs (FS or str): Destination filesystem (URL or instance).
walker (~fs.walk.Walker, optional): A walker object that will be
used to scan for files in ``src_fs``. Set this if you only want
to consider a sub-set of the resources in ``src_fs``.
on_copy (callable): A function callback called after a single file copy
is executed. Expected signature is ``(src_fs, src_path, dst_fs,
dst_path)``.
workers (int): Use `worker` threads to copy data, or ``0`` (default) for
a single-threaded copy. | [
"Copy",
"the",
"contents",
"of",
"one",
"filesystem",
"to",
"another",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/copy.py#L22-L47 | train | 228,488 |
PyFilesystem/pyfilesystem2 | fs/copy.py | copy_fs_if_newer | def copy_fs_if_newer(
src_fs, # type: Union[FS, Text]
dst_fs, # type: Union[FS, Text]
walker=None, # type: Optional[Walker]
on_copy=None, # type: Optional[_OnCopy]
workers=0, # type: int
):
# type: (...) -> None
"""Copy the contents of one filesystem to another, checking times.
If both source and destination files exist, the copy is executed
only if the source file is newer than the destination file. In case
modification times of source or destination files are not available,
copy file is always executed.
Arguments:
src_fs (FS or str): Source filesystem (URL or instance).
dst_fs (FS or str): Destination filesystem (URL or instance).
walker (~fs.walk.Walker, optional): A walker object that will be
used to scan for files in ``src_fs``. Set this if you only want
to consider a sub-set of the resources in ``src_fs``.
on_copy (callable):A function callback called after a single file copy
is executed. Expected signature is ``(src_fs, src_path, dst_fs,
dst_path)``.
workers (int): Use ``worker`` threads to copy data, or ``0`` (default) for
a single-threaded copy.
"""
return copy_dir_if_newer(
src_fs, "/", dst_fs, "/", walker=walker, on_copy=on_copy, workers=workers
) | python | def copy_fs_if_newer(
src_fs, # type: Union[FS, Text]
dst_fs, # type: Union[FS, Text]
walker=None, # type: Optional[Walker]
on_copy=None, # type: Optional[_OnCopy]
workers=0, # type: int
):
# type: (...) -> None
"""Copy the contents of one filesystem to another, checking times.
If both source and destination files exist, the copy is executed
only if the source file is newer than the destination file. In case
modification times of source or destination files are not available,
copy file is always executed.
Arguments:
src_fs (FS or str): Source filesystem (URL or instance).
dst_fs (FS or str): Destination filesystem (URL or instance).
walker (~fs.walk.Walker, optional): A walker object that will be
used to scan for files in ``src_fs``. Set this if you only want
to consider a sub-set of the resources in ``src_fs``.
on_copy (callable):A function callback called after a single file copy
is executed. Expected signature is ``(src_fs, src_path, dst_fs,
dst_path)``.
workers (int): Use ``worker`` threads to copy data, or ``0`` (default) for
a single-threaded copy.
"""
return copy_dir_if_newer(
src_fs, "/", dst_fs, "/", walker=walker, on_copy=on_copy, workers=workers
) | [
"def",
"copy_fs_if_newer",
"(",
"src_fs",
",",
"# type: Union[FS, Text]",
"dst_fs",
",",
"# type: Union[FS, Text]",
"walker",
"=",
"None",
",",
"# type: Optional[Walker]",
"on_copy",
"=",
"None",
",",
"# type: Optional[_OnCopy]",
"workers",
"=",
"0",
",",
"# type: int",... | Copy the contents of one filesystem to another, checking times.
If both source and destination files exist, the copy is executed
only if the source file is newer than the destination file. In case
modification times of source or destination files are not available,
copy file is always executed.
Arguments:
src_fs (FS or str): Source filesystem (URL or instance).
dst_fs (FS or str): Destination filesystem (URL or instance).
walker (~fs.walk.Walker, optional): A walker object that will be
used to scan for files in ``src_fs``. Set this if you only want
to consider a sub-set of the resources in ``src_fs``.
on_copy (callable):A function callback called after a single file copy
is executed. Expected signature is ``(src_fs, src_path, dst_fs,
dst_path)``.
workers (int): Use ``worker`` threads to copy data, or ``0`` (default) for
a single-threaded copy. | [
"Copy",
"the",
"contents",
"of",
"one",
"filesystem",
"to",
"another",
"checking",
"times",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/copy.py#L50-L80 | train | 228,489 |
PyFilesystem/pyfilesystem2 | fs/copy.py | _source_is_newer | def _source_is_newer(src_fs, src_path, dst_fs, dst_path):
# type: (FS, Text, FS, Text) -> bool
"""Determine if source file is newer than destination file.
Arguments:
src_fs (FS): Source filesystem (instance or URL).
src_path (str): Path to a file on the source filesystem.
dst_fs (FS): Destination filesystem (instance or URL).
dst_path (str): Path to a file on the destination filesystem.
Returns:
bool: `True` if the source file is newer than the destination
file or file modification time cannot be determined, `False`
otherwise.
"""
try:
if dst_fs.exists(dst_path):
namespace = ("details", "modified")
src_modified = src_fs.getinfo(src_path, namespace).modified
if src_modified is not None:
dst_modified = dst_fs.getinfo(dst_path, namespace).modified
return dst_modified is None or src_modified > dst_modified
return True
except FSError: # pragma: no cover
# todo: should log something here
return True | python | def _source_is_newer(src_fs, src_path, dst_fs, dst_path):
# type: (FS, Text, FS, Text) -> bool
"""Determine if source file is newer than destination file.
Arguments:
src_fs (FS): Source filesystem (instance or URL).
src_path (str): Path to a file on the source filesystem.
dst_fs (FS): Destination filesystem (instance or URL).
dst_path (str): Path to a file on the destination filesystem.
Returns:
bool: `True` if the source file is newer than the destination
file or file modification time cannot be determined, `False`
otherwise.
"""
try:
if dst_fs.exists(dst_path):
namespace = ("details", "modified")
src_modified = src_fs.getinfo(src_path, namespace).modified
if src_modified is not None:
dst_modified = dst_fs.getinfo(dst_path, namespace).modified
return dst_modified is None or src_modified > dst_modified
return True
except FSError: # pragma: no cover
# todo: should log something here
return True | [
"def",
"_source_is_newer",
"(",
"src_fs",
",",
"src_path",
",",
"dst_fs",
",",
"dst_path",
")",
":",
"# type: (FS, Text, FS, Text) -> bool",
"try",
":",
"if",
"dst_fs",
".",
"exists",
"(",
"dst_path",
")",
":",
"namespace",
"=",
"(",
"\"details\"",
",",
"\"mod... | Determine if source file is newer than destination file.
Arguments:
src_fs (FS): Source filesystem (instance or URL).
src_path (str): Path to a file on the source filesystem.
dst_fs (FS): Destination filesystem (instance or URL).
dst_path (str): Path to a file on the destination filesystem.
Returns:
bool: `True` if the source file is newer than the destination
file or file modification time cannot be determined, `False`
otherwise. | [
"Determine",
"if",
"source",
"file",
"is",
"newer",
"than",
"destination",
"file",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/copy.py#L83-L109 | train | 228,490 |
PyFilesystem/pyfilesystem2 | fs/copy.py | copy_file | def copy_file(
src_fs, # type: Union[FS, Text]
src_path, # type: Text
dst_fs, # type: Union[FS, Text]
dst_path, # type: Text
):
# type: (...) -> None
"""Copy a file from one filesystem to another.
If the destination exists, and is a file, it will be first truncated.
Arguments:
src_fs (FS or str): Source filesystem (instance or URL).
src_path (str): Path to a file on the source filesystem.
dst_fs (FS or str): Destination filesystem (instance or URL).
dst_path (str): Path to a file on the destination filesystem.
"""
with manage_fs(src_fs, writeable=False) as _src_fs:
with manage_fs(dst_fs, create=True) as _dst_fs:
if _src_fs is _dst_fs:
# Same filesystem, so we can do a potentially optimized
# copy
_src_fs.copy(src_path, dst_path, overwrite=True)
else:
# Standard copy
with _src_fs.lock(), _dst_fs.lock():
if _dst_fs.hassyspath(dst_path):
with _dst_fs.openbin(dst_path, "w") as write_file:
_src_fs.download(src_path, write_file)
else:
with _src_fs.openbin(src_path) as read_file:
_dst_fs.upload(dst_path, read_file) | python | def copy_file(
src_fs, # type: Union[FS, Text]
src_path, # type: Text
dst_fs, # type: Union[FS, Text]
dst_path, # type: Text
):
# type: (...) -> None
"""Copy a file from one filesystem to another.
If the destination exists, and is a file, it will be first truncated.
Arguments:
src_fs (FS or str): Source filesystem (instance or URL).
src_path (str): Path to a file on the source filesystem.
dst_fs (FS or str): Destination filesystem (instance or URL).
dst_path (str): Path to a file on the destination filesystem.
"""
with manage_fs(src_fs, writeable=False) as _src_fs:
with manage_fs(dst_fs, create=True) as _dst_fs:
if _src_fs is _dst_fs:
# Same filesystem, so we can do a potentially optimized
# copy
_src_fs.copy(src_path, dst_path, overwrite=True)
else:
# Standard copy
with _src_fs.lock(), _dst_fs.lock():
if _dst_fs.hassyspath(dst_path):
with _dst_fs.openbin(dst_path, "w") as write_file:
_src_fs.download(src_path, write_file)
else:
with _src_fs.openbin(src_path) as read_file:
_dst_fs.upload(dst_path, read_file) | [
"def",
"copy_file",
"(",
"src_fs",
",",
"# type: Union[FS, Text]",
"src_path",
",",
"# type: Text",
"dst_fs",
",",
"# type: Union[FS, Text]",
"dst_path",
",",
"# type: Text",
")",
":",
"# type: (...) -> None",
"with",
"manage_fs",
"(",
"src_fs",
",",
"writeable",
"=",... | Copy a file from one filesystem to another.
If the destination exists, and is a file, it will be first truncated.
Arguments:
src_fs (FS or str): Source filesystem (instance or URL).
src_path (str): Path to a file on the source filesystem.
dst_fs (FS or str): Destination filesystem (instance or URL).
dst_path (str): Path to a file on the destination filesystem. | [
"Copy",
"a",
"file",
"from",
"one",
"filesystem",
"to",
"another",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/copy.py#L112-L144 | train | 228,491 |
PyFilesystem/pyfilesystem2 | fs/copy.py | copy_file_internal | def copy_file_internal(
src_fs, # type: FS
src_path, # type: Text
dst_fs, # type: FS
dst_path, # type: Text
):
# type: (...) -> None
"""Low level copy, that doesn't call manage_fs or lock.
If the destination exists, and is a file, it will be first truncated.
This method exists to optimize copying in loops. In general you
should prefer `copy_file`.
Arguments:
src_fs (FS): Source filesystem.
src_path (str): Path to a file on the source filesystem.
dst_fs (FS: Destination filesystem.
dst_path (str): Path to a file on the destination filesystem.
"""
if src_fs is dst_fs:
# Same filesystem, so we can do a potentially optimized
# copy
src_fs.copy(src_path, dst_path, overwrite=True)
elif dst_fs.hassyspath(dst_path):
with dst_fs.openbin(dst_path, "w") as write_file:
src_fs.download(src_path, write_file)
else:
with src_fs.openbin(src_path) as read_file:
dst_fs.upload(dst_path, read_file) | python | def copy_file_internal(
src_fs, # type: FS
src_path, # type: Text
dst_fs, # type: FS
dst_path, # type: Text
):
# type: (...) -> None
"""Low level copy, that doesn't call manage_fs or lock.
If the destination exists, and is a file, it will be first truncated.
This method exists to optimize copying in loops. In general you
should prefer `copy_file`.
Arguments:
src_fs (FS): Source filesystem.
src_path (str): Path to a file on the source filesystem.
dst_fs (FS: Destination filesystem.
dst_path (str): Path to a file on the destination filesystem.
"""
if src_fs is dst_fs:
# Same filesystem, so we can do a potentially optimized
# copy
src_fs.copy(src_path, dst_path, overwrite=True)
elif dst_fs.hassyspath(dst_path):
with dst_fs.openbin(dst_path, "w") as write_file:
src_fs.download(src_path, write_file)
else:
with src_fs.openbin(src_path) as read_file:
dst_fs.upload(dst_path, read_file) | [
"def",
"copy_file_internal",
"(",
"src_fs",
",",
"# type: FS",
"src_path",
",",
"# type: Text",
"dst_fs",
",",
"# type: FS",
"dst_path",
",",
"# type: Text",
")",
":",
"# type: (...) -> None",
"if",
"src_fs",
"is",
"dst_fs",
":",
"# Same filesystem, so we can do a poten... | Low level copy, that doesn't call manage_fs or lock.
If the destination exists, and is a file, it will be first truncated.
This method exists to optimize copying in loops. In general you
should prefer `copy_file`.
Arguments:
src_fs (FS): Source filesystem.
src_path (str): Path to a file on the source filesystem.
dst_fs (FS: Destination filesystem.
dst_path (str): Path to a file on the destination filesystem. | [
"Low",
"level",
"copy",
"that",
"doesn",
"t",
"call",
"manage_fs",
"or",
"lock",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/copy.py#L147-L177 | train | 228,492 |
PyFilesystem/pyfilesystem2 | fs/copy.py | copy_file_if_newer | def copy_file_if_newer(
src_fs, # type: Union[FS, Text]
src_path, # type: Text
dst_fs, # type: Union[FS, Text]
dst_path, # type: Text
):
# type: (...) -> bool
"""Copy a file from one filesystem to another, checking times.
If the destination exists, and is a file, it will be first truncated.
If both source and destination files exist, the copy is executed only
if the source file is newer than the destination file. In case
modification times of source or destination files are not available,
copy is always executed.
Arguments:
src_fs (FS or str): Source filesystem (instance or URL).
src_path (str): Path to a file on the source filesystem.
dst_fs (FS or str): Destination filesystem (instance or URL).
dst_path (str): Path to a file on the destination filesystem.
Returns:
bool: `True` if the file copy was executed, `False` otherwise.
"""
with manage_fs(src_fs, writeable=False) as _src_fs:
with manage_fs(dst_fs, create=True) as _dst_fs:
if _src_fs is _dst_fs:
# Same filesystem, so we can do a potentially optimized
# copy
if _source_is_newer(_src_fs, src_path, _dst_fs, dst_path):
_src_fs.copy(src_path, dst_path, overwrite=True)
return True
else:
return False
else:
# Standard copy
with _src_fs.lock(), _dst_fs.lock():
if _source_is_newer(_src_fs, src_path, _dst_fs, dst_path):
copy_file_internal(_src_fs, src_path, _dst_fs, dst_path)
return True
else:
return False | python | def copy_file_if_newer(
src_fs, # type: Union[FS, Text]
src_path, # type: Text
dst_fs, # type: Union[FS, Text]
dst_path, # type: Text
):
# type: (...) -> bool
"""Copy a file from one filesystem to another, checking times.
If the destination exists, and is a file, it will be first truncated.
If both source and destination files exist, the copy is executed only
if the source file is newer than the destination file. In case
modification times of source or destination files are not available,
copy is always executed.
Arguments:
src_fs (FS or str): Source filesystem (instance or URL).
src_path (str): Path to a file on the source filesystem.
dst_fs (FS or str): Destination filesystem (instance or URL).
dst_path (str): Path to a file on the destination filesystem.
Returns:
bool: `True` if the file copy was executed, `False` otherwise.
"""
with manage_fs(src_fs, writeable=False) as _src_fs:
with manage_fs(dst_fs, create=True) as _dst_fs:
if _src_fs is _dst_fs:
# Same filesystem, so we can do a potentially optimized
# copy
if _source_is_newer(_src_fs, src_path, _dst_fs, dst_path):
_src_fs.copy(src_path, dst_path, overwrite=True)
return True
else:
return False
else:
# Standard copy
with _src_fs.lock(), _dst_fs.lock():
if _source_is_newer(_src_fs, src_path, _dst_fs, dst_path):
copy_file_internal(_src_fs, src_path, _dst_fs, dst_path)
return True
else:
return False | [
"def",
"copy_file_if_newer",
"(",
"src_fs",
",",
"# type: Union[FS, Text]",
"src_path",
",",
"# type: Text",
"dst_fs",
",",
"# type: Union[FS, Text]",
"dst_path",
",",
"# type: Text",
")",
":",
"# type: (...) -> bool",
"with",
"manage_fs",
"(",
"src_fs",
",",
"writeable... | Copy a file from one filesystem to another, checking times.
If the destination exists, and is a file, it will be first truncated.
If both source and destination files exist, the copy is executed only
if the source file is newer than the destination file. In case
modification times of source or destination files are not available,
copy is always executed.
Arguments:
src_fs (FS or str): Source filesystem (instance or URL).
src_path (str): Path to a file on the source filesystem.
dst_fs (FS or str): Destination filesystem (instance or URL).
dst_path (str): Path to a file on the destination filesystem.
Returns:
bool: `True` if the file copy was executed, `False` otherwise. | [
"Copy",
"a",
"file",
"from",
"one",
"filesystem",
"to",
"another",
"checking",
"times",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/copy.py#L180-L222 | train | 228,493 |
PyFilesystem/pyfilesystem2 | fs/copy.py | copy_dir | def copy_dir(
src_fs, # type: Union[FS, Text]
src_path, # type: Text
dst_fs, # type: Union[FS, Text]
dst_path, # type: Text
walker=None, # type: Optional[Walker]
on_copy=None, # type: Optional[_OnCopy]
workers=0, # type: int
):
# type: (...) -> None
"""Copy a directory from one filesystem to another.
Arguments:
src_fs (FS or str): Source filesystem (instance or URL).
src_path (str): Path to a directory on the source filesystem.
dst_fs (FS or str): Destination filesystem (instance or URL).
dst_path (str): Path to a directory on the destination filesystem.
walker (~fs.walk.Walker, optional): A walker object that will be
used to scan for files in ``src_fs``. Set this if you only
want to consider a sub-set of the resources in ``src_fs``.
on_copy (callable, optional): A function callback called after
a single file copy is executed. Expected signature is
``(src_fs, src_path, dst_fs, dst_path)``.
workers (int): Use ``worker`` threads to copy data, or ``0`` (default) for
a single-threaded copy.
"""
on_copy = on_copy or (lambda *args: None)
walker = walker or Walker()
_src_path = abspath(normpath(src_path))
_dst_path = abspath(normpath(dst_path))
def src():
return manage_fs(src_fs, writeable=False)
def dst():
return manage_fs(dst_fs, create=True)
from ._bulk import Copier
with src() as _src_fs, dst() as _dst_fs:
with _src_fs.lock(), _dst_fs.lock():
_thread_safe = is_thread_safe(_src_fs, _dst_fs)
with Copier(num_workers=workers if _thread_safe else 0) as copier:
_dst_fs.makedir(_dst_path, recreate=True)
for dir_path, dirs, files in walker.walk(_src_fs, _src_path):
copy_path = combine(_dst_path, frombase(_src_path, dir_path))
for info in dirs:
_dst_fs.makedir(info.make_path(copy_path), recreate=True)
for info in files:
src_path = info.make_path(dir_path)
dst_path = info.make_path(copy_path)
copier.copy(_src_fs, src_path, _dst_fs, dst_path)
on_copy(_src_fs, src_path, _dst_fs, dst_path) | python | def copy_dir(
src_fs, # type: Union[FS, Text]
src_path, # type: Text
dst_fs, # type: Union[FS, Text]
dst_path, # type: Text
walker=None, # type: Optional[Walker]
on_copy=None, # type: Optional[_OnCopy]
workers=0, # type: int
):
# type: (...) -> None
"""Copy a directory from one filesystem to another.
Arguments:
src_fs (FS or str): Source filesystem (instance or URL).
src_path (str): Path to a directory on the source filesystem.
dst_fs (FS or str): Destination filesystem (instance or URL).
dst_path (str): Path to a directory on the destination filesystem.
walker (~fs.walk.Walker, optional): A walker object that will be
used to scan for files in ``src_fs``. Set this if you only
want to consider a sub-set of the resources in ``src_fs``.
on_copy (callable, optional): A function callback called after
a single file copy is executed. Expected signature is
``(src_fs, src_path, dst_fs, dst_path)``.
workers (int): Use ``worker`` threads to copy data, or ``0`` (default) for
a single-threaded copy.
"""
on_copy = on_copy or (lambda *args: None)
walker = walker or Walker()
_src_path = abspath(normpath(src_path))
_dst_path = abspath(normpath(dst_path))
def src():
return manage_fs(src_fs, writeable=False)
def dst():
return manage_fs(dst_fs, create=True)
from ._bulk import Copier
with src() as _src_fs, dst() as _dst_fs:
with _src_fs.lock(), _dst_fs.lock():
_thread_safe = is_thread_safe(_src_fs, _dst_fs)
with Copier(num_workers=workers if _thread_safe else 0) as copier:
_dst_fs.makedir(_dst_path, recreate=True)
for dir_path, dirs, files in walker.walk(_src_fs, _src_path):
copy_path = combine(_dst_path, frombase(_src_path, dir_path))
for info in dirs:
_dst_fs.makedir(info.make_path(copy_path), recreate=True)
for info in files:
src_path = info.make_path(dir_path)
dst_path = info.make_path(copy_path)
copier.copy(_src_fs, src_path, _dst_fs, dst_path)
on_copy(_src_fs, src_path, _dst_fs, dst_path) | [
"def",
"copy_dir",
"(",
"src_fs",
",",
"# type: Union[FS, Text]",
"src_path",
",",
"# type: Text",
"dst_fs",
",",
"# type: Union[FS, Text]",
"dst_path",
",",
"# type: Text",
"walker",
"=",
"None",
",",
"# type: Optional[Walker]",
"on_copy",
"=",
"None",
",",
"# type: ... | Copy a directory from one filesystem to another.
Arguments:
src_fs (FS or str): Source filesystem (instance or URL).
src_path (str): Path to a directory on the source filesystem.
dst_fs (FS or str): Destination filesystem (instance or URL).
dst_path (str): Path to a directory on the destination filesystem.
walker (~fs.walk.Walker, optional): A walker object that will be
used to scan for files in ``src_fs``. Set this if you only
want to consider a sub-set of the resources in ``src_fs``.
on_copy (callable, optional): A function callback called after
a single file copy is executed. Expected signature is
``(src_fs, src_path, dst_fs, dst_path)``.
workers (int): Use ``worker`` threads to copy data, or ``0`` (default) for
a single-threaded copy. | [
"Copy",
"a",
"directory",
"from",
"one",
"filesystem",
"to",
"another",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/copy.py#L249-L302 | train | 228,494 |
PyFilesystem/pyfilesystem2 | fs/copy.py | copy_dir_if_newer | def copy_dir_if_newer(
src_fs, # type: Union[FS, Text]
src_path, # type: Text
dst_fs, # type: Union[FS, Text]
dst_path, # type: Text
walker=None, # type: Optional[Walker]
on_copy=None, # type: Optional[_OnCopy]
workers=0, # type: int
):
# type: (...) -> None
"""Copy a directory from one filesystem to another, checking times.
If both source and destination files exist, the copy is executed only
if the source file is newer than the destination file. In case
modification times of source or destination files are not available,
copy is always executed.
Arguments:
src_fs (FS or str): Source filesystem (instance or URL).
src_path (str): Path to a directory on the source filesystem.
dst_fs (FS or str): Destination filesystem (instance or URL).
dst_path (str): Path to a directory on the destination filesystem.
walker (~fs.walk.Walker, optional): A walker object that will be
used to scan for files in ``src_fs``. Set this if you only
want to consider a sub-set of the resources in ``src_fs``.
on_copy (callable, optional): A function callback called after
a single file copy is executed. Expected signature is
``(src_fs, src_path, dst_fs, dst_path)``.
workers (int): Use ``worker`` threads to copy data, or ``0`` (default) for
a single-threaded copy.
"""
on_copy = on_copy or (lambda *args: None)
walker = walker or Walker()
_src_path = abspath(normpath(src_path))
_dst_path = abspath(normpath(dst_path))
def src():
return manage_fs(src_fs, writeable=False)
def dst():
return manage_fs(dst_fs, create=True)
from ._bulk import Copier
with src() as _src_fs, dst() as _dst_fs:
with _src_fs.lock(), _dst_fs.lock():
_thread_safe = is_thread_safe(_src_fs, _dst_fs)
with Copier(num_workers=workers if _thread_safe else 0) as copier:
_dst_fs.makedir(_dst_path, recreate=True)
namespace = ("details", "modified")
dst_state = {
path: info
for path, info in walker.info(_dst_fs, _dst_path, namespace)
if info.is_file
}
src_state = [
(path, info)
for path, info in walker.info(_src_fs, _src_path, namespace)
]
for dir_path, copy_info in src_state:
copy_path = combine(_dst_path, frombase(_src_path, dir_path))
if copy_info.is_dir:
_dst_fs.makedir(copy_path, recreate=True)
elif copy_info.is_file:
# dst file is present, try to figure out if copy
# is necessary
try:
src_modified = copy_info.modified
dst_modified = dst_state[dir_path].modified
except KeyError:
do_copy = True
else:
do_copy = (
src_modified is None
or dst_modified is None
or src_modified > dst_modified
)
if do_copy:
copier.copy(_src_fs, dir_path, _dst_fs, copy_path)
on_copy(_src_fs, dir_path, _dst_fs, copy_path) | python | def copy_dir_if_newer(
src_fs, # type: Union[FS, Text]
src_path, # type: Text
dst_fs, # type: Union[FS, Text]
dst_path, # type: Text
walker=None, # type: Optional[Walker]
on_copy=None, # type: Optional[_OnCopy]
workers=0, # type: int
):
# type: (...) -> None
"""Copy a directory from one filesystem to another, checking times.
If both source and destination files exist, the copy is executed only
if the source file is newer than the destination file. In case
modification times of source or destination files are not available,
copy is always executed.
Arguments:
src_fs (FS or str): Source filesystem (instance or URL).
src_path (str): Path to a directory on the source filesystem.
dst_fs (FS or str): Destination filesystem (instance or URL).
dst_path (str): Path to a directory on the destination filesystem.
walker (~fs.walk.Walker, optional): A walker object that will be
used to scan for files in ``src_fs``. Set this if you only
want to consider a sub-set of the resources in ``src_fs``.
on_copy (callable, optional): A function callback called after
a single file copy is executed. Expected signature is
``(src_fs, src_path, dst_fs, dst_path)``.
workers (int): Use ``worker`` threads to copy data, or ``0`` (default) for
a single-threaded copy.
"""
on_copy = on_copy or (lambda *args: None)
walker = walker or Walker()
_src_path = abspath(normpath(src_path))
_dst_path = abspath(normpath(dst_path))
def src():
return manage_fs(src_fs, writeable=False)
def dst():
return manage_fs(dst_fs, create=True)
from ._bulk import Copier
with src() as _src_fs, dst() as _dst_fs:
with _src_fs.lock(), _dst_fs.lock():
_thread_safe = is_thread_safe(_src_fs, _dst_fs)
with Copier(num_workers=workers if _thread_safe else 0) as copier:
_dst_fs.makedir(_dst_path, recreate=True)
namespace = ("details", "modified")
dst_state = {
path: info
for path, info in walker.info(_dst_fs, _dst_path, namespace)
if info.is_file
}
src_state = [
(path, info)
for path, info in walker.info(_src_fs, _src_path, namespace)
]
for dir_path, copy_info in src_state:
copy_path = combine(_dst_path, frombase(_src_path, dir_path))
if copy_info.is_dir:
_dst_fs.makedir(copy_path, recreate=True)
elif copy_info.is_file:
# dst file is present, try to figure out if copy
# is necessary
try:
src_modified = copy_info.modified
dst_modified = dst_state[dir_path].modified
except KeyError:
do_copy = True
else:
do_copy = (
src_modified is None
or dst_modified is None
or src_modified > dst_modified
)
if do_copy:
copier.copy(_src_fs, dir_path, _dst_fs, copy_path)
on_copy(_src_fs, dir_path, _dst_fs, copy_path) | [
"def",
"copy_dir_if_newer",
"(",
"src_fs",
",",
"# type: Union[FS, Text]",
"src_path",
",",
"# type: Text",
"dst_fs",
",",
"# type: Union[FS, Text]",
"dst_path",
",",
"# type: Text",
"walker",
"=",
"None",
",",
"# type: Optional[Walker]",
"on_copy",
"=",
"None",
",",
... | Copy a directory from one filesystem to another, checking times.
If both source and destination files exist, the copy is executed only
if the source file is newer than the destination file. In case
modification times of source or destination files are not available,
copy is always executed.
Arguments:
src_fs (FS or str): Source filesystem (instance or URL).
src_path (str): Path to a directory on the source filesystem.
dst_fs (FS or str): Destination filesystem (instance or URL).
dst_path (str): Path to a directory on the destination filesystem.
walker (~fs.walk.Walker, optional): A walker object that will be
used to scan for files in ``src_fs``. Set this if you only
want to consider a sub-set of the resources in ``src_fs``.
on_copy (callable, optional): A function callback called after
a single file copy is executed. Expected signature is
``(src_fs, src_path, dst_fs, dst_path)``.
workers (int): Use ``worker`` threads to copy data, or ``0`` (default) for
a single-threaded copy. | [
"Copy",
"a",
"directory",
"from",
"one",
"filesystem",
"to",
"another",
"checking",
"times",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/copy.py#L305-L386 | train | 228,495 |
PyFilesystem/pyfilesystem2 | fs/ftpfs.py | _parse_ftp_error | def _parse_ftp_error(error):
# type: (ftplib.Error) -> Tuple[Text, Text]
"""Extract code and message from ftp error."""
code, _, message = text_type(error).partition(" ")
return code, message | python | def _parse_ftp_error(error):
# type: (ftplib.Error) -> Tuple[Text, Text]
"""Extract code and message from ftp error."""
code, _, message = text_type(error).partition(" ")
return code, message | [
"def",
"_parse_ftp_error",
"(",
"error",
")",
":",
"# type: (ftplib.Error) -> Tuple[Text, Text]",
"code",
",",
"_",
",",
"message",
"=",
"text_type",
"(",
"error",
")",
".",
"partition",
"(",
"\" \"",
")",
"return",
"code",
",",
"message"
] | Extract code and message from ftp error. | [
"Extract",
"code",
"and",
"message",
"from",
"ftp",
"error",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/ftpfs.py#L108-L112 | train | 228,496 |
PyFilesystem/pyfilesystem2 | fs/ftpfs.py | FTPFile._open_ftp | def _open_ftp(self):
# type: () -> FTP
"""Open an ftp object for the file."""
ftp = self.fs._open_ftp()
ftp.voidcmd(str("TYPE I"))
return ftp | python | def _open_ftp(self):
# type: () -> FTP
"""Open an ftp object for the file."""
ftp = self.fs._open_ftp()
ftp.voidcmd(str("TYPE I"))
return ftp | [
"def",
"_open_ftp",
"(",
"self",
")",
":",
"# type: () -> FTP",
"ftp",
"=",
"self",
".",
"fs",
".",
"_open_ftp",
"(",
")",
"ftp",
".",
"voidcmd",
"(",
"str",
"(",
"\"TYPE I\"",
")",
")",
"return",
"ftp"
] | Open an ftp object for the file. | [
"Open",
"an",
"ftp",
"object",
"for",
"the",
"file",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/ftpfs.py#L150-L155 | train | 228,497 |
PyFilesystem/pyfilesystem2 | fs/ftpfs.py | FTPFS._parse_features | def _parse_features(cls, feat_response):
# type: (Text) -> Dict[Text, Text]
"""Parse a dict of features from FTP feat response.
"""
features = {}
if feat_response.split("-")[0] == "211":
for line in feat_response.splitlines():
if line.startswith(" "):
key, _, value = line[1:].partition(" ")
features[key] = value
return features | python | def _parse_features(cls, feat_response):
# type: (Text) -> Dict[Text, Text]
"""Parse a dict of features from FTP feat response.
"""
features = {}
if feat_response.split("-")[0] == "211":
for line in feat_response.splitlines():
if line.startswith(" "):
key, _, value = line[1:].partition(" ")
features[key] = value
return features | [
"def",
"_parse_features",
"(",
"cls",
",",
"feat_response",
")",
":",
"# type: (Text) -> Dict[Text, Text]",
"features",
"=",
"{",
"}",
"if",
"feat_response",
".",
"split",
"(",
"\"-\"",
")",
"[",
"0",
"]",
"==",
"\"211\"",
":",
"for",
"line",
"in",
"feat_res... | Parse a dict of features from FTP feat response. | [
"Parse",
"a",
"dict",
"of",
"features",
"from",
"FTP",
"feat",
"response",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/ftpfs.py#L397-L407 | train | 228,498 |
PyFilesystem/pyfilesystem2 | fs/ftpfs.py | FTPFS._open_ftp | def _open_ftp(self):
# type: () -> FTP
"""Open a new ftp object.
"""
_ftp = FTP()
_ftp.set_debuglevel(0)
with ftp_errors(self):
_ftp.connect(self.host, self.port, self.timeout)
_ftp.login(self.user, self.passwd, self.acct)
self._features = {}
try:
feat_response = _decode(_ftp.sendcmd("FEAT"), "latin-1")
except error_perm: # pragma: no cover
self.encoding = "latin-1"
else:
self._features = self._parse_features(feat_response)
self.encoding = "utf-8" if "UTF8" in self._features else "latin-1"
if not PY2:
_ftp.file = _ftp.sock.makefile( # type: ignore
"r", encoding=self.encoding
)
_ftp.encoding = self.encoding
self._welcome = _ftp.welcome
return _ftp | python | def _open_ftp(self):
# type: () -> FTP
"""Open a new ftp object.
"""
_ftp = FTP()
_ftp.set_debuglevel(0)
with ftp_errors(self):
_ftp.connect(self.host, self.port, self.timeout)
_ftp.login(self.user, self.passwd, self.acct)
self._features = {}
try:
feat_response = _decode(_ftp.sendcmd("FEAT"), "latin-1")
except error_perm: # pragma: no cover
self.encoding = "latin-1"
else:
self._features = self._parse_features(feat_response)
self.encoding = "utf-8" if "UTF8" in self._features else "latin-1"
if not PY2:
_ftp.file = _ftp.sock.makefile( # type: ignore
"r", encoding=self.encoding
)
_ftp.encoding = self.encoding
self._welcome = _ftp.welcome
return _ftp | [
"def",
"_open_ftp",
"(",
"self",
")",
":",
"# type: () -> FTP",
"_ftp",
"=",
"FTP",
"(",
")",
"_ftp",
".",
"set_debuglevel",
"(",
"0",
")",
"with",
"ftp_errors",
"(",
"self",
")",
":",
"_ftp",
".",
"connect",
"(",
"self",
".",
"host",
",",
"self",
".... | Open a new ftp object. | [
"Open",
"a",
"new",
"ftp",
"object",
"."
] | 047f3593f297d1442194cda3da7a7335bcc9c14a | https://github.com/PyFilesystem/pyfilesystem2/blob/047f3593f297d1442194cda3da7a7335bcc9c14a/fs/ftpfs.py#L409-L432 | train | 228,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.