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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
Opentrons/opentrons | update-server/otupdate/buildroot/file_actions.py | unzip_update | def unzip_update(filepath: str,
progress_callback: Callable[[float], None],
acceptable_files: Sequence[str],
mandatory_files: Sequence[str],
chunk_size: int = 1024) -> Tuple[Mapping[str, Optional[str]],
Mapping[str, int]]:
""" Unzip an update file
The update file must contain
- a file called rootfs.ext4
- a file called rootfs.ext4.hash
It may contain
- a file called rootfs.ext4.hash.sig
These will all be unzipped (discarding their leading directories) to
the same file as the zipfile.
This function is blocking and takes a while. It calls ``progress_callback``
to indicate update progress with a number between 0 and 1 indicating
overall archive unzip progress.
:param filepath: The path zipfile to unzip. The contents will be in its
directory
:param progress_callback: A callable taking a number between 0 and 1 that
will be called periodically to check progress.
This is for user display; it may not reach 1.0
exactly.
:param acceptable_files: A list of files to unzip if found. Others will be
ignored.
:param mandatory_files: A list of files to raise an error about if they're
not in the zip. Should probably be a subset of
``acceptable_files``.
:param chunk_size: If specified, the size of the chunk to read and write.
If not specified, will default to 1024
:return: Two dictionaries, the first mapping file names to paths and the
second mapping file names to sizes
:raises FileMissing: If a mandatory file is missing
"""
assert chunk_size
total_size = 0
written_size = 0
to_unzip: List[zipfile.ZipInfo] = []
file_paths: Dict[str, Optional[str]] = {fn: None
for fn in acceptable_files}
file_sizes: Dict[str, int] = {fn: 0 for fn in acceptable_files}
LOG.info(f"Unzipping {filepath}")
with zipfile.ZipFile(filepath, 'r') as zf:
files = zf.infolist()
remaining_filenames = [fn for fn in acceptable_files]
for fi in files:
if fi.filename in acceptable_files:
to_unzip.append(fi)
total_size += fi.file_size
remaining_filenames.remove(fi.filename)
LOG.debug(f"Found {fi.filename} ({fi.file_size}B)")
else:
LOG.debug(f"Ignoring {fi.filename}")
for name in remaining_filenames:
if name in mandatory_files:
raise FileMissing(f'File {name} missing from zip')
for fi in to_unzip:
uncomp_path = os.path.join(os.path.dirname(filepath), fi.filename)
with zf.open(fi) as zipped, open(uncomp_path, 'wb') as unzipped:
LOG.debug(f"Beginning unzip of {fi.filename} to {uncomp_path}")
while True:
chunk = zipped.read(chunk_size)
unzipped.write(chunk)
written_size += len(chunk)
progress_callback(written_size/total_size)
if len(chunk) != chunk_size:
break
file_paths[fi.filename] = uncomp_path
file_sizes[fi.filename] = fi.file_size
LOG.debug(f"Unzipped {fi.filename} to {uncomp_path}")
LOG.info(
f"Unzipped {filepath}, results: \n\t" + '\n\t'.join(
[f'{k}: {file_paths[k]} ({file_sizes[k]}B)'
for k in file_paths.keys()]))
return file_paths, file_sizes | python | def unzip_update(filepath: str,
progress_callback: Callable[[float], None],
acceptable_files: Sequence[str],
mandatory_files: Sequence[str],
chunk_size: int = 1024) -> Tuple[Mapping[str, Optional[str]],
Mapping[str, int]]:
""" Unzip an update file
The update file must contain
- a file called rootfs.ext4
- a file called rootfs.ext4.hash
It may contain
- a file called rootfs.ext4.hash.sig
These will all be unzipped (discarding their leading directories) to
the same file as the zipfile.
This function is blocking and takes a while. It calls ``progress_callback``
to indicate update progress with a number between 0 and 1 indicating
overall archive unzip progress.
:param filepath: The path zipfile to unzip. The contents will be in its
directory
:param progress_callback: A callable taking a number between 0 and 1 that
will be called periodically to check progress.
This is for user display; it may not reach 1.0
exactly.
:param acceptable_files: A list of files to unzip if found. Others will be
ignored.
:param mandatory_files: A list of files to raise an error about if they're
not in the zip. Should probably be a subset of
``acceptable_files``.
:param chunk_size: If specified, the size of the chunk to read and write.
If not specified, will default to 1024
:return: Two dictionaries, the first mapping file names to paths and the
second mapping file names to sizes
:raises FileMissing: If a mandatory file is missing
"""
assert chunk_size
total_size = 0
written_size = 0
to_unzip: List[zipfile.ZipInfo] = []
file_paths: Dict[str, Optional[str]] = {fn: None
for fn in acceptable_files}
file_sizes: Dict[str, int] = {fn: 0 for fn in acceptable_files}
LOG.info(f"Unzipping {filepath}")
with zipfile.ZipFile(filepath, 'r') as zf:
files = zf.infolist()
remaining_filenames = [fn for fn in acceptable_files]
for fi in files:
if fi.filename in acceptable_files:
to_unzip.append(fi)
total_size += fi.file_size
remaining_filenames.remove(fi.filename)
LOG.debug(f"Found {fi.filename} ({fi.file_size}B)")
else:
LOG.debug(f"Ignoring {fi.filename}")
for name in remaining_filenames:
if name in mandatory_files:
raise FileMissing(f'File {name} missing from zip')
for fi in to_unzip:
uncomp_path = os.path.join(os.path.dirname(filepath), fi.filename)
with zf.open(fi) as zipped, open(uncomp_path, 'wb') as unzipped:
LOG.debug(f"Beginning unzip of {fi.filename} to {uncomp_path}")
while True:
chunk = zipped.read(chunk_size)
unzipped.write(chunk)
written_size += len(chunk)
progress_callback(written_size/total_size)
if len(chunk) != chunk_size:
break
file_paths[fi.filename] = uncomp_path
file_sizes[fi.filename] = fi.file_size
LOG.debug(f"Unzipped {fi.filename} to {uncomp_path}")
LOG.info(
f"Unzipped {filepath}, results: \n\t" + '\n\t'.join(
[f'{k}: {file_paths[k]} ({file_sizes[k]}B)'
for k in file_paths.keys()]))
return file_paths, file_sizes | [
"def",
"unzip_update",
"(",
"filepath",
":",
"str",
",",
"progress_callback",
":",
"Callable",
"[",
"[",
"float",
"]",
",",
"None",
"]",
",",
"acceptable_files",
":",
"Sequence",
"[",
"str",
"]",
",",
"mandatory_files",
":",
"Sequence",
"[",
"str",
"]",
... | Unzip an update file
The update file must contain
- a file called rootfs.ext4
- a file called rootfs.ext4.hash
It may contain
- a file called rootfs.ext4.hash.sig
These will all be unzipped (discarding their leading directories) to
the same file as the zipfile.
This function is blocking and takes a while. It calls ``progress_callback``
to indicate update progress with a number between 0 and 1 indicating
overall archive unzip progress.
:param filepath: The path zipfile to unzip. The contents will be in its
directory
:param progress_callback: A callable taking a number between 0 and 1 that
will be called periodically to check progress.
This is for user display; it may not reach 1.0
exactly.
:param acceptable_files: A list of files to unzip if found. Others will be
ignored.
:param mandatory_files: A list of files to raise an error about if they're
not in the zip. Should probably be a subset of
``acceptable_files``.
:param chunk_size: If specified, the size of the chunk to read and write.
If not specified, will default to 1024
:return: Two dictionaries, the first mapping file names to paths and the
second mapping file names to sizes
:raises FileMissing: If a mandatory file is missing | [
"Unzip",
"an",
"update",
"file"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/buildroot/file_actions.py#L74-L158 | train | 198,100 |
Opentrons/opentrons | update-server/otupdate/buildroot/file_actions.py | hash_file | def hash_file(path: str,
progress_callback: Callable[[float], None],
chunk_size: int = 1024,
file_size: int = None,
algo: str = 'sha256') -> bytes:
"""
Hash a file and return the hash, providing progress callbacks
:param path: The file to hash
:param progress_callback: The callback to call with progress between 0 and
1. May not ever be precisely 1.0.
:param chunk_size: If specified, the size of the chunks to hash in one call
If not specified, defaults to 1024
:param file_size: If specified, the size of the file to hash (used for
progress callback generation). If not specified,
calculated internally.
:param algo: The algorithm to use. Can be anything used by
:py:mod:`hashlib`
:returns: The output has ascii hex
"""
hasher = hashlib.new(algo)
have_read = 0
if not chunk_size:
chunk_size = 1024
with open(path, 'rb') as to_hash:
if not file_size:
file_size = to_hash.seek(0, 2)
to_hash.seek(0)
while True:
chunk = to_hash.read(chunk_size)
hasher.update(chunk)
have_read += len(chunk)
progress_callback(have_read/file_size)
if len(chunk) != chunk_size:
break
return binascii.hexlify(hasher.digest()) | python | def hash_file(path: str,
progress_callback: Callable[[float], None],
chunk_size: int = 1024,
file_size: int = None,
algo: str = 'sha256') -> bytes:
"""
Hash a file and return the hash, providing progress callbacks
:param path: The file to hash
:param progress_callback: The callback to call with progress between 0 and
1. May not ever be precisely 1.0.
:param chunk_size: If specified, the size of the chunks to hash in one call
If not specified, defaults to 1024
:param file_size: If specified, the size of the file to hash (used for
progress callback generation). If not specified,
calculated internally.
:param algo: The algorithm to use. Can be anything used by
:py:mod:`hashlib`
:returns: The output has ascii hex
"""
hasher = hashlib.new(algo)
have_read = 0
if not chunk_size:
chunk_size = 1024
with open(path, 'rb') as to_hash:
if not file_size:
file_size = to_hash.seek(0, 2)
to_hash.seek(0)
while True:
chunk = to_hash.read(chunk_size)
hasher.update(chunk)
have_read += len(chunk)
progress_callback(have_read/file_size)
if len(chunk) != chunk_size:
break
return binascii.hexlify(hasher.digest()) | [
"def",
"hash_file",
"(",
"path",
":",
"str",
",",
"progress_callback",
":",
"Callable",
"[",
"[",
"float",
"]",
",",
"None",
"]",
",",
"chunk_size",
":",
"int",
"=",
"1024",
",",
"file_size",
":",
"int",
"=",
"None",
",",
"algo",
":",
"str",
"=",
"... | Hash a file and return the hash, providing progress callbacks
:param path: The file to hash
:param progress_callback: The callback to call with progress between 0 and
1. May not ever be precisely 1.0.
:param chunk_size: If specified, the size of the chunks to hash in one call
If not specified, defaults to 1024
:param file_size: If specified, the size of the file to hash (used for
progress callback generation). If not specified,
calculated internally.
:param algo: The algorithm to use. Can be anything used by
:py:mod:`hashlib`
:returns: The output has ascii hex | [
"Hash",
"a",
"file",
"and",
"return",
"the",
"hash",
"providing",
"progress",
"callbacks"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/buildroot/file_actions.py#L161-L196 | train | 198,101 |
Opentrons/opentrons | update-server/otupdate/buildroot/file_actions.py | _find_unused_partition | def _find_unused_partition() -> RootPartitions:
""" Find the currently-unused root partition to write to """
which = subprocess.check_output(['ot-unused-partition']).strip()
return {b'2': RootPartitions.TWO,
b'3': RootPartitions.THREE}[which] | python | def _find_unused_partition() -> RootPartitions:
""" Find the currently-unused root partition to write to """
which = subprocess.check_output(['ot-unused-partition']).strip()
return {b'2': RootPartitions.TWO,
b'3': RootPartitions.THREE}[which] | [
"def",
"_find_unused_partition",
"(",
")",
"->",
"RootPartitions",
":",
"which",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'ot-unused-partition'",
"]",
")",
".",
"strip",
"(",
")",
"return",
"{",
"b'2'",
":",
"RootPartitions",
".",
"TWO",
",",
"b'3'... | Find the currently-unused root partition to write to | [
"Find",
"the",
"currently",
"-",
"unused",
"root",
"partition",
"to",
"write",
"to"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/buildroot/file_actions.py#L288-L292 | train | 198,102 |
Opentrons/opentrons | update-server/otupdate/buildroot/file_actions.py | write_file | def write_file(infile: str,
outfile: str,
progress_callback: Callable[[float], None],
chunk_size: int = 1024,
file_size: int = None):
""" Write a file to another file with progress callbacks.
:param infile: The input filepath
:param outfile: The output filepath
:param progress_callback: The callback to call for progress
:param chunk_size: The size of file chunks to copy in between progress
notifications
:param file_size: The total size of the update file (for generating
progress percentage). If ``None``, generated with
``seek``/``tell``.
"""
total_written = 0
with open(infile, 'rb') as img, open(outfile, 'wb') as part:
if None is file_size:
file_size = img.seek(0, 2)
img.seek(0)
LOG.info(f'write_file: file size calculated as {file_size}B')
LOG.info(f'write_file: writing {infile} ({file_size}B)'
f' to {outfile} in {chunk_size}B chunks')
while True:
chunk = img.read(chunk_size)
part.write(chunk)
total_written += len(chunk)
progress_callback(total_written / file_size)
if len(chunk) != chunk_size:
break | python | def write_file(infile: str,
outfile: str,
progress_callback: Callable[[float], None],
chunk_size: int = 1024,
file_size: int = None):
""" Write a file to another file with progress callbacks.
:param infile: The input filepath
:param outfile: The output filepath
:param progress_callback: The callback to call for progress
:param chunk_size: The size of file chunks to copy in between progress
notifications
:param file_size: The total size of the update file (for generating
progress percentage). If ``None``, generated with
``seek``/``tell``.
"""
total_written = 0
with open(infile, 'rb') as img, open(outfile, 'wb') as part:
if None is file_size:
file_size = img.seek(0, 2)
img.seek(0)
LOG.info(f'write_file: file size calculated as {file_size}B')
LOG.info(f'write_file: writing {infile} ({file_size}B)'
f' to {outfile} in {chunk_size}B chunks')
while True:
chunk = img.read(chunk_size)
part.write(chunk)
total_written += len(chunk)
progress_callback(total_written / file_size)
if len(chunk) != chunk_size:
break | [
"def",
"write_file",
"(",
"infile",
":",
"str",
",",
"outfile",
":",
"str",
",",
"progress_callback",
":",
"Callable",
"[",
"[",
"float",
"]",
",",
"None",
"]",
",",
"chunk_size",
":",
"int",
"=",
"1024",
",",
"file_size",
":",
"int",
"=",
"None",
")... | Write a file to another file with progress callbacks.
:param infile: The input filepath
:param outfile: The output filepath
:param progress_callback: The callback to call for progress
:param chunk_size: The size of file chunks to copy in between progress
notifications
:param file_size: The total size of the update file (for generating
progress percentage). If ``None``, generated with
``seek``/``tell``. | [
"Write",
"a",
"file",
"to",
"another",
"file",
"with",
"progress",
"callbacks",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/buildroot/file_actions.py#L295-L325 | train | 198,103 |
Opentrons/opentrons | update-server/otupdate/buildroot/file_actions.py | write_update | def write_update(rootfs_filepath: str,
progress_callback: Callable[[float], None],
chunk_size: int = 1024,
file_size: int = None) -> RootPartitions:
"""
Write the new rootfs to the next root partition
- Figure out, from the system, the correct root partition to write to
- Write the rootfs at ``rootfs_filepath`` there, with progress
:param rootfs_filepath: The path to a checked rootfs.ext4
:param progress_callback: A callback to call periodically with progress
between 0 and 1.0. May never reach precisely
1.0, best only for user information.
:param chunk_size: The size of file chunks to copy in between progress
notifications
:param file_size: The total size of the update file (for generating
progress percentage). If ``None``, generated with
``seek``/``tell``.
:returns: The root partition that the rootfs image was written to, e.g.
``RootPartitions.TWO`` or ``RootPartitions.THREE``.
"""
unused = _find_unused_partition()
part_path = unused.value.path
write_file(rootfs_filepath, part_path, progress_callback,
chunk_size, file_size)
return unused | python | def write_update(rootfs_filepath: str,
progress_callback: Callable[[float], None],
chunk_size: int = 1024,
file_size: int = None) -> RootPartitions:
"""
Write the new rootfs to the next root partition
- Figure out, from the system, the correct root partition to write to
- Write the rootfs at ``rootfs_filepath`` there, with progress
:param rootfs_filepath: The path to a checked rootfs.ext4
:param progress_callback: A callback to call periodically with progress
between 0 and 1.0. May never reach precisely
1.0, best only for user information.
:param chunk_size: The size of file chunks to copy in between progress
notifications
:param file_size: The total size of the update file (for generating
progress percentage). If ``None``, generated with
``seek``/``tell``.
:returns: The root partition that the rootfs image was written to, e.g.
``RootPartitions.TWO`` or ``RootPartitions.THREE``.
"""
unused = _find_unused_partition()
part_path = unused.value.path
write_file(rootfs_filepath, part_path, progress_callback,
chunk_size, file_size)
return unused | [
"def",
"write_update",
"(",
"rootfs_filepath",
":",
"str",
",",
"progress_callback",
":",
"Callable",
"[",
"[",
"float",
"]",
",",
"None",
"]",
",",
"chunk_size",
":",
"int",
"=",
"1024",
",",
"file_size",
":",
"int",
"=",
"None",
")",
"->",
"RootPartiti... | Write the new rootfs to the next root partition
- Figure out, from the system, the correct root partition to write to
- Write the rootfs at ``rootfs_filepath`` there, with progress
:param rootfs_filepath: The path to a checked rootfs.ext4
:param progress_callback: A callback to call periodically with progress
between 0 and 1.0. May never reach precisely
1.0, best only for user information.
:param chunk_size: The size of file chunks to copy in between progress
notifications
:param file_size: The total size of the update file (for generating
progress percentage). If ``None``, generated with
``seek``/``tell``.
:returns: The root partition that the rootfs image was written to, e.g.
``RootPartitions.TWO`` or ``RootPartitions.THREE``. | [
"Write",
"the",
"new",
"rootfs",
"to",
"the",
"next",
"root",
"partition"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/buildroot/file_actions.py#L328-L354 | train | 198,104 |
Opentrons/opentrons | update-server/otupdate/buildroot/file_actions.py | _switch_partition | def _switch_partition() -> RootPartitions:
""" Switch the active boot partition using the switch script """
res = subprocess.check_output(['ot-switch-partitions'])
for line in res.split(b'\n'):
matches = re.match(
b'Current boot partition: ([23]), setting to ([23])',
line)
if matches:
return {b'2': RootPartitions.TWO,
b'3': RootPartitions.THREE}[matches.group(2)]
else:
raise RuntimeError(f'Bad output from ot-switch-partitions: {res}') | python | def _switch_partition() -> RootPartitions:
""" Switch the active boot partition using the switch script """
res = subprocess.check_output(['ot-switch-partitions'])
for line in res.split(b'\n'):
matches = re.match(
b'Current boot partition: ([23]), setting to ([23])',
line)
if matches:
return {b'2': RootPartitions.TWO,
b'3': RootPartitions.THREE}[matches.group(2)]
else:
raise RuntimeError(f'Bad output from ot-switch-partitions: {res}') | [
"def",
"_switch_partition",
"(",
")",
"->",
"RootPartitions",
":",
"res",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'ot-switch-partitions'",
"]",
")",
"for",
"line",
"in",
"res",
".",
"split",
"(",
"b'\\n'",
")",
":",
"matches",
"=",
"re",
".",
... | Switch the active boot partition using the switch script | [
"Switch",
"the",
"active",
"boot",
"partition",
"using",
"the",
"switch",
"script"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/buildroot/file_actions.py#L357-L368 | train | 198,105 |
Opentrons/opentrons | update-server/otupdate/buildroot/file_actions.py | commit_update | def commit_update():
""" Switch the target boot partition. """
unused = _find_unused_partition()
new = _switch_partition()
if new != unused:
msg = f"Bad switch: switched to {new} when {unused} was unused"
LOG.error(msg)
raise RuntimeError(msg)
else:
LOG.info(f'commit_update: committed to booting {new}') | python | def commit_update():
""" Switch the target boot partition. """
unused = _find_unused_partition()
new = _switch_partition()
if new != unused:
msg = f"Bad switch: switched to {new} when {unused} was unused"
LOG.error(msg)
raise RuntimeError(msg)
else:
LOG.info(f'commit_update: committed to booting {new}') | [
"def",
"commit_update",
"(",
")",
":",
"unused",
"=",
"_find_unused_partition",
"(",
")",
"new",
"=",
"_switch_partition",
"(",
")",
"if",
"new",
"!=",
"unused",
":",
"msg",
"=",
"f\"Bad switch: switched to {new} when {unused} was unused\"",
"LOG",
".",
"error",
"... | Switch the target boot partition. | [
"Switch",
"the",
"target",
"boot",
"partition",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/buildroot/file_actions.py#L371-L380 | train | 198,106 |
Opentrons/opentrons | api/src/opentrons/legacy_api/containers/placeable.py | Placeable.get_module | def get_module(self):
"""
Returns the module placeable if present
"""
for md in SUPPORTED_MODULES:
maybe_module = self.get_child_by_name(md)
if maybe_module:
# No probability of a placeable having more than one module
return maybe_module
return None | python | def get_module(self):
"""
Returns the module placeable if present
"""
for md in SUPPORTED_MODULES:
maybe_module = self.get_child_by_name(md)
if maybe_module:
# No probability of a placeable having more than one module
return maybe_module
return None | [
"def",
"get_module",
"(",
"self",
")",
":",
"for",
"md",
"in",
"SUPPORTED_MODULES",
":",
"maybe_module",
"=",
"self",
".",
"get_child_by_name",
"(",
"md",
")",
"if",
"maybe_module",
":",
"# No probability of a placeable having more than one module",
"return",
"maybe_m... | Returns the module placeable if present | [
"Returns",
"the",
"module",
"placeable",
"if",
"present"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/containers/placeable.py#L280-L289 | train | 198,107 |
Opentrons/opentrons | api/src/opentrons/legacy_api/containers/placeable.py | Placeable.get_children_from_slice | def get_children_from_slice(self, s):
"""
Retrieves list of children within slice
"""
if isinstance(s.start, str):
s = slice(
self.get_index_from_name(s.start), s.stop, s.step)
if isinstance(s.stop, str):
s = slice(
s.start, self.get_index_from_name(s.stop), s.step)
return WellSeries(self.get_children_list()[s]) | python | def get_children_from_slice(self, s):
"""
Retrieves list of children within slice
"""
if isinstance(s.start, str):
s = slice(
self.get_index_from_name(s.start), s.stop, s.step)
if isinstance(s.stop, str):
s = slice(
s.start, self.get_index_from_name(s.stop), s.step)
return WellSeries(self.get_children_list()[s]) | [
"def",
"get_children_from_slice",
"(",
"self",
",",
"s",
")",
":",
"if",
"isinstance",
"(",
"s",
".",
"start",
",",
"str",
")",
":",
"s",
"=",
"slice",
"(",
"self",
".",
"get_index_from_name",
"(",
"s",
".",
"start",
")",
",",
"s",
".",
"stop",
","... | Retrieves list of children within slice | [
"Retrieves",
"list",
"of",
"children",
"within",
"slice"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/containers/placeable.py#L310-L320 | train | 198,108 |
Opentrons/opentrons | api/src/opentrons/legacy_api/containers/placeable.py | Placeable.get_all_children | def get_all_children(self):
"""
Returns all children recursively
"""
my_children = self.get_children_list()
children = []
children.extend(my_children)
for child in my_children:
children.extend(child.get_all_children())
return children | python | def get_all_children(self):
"""
Returns all children recursively
"""
my_children = self.get_children_list()
children = []
children.extend(my_children)
for child in my_children:
children.extend(child.get_all_children())
return children | [
"def",
"get_all_children",
"(",
"self",
")",
":",
"my_children",
"=",
"self",
".",
"get_children_list",
"(",
")",
"children",
"=",
"[",
"]",
"children",
".",
"extend",
"(",
"my_children",
")",
"for",
"child",
"in",
"my_children",
":",
"children",
".",
"ext... | Returns all children recursively | [
"Returns",
"all",
"children",
"recursively"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/containers/placeable.py#L363-L372 | train | 198,109 |
Opentrons/opentrons | api/src/opentrons/legacy_api/containers/placeable.py | Deck.containers | def containers(self) -> list:
"""
Returns all containers on a deck as a list
"""
all_containers: List = list()
for slot in self:
all_containers += slot.get_children_list()
for container in all_containers:
if getattr(container, 'stackable', False):
all_containers += container.get_children_list()
return all_containers | python | def containers(self) -> list:
"""
Returns all containers on a deck as a list
"""
all_containers: List = list()
for slot in self:
all_containers += slot.get_children_list()
for container in all_containers:
if getattr(container, 'stackable', False):
all_containers += container.get_children_list()
return all_containers | [
"def",
"containers",
"(",
"self",
")",
"->",
"list",
":",
"all_containers",
":",
"List",
"=",
"list",
"(",
")",
"for",
"slot",
"in",
"self",
":",
"all_containers",
"+=",
"slot",
".",
"get_children_list",
"(",
")",
"for",
"container",
"in",
"all_containers"... | Returns all containers on a deck as a list | [
"Returns",
"all",
"containers",
"on",
"a",
"deck",
"as",
"a",
"list"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/containers/placeable.py#L465-L478 | train | 198,110 |
Opentrons/opentrons | api/src/opentrons/legacy_api/containers/placeable.py | Container.calculate_grid | def calculate_grid(self):
"""
Calculates and stores grid structure
"""
if self.grid is None:
self.grid = self.get_wellseries(self.get_grid())
if self.grid_transposed is None:
self.grid_transposed = self.get_wellseries(
self.transpose(
self.get_grid())) | python | def calculate_grid(self):
"""
Calculates and stores grid structure
"""
if self.grid is None:
self.grid = self.get_wellseries(self.get_grid())
if self.grid_transposed is None:
self.grid_transposed = self.get_wellseries(
self.transpose(
self.get_grid())) | [
"def",
"calculate_grid",
"(",
"self",
")",
":",
"if",
"self",
".",
"grid",
"is",
"None",
":",
"self",
".",
"grid",
"=",
"self",
".",
"get_wellseries",
"(",
"self",
".",
"get_grid",
"(",
")",
")",
"if",
"self",
".",
"grid_transposed",
"is",
"None",
":... | Calculates and stores grid structure | [
"Calculates",
"and",
"stores",
"grid",
"structure"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/containers/placeable.py#L526-L536 | train | 198,111 |
Opentrons/opentrons | api/src/opentrons/legacy_api/containers/placeable.py | Container.transpose | def transpose(self, rows):
"""
Transposes the grid to allow for cols
"""
res = OrderedDict()
for row, cols in rows.items():
for col, cell in cols.items():
if col not in res:
res[col] = OrderedDict()
res[col][row] = cell
return res | python | def transpose(self, rows):
"""
Transposes the grid to allow for cols
"""
res = OrderedDict()
for row, cols in rows.items():
for col, cell in cols.items():
if col not in res:
res[col] = OrderedDict()
res[col][row] = cell
return res | [
"def",
"transpose",
"(",
"self",
",",
"rows",
")",
":",
"res",
"=",
"OrderedDict",
"(",
")",
"for",
"row",
",",
"cols",
"in",
"rows",
".",
"items",
"(",
")",
":",
"for",
"col",
",",
"cell",
"in",
"cols",
".",
"items",
"(",
")",
":",
"if",
"col"... | Transposes the grid to allow for cols | [
"Transposes",
"the",
"grid",
"to",
"allow",
"for",
"cols"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/containers/placeable.py#L556-L566 | train | 198,112 |
Opentrons/opentrons | api/src/opentrons/legacy_api/containers/placeable.py | Container.get_wellseries | def get_wellseries(self, matrix):
"""
Returns the grid as a WellSeries of WellSeries
"""
res = OrderedDict()
for col, cells in matrix.items():
if col not in res:
res[col] = OrderedDict()
for row, cell in cells.items():
res[col][row] = self.children_by_name[
''.join(cell)
]
res[col] = WellSeries(res[col], name=col)
return WellSeries(res) | python | def get_wellseries(self, matrix):
"""
Returns the grid as a WellSeries of WellSeries
"""
res = OrderedDict()
for col, cells in matrix.items():
if col not in res:
res[col] = OrderedDict()
for row, cell in cells.items():
res[col][row] = self.children_by_name[
''.join(cell)
]
res[col] = WellSeries(res[col], name=col)
return WellSeries(res) | [
"def",
"get_wellseries",
"(",
"self",
",",
"matrix",
")",
":",
"res",
"=",
"OrderedDict",
"(",
")",
"for",
"col",
",",
"cells",
"in",
"matrix",
".",
"items",
"(",
")",
":",
"if",
"col",
"not",
"in",
"res",
":",
"res",
"[",
"col",
"]",
"=",
"Order... | Returns the grid as a WellSeries of WellSeries | [
"Returns",
"the",
"grid",
"as",
"a",
"WellSeries",
"of",
"WellSeries"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/containers/placeable.py#L568-L581 | train | 198,113 |
Opentrons/opentrons | api/src/opentrons/legacy_api/containers/placeable.py | Container.wells | def wells(self, *args, **kwargs):
"""
Returns child Well or list of child Wells
"""
if len(args) and isinstance(args[0], list):
args = args[0]
new_wells = None
if not args and not kwargs:
new_wells = WellSeries(self.get_children_list())
elif len(args) > 1:
new_wells = WellSeries([self.well(n) for n in args])
elif 'x' in kwargs or 'y' in kwargs:
new_wells = self._parse_wells_x_y(*args, **kwargs)
else:
new_wells = self._parse_wells_to_and_length(*args, **kwargs)
if len(new_wells) == 1:
return new_wells[0]
return new_wells | python | def wells(self, *args, **kwargs):
"""
Returns child Well or list of child Wells
"""
if len(args) and isinstance(args[0], list):
args = args[0]
new_wells = None
if not args and not kwargs:
new_wells = WellSeries(self.get_children_list())
elif len(args) > 1:
new_wells = WellSeries([self.well(n) for n in args])
elif 'x' in kwargs or 'y' in kwargs:
new_wells = self._parse_wells_x_y(*args, **kwargs)
else:
new_wells = self._parse_wells_to_and_length(*args, **kwargs)
if len(new_wells) == 1:
return new_wells[0]
return new_wells | [
"def",
"wells",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"args",
")",
"and",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"list",
")",
":",
"args",
"=",
"args",
"[",
"0",
"]",
"new_wells",
"=",
"No... | Returns child Well or list of child Wells | [
"Returns",
"child",
"Well",
"or",
"list",
"of",
"child",
"Wells"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/containers/placeable.py#L630-L650 | train | 198,114 |
Opentrons/opentrons | api/src/opentrons/drivers/utils.py | parse_device_information | def parse_device_information(
device_info_string: str) -> Mapping[str, str]:
'''
Parse the modules's device information response.
Example response from temp-deck: "serial:aa11 model:bb22 version:cc33"
'''
error_msg = 'Unexpected argument to parse_device_information: {}'.format(
device_info_string)
if not device_info_string or \
not isinstance(device_info_string, str):
raise ParseError(error_msg)
parsed_values = device_info_string.strip().split(' ')
if len(parsed_values) < 3:
log.error(error_msg)
raise ParseError(error_msg)
res = {
parse_key_from_substring(s): parse_string_value_from_substring(s)
for s in parsed_values[:3]
}
for key in ['model', 'version', 'serial']:
if key not in res:
raise ParseError(error_msg)
return res | python | def parse_device_information(
device_info_string: str) -> Mapping[str, str]:
'''
Parse the modules's device information response.
Example response from temp-deck: "serial:aa11 model:bb22 version:cc33"
'''
error_msg = 'Unexpected argument to parse_device_information: {}'.format(
device_info_string)
if not device_info_string or \
not isinstance(device_info_string, str):
raise ParseError(error_msg)
parsed_values = device_info_string.strip().split(' ')
if len(parsed_values) < 3:
log.error(error_msg)
raise ParseError(error_msg)
res = {
parse_key_from_substring(s): parse_string_value_from_substring(s)
for s in parsed_values[:3]
}
for key in ['model', 'version', 'serial']:
if key not in res:
raise ParseError(error_msg)
return res | [
"def",
"parse_device_information",
"(",
"device_info_string",
":",
"str",
")",
"->",
"Mapping",
"[",
"str",
",",
"str",
"]",
":",
"error_msg",
"=",
"'Unexpected argument to parse_device_information: {}'",
".",
"format",
"(",
"device_info_string",
")",
"if",
"not",
"... | Parse the modules's device information response.
Example response from temp-deck: "serial:aa11 model:bb22 version:cc33" | [
"Parse",
"the",
"modules",
"s",
"device",
"information",
"response",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/drivers/utils.py#L93-L116 | train | 198,115 |
Opentrons/opentrons | api/src/opentrons/simulate.py | simulate | def simulate(protocol_file,
propagate_logs=False,
log_level='warning') -> List[Mapping[str, Any]]:
"""
Simulate the protocol itself.
This is a one-stop function to simulate a protocol, whether python or json,
no matter the api version, from external (i.e. not bound up in other
internal server infrastructure) sources.
To simulate an opentrons protocol from other places, pass in a file like
object as protocol_file; this function either returns (if the simulation
has no problems) or raises an exception.
To call from the command line use either the autogenerated entrypoint
``opentrons_simulate`` (``opentrons_simulate.exe``, on windows) or
``python -m opentrons.simulate``.
The return value is the run log, a list of dicts that represent the
commands executed by the robot. Each dict has the following keys:
- ``level``: The depth at which this command is nested - if this an
aspirate inside a mix inside a transfer, for instance,
it would be 3.
- ``payload``: The command, its arguments, and how to format its text.
For more specific details see
:py:mod:`opentrons.commands`. To format a message from
a payload do ``payload['text'].format(**payload)``.
- ``logs``: Any log messages that occurred during execution of this
command, as a logging.LogRecord
:param file-like protocol_file: The protocol file to simulate.
:param propagate_logs: Whether this function should allow logs from the
Opentrons stack to propagate up to the root handler.
This can be useful if you're integrating this
function in a larger application, but most logs that
occur during protocol simulation are best associated
with the actions in the protocol that cause them.
:type propagate_logs: bool
:param log_level: The level of logs to capture in the runlog
:type log_level: 'debug', 'info', 'warning', or 'error'
:returns List[Dict[str, Dict[str, Any]]]: A run log for user output.
"""
stack_logger = logging.getLogger('opentrons')
stack_logger.propagate = propagate_logs
contents = protocol_file.read()
if opentrons.config.feature_flags.use_protocol_api_v2():
try:
execute_args = {'protocol_json': json.loads(contents)}
except json.JSONDecodeError:
execute_args = {'protocol_code': contents}
context = opentrons.protocol_api.contexts.ProtocolContext()
context.home()
scraper = CommandScraper(stack_logger, log_level, context.broker)
execute_args.update({'simulate': True,
'context': context})
opentrons.protocol_api.execute.run_protocol(**execute_args)
else:
try:
proto = json.loads(contents)
except json.JSONDecodeError:
proto = contents
opentrons.robot.disconnect()
scraper = CommandScraper(stack_logger, log_level,
opentrons.robot.broker)
if isinstance(proto, dict):
opentrons.protocols.execute_protocol(proto)
else:
exec(proto, {})
return scraper.commands | python | def simulate(protocol_file,
propagate_logs=False,
log_level='warning') -> List[Mapping[str, Any]]:
"""
Simulate the protocol itself.
This is a one-stop function to simulate a protocol, whether python or json,
no matter the api version, from external (i.e. not bound up in other
internal server infrastructure) sources.
To simulate an opentrons protocol from other places, pass in a file like
object as protocol_file; this function either returns (if the simulation
has no problems) or raises an exception.
To call from the command line use either the autogenerated entrypoint
``opentrons_simulate`` (``opentrons_simulate.exe``, on windows) or
``python -m opentrons.simulate``.
The return value is the run log, a list of dicts that represent the
commands executed by the robot. Each dict has the following keys:
- ``level``: The depth at which this command is nested - if this an
aspirate inside a mix inside a transfer, for instance,
it would be 3.
- ``payload``: The command, its arguments, and how to format its text.
For more specific details see
:py:mod:`opentrons.commands`. To format a message from
a payload do ``payload['text'].format(**payload)``.
- ``logs``: Any log messages that occurred during execution of this
command, as a logging.LogRecord
:param file-like protocol_file: The protocol file to simulate.
:param propagate_logs: Whether this function should allow logs from the
Opentrons stack to propagate up to the root handler.
This can be useful if you're integrating this
function in a larger application, but most logs that
occur during protocol simulation are best associated
with the actions in the protocol that cause them.
:type propagate_logs: bool
:param log_level: The level of logs to capture in the runlog
:type log_level: 'debug', 'info', 'warning', or 'error'
:returns List[Dict[str, Dict[str, Any]]]: A run log for user output.
"""
stack_logger = logging.getLogger('opentrons')
stack_logger.propagate = propagate_logs
contents = protocol_file.read()
if opentrons.config.feature_flags.use_protocol_api_v2():
try:
execute_args = {'protocol_json': json.loads(contents)}
except json.JSONDecodeError:
execute_args = {'protocol_code': contents}
context = opentrons.protocol_api.contexts.ProtocolContext()
context.home()
scraper = CommandScraper(stack_logger, log_level, context.broker)
execute_args.update({'simulate': True,
'context': context})
opentrons.protocol_api.execute.run_protocol(**execute_args)
else:
try:
proto = json.loads(contents)
except json.JSONDecodeError:
proto = contents
opentrons.robot.disconnect()
scraper = CommandScraper(stack_logger, log_level,
opentrons.robot.broker)
if isinstance(proto, dict):
opentrons.protocols.execute_protocol(proto)
else:
exec(proto, {})
return scraper.commands | [
"def",
"simulate",
"(",
"protocol_file",
",",
"propagate_logs",
"=",
"False",
",",
"log_level",
"=",
"'warning'",
")",
"->",
"List",
"[",
"Mapping",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"stack_logger",
"=",
"logging",
".",
"getLogger",
"(",
"'opentrons'"... | Simulate the protocol itself.
This is a one-stop function to simulate a protocol, whether python or json,
no matter the api version, from external (i.e. not bound up in other
internal server infrastructure) sources.
To simulate an opentrons protocol from other places, pass in a file like
object as protocol_file; this function either returns (if the simulation
has no problems) or raises an exception.
To call from the command line use either the autogenerated entrypoint
``opentrons_simulate`` (``opentrons_simulate.exe``, on windows) or
``python -m opentrons.simulate``.
The return value is the run log, a list of dicts that represent the
commands executed by the robot. Each dict has the following keys:
- ``level``: The depth at which this command is nested - if this an
aspirate inside a mix inside a transfer, for instance,
it would be 3.
- ``payload``: The command, its arguments, and how to format its text.
For more specific details see
:py:mod:`opentrons.commands`. To format a message from
a payload do ``payload['text'].format(**payload)``.
- ``logs``: Any log messages that occurred during execution of this
command, as a logging.LogRecord
:param file-like protocol_file: The protocol file to simulate.
:param propagate_logs: Whether this function should allow logs from the
Opentrons stack to propagate up to the root handler.
This can be useful if you're integrating this
function in a larger application, but most logs that
occur during protocol simulation are best associated
with the actions in the protocol that cause them.
:type propagate_logs: bool
:param log_level: The level of logs to capture in the runlog
:type log_level: 'debug', 'info', 'warning', or 'error'
:returns List[Dict[str, Dict[str, Any]]]: A run log for user output. | [
"Simulate",
"the",
"protocol",
"itself",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/simulate.py#L93-L164 | train | 198,116 |
Opentrons/opentrons | api/src/opentrons/simulate.py | main | def main():
""" Run the simulation """
parser = argparse.ArgumentParser(prog='opentrons_simulate',
description=__doc__)
parser.add_argument(
'protocol', metavar='PROTOCOL_FILE',
type=argparse.FileType('r'),
help='The protocol file to simulate (specify - to read from stdin).')
parser.add_argument(
'-v', '--version', action='version',
version=f'%(prog)s {opentrons.__version__}',
help='Print the opentrons package version and exit')
parser.add_argument(
'-o', '--output', action='store',
help='What to output during simulations',
choices=['runlog', 'nothing'],
default='runlog')
parser.add_argument(
'-l', '--log-level', action='store',
help=('Log level for the opentrons stack. Anything below warning '
'can be chatty'),
choices=['error', 'warning', 'info', 'debug'],
default='warning'
)
args = parser.parse_args()
runlog = simulate(args.protocol, log_level=args.log_level)
if args.output == 'runlog':
print(format_runlog(runlog))
return 0 | python | def main():
""" Run the simulation """
parser = argparse.ArgumentParser(prog='opentrons_simulate',
description=__doc__)
parser.add_argument(
'protocol', metavar='PROTOCOL_FILE',
type=argparse.FileType('r'),
help='The protocol file to simulate (specify - to read from stdin).')
parser.add_argument(
'-v', '--version', action='version',
version=f'%(prog)s {opentrons.__version__}',
help='Print the opentrons package version and exit')
parser.add_argument(
'-o', '--output', action='store',
help='What to output during simulations',
choices=['runlog', 'nothing'],
default='runlog')
parser.add_argument(
'-l', '--log-level', action='store',
help=('Log level for the opentrons stack. Anything below warning '
'can be chatty'),
choices=['error', 'warning', 'info', 'debug'],
default='warning'
)
args = parser.parse_args()
runlog = simulate(args.protocol, log_level=args.log_level)
if args.output == 'runlog':
print(format_runlog(runlog))
return 0 | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"prog",
"=",
"'opentrons_simulate'",
",",
"description",
"=",
"__doc__",
")",
"parser",
".",
"add_argument",
"(",
"'protocol'",
",",
"metavar",
"=",
"'PROTOCOL_FILE'",
",",
... | Run the simulation | [
"Run",
"the",
"simulation"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/simulate.py#L191-L220 | train | 198,117 |
Opentrons/opentrons | api/src/opentrons/simulate.py | CommandScraper._command_callback | def _command_callback(self, message):
""" The callback subscribed to the broker """
payload = message['payload']
if message['$'] == 'before':
self._commands.append({'level': self._depth,
'payload': payload,
'logs': []})
self._depth += 1
else:
while not self._queue.empty():
self._commands[-1]['logs'].append(self._queue.get())
self._depth = max(self._depth-1, 0) | python | def _command_callback(self, message):
""" The callback subscribed to the broker """
payload = message['payload']
if message['$'] == 'before':
self._commands.append({'level': self._depth,
'payload': payload,
'logs': []})
self._depth += 1
else:
while not self._queue.empty():
self._commands[-1]['logs'].append(self._queue.get())
self._depth = max(self._depth-1, 0) | [
"def",
"_command_callback",
"(",
"self",
",",
"message",
")",
":",
"payload",
"=",
"message",
"[",
"'payload'",
"]",
"if",
"message",
"[",
"'$'",
"]",
"==",
"'before'",
":",
"self",
".",
"_commands",
".",
"append",
"(",
"{",
"'level'",
":",
"self",
"."... | The callback subscribed to the broker | [
"The",
"callback",
"subscribed",
"to",
"the",
"broker"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/simulate.py#L79-L90 | train | 198,118 |
Opentrons/opentrons | update-server/otupdate/balena/install.py | _update_firmware | async def _update_firmware(filename, loop):
"""
Currently uses the robot singleton from the API server to connect to
Smoothie. Those calls should be separated out from the singleton so it can
be used directly without requiring a full initialization of the API robot.
"""
try:
from opentrons import robot
except ModuleNotFoundError:
res = "Unable to find module `opentrons`--not updating firmware"
rc = 1
log.error(res)
else:
# ensure there is a reference to the port
if not robot.is_connected():
robot.connect()
# get port name
port = str(robot._driver.port)
# set smoothieware into programming mode
robot._driver._smoothie_programming_mode()
# close the port so other application can access it
robot._driver._connection.close()
# run lpc21isp, THIS WILL TAKE AROUND 1 MINUTE TO COMPLETE
update_cmd = 'lpc21isp -wipe -donotstart {0} {1} {2} 12000'.format(
filename, port, robot.config.serial_speed)
proc = await asyncio.create_subprocess_shell(
update_cmd,
stdout=asyncio.subprocess.PIPE,
loop=loop)
rd = await proc.stdout.read()
res = rd.decode().strip()
await proc.communicate()
rc = proc.returncode
if rc == 0:
# re-open the port
robot._driver._connection.open()
# reset smoothieware
robot._driver._smoothie_reset()
# run setup gcodes
robot._driver._setup()
return res, rc | python | async def _update_firmware(filename, loop):
"""
Currently uses the robot singleton from the API server to connect to
Smoothie. Those calls should be separated out from the singleton so it can
be used directly without requiring a full initialization of the API robot.
"""
try:
from opentrons import robot
except ModuleNotFoundError:
res = "Unable to find module `opentrons`--not updating firmware"
rc = 1
log.error(res)
else:
# ensure there is a reference to the port
if not robot.is_connected():
robot.connect()
# get port name
port = str(robot._driver.port)
# set smoothieware into programming mode
robot._driver._smoothie_programming_mode()
# close the port so other application can access it
robot._driver._connection.close()
# run lpc21isp, THIS WILL TAKE AROUND 1 MINUTE TO COMPLETE
update_cmd = 'lpc21isp -wipe -donotstart {0} {1} {2} 12000'.format(
filename, port, robot.config.serial_speed)
proc = await asyncio.create_subprocess_shell(
update_cmd,
stdout=asyncio.subprocess.PIPE,
loop=loop)
rd = await proc.stdout.read()
res = rd.decode().strip()
await proc.communicate()
rc = proc.returncode
if rc == 0:
# re-open the port
robot._driver._connection.open()
# reset smoothieware
robot._driver._smoothie_reset()
# run setup gcodes
robot._driver._setup()
return res, rc | [
"async",
"def",
"_update_firmware",
"(",
"filename",
",",
"loop",
")",
":",
"try",
":",
"from",
"opentrons",
"import",
"robot",
"except",
"ModuleNotFoundError",
":",
"res",
"=",
"\"Unable to find module `opentrons`--not updating firmware\"",
"rc",
"=",
"1",
"log",
"... | Currently uses the robot singleton from the API server to connect to
Smoothie. Those calls should be separated out from the singleton so it can
be used directly without requiring a full initialization of the API robot. | [
"Currently",
"uses",
"the",
"robot",
"singleton",
"from",
"the",
"API",
"server",
"to",
"connect",
"to",
"Smoothie",
".",
"Those",
"calls",
"should",
"be",
"separated",
"out",
"from",
"the",
"singleton",
"so",
"it",
"can",
"be",
"used",
"directly",
"without"... | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/balena/install.py#L95-L139 | train | 198,119 |
Opentrons/opentrons | api/src/opentrons/server/endpoints/control.py | execute_module_command | async def execute_module_command(request):
"""
Execute a command on a given module by its serial number
"""
hw = hw_from_req(request)
requested_serial = request.match_info['serial']
data = await request.json()
command_type = data.get('command_type')
args = data.get('args')
if ff.use_protocol_api_v2():
hw_mods = await hw.discover_modules()
else:
hw_mods = hw.attached_modules.values()
if len(hw_mods) == 0:
return web.json_response({"message": "No connected modules"},
status=404)
matching_mod = next((mod for mod in hw_mods if
mod.device_info.get('serial') == requested_serial),
None)
if not matching_mod:
return web.json_response({"message": "Specified module not found"},
status=404)
if hasattr(matching_mod, command_type):
clean_args = args or []
method = getattr(matching_mod, command_type)
if asyncio.iscoroutinefunction(method):
val = await method(*clean_args)
else:
val = method(*clean_args)
return web.json_response(
{'message': 'Success', 'returnValue': val},
status=200)
else:
return web.json_response(
{'message': f'Module does not have command: {command_type}'},
status=400) | python | async def execute_module_command(request):
"""
Execute a command on a given module by its serial number
"""
hw = hw_from_req(request)
requested_serial = request.match_info['serial']
data = await request.json()
command_type = data.get('command_type')
args = data.get('args')
if ff.use_protocol_api_v2():
hw_mods = await hw.discover_modules()
else:
hw_mods = hw.attached_modules.values()
if len(hw_mods) == 0:
return web.json_response({"message": "No connected modules"},
status=404)
matching_mod = next((mod for mod in hw_mods if
mod.device_info.get('serial') == requested_serial),
None)
if not matching_mod:
return web.json_response({"message": "Specified module not found"},
status=404)
if hasattr(matching_mod, command_type):
clean_args = args or []
method = getattr(matching_mod, command_type)
if asyncio.iscoroutinefunction(method):
val = await method(*clean_args)
else:
val = method(*clean_args)
return web.json_response(
{'message': 'Success', 'returnValue': val},
status=200)
else:
return web.json_response(
{'message': f'Module does not have command: {command_type}'},
status=400) | [
"async",
"def",
"execute_module_command",
"(",
"request",
")",
":",
"hw",
"=",
"hw_from_req",
"(",
"request",
")",
"requested_serial",
"=",
"request",
".",
"match_info",
"[",
"'serial'",
"]",
"data",
"=",
"await",
"request",
".",
"json",
"(",
")",
"command_t... | Execute a command on a given module by its serial number | [
"Execute",
"a",
"command",
"on",
"a",
"given",
"module",
"by",
"its",
"serial",
"number"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/server/endpoints/control.py#L166-L207 | train | 198,120 |
Opentrons/opentrons | api/src/opentrons/server/endpoints/control.py | get_engaged_axes | async def get_engaged_axes(request):
"""
Query driver for engaged state by axis. Response keys will be axes XYZABC
and keys will be True for engaged and False for disengaged. Axes must be
manually disengaged, and are automatically re-engaged whenever a "move" or
"home" command is called on that axis.
Response shape example:
{"x": {"enabled": true}, "y": {"enabled": false}, ...}
"""
hw = hw_from_req(request)
return web.json_response(
{str(k).lower(): {'enabled': v}
for k, v in hw.engaged_axes.items()}) | python | async def get_engaged_axes(request):
"""
Query driver for engaged state by axis. Response keys will be axes XYZABC
and keys will be True for engaged and False for disengaged. Axes must be
manually disengaged, and are automatically re-engaged whenever a "move" or
"home" command is called on that axis.
Response shape example:
{"x": {"enabled": true}, "y": {"enabled": false}, ...}
"""
hw = hw_from_req(request)
return web.json_response(
{str(k).lower(): {'enabled': v}
for k, v in hw.engaged_axes.items()}) | [
"async",
"def",
"get_engaged_axes",
"(",
"request",
")",
":",
"hw",
"=",
"hw_from_req",
"(",
"request",
")",
"return",
"web",
".",
"json_response",
"(",
"{",
"str",
"(",
"k",
")",
".",
"lower",
"(",
")",
":",
"{",
"'enabled'",
":",
"v",
"}",
"for",
... | Query driver for engaged state by axis. Response keys will be axes XYZABC
and keys will be True for engaged and False for disengaged. Axes must be
manually disengaged, and are automatically re-engaged whenever a "move" or
"home" command is called on that axis.
Response shape example:
{"x": {"enabled": true}, "y": {"enabled": false}, ...} | [
"Query",
"driver",
"for",
"engaged",
"state",
"by",
"axis",
".",
"Response",
"keys",
"will",
"be",
"axes",
"XYZABC",
"and",
"keys",
"will",
"be",
"True",
"for",
"engaged",
"and",
"False",
"for",
"disengaged",
".",
"Axes",
"must",
"be",
"manually",
"disenga... | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/server/endpoints/control.py#L210-L223 | train | 198,121 |
Opentrons/opentrons | api/src/opentrons/server/endpoints/control.py | move | async def move(request):
"""
Moves the robot to the specified position as provided by the `control.info`
endpoint response
Post body must include the following keys:
- 'target': either 'mount' or 'pipette'
- 'point': a tuple of 3 floats for x, y, z
- 'mount': must be 'left' or 'right'
If 'target' is 'pipette', body must also contain:
- 'model': must be a valid pipette model (as defined in `pipette_config`)
"""
hw = hw_from_req(request)
req = await request.text()
data = json.loads(req)
target, point, mount, model, message, error = _validate_move_data(data)
if error:
status = 400
else:
status = 200
if ff.use_protocol_api_v2():
await hw.cache_instruments()
if target == 'mount':
critical_point = CriticalPoint.MOUNT
else:
critical_point = None
mount = Mount[mount.upper()]
target = Point(*point)
await hw.home_z()
pos = await hw.gantry_position(mount, critical_point)
await hw.move_to(mount, target._replace(z=pos.z),
critical_point=critical_point)
await hw.move_to(mount, target,
critical_point=critical_point)
pos = await hw.gantry_position(mount)
message = 'Move complete. New position: {}'.format(pos)
else:
if target == 'mount':
message = _move_mount(hw, mount, point)
elif target == 'pipette':
message = _move_pipette(hw, mount, model, point)
return web.json_response({"message": message}, status=status) | python | async def move(request):
"""
Moves the robot to the specified position as provided by the `control.info`
endpoint response
Post body must include the following keys:
- 'target': either 'mount' or 'pipette'
- 'point': a tuple of 3 floats for x, y, z
- 'mount': must be 'left' or 'right'
If 'target' is 'pipette', body must also contain:
- 'model': must be a valid pipette model (as defined in `pipette_config`)
"""
hw = hw_from_req(request)
req = await request.text()
data = json.loads(req)
target, point, mount, model, message, error = _validate_move_data(data)
if error:
status = 400
else:
status = 200
if ff.use_protocol_api_v2():
await hw.cache_instruments()
if target == 'mount':
critical_point = CriticalPoint.MOUNT
else:
critical_point = None
mount = Mount[mount.upper()]
target = Point(*point)
await hw.home_z()
pos = await hw.gantry_position(mount, critical_point)
await hw.move_to(mount, target._replace(z=pos.z),
critical_point=critical_point)
await hw.move_to(mount, target,
critical_point=critical_point)
pos = await hw.gantry_position(mount)
message = 'Move complete. New position: {}'.format(pos)
else:
if target == 'mount':
message = _move_mount(hw, mount, point)
elif target == 'pipette':
message = _move_pipette(hw, mount, model, point)
return web.json_response({"message": message}, status=status) | [
"async",
"def",
"move",
"(",
"request",
")",
":",
"hw",
"=",
"hw_from_req",
"(",
"request",
")",
"req",
"=",
"await",
"request",
".",
"text",
"(",
")",
"data",
"=",
"json",
".",
"loads",
"(",
"req",
")",
"target",
",",
"point",
",",
"mount",
",",
... | Moves the robot to the specified position as provided by the `control.info`
endpoint response
Post body must include the following keys:
- 'target': either 'mount' or 'pipette'
- 'point': a tuple of 3 floats for x, y, z
- 'mount': must be 'left' or 'right'
If 'target' is 'pipette', body must also contain:
- 'model': must be a valid pipette model (as defined in `pipette_config`) | [
"Moves",
"the",
"robot",
"to",
"the",
"specified",
"position",
"as",
"provided",
"by",
"the",
"control",
".",
"info",
"endpoint",
"response"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/server/endpoints/control.py#L309-L353 | train | 198,122 |
Opentrons/opentrons | api/src/opentrons/server/endpoints/control.py | _move_mount | def _move_mount(robot, mount, point):
"""
The carriage moves the mount in the Z axis, and the gantry moves in X and Y
Mount movements do not have the same protections calculated in to an
existing `move` command like Pipette does, so the safest thing is to home
the Z axis, then move in X and Y, then move down to the specified Z height
"""
carriage = robot._actuators[mount]['carriage']
# Home both carriages, to prevent collisions and to ensure that the other
# mount doesn't block the one being moved (mount moves are primarily for
# changing pipettes, so we don't want the other pipette blocking access)
robot.poses = carriage.home(robot.poses)
other_mount = 'left' if mount == 'right' else 'right'
robot.poses = robot._actuators[other_mount]['carriage'].home(robot.poses)
robot.gantry.move(
robot.poses, x=point[0], y=point[1])
robot.poses = carriage.move(
robot.poses, z=point[2])
# These x and y values are hard to interpret because of some internals of
# pose tracker. It's mostly z that matters for this operation anyway
x, y, _ = tuple(
pose_tracker.absolute(
robot.poses, robot._actuators[mount]['carriage']))
_, _, z = tuple(
pose_tracker.absolute(
robot.poses, robot.gantry))
new_position = (x, y, z)
return "Move complete. New position: {}".format(new_position) | python | def _move_mount(robot, mount, point):
"""
The carriage moves the mount in the Z axis, and the gantry moves in X and Y
Mount movements do not have the same protections calculated in to an
existing `move` command like Pipette does, so the safest thing is to home
the Z axis, then move in X and Y, then move down to the specified Z height
"""
carriage = robot._actuators[mount]['carriage']
# Home both carriages, to prevent collisions and to ensure that the other
# mount doesn't block the one being moved (mount moves are primarily for
# changing pipettes, so we don't want the other pipette blocking access)
robot.poses = carriage.home(robot.poses)
other_mount = 'left' if mount == 'right' else 'right'
robot.poses = robot._actuators[other_mount]['carriage'].home(robot.poses)
robot.gantry.move(
robot.poses, x=point[0], y=point[1])
robot.poses = carriage.move(
robot.poses, z=point[2])
# These x and y values are hard to interpret because of some internals of
# pose tracker. It's mostly z that matters for this operation anyway
x, y, _ = tuple(
pose_tracker.absolute(
robot.poses, robot._actuators[mount]['carriage']))
_, _, z = tuple(
pose_tracker.absolute(
robot.poses, robot.gantry))
new_position = (x, y, z)
return "Move complete. New position: {}".format(new_position) | [
"def",
"_move_mount",
"(",
"robot",
",",
"mount",
",",
"point",
")",
":",
"carriage",
"=",
"robot",
".",
"_actuators",
"[",
"mount",
"]",
"[",
"'carriage'",
"]",
"# Home both carriages, to prevent collisions and to ensure that the other",
"# mount doesn't block the one be... | The carriage moves the mount in the Z axis, and the gantry moves in X and Y
Mount movements do not have the same protections calculated in to an
existing `move` command like Pipette does, so the safest thing is to home
the Z axis, then move in X and Y, then move down to the specified Z height | [
"The",
"carriage",
"moves",
"the",
"mount",
"in",
"the",
"Z",
"axis",
"and",
"the",
"gantry",
"moves",
"in",
"X",
"and",
"Y"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/server/endpoints/control.py#L385-L416 | train | 198,123 |
Opentrons/opentrons | api/src/opentrons/server/endpoints/networking.py | _eap_check_config | def _eap_check_config(eap_config: Dict[str, Any]) -> Dict[str, Any]:
""" Check the eap specific args, and replace values where needed.
Similar to _check_configure_args but for only EAP.
"""
eap_type = eap_config.get('eapType')
for method in EAP_CONFIG_SHAPE['options']:
if method['name'] == eap_type:
options = method['options']
break
else:
raise ConfigureArgsError('EAP method {} is not valid'.format(eap_type))
_eap_check_no_extra_args(eap_config, options)
for opt in options: # type: ignore
# Ignoring most types to do with EAP_CONFIG_SHAPE because of issues
# wth type inference for dict comprehensions
_eap_check_option_ok(opt, eap_config)
if opt['type'] == 'file' and opt['name'] in eap_config:
# Special work for file: rewrite from key id to path
eap_config[opt['name']] = _get_key_file(eap_config[opt['name']])
return eap_config | python | def _eap_check_config(eap_config: Dict[str, Any]) -> Dict[str, Any]:
""" Check the eap specific args, and replace values where needed.
Similar to _check_configure_args but for only EAP.
"""
eap_type = eap_config.get('eapType')
for method in EAP_CONFIG_SHAPE['options']:
if method['name'] == eap_type:
options = method['options']
break
else:
raise ConfigureArgsError('EAP method {} is not valid'.format(eap_type))
_eap_check_no_extra_args(eap_config, options)
for opt in options: # type: ignore
# Ignoring most types to do with EAP_CONFIG_SHAPE because of issues
# wth type inference for dict comprehensions
_eap_check_option_ok(opt, eap_config)
if opt['type'] == 'file' and opt['name'] in eap_config:
# Special work for file: rewrite from key id to path
eap_config[opt['name']] = _get_key_file(eap_config[opt['name']])
return eap_config | [
"def",
"_eap_check_config",
"(",
"eap_config",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"eap_type",
"=",
"eap_config",
".",
"get",
"(",
"'eapType'",
")",
"for",
"method",
"in",
"EAP_CONFIG_SHAPE",
"... | Check the eap specific args, and replace values where needed.
Similar to _check_configure_args but for only EAP. | [
"Check",
"the",
"eap",
"specific",
"args",
"and",
"replace",
"values",
"where",
"needed",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/server/endpoints/networking.py#L130-L152 | train | 198,124 |
Opentrons/opentrons | api/src/opentrons/server/endpoints/networking.py | _deduce_security | def _deduce_security(kwargs) -> nmcli.SECURITY_TYPES:
""" Make sure that the security_type is known, or throw. """
# Security should be one of our valid strings
sec_translation = {
'wpa-psk': nmcli.SECURITY_TYPES.WPA_PSK,
'none': nmcli.SECURITY_TYPES.NONE,
'wpa-eap': nmcli.SECURITY_TYPES.WPA_EAP,
}
if not kwargs.get('securityType'):
if kwargs.get('psk') and kwargs.get('eapConfig'):
raise ConfigureArgsError(
'Cannot deduce security type: psk and eap both passed')
elif kwargs.get('psk'):
kwargs['securityType'] = 'wpa-psk'
elif kwargs.get('eapConfig'):
kwargs['securityType'] = 'wpa-eap'
else:
kwargs['securityType'] = 'none'
try:
return sec_translation[kwargs['securityType']]
except KeyError:
raise ConfigureArgsError('securityType must be one of {}'
.format(','.join(sec_translation.keys()))) | python | def _deduce_security(kwargs) -> nmcli.SECURITY_TYPES:
""" Make sure that the security_type is known, or throw. """
# Security should be one of our valid strings
sec_translation = {
'wpa-psk': nmcli.SECURITY_TYPES.WPA_PSK,
'none': nmcli.SECURITY_TYPES.NONE,
'wpa-eap': nmcli.SECURITY_TYPES.WPA_EAP,
}
if not kwargs.get('securityType'):
if kwargs.get('psk') and kwargs.get('eapConfig'):
raise ConfigureArgsError(
'Cannot deduce security type: psk and eap both passed')
elif kwargs.get('psk'):
kwargs['securityType'] = 'wpa-psk'
elif kwargs.get('eapConfig'):
kwargs['securityType'] = 'wpa-eap'
else:
kwargs['securityType'] = 'none'
try:
return sec_translation[kwargs['securityType']]
except KeyError:
raise ConfigureArgsError('securityType must be one of {}'
.format(','.join(sec_translation.keys()))) | [
"def",
"_deduce_security",
"(",
"kwargs",
")",
"->",
"nmcli",
".",
"SECURITY_TYPES",
":",
"# Security should be one of our valid strings",
"sec_translation",
"=",
"{",
"'wpa-psk'",
":",
"nmcli",
".",
"SECURITY_TYPES",
".",
"WPA_PSK",
",",
"'none'",
":",
"nmcli",
"."... | Make sure that the security_type is known, or throw. | [
"Make",
"sure",
"that",
"the",
"security_type",
"is",
"known",
"or",
"throw",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/server/endpoints/networking.py#L155-L177 | train | 198,125 |
Opentrons/opentrons | api/src/opentrons/server/endpoints/networking.py | _check_configure_args | def _check_configure_args(configure_args: Dict[str, Any]) -> Dict[str, Any]:
""" Check the arguments passed to configure.
Raises an exception on failure. On success, returns a dict of
configure_args with any necessary mutations.
"""
# SSID must always be present
if not configure_args.get('ssid')\
or not isinstance(configure_args['ssid'], str):
raise ConfigureArgsError("SSID must be specified")
# If specified, hidden must be a bool
if not configure_args.get('hidden'):
configure_args['hidden'] = False
elif not isinstance(configure_args['hidden'], bool):
raise ConfigureArgsError('If specified, hidden must be a bool')
configure_args['securityType'] = _deduce_security(configure_args)
# If we have wpa2-personal, we need a psk
if configure_args['securityType'] == nmcli.SECURITY_TYPES.WPA_PSK:
if not configure_args.get('psk'):
raise ConfigureArgsError(
'If securityType is wpa-psk, psk must be specified')
return configure_args
# If we have wpa2-enterprise, we need eap config, and we need to check
# it
if configure_args['securityType'] == nmcli.SECURITY_TYPES.WPA_EAP:
if not configure_args.get('eapConfig'):
raise ConfigureArgsError(
'If securityType is wpa-eap, eapConfig must be specified')
configure_args['eapConfig']\
= _eap_check_config(configure_args['eapConfig'])
return configure_args
# If we’re still here we have no security and we’re done
return configure_args | python | def _check_configure_args(configure_args: Dict[str, Any]) -> Dict[str, Any]:
""" Check the arguments passed to configure.
Raises an exception on failure. On success, returns a dict of
configure_args with any necessary mutations.
"""
# SSID must always be present
if not configure_args.get('ssid')\
or not isinstance(configure_args['ssid'], str):
raise ConfigureArgsError("SSID must be specified")
# If specified, hidden must be a bool
if not configure_args.get('hidden'):
configure_args['hidden'] = False
elif not isinstance(configure_args['hidden'], bool):
raise ConfigureArgsError('If specified, hidden must be a bool')
configure_args['securityType'] = _deduce_security(configure_args)
# If we have wpa2-personal, we need a psk
if configure_args['securityType'] == nmcli.SECURITY_TYPES.WPA_PSK:
if not configure_args.get('psk'):
raise ConfigureArgsError(
'If securityType is wpa-psk, psk must be specified')
return configure_args
# If we have wpa2-enterprise, we need eap config, and we need to check
# it
if configure_args['securityType'] == nmcli.SECURITY_TYPES.WPA_EAP:
if not configure_args.get('eapConfig'):
raise ConfigureArgsError(
'If securityType is wpa-eap, eapConfig must be specified')
configure_args['eapConfig']\
= _eap_check_config(configure_args['eapConfig'])
return configure_args
# If we’re still here we have no security and we’re done
return configure_args | [
"def",
"_check_configure_args",
"(",
"configure_args",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"# SSID must always be present",
"if",
"not",
"configure_args",
".",
"get",
"(",
"'ssid'",
")",
"or",
"not... | Check the arguments passed to configure.
Raises an exception on failure. On success, returns a dict of
configure_args with any necessary mutations. | [
"Check",
"the",
"arguments",
"passed",
"to",
"configure",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/server/endpoints/networking.py#L180-L216 | train | 198,126 |
Opentrons/opentrons | api/src/opentrons/server/endpoints/networking.py | status | async def status(request: web.Request) -> web.Response:
"""
Get request will return the status of the machine's connection to the
internet as well as the status of its network interfaces.
The body of the response is a json dict containing
'status': internet connectivity status, where the options are:
"none" - no connection to router or network
"portal" - device behind a captive portal and cannot reach full internet
"limited" - connection to router but not internet
"full" - connection to router and internet
"unknown" - an exception occured while trying to determine status
'interfaces': JSON object of networking interfaces, keyed by device name,
where the value of each entry is another object with the keys:
- 'type': "ethernet" or "wifi"
- 'state': state string, e.g. "disconnected", "connecting", "connected"
- 'ipAddress': the ip address, if it exists (null otherwise); this also
contains the subnet mask in CIDR notation, e.g. 10.2.12.120/16
- 'macAddress': the MAC address of the interface device
- 'gatewayAddress': the address of the current gateway, if it exists
(null otherwise)
Example request:
```
GET /networking/status
```
Example response:
```
200 OK
{
"status": "full",
"interfaces": {
"wlan0": {
"ipAddress": "192.168.43.97/24",
"macAddress": "B8:27:EB:6C:95:CF",
"gatewayAddress": "192.168.43.161",
"state": "connected",
"type": "wifi"
},
"eth0": {
"ipAddress": "169.254.229.173/16",
"macAddress": "B8:27:EB:39:C0:9A",
"gatewayAddress": null,
"state": "connected",
"type": "ethernet"
}
}
}
```
"""
connectivity = {'status': 'none', 'interfaces': {}}
try:
connectivity['status'] = await nmcli.is_connected()
connectivity['interfaces'] = {
i.value: await nmcli.iface_info(i) for i in nmcli.NETWORK_IFACES
}
log.debug("Connectivity: {}".format(connectivity['status']))
log.debug("Interfaces: {}".format(connectivity['interfaces']))
status = 200
except subprocess.CalledProcessError as e:
log.error("CalledProcessError: {}".format(e.stdout))
status = 500
except FileNotFoundError as e:
log.error("FileNotFoundError: {}".format(e))
status = 500
return web.json_response(connectivity, status=status) | python | async def status(request: web.Request) -> web.Response:
"""
Get request will return the status of the machine's connection to the
internet as well as the status of its network interfaces.
The body of the response is a json dict containing
'status': internet connectivity status, where the options are:
"none" - no connection to router or network
"portal" - device behind a captive portal and cannot reach full internet
"limited" - connection to router but not internet
"full" - connection to router and internet
"unknown" - an exception occured while trying to determine status
'interfaces': JSON object of networking interfaces, keyed by device name,
where the value of each entry is another object with the keys:
- 'type': "ethernet" or "wifi"
- 'state': state string, e.g. "disconnected", "connecting", "connected"
- 'ipAddress': the ip address, if it exists (null otherwise); this also
contains the subnet mask in CIDR notation, e.g. 10.2.12.120/16
- 'macAddress': the MAC address of the interface device
- 'gatewayAddress': the address of the current gateway, if it exists
(null otherwise)
Example request:
```
GET /networking/status
```
Example response:
```
200 OK
{
"status": "full",
"interfaces": {
"wlan0": {
"ipAddress": "192.168.43.97/24",
"macAddress": "B8:27:EB:6C:95:CF",
"gatewayAddress": "192.168.43.161",
"state": "connected",
"type": "wifi"
},
"eth0": {
"ipAddress": "169.254.229.173/16",
"macAddress": "B8:27:EB:39:C0:9A",
"gatewayAddress": null,
"state": "connected",
"type": "ethernet"
}
}
}
```
"""
connectivity = {'status': 'none', 'interfaces': {}}
try:
connectivity['status'] = await nmcli.is_connected()
connectivity['interfaces'] = {
i.value: await nmcli.iface_info(i) for i in nmcli.NETWORK_IFACES
}
log.debug("Connectivity: {}".format(connectivity['status']))
log.debug("Interfaces: {}".format(connectivity['interfaces']))
status = 200
except subprocess.CalledProcessError as e:
log.error("CalledProcessError: {}".format(e.stdout))
status = 500
except FileNotFoundError as e:
log.error("FileNotFoundError: {}".format(e))
status = 500
return web.json_response(connectivity, status=status) | [
"async",
"def",
"status",
"(",
"request",
":",
"web",
".",
"Request",
")",
"->",
"web",
".",
"Response",
":",
"connectivity",
"=",
"{",
"'status'",
":",
"'none'",
",",
"'interfaces'",
":",
"{",
"}",
"}",
"try",
":",
"connectivity",
"[",
"'status'",
"]"... | Get request will return the status of the machine's connection to the
internet as well as the status of its network interfaces.
The body of the response is a json dict containing
'status': internet connectivity status, where the options are:
"none" - no connection to router or network
"portal" - device behind a captive portal and cannot reach full internet
"limited" - connection to router but not internet
"full" - connection to router and internet
"unknown" - an exception occured while trying to determine status
'interfaces': JSON object of networking interfaces, keyed by device name,
where the value of each entry is another object with the keys:
- 'type': "ethernet" or "wifi"
- 'state': state string, e.g. "disconnected", "connecting", "connected"
- 'ipAddress': the ip address, if it exists (null otherwise); this also
contains the subnet mask in CIDR notation, e.g. 10.2.12.120/16
- 'macAddress': the MAC address of the interface device
- 'gatewayAddress': the address of the current gateway, if it exists
(null otherwise)
Example request:
```
GET /networking/status
```
Example response:
```
200 OK
{
"status": "full",
"interfaces": {
"wlan0": {
"ipAddress": "192.168.43.97/24",
"macAddress": "B8:27:EB:6C:95:CF",
"gatewayAddress": "192.168.43.161",
"state": "connected",
"type": "wifi"
},
"eth0": {
"ipAddress": "169.254.229.173/16",
"macAddress": "B8:27:EB:39:C0:9A",
"gatewayAddress": null,
"state": "connected",
"type": "ethernet"
}
}
}
``` | [
"Get",
"request",
"will",
"return",
"the",
"status",
"of",
"the",
"machine",
"s",
"connection",
"to",
"the",
"internet",
"as",
"well",
"as",
"the",
"status",
"of",
"its",
"network",
"interfaces",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/server/endpoints/networking.py#L277-L346 | train | 198,127 |
Opentrons/opentrons | api/src/opentrons/server/endpoints/networking.py | list_keys | async def list_keys(request: web.Request) -> web.Response:
""" List the key files installed in the system.
This responds with a list of the same objects as key:
```
GET /wifi/keys -> 200 OK
{ keys: [
{
uri: '/wifi/keys/some-hex-digest',
id: 'some-hex-digest',
name: 'keyfile.pem'
},
...
]
}
```
"""
keys_dir = CONFIG['wifi_keys_dir']
keys: List[Dict[str, str]] = []
# TODO(mc, 2018-10-24): add last modified info to keys for sort purposes
for path in os.listdir(keys_dir):
full_path = os.path.join(keys_dir, path)
if os.path.isdir(full_path):
in_path = os.listdir(full_path)
if len(in_path) > 1:
log.warning("Garbage in key dir for key {}".format(path))
keys.append(
{'uri': '/wifi/keys/{}'.format(path),
'id': path,
'name': os.path.basename(in_path[0])})
else:
log.warning("Garbage in wifi keys dir: {}".format(full_path))
return web.json_response({'keys': keys}, status=200) | python | async def list_keys(request: web.Request) -> web.Response:
""" List the key files installed in the system.
This responds with a list of the same objects as key:
```
GET /wifi/keys -> 200 OK
{ keys: [
{
uri: '/wifi/keys/some-hex-digest',
id: 'some-hex-digest',
name: 'keyfile.pem'
},
...
]
}
```
"""
keys_dir = CONFIG['wifi_keys_dir']
keys: List[Dict[str, str]] = []
# TODO(mc, 2018-10-24): add last modified info to keys for sort purposes
for path in os.listdir(keys_dir):
full_path = os.path.join(keys_dir, path)
if os.path.isdir(full_path):
in_path = os.listdir(full_path)
if len(in_path) > 1:
log.warning("Garbage in key dir for key {}".format(path))
keys.append(
{'uri': '/wifi/keys/{}'.format(path),
'id': path,
'name': os.path.basename(in_path[0])})
else:
log.warning("Garbage in wifi keys dir: {}".format(full_path))
return web.json_response({'keys': keys}, status=200) | [
"async",
"def",
"list_keys",
"(",
"request",
":",
"web",
".",
"Request",
")",
"->",
"web",
".",
"Response",
":",
"keys_dir",
"=",
"CONFIG",
"[",
"'wifi_keys_dir'",
"]",
"keys",
":",
"List",
"[",
"Dict",
"[",
"str",
",",
"str",
"]",
"]",
"=",
"[",
"... | List the key files installed in the system.
This responds with a list of the same objects as key:
```
GET /wifi/keys -> 200 OK
{ keys: [
{
uri: '/wifi/keys/some-hex-digest',
id: 'some-hex-digest',
name: 'keyfile.pem'
},
...
]
}
``` | [
"List",
"the",
"key",
"files",
"installed",
"in",
"the",
"system",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/server/endpoints/networking.py#L418-L451 | train | 198,128 |
Opentrons/opentrons | api/src/opentrons/server/endpoints/networking.py | remove_key | async def remove_key(request: web.Request) -> web.Response:
""" Remove a key.
```
DELETE /wifi/keys/:id
-> 200 OK
{message: 'Removed key keyfile.pem'}
```
"""
keys_dir = CONFIG['wifi_keys_dir']
available_keys = os.listdir(keys_dir)
requested_hash = request.match_info['key_uuid']
if requested_hash not in available_keys:
return web.json_response(
{'message': 'No such key file {}'
.format(requested_hash)},
status=404)
key_path = os.path.join(keys_dir, requested_hash)
name = os.listdir(key_path)[0]
shutil.rmtree(key_path)
return web.json_response(
{'message': 'Key file {} deleted'.format(name)},
status=200) | python | async def remove_key(request: web.Request) -> web.Response:
""" Remove a key.
```
DELETE /wifi/keys/:id
-> 200 OK
{message: 'Removed key keyfile.pem'}
```
"""
keys_dir = CONFIG['wifi_keys_dir']
available_keys = os.listdir(keys_dir)
requested_hash = request.match_info['key_uuid']
if requested_hash not in available_keys:
return web.json_response(
{'message': 'No such key file {}'
.format(requested_hash)},
status=404)
key_path = os.path.join(keys_dir, requested_hash)
name = os.listdir(key_path)[0]
shutil.rmtree(key_path)
return web.json_response(
{'message': 'Key file {} deleted'.format(name)},
status=200) | [
"async",
"def",
"remove_key",
"(",
"request",
":",
"web",
".",
"Request",
")",
"->",
"web",
".",
"Response",
":",
"keys_dir",
"=",
"CONFIG",
"[",
"'wifi_keys_dir'",
"]",
"available_keys",
"=",
"os",
".",
"listdir",
"(",
"keys_dir",
")",
"requested_hash",
"... | Remove a key.
```
DELETE /wifi/keys/:id
-> 200 OK
{message: 'Removed key keyfile.pem'}
``` | [
"Remove",
"a",
"key",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/server/endpoints/networking.py#L454-L477 | train | 198,129 |
Opentrons/opentrons | api/src/opentrons/server/endpoints/networking.py | eap_options | async def eap_options(request: web.Request) -> web.Response:
""" Get request returns the available configuration options for WPA-EAP.
Because the options for connecting to WPA-EAP secured networks are quite
complex, to avoid duplicating logic this endpoint returns a json object
describing the structure of arguments and options for the eap_config arg to
/wifi/configure.
The object is shaped like this:
{
options: [ // Supported EAP methods and their options. One of these
// method names must be passed in the eapConfig dict
{
name: str // i.e. TTLS-EAPMSCHAPv2. Should be in the eapType
// key of eapConfig when sent to /configure.
options: [
{
name: str // i.e. "username"
displayName: str // i.e. "Username"
required: bool,
type: str
}
]
}
]
}
The ``type`` keys denote the semantic kind of the argument. Valid types
are:
password: This is some kind of password. It may be a psk for the network,
an Active Directory password, or the passphrase for a private key
string: A generic string; perhaps a username, or a subject-matches
domain name for server validation
file: A file that the user must provide. This should be the id of a
file previously uploaded via POST /wifi/keys.
Although the arguments are described hierarchically, they should be
specified in eap_config as a flat dict. For instance, a /configure
invocation for TTLS/EAP-TLS might look like
```
POST
{
ssid: "my-ssid",
securityType: "wpa-eap",
hidden: false,
eapConfig : {
eapType: "TTLS/EAP-TLS", // One of the method options
identity: "alice@example.com", // And then its arguments
anonymousIdentity: "anonymous@example.com",
password: "testing123",
caCert: "12d1f180f081b",
phase2CaCert: "12d1f180f081b",
phase2ClientCert: "009909fd9fa",
phase2PrivateKey: "081009fbcbc"
phase2PrivateKeyPassword: "testing321"
}
}
```
"""
return web.json_response(EAP_CONFIG_SHAPE, status=200) | python | async def eap_options(request: web.Request) -> web.Response:
""" Get request returns the available configuration options for WPA-EAP.
Because the options for connecting to WPA-EAP secured networks are quite
complex, to avoid duplicating logic this endpoint returns a json object
describing the structure of arguments and options for the eap_config arg to
/wifi/configure.
The object is shaped like this:
{
options: [ // Supported EAP methods and their options. One of these
// method names must be passed in the eapConfig dict
{
name: str // i.e. TTLS-EAPMSCHAPv2. Should be in the eapType
// key of eapConfig when sent to /configure.
options: [
{
name: str // i.e. "username"
displayName: str // i.e. "Username"
required: bool,
type: str
}
]
}
]
}
The ``type`` keys denote the semantic kind of the argument. Valid types
are:
password: This is some kind of password. It may be a psk for the network,
an Active Directory password, or the passphrase for a private key
string: A generic string; perhaps a username, or a subject-matches
domain name for server validation
file: A file that the user must provide. This should be the id of a
file previously uploaded via POST /wifi/keys.
Although the arguments are described hierarchically, they should be
specified in eap_config as a flat dict. For instance, a /configure
invocation for TTLS/EAP-TLS might look like
```
POST
{
ssid: "my-ssid",
securityType: "wpa-eap",
hidden: false,
eapConfig : {
eapType: "TTLS/EAP-TLS", // One of the method options
identity: "alice@example.com", // And then its arguments
anonymousIdentity: "anonymous@example.com",
password: "testing123",
caCert: "12d1f180f081b",
phase2CaCert: "12d1f180f081b",
phase2ClientCert: "009909fd9fa",
phase2PrivateKey: "081009fbcbc"
phase2PrivateKeyPassword: "testing321"
}
}
```
"""
return web.json_response(EAP_CONFIG_SHAPE, status=200) | [
"async",
"def",
"eap_options",
"(",
"request",
":",
"web",
".",
"Request",
")",
"->",
"web",
".",
"Response",
":",
"return",
"web",
".",
"json_response",
"(",
"EAP_CONFIG_SHAPE",
",",
"status",
"=",
"200",
")"
] | Get request returns the available configuration options for WPA-EAP.
Because the options for connecting to WPA-EAP secured networks are quite
complex, to avoid duplicating logic this endpoint returns a json object
describing the structure of arguments and options for the eap_config arg to
/wifi/configure.
The object is shaped like this:
{
options: [ // Supported EAP methods and their options. One of these
// method names must be passed in the eapConfig dict
{
name: str // i.e. TTLS-EAPMSCHAPv2. Should be in the eapType
// key of eapConfig when sent to /configure.
options: [
{
name: str // i.e. "username"
displayName: str // i.e. "Username"
required: bool,
type: str
}
]
}
]
}
The ``type`` keys denote the semantic kind of the argument. Valid types
are:
password: This is some kind of password. It may be a psk for the network,
an Active Directory password, or the passphrase for a private key
string: A generic string; perhaps a username, or a subject-matches
domain name for server validation
file: A file that the user must provide. This should be the id of a
file previously uploaded via POST /wifi/keys.
Although the arguments are described hierarchically, they should be
specified in eap_config as a flat dict. For instance, a /configure
invocation for TTLS/EAP-TLS might look like
```
POST
{
ssid: "my-ssid",
securityType: "wpa-eap",
hidden: false,
eapConfig : {
eapType: "TTLS/EAP-TLS", // One of the method options
identity: "alice@example.com", // And then its arguments
anonymousIdentity: "anonymous@example.com",
password: "testing123",
caCert: "12d1f180f081b",
phase2CaCert: "12d1f180f081b",
phase2ClientCert: "009909fd9fa",
phase2PrivateKey: "081009fbcbc"
phase2PrivateKeyPassword: "testing321"
}
}
``` | [
"Get",
"request",
"returns",
"the",
"available",
"configuration",
"options",
"for",
"WPA",
"-",
"EAP",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/server/endpoints/networking.py#L480-L544 | train | 198,130 |
Opentrons/opentrons | api/src/opentrons/commands/commands.py | do_publish | def do_publish(broker, cmd, f, when, res, meta, *args, **kwargs):
""" Implement the publish so it can be called outside the decorator """
publish_command = functools.partial(
broker.publish,
topic=command_types.COMMAND)
call_args = _get_args(f, args, kwargs)
if when == 'before':
broker.logger.info("{}: {}".format(
f.__qualname__,
{k: v for k, v in call_args.items() if str(k) != 'self'}))
command_args = dict(
zip(
reversed(inspect.getfullargspec(cmd).args),
reversed(inspect.getfullargspec(cmd).defaults
or [])))
# TODO (artyom, 20170927): we are doing this to be able to use
# the decorator in Instrument class methods, in which case
# self is effectively an instrument.
# To narrow the scope of this hack, we are checking if the
# command is expecting instrument first.
if 'instrument' in inspect.getfullargspec(cmd).args:
# We are also checking if call arguments have 'self' and
# don't have instruments specified, in which case
# instruments should take precedence.
if 'self' in call_args and 'instrument' not in call_args:
call_args['instrument'] = call_args['self']
command_args.update({
key: call_args[key]
for key in
(set(inspect.getfullargspec(cmd).args)
& call_args.keys())
})
if meta:
command_args['meta'] = meta
payload = cmd(**command_args)
message = {**payload, '$': when}
if when == 'after':
message['return'] = res
publish_command(
message={**payload, '$': when}) | python | def do_publish(broker, cmd, f, when, res, meta, *args, **kwargs):
""" Implement the publish so it can be called outside the decorator """
publish_command = functools.partial(
broker.publish,
topic=command_types.COMMAND)
call_args = _get_args(f, args, kwargs)
if when == 'before':
broker.logger.info("{}: {}".format(
f.__qualname__,
{k: v for k, v in call_args.items() if str(k) != 'self'}))
command_args = dict(
zip(
reversed(inspect.getfullargspec(cmd).args),
reversed(inspect.getfullargspec(cmd).defaults
or [])))
# TODO (artyom, 20170927): we are doing this to be able to use
# the decorator in Instrument class methods, in which case
# self is effectively an instrument.
# To narrow the scope of this hack, we are checking if the
# command is expecting instrument first.
if 'instrument' in inspect.getfullargspec(cmd).args:
# We are also checking if call arguments have 'self' and
# don't have instruments specified, in which case
# instruments should take precedence.
if 'self' in call_args and 'instrument' not in call_args:
call_args['instrument'] = call_args['self']
command_args.update({
key: call_args[key]
for key in
(set(inspect.getfullargspec(cmd).args)
& call_args.keys())
})
if meta:
command_args['meta'] = meta
payload = cmd(**command_args)
message = {**payload, '$': when}
if when == 'after':
message['return'] = res
publish_command(
message={**payload, '$': when}) | [
"def",
"do_publish",
"(",
"broker",
",",
"cmd",
",",
"f",
",",
"when",
",",
"res",
",",
"meta",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"publish_command",
"=",
"functools",
".",
"partial",
"(",
"broker",
".",
"publish",
",",
"topic",
"... | Implement the publish so it can be called outside the decorator | [
"Implement",
"the",
"publish",
"so",
"it",
"can",
"be",
"called",
"outside",
"the",
"decorator"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/commands/commands.py#L432-L476 | train | 198,131 |
Opentrons/opentrons | api/src/opentrons/deck_calibration/__init__.py | position | def position(axis, hardware, cp=None):
"""
Read position from driver into a tuple and map 3-rd value
to the axis of a pipette currently used
"""
if not ff.use_protocol_api_v2():
p = hardware._driver.position
return (p['X'], p['Y'], p[axis])
else:
p = hardware.gantry_position(axis, critical_point=cp)
return (p.x, p.y, p.z) | python | def position(axis, hardware, cp=None):
"""
Read position from driver into a tuple and map 3-rd value
to the axis of a pipette currently used
"""
if not ff.use_protocol_api_v2():
p = hardware._driver.position
return (p['X'], p['Y'], p[axis])
else:
p = hardware.gantry_position(axis, critical_point=cp)
return (p.x, p.y, p.z) | [
"def",
"position",
"(",
"axis",
",",
"hardware",
",",
"cp",
"=",
"None",
")",
":",
"if",
"not",
"ff",
".",
"use_protocol_api_v2",
"(",
")",
":",
"p",
"=",
"hardware",
".",
"_driver",
".",
"position",
"return",
"(",
"p",
"[",
"'X'",
"]",
",",
"p",
... | Read position from driver into a tuple and map 3-rd value
to the axis of a pipette currently used | [
"Read",
"position",
"from",
"driver",
"into",
"a",
"tuple",
"and",
"map",
"3",
"-",
"rd",
"value",
"to",
"the",
"axis",
"of",
"a",
"pipette",
"currently",
"used"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/deck_calibration/__init__.py#L66-L77 | train | 198,132 |
Opentrons/opentrons | update-server/otupdate/buildroot/name_management.py | setup_hostname | async def setup_hostname() -> str:
"""
Intended to be run when the server starts. Sets the machine hostname.
The machine hostname is set from the systemd-generated machine-id, which
changes at every boot.
Once the hostname is set, we restart avahi.
This is a separate task from establishing and changing the opentrons
machine name, which is UTF-8 and stored in /etc/machine-info as the
PRETTY_HOSTNAME and used in the avahi service name.
:returns: the hostname
"""
machine_id = open('/etc/machine-id').read().strip()
hostname = machine_id[:6]
with open('/etc/hostname', 'w') as ehn:
ehn.write(f'{hostname}\n')
# First, we run hostnamed which will set the transient hostname
# and loaded static hostname from the value we just wrote to
# /etc/hostname
LOG.debug("Setting hostname")
proc = await asyncio.create_subprocess_exec(
'hostname', '-F', '/etc/hostname',
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
stdout, stderr = await proc.communicate()
ret = proc.returncode
if ret != 0:
LOG.error(
f'Error starting hostname: {ret} '
f'stdout: {stdout} stderr: {stderr}')
raise RuntimeError("Couldn't run hostname")
# Then, with the hostname set, we can restart avahi
LOG.debug("Restarting avahi")
proc = await asyncio.create_subprocess_exec(
'systemctl', 'restart', 'avahi-daemon',
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
stdout, stderr = await proc.communicate()
ret = proc.returncode
if ret != 0:
LOG.error(
f'Error restarting avahi-daemon: {ret} '
f'stdout: {stdout} stderr: {stderr}')
raise RuntimeError("Error restarting avahi")
LOG.debug("Updated hostname and restarted avahi OK")
return hostname | python | async def setup_hostname() -> str:
"""
Intended to be run when the server starts. Sets the machine hostname.
The machine hostname is set from the systemd-generated machine-id, which
changes at every boot.
Once the hostname is set, we restart avahi.
This is a separate task from establishing and changing the opentrons
machine name, which is UTF-8 and stored in /etc/machine-info as the
PRETTY_HOSTNAME and used in the avahi service name.
:returns: the hostname
"""
machine_id = open('/etc/machine-id').read().strip()
hostname = machine_id[:6]
with open('/etc/hostname', 'w') as ehn:
ehn.write(f'{hostname}\n')
# First, we run hostnamed which will set the transient hostname
# and loaded static hostname from the value we just wrote to
# /etc/hostname
LOG.debug("Setting hostname")
proc = await asyncio.create_subprocess_exec(
'hostname', '-F', '/etc/hostname',
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
stdout, stderr = await proc.communicate()
ret = proc.returncode
if ret != 0:
LOG.error(
f'Error starting hostname: {ret} '
f'stdout: {stdout} stderr: {stderr}')
raise RuntimeError("Couldn't run hostname")
# Then, with the hostname set, we can restart avahi
LOG.debug("Restarting avahi")
proc = await asyncio.create_subprocess_exec(
'systemctl', 'restart', 'avahi-daemon',
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
stdout, stderr = await proc.communicate()
ret = proc.returncode
if ret != 0:
LOG.error(
f'Error restarting avahi-daemon: {ret} '
f'stdout: {stdout} stderr: {stderr}')
raise RuntimeError("Error restarting avahi")
LOG.debug("Updated hostname and restarted avahi OK")
return hostname | [
"async",
"def",
"setup_hostname",
"(",
")",
"->",
"str",
":",
"machine_id",
"=",
"open",
"(",
"'/etc/machine-id'",
")",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
"hostname",
"=",
"machine_id",
"[",
":",
"6",
"]",
"with",
"open",
"(",
"'/etc/hostna... | Intended to be run when the server starts. Sets the machine hostname.
The machine hostname is set from the systemd-generated machine-id, which
changes at every boot.
Once the hostname is set, we restart avahi.
This is a separate task from establishing and changing the opentrons
machine name, which is UTF-8 and stored in /etc/machine-info as the
PRETTY_HOSTNAME and used in the avahi service name.
:returns: the hostname | [
"Intended",
"to",
"be",
"run",
"when",
"the",
"server",
"starts",
".",
"Sets",
"the",
"machine",
"hostname",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/buildroot/name_management.py#L98-L146 | train | 198,133 |
Opentrons/opentrons | update-server/otupdate/buildroot/name_management.py | _update_pretty_hostname | def _update_pretty_hostname(new_val: str):
""" Write a new value for the pretty hostname.
:raises OSError: If the new value could not be written.
"""
try:
with open('/etc/machine-info') as emi:
contents = emi.read()
except OSError:
LOG.exception("Couldn't read /etc/machine-info")
contents = ''
new_contents = ''
for line in contents.split('\n'):
if not line.startswith('PRETTY_HOSTNAME'):
new_contents += f'{line}\n'
new_contents += f'PRETTY_HOSTNAME={new_val}\n'
with open('/etc/machine-info', 'w') as emi:
emi.write(new_contents) | python | def _update_pretty_hostname(new_val: str):
""" Write a new value for the pretty hostname.
:raises OSError: If the new value could not be written.
"""
try:
with open('/etc/machine-info') as emi:
contents = emi.read()
except OSError:
LOG.exception("Couldn't read /etc/machine-info")
contents = ''
new_contents = ''
for line in contents.split('\n'):
if not line.startswith('PRETTY_HOSTNAME'):
new_contents += f'{line}\n'
new_contents += f'PRETTY_HOSTNAME={new_val}\n'
with open('/etc/machine-info', 'w') as emi:
emi.write(new_contents) | [
"def",
"_update_pretty_hostname",
"(",
"new_val",
":",
"str",
")",
":",
"try",
":",
"with",
"open",
"(",
"'/etc/machine-info'",
")",
"as",
"emi",
":",
"contents",
"=",
"emi",
".",
"read",
"(",
")",
"except",
"OSError",
":",
"LOG",
".",
"exception",
"(",
... | Write a new value for the pretty hostname.
:raises OSError: If the new value could not be written. | [
"Write",
"a",
"new",
"value",
"for",
"the",
"pretty",
"hostname",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/buildroot/name_management.py#L149-L166 | train | 198,134 |
Opentrons/opentrons | update-server/otupdate/buildroot/name_management.py | get_name | def get_name(default: str = 'no name set'):
""" Get the currently-configured name of the machine """
try:
with open('/etc/machine-info') as emi:
contents = emi.read()
except OSError:
LOG.exception(
"Couldn't read /etc/machine-info")
contents = ''
for line in contents.split('\n'):
if line.startswith('PRETTY_HOSTNAME='):
return '='.join(line.split('=')[1:])
LOG.warning(f"No PRETTY_HOSTNAME in {contents}, defaulting to {default}")
try:
_update_pretty_hostname(default)
except OSError:
LOG.exception("Could not write new pretty hostname!")
return default | python | def get_name(default: str = 'no name set'):
""" Get the currently-configured name of the machine """
try:
with open('/etc/machine-info') as emi:
contents = emi.read()
except OSError:
LOG.exception(
"Couldn't read /etc/machine-info")
contents = ''
for line in contents.split('\n'):
if line.startswith('PRETTY_HOSTNAME='):
return '='.join(line.split('=')[1:])
LOG.warning(f"No PRETTY_HOSTNAME in {contents}, defaulting to {default}")
try:
_update_pretty_hostname(default)
except OSError:
LOG.exception("Could not write new pretty hostname!")
return default | [
"def",
"get_name",
"(",
"default",
":",
"str",
"=",
"'no name set'",
")",
":",
"try",
":",
"with",
"open",
"(",
"'/etc/machine-info'",
")",
"as",
"emi",
":",
"contents",
"=",
"emi",
".",
"read",
"(",
")",
"except",
"OSError",
":",
"LOG",
".",
"exceptio... | Get the currently-configured name of the machine | [
"Get",
"the",
"currently",
"-",
"configured",
"name",
"of",
"the",
"machine"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/buildroot/name_management.py#L169-L186 | train | 198,135 |
Opentrons/opentrons | update-server/otupdate/buildroot/name_management.py | set_name_endpoint | async def set_name_endpoint(request: web.Request) -> web.Response:
""" Set the name of the robot.
Request with POST /server/name {"name": new_name}
Responds with 200 OK {"hostname": new_name, "prettyname": pretty_name}
or 400 Bad Request
In general, the new pretty name will be the specified name. The true
hostname will be capped to 53 letters, and have any characters other than
ascii letters or dashes replaced with dashes to fit the requirements here
https://www.freedesktop.org/software/systemd/man/hostname.html#.
"""
def build_400(msg: str) -> web.Response:
return web.json_response(
data={'message': msg},
status=400)
body = await request.json()
if 'name' not in body or not isinstance(body['name'], str):
return build_400('Body has no "name" key with a string')
new_name = await set_name(body['name'])
request.app[DEVICE_NAME_VARNAME] = new_name
return web.json_response(data={'name': new_name},
status=200) | python | async def set_name_endpoint(request: web.Request) -> web.Response:
""" Set the name of the robot.
Request with POST /server/name {"name": new_name}
Responds with 200 OK {"hostname": new_name, "prettyname": pretty_name}
or 400 Bad Request
In general, the new pretty name will be the specified name. The true
hostname will be capped to 53 letters, and have any characters other than
ascii letters or dashes replaced with dashes to fit the requirements here
https://www.freedesktop.org/software/systemd/man/hostname.html#.
"""
def build_400(msg: str) -> web.Response:
return web.json_response(
data={'message': msg},
status=400)
body = await request.json()
if 'name' not in body or not isinstance(body['name'], str):
return build_400('Body has no "name" key with a string')
new_name = await set_name(body['name'])
request.app[DEVICE_NAME_VARNAME] = new_name
return web.json_response(data={'name': new_name},
status=200) | [
"async",
"def",
"set_name_endpoint",
"(",
"request",
":",
"web",
".",
"Request",
")",
"->",
"web",
".",
"Response",
":",
"def",
"build_400",
"(",
"msg",
":",
"str",
")",
"->",
"web",
".",
"Response",
":",
"return",
"web",
".",
"json_response",
"(",
"da... | Set the name of the robot.
Request with POST /server/name {"name": new_name}
Responds with 200 OK {"hostname": new_name, "prettyname": pretty_name}
or 400 Bad Request
In general, the new pretty name will be the specified name. The true
hostname will be capped to 53 letters, and have any characters other than
ascii letters or dashes replaced with dashes to fit the requirements here
https://www.freedesktop.org/software/systemd/man/hostname.html#. | [
"Set",
"the",
"name",
"of",
"the",
"robot",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/buildroot/name_management.py#L214-L240 | train | 198,136 |
Opentrons/opentrons | update-server/otupdate/buildroot/name_management.py | get_name_endpoint | async def get_name_endpoint(request: web.Request) -> web.Response:
""" Get the name of the robot.
This information is also accessible in /server/update/health, but this
endpoint provides symmetry with POST /server/name.
GET /server/name -> 200 OK, {'name': robot name}
"""
return web.json_response(
data={'name': request.app[DEVICE_NAME_VARNAME]},
status=200) | python | async def get_name_endpoint(request: web.Request) -> web.Response:
""" Get the name of the robot.
This information is also accessible in /server/update/health, but this
endpoint provides symmetry with POST /server/name.
GET /server/name -> 200 OK, {'name': robot name}
"""
return web.json_response(
data={'name': request.app[DEVICE_NAME_VARNAME]},
status=200) | [
"async",
"def",
"get_name_endpoint",
"(",
"request",
":",
"web",
".",
"Request",
")",
"->",
"web",
".",
"Response",
":",
"return",
"web",
".",
"json_response",
"(",
"data",
"=",
"{",
"'name'",
":",
"request",
".",
"app",
"[",
"DEVICE_NAME_VARNAME",
"]",
... | Get the name of the robot.
This information is also accessible in /server/update/health, but this
endpoint provides symmetry with POST /server/name.
GET /server/name -> 200 OK, {'name': robot name} | [
"Get",
"the",
"name",
"of",
"the",
"robot",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/buildroot/name_management.py#L243-L253 | train | 198,137 |
Opentrons/opentrons | api/src/opentrons/types.py | Location.move | def move(self, point: Point) -> 'Location':
"""
Alter the point stored in the location while preserving the labware.
This returns a new Location and does not alter the current one. It
should be used like
.. code-block:: python
>>> loc = Location(Point(1, 1, 1), 'Hi')
>>> new_loc = loc.move(Point(1, 1, 1))
>>> assert loc_2.point == Point(2, 2, 2) # True
>>> assert loc.point == Point(1, 1, 1) # True
"""
return self._replace(point=self.point + point) | python | def move(self, point: Point) -> 'Location':
"""
Alter the point stored in the location while preserving the labware.
This returns a new Location and does not alter the current one. It
should be used like
.. code-block:: python
>>> loc = Location(Point(1, 1, 1), 'Hi')
>>> new_loc = loc.move(Point(1, 1, 1))
>>> assert loc_2.point == Point(2, 2, 2) # True
>>> assert loc.point == Point(1, 1, 1) # True
"""
return self._replace(point=self.point + point) | [
"def",
"move",
"(",
"self",
",",
"point",
":",
"Point",
")",
"->",
"'Location'",
":",
"return",
"self",
".",
"_replace",
"(",
"point",
"=",
"self",
".",
"point",
"+",
"point",
")"
] | Alter the point stored in the location while preserving the labware.
This returns a new Location and does not alter the current one. It
should be used like
.. code-block:: python
>>> loc = Location(Point(1, 1, 1), 'Hi')
>>> new_loc = loc.move(Point(1, 1, 1))
>>> assert loc_2.point == Point(2, 2, 2) # True
>>> assert loc.point == Point(1, 1, 1) # True | [
"Alter",
"the",
"point",
"stored",
"in",
"the",
"location",
"while",
"preserving",
"the",
"labware",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/types.py#L70-L85 | train | 198,138 |
Opentrons/opentrons | api/src/opentrons/legacy_api/robot/robot.py | _load_weird_container | def _load_weird_container(container_name):
""" Load a container from persisted containers, whatever that is """
# First must populate "get persisted container" list
old_container_loading.load_all_containers_from_disk()
# Load container from old json file
container = old_container_loading.get_persisted_container(
container_name)
# Rotate coordinates to fit the new deck map
rotated_container = database_migration.rotate_container_for_alpha(
container)
# Save to the new database
database.save_new_container(rotated_container, container_name)
return container | python | def _load_weird_container(container_name):
""" Load a container from persisted containers, whatever that is """
# First must populate "get persisted container" list
old_container_loading.load_all_containers_from_disk()
# Load container from old json file
container = old_container_loading.get_persisted_container(
container_name)
# Rotate coordinates to fit the new deck map
rotated_container = database_migration.rotate_container_for_alpha(
container)
# Save to the new database
database.save_new_container(rotated_container, container_name)
return container | [
"def",
"_load_weird_container",
"(",
"container_name",
")",
":",
"# First must populate \"get persisted container\" list",
"old_container_loading",
".",
"load_all_containers_from_disk",
"(",
")",
"# Load container from old json file",
"container",
"=",
"old_container_loading",
".",
... | Load a container from persisted containers, whatever that is | [
"Load",
"a",
"container",
"from",
"persisted",
"containers",
"whatever",
"that",
"is"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/robot/robot.py#L32-L44 | train | 198,139 |
Opentrons/opentrons | api/src/opentrons/legacy_api/robot/robot.py | _setup_container | def _setup_container(container_name):
""" Try and find a container in a variety of methods """
for meth in (database.load_container,
load_new_labware,
_load_weird_container):
log.debug(
f"Trying to load container {container_name} via {meth.__name__}")
try:
container = meth(container_name)
if meth == _load_weird_container:
container.properties['type'] = container_name
log.info(f"Loaded {container_name} from {meth.__name__}")
break
except (ValueError, KeyError):
log.info(f"{container_name} not in {meth.__name__}")
else:
raise KeyError(f"Unknown labware {container_name}")
container_x, container_y, container_z = container._coordinates
# infer z from height
if container_z == 0 and 'height' in container[0].properties:
container_z = container[0].properties['height']
from opentrons.util.vector import Vector
container._coordinates = Vector(
container_x,
container_y,
container_z)
return container | python | def _setup_container(container_name):
""" Try and find a container in a variety of methods """
for meth in (database.load_container,
load_new_labware,
_load_weird_container):
log.debug(
f"Trying to load container {container_name} via {meth.__name__}")
try:
container = meth(container_name)
if meth == _load_weird_container:
container.properties['type'] = container_name
log.info(f"Loaded {container_name} from {meth.__name__}")
break
except (ValueError, KeyError):
log.info(f"{container_name} not in {meth.__name__}")
else:
raise KeyError(f"Unknown labware {container_name}")
container_x, container_y, container_z = container._coordinates
# infer z from height
if container_z == 0 and 'height' in container[0].properties:
container_z = container[0].properties['height']
from opentrons.util.vector import Vector
container._coordinates = Vector(
container_x,
container_y,
container_z)
return container | [
"def",
"_setup_container",
"(",
"container_name",
")",
":",
"for",
"meth",
"in",
"(",
"database",
".",
"load_container",
",",
"load_new_labware",
",",
"_load_weird_container",
")",
":",
"log",
".",
"debug",
"(",
"f\"Trying to load container {container_name} via {meth.__... | Try and find a container in a variety of methods | [
"Try",
"and",
"find",
"a",
"container",
"in",
"a",
"variety",
"of",
"methods"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/robot/robot.py#L47-L77 | train | 198,140 |
Opentrons/opentrons | api/src/opentrons/legacy_api/robot/robot.py | Robot.clear_tips | def clear_tips(self):
"""
If reset is called with a tip attached, the tip must be removed
before the poses and _instruments members are cleared. If the tip is
not removed, the effective length of the pipette remains increased by
the length of the tip, and subsequent `_add_tip` calls will increase
the length in addition to this. This should be fixed by changing pose
tracking to that it tracks the tip as a separate node rather than
adding and subtracting the tip length to the pipette length.
"""
for instrument in self._instruments.values():
if instrument.tip_attached:
instrument._remove_tip(instrument._tip_length) | python | def clear_tips(self):
"""
If reset is called with a tip attached, the tip must be removed
before the poses and _instruments members are cleared. If the tip is
not removed, the effective length of the pipette remains increased by
the length of the tip, and subsequent `_add_tip` calls will increase
the length in addition to this. This should be fixed by changing pose
tracking to that it tracks the tip as a separate node rather than
adding and subtracting the tip length to the pipette length.
"""
for instrument in self._instruments.values():
if instrument.tip_attached:
instrument._remove_tip(instrument._tip_length) | [
"def",
"clear_tips",
"(",
"self",
")",
":",
"for",
"instrument",
"in",
"self",
".",
"_instruments",
".",
"values",
"(",
")",
":",
"if",
"instrument",
".",
"tip_attached",
":",
"instrument",
".",
"_remove_tip",
"(",
"instrument",
".",
"_tip_length",
")"
] | If reset is called with a tip attached, the tip must be removed
before the poses and _instruments members are cleared. If the tip is
not removed, the effective length of the pipette remains increased by
the length of the tip, and subsequent `_add_tip` calls will increase
the length in addition to this. This should be fixed by changing pose
tracking to that it tracks the tip as a separate node rather than
adding and subtracting the tip length to the pipette length. | [
"If",
"reset",
"is",
"called",
"with",
"a",
"tip",
"attached",
"the",
"tip",
"must",
"be",
"removed",
"before",
"the",
"poses",
"and",
"_instruments",
"members",
"are",
"cleared",
".",
"If",
"the",
"tip",
"is",
"not",
"removed",
"the",
"effective",
"length... | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/robot/robot.py#L162-L174 | train | 198,141 |
Opentrons/opentrons | api/src/opentrons/legacy_api/robot/robot.py | Robot.identify | def identify(self, seconds):
"""
Identify a robot by flashing the light around the frame button for 10s
"""
from time import sleep
for i in range(seconds):
self.turn_off_button_light()
sleep(0.25)
self.turn_on_button_light()
sleep(0.25) | python | def identify(self, seconds):
"""
Identify a robot by flashing the light around the frame button for 10s
"""
from time import sleep
for i in range(seconds):
self.turn_off_button_light()
sleep(0.25)
self.turn_on_button_light()
sleep(0.25) | [
"def",
"identify",
"(",
"self",
",",
"seconds",
")",
":",
"from",
"time",
"import",
"sleep",
"for",
"i",
"in",
"range",
"(",
"seconds",
")",
":",
"self",
".",
"turn_off_button_light",
"(",
")",
"sleep",
"(",
"0.25",
")",
"self",
".",
"turn_on_button_ligh... | Identify a robot by flashing the light around the frame button for 10s | [
"Identify",
"a",
"robot",
"by",
"flashing",
"the",
"light",
"around",
"the",
"frame",
"button",
"for",
"10s"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/robot/robot.py#L308-L317 | train | 198,142 |
Opentrons/opentrons | api/src/opentrons/legacy_api/robot/robot.py | Robot.add_instrument | def add_instrument(self, mount, instrument):
"""
Adds instrument to a robot.
Parameters
----------
mount : str
Specifies which axis the instruments is attached to.
Valid options are "left" or "right".
instrument : Instrument
An instance of a :class:`Pipette` to attached to the axis.
Notes
-----
A canonical way to add to add a Pipette to a robot is:
::
from opentrons import instruments
m300 = instruments.P300_Multi(mount='left')
This will create a pipette and call :func:`add_instrument`
to attach the instrument.
"""
if mount in self._instruments:
prev_instr = self._instruments[mount]
raise RuntimeError('Instrument {0} already on {1} mount'.format(
prev_instr.name, mount))
self._instruments[mount] = instrument
instrument.instrument_actuator = self._actuators[mount]['plunger']
instrument.instrument_mover = self._actuators[mount]['carriage']
# instrument_offset is the distance found (with tip-probe) between
# the pipette's expected position, and the actual position
# this is expected to be no greater than ~3mm
# Z is not included, because Z offsets found during tip-probe are used
# to determined the tip's length
cx, cy, _ = self.config.instrument_offset[mount][instrument.type]
# model_offset is the expected position of the pipette, determined
# by designed dimensions of that model (eg: p10-multi vs p300-single)
mx, my, mz = instrument.model_offset
# combine each offset to get the pipette's position relative to gantry
_x, _y, _z = (
mx + cx,
my + cy,
mz
)
# if it's the left mount, apply the offset from right pipette
if mount == 'left':
_x, _y, _z = (
_x + self.config.mount_offset[0],
_y + self.config.mount_offset[1],
_z + self.config.mount_offset[2]
)
self.poses = pose_tracker.add(
self.poses,
instrument,
parent=mount,
point=(_x, _y, _z)
) | python | def add_instrument(self, mount, instrument):
"""
Adds instrument to a robot.
Parameters
----------
mount : str
Specifies which axis the instruments is attached to.
Valid options are "left" or "right".
instrument : Instrument
An instance of a :class:`Pipette` to attached to the axis.
Notes
-----
A canonical way to add to add a Pipette to a robot is:
::
from opentrons import instruments
m300 = instruments.P300_Multi(mount='left')
This will create a pipette and call :func:`add_instrument`
to attach the instrument.
"""
if mount in self._instruments:
prev_instr = self._instruments[mount]
raise RuntimeError('Instrument {0} already on {1} mount'.format(
prev_instr.name, mount))
self._instruments[mount] = instrument
instrument.instrument_actuator = self._actuators[mount]['plunger']
instrument.instrument_mover = self._actuators[mount]['carriage']
# instrument_offset is the distance found (with tip-probe) between
# the pipette's expected position, and the actual position
# this is expected to be no greater than ~3mm
# Z is not included, because Z offsets found during tip-probe are used
# to determined the tip's length
cx, cy, _ = self.config.instrument_offset[mount][instrument.type]
# model_offset is the expected position of the pipette, determined
# by designed dimensions of that model (eg: p10-multi vs p300-single)
mx, my, mz = instrument.model_offset
# combine each offset to get the pipette's position relative to gantry
_x, _y, _z = (
mx + cx,
my + cy,
mz
)
# if it's the left mount, apply the offset from right pipette
if mount == 'left':
_x, _y, _z = (
_x + self.config.mount_offset[0],
_y + self.config.mount_offset[1],
_z + self.config.mount_offset[2]
)
self.poses = pose_tracker.add(
self.poses,
instrument,
parent=mount,
point=(_x, _y, _z)
) | [
"def",
"add_instrument",
"(",
"self",
",",
"mount",
",",
"instrument",
")",
":",
"if",
"mount",
"in",
"self",
".",
"_instruments",
":",
"prev_instr",
"=",
"self",
".",
"_instruments",
"[",
"mount",
"]",
"raise",
"RuntimeError",
"(",
"'Instrument {0} already on... | Adds instrument to a robot.
Parameters
----------
mount : str
Specifies which axis the instruments is attached to.
Valid options are "left" or "right".
instrument : Instrument
An instance of a :class:`Pipette` to attached to the axis.
Notes
-----
A canonical way to add to add a Pipette to a robot is:
::
from opentrons import instruments
m300 = instruments.P300_Multi(mount='left')
This will create a pipette and call :func:`add_instrument`
to attach the instrument. | [
"Adds",
"instrument",
"to",
"a",
"robot",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/robot/robot.py#L359-L421 | train | 198,143 |
Opentrons/opentrons | api/src/opentrons/legacy_api/robot/robot.py | Robot.connect | def connect(self, port=None, options=None):
"""
Connects the robot to a serial port.
Parameters
----------
port : str
OS-specific port name or ``'Virtual Smoothie'``
options : dict
if :attr:`port` is set to ``'Virtual Smoothie'``, provide
the list of options to be passed to :func:`get_virtual_device`
Returns
-------
``True`` for success, ``False`` for failure.
Note
----
If you wish to connect to the robot without using the OT App, you will
need to use this function.
Examples
--------
>>> from opentrons import robot # doctest: +SKIP
>>> robot.connect() # doctest: +SKIP
"""
self._driver.connect(port=port)
self.fw_version = self._driver.get_fw_version()
# the below call to `cache_instrument_models` is relied upon by
# `Session._simulate()`, which calls `robot.connect()` after exec'ing a
# protocol. That protocol could very well have different pipettes than
# what are physically attached to the robot
self.cache_instrument_models() | python | def connect(self, port=None, options=None):
"""
Connects the robot to a serial port.
Parameters
----------
port : str
OS-specific port name or ``'Virtual Smoothie'``
options : dict
if :attr:`port` is set to ``'Virtual Smoothie'``, provide
the list of options to be passed to :func:`get_virtual_device`
Returns
-------
``True`` for success, ``False`` for failure.
Note
----
If you wish to connect to the robot without using the OT App, you will
need to use this function.
Examples
--------
>>> from opentrons import robot # doctest: +SKIP
>>> robot.connect() # doctest: +SKIP
"""
self._driver.connect(port=port)
self.fw_version = self._driver.get_fw_version()
# the below call to `cache_instrument_models` is relied upon by
# `Session._simulate()`, which calls `robot.connect()` after exec'ing a
# protocol. That protocol could very well have different pipettes than
# what are physically attached to the robot
self.cache_instrument_models() | [
"def",
"connect",
"(",
"self",
",",
"port",
"=",
"None",
",",
"options",
"=",
"None",
")",
":",
"self",
".",
"_driver",
".",
"connect",
"(",
"port",
"=",
"port",
")",
"self",
".",
"fw_version",
"=",
"self",
".",
"_driver",
".",
"get_fw_version",
"(",... | Connects the robot to a serial port.
Parameters
----------
port : str
OS-specific port name or ``'Virtual Smoothie'``
options : dict
if :attr:`port` is set to ``'Virtual Smoothie'``, provide
the list of options to be passed to :func:`get_virtual_device`
Returns
-------
``True`` for success, ``False`` for failure.
Note
----
If you wish to connect to the robot without using the OT App, you will
need to use this function.
Examples
--------
>>> from opentrons import robot # doctest: +SKIP
>>> robot.connect() # doctest: +SKIP | [
"Connects",
"the",
"robot",
"to",
"a",
"serial",
"port",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/robot/robot.py#L447-L482 | train | 198,144 |
Opentrons/opentrons | api/src/opentrons/legacy_api/robot/robot.py | Robot.home | def home(self, *args, **kwargs):
"""
Home robot's head and plunger motors.
"""
# Home gantry first to avoid colliding with labware
# and to make sure tips are not in the liquid while
# homing plungers. Z/A axis will automatically home before X/Y
self.poses = self.gantry.home(self.poses)
# Then plungers
self.poses = self._actuators['left']['plunger'].home(self.poses)
self.poses = self._actuators['right']['plunger'].home(self.poses)
# next move should not use any previously used instrument or labware
# to prevent robot.move_to() from using risky path optimization
self._previous_instrument = None
self._prev_container = None
# explicitly update carriage Mover positions in pose tree
# because their Mover.home() commands aren't used here
for a in self._actuators.values():
self.poses = a['carriage'].update_pose_from_driver(self.poses) | python | def home(self, *args, **kwargs):
"""
Home robot's head and plunger motors.
"""
# Home gantry first to avoid colliding with labware
# and to make sure tips are not in the liquid while
# homing plungers. Z/A axis will automatically home before X/Y
self.poses = self.gantry.home(self.poses)
# Then plungers
self.poses = self._actuators['left']['plunger'].home(self.poses)
self.poses = self._actuators['right']['plunger'].home(self.poses)
# next move should not use any previously used instrument or labware
# to prevent robot.move_to() from using risky path optimization
self._previous_instrument = None
self._prev_container = None
# explicitly update carriage Mover positions in pose tree
# because their Mover.home() commands aren't used here
for a in self._actuators.values():
self.poses = a['carriage'].update_pose_from_driver(self.poses) | [
"def",
"home",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Home gantry first to avoid colliding with labware",
"# and to make sure tips are not in the liquid while",
"# homing plungers. Z/A axis will automatically home before X/Y",
"self",
".",
"poses",
... | Home robot's head and plunger motors. | [
"Home",
"robot",
"s",
"head",
"and",
"plunger",
"motors",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/robot/robot.py#L490-L511 | train | 198,145 |
Opentrons/opentrons | api/src/opentrons/legacy_api/robot/robot.py | Robot.move_to | def move_to(
self,
location,
instrument,
strategy='arc',
**kwargs):
"""
Move an instrument to a coordinate, container or a coordinate within
a container.
Parameters
----------
location : one of the following:
1. :class:`Placeable` (i.e. Container, Deck, Slot, Well) — will
move to the origin of a container.
2. :class:`Vector` move to the given coordinate in Deck coordinate
system.
3. (:class:`Placeable`, :class:`Vector`) move to a given coordinate
within object's coordinate system.
instrument :
Instrument to move relative to. If ``None``, move relative to the
center of a gantry.
strategy : {'arc', 'direct'}
``arc`` : move to the point using arc trajectory
avoiding obstacles.
``direct`` : move to the point in a straight line.
"""
placeable, coordinates = containers.unpack_location(location)
# because the top position is what is tracked,
# this checks if coordinates doesn't equal top
offset = subtract(coordinates, placeable.top()[1])
if isinstance(placeable, containers.WellSeries):
placeable = placeable[0]
target = add(
pose_tracker.absolute(
self.poses,
placeable
),
offset.coordinates
)
if self._previous_instrument:
if self._previous_instrument != instrument:
self._previous_instrument.retract()
# because we're switching pipettes, this ensures a large (safe)
# Z arc height will be used for the new pipette
self._prev_container = None
self._previous_instrument = instrument
if strategy == 'arc':
arc_coords = self._create_arc(instrument, target, placeable)
for coord in arc_coords:
self.poses = instrument._move(
self.poses,
**coord)
elif strategy == 'direct':
position = {'x': target[0], 'y': target[1], 'z': target[2]}
self.poses = instrument._move(
self.poses,
**position)
else:
raise RuntimeError(
'Unknown move strategy: {}'.format(strategy)) | python | def move_to(
self,
location,
instrument,
strategy='arc',
**kwargs):
"""
Move an instrument to a coordinate, container or a coordinate within
a container.
Parameters
----------
location : one of the following:
1. :class:`Placeable` (i.e. Container, Deck, Slot, Well) — will
move to the origin of a container.
2. :class:`Vector` move to the given coordinate in Deck coordinate
system.
3. (:class:`Placeable`, :class:`Vector`) move to a given coordinate
within object's coordinate system.
instrument :
Instrument to move relative to. If ``None``, move relative to the
center of a gantry.
strategy : {'arc', 'direct'}
``arc`` : move to the point using arc trajectory
avoiding obstacles.
``direct`` : move to the point in a straight line.
"""
placeable, coordinates = containers.unpack_location(location)
# because the top position is what is tracked,
# this checks if coordinates doesn't equal top
offset = subtract(coordinates, placeable.top()[1])
if isinstance(placeable, containers.WellSeries):
placeable = placeable[0]
target = add(
pose_tracker.absolute(
self.poses,
placeable
),
offset.coordinates
)
if self._previous_instrument:
if self._previous_instrument != instrument:
self._previous_instrument.retract()
# because we're switching pipettes, this ensures a large (safe)
# Z arc height will be used for the new pipette
self._prev_container = None
self._previous_instrument = instrument
if strategy == 'arc':
arc_coords = self._create_arc(instrument, target, placeable)
for coord in arc_coords:
self.poses = instrument._move(
self.poses,
**coord)
elif strategy == 'direct':
position = {'x': target[0], 'y': target[1], 'z': target[2]}
self.poses = instrument._move(
self.poses,
**position)
else:
raise RuntimeError(
'Unknown move strategy: {}'.format(strategy)) | [
"def",
"move_to",
"(",
"self",
",",
"location",
",",
"instrument",
",",
"strategy",
"=",
"'arc'",
",",
"*",
"*",
"kwargs",
")",
":",
"placeable",
",",
"coordinates",
"=",
"containers",
".",
"unpack_location",
"(",
"location",
")",
"# because the top position i... | Move an instrument to a coordinate, container or a coordinate within
a container.
Parameters
----------
location : one of the following:
1. :class:`Placeable` (i.e. Container, Deck, Slot, Well) — will
move to the origin of a container.
2. :class:`Vector` move to the given coordinate in Deck coordinate
system.
3. (:class:`Placeable`, :class:`Vector`) move to a given coordinate
within object's coordinate system.
instrument :
Instrument to move relative to. If ``None``, move relative to the
center of a gantry.
strategy : {'arc', 'direct'}
``arc`` : move to the point using arc trajectory
avoiding obstacles.
``direct`` : move to the point in a straight line. | [
"Move",
"an",
"instrument",
"to",
"a",
"coordinate",
"container",
"or",
"a",
"coordinate",
"within",
"a",
"container",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/robot/robot.py#L552-L623 | train | 198,146 |
Opentrons/opentrons | api/src/opentrons/legacy_api/robot/robot.py | Robot._create_arc | def _create_arc(self, inst, destination, placeable=None):
"""
Returns a list of coordinates to arrive to the destination coordinate
"""
this_container = None
if isinstance(placeable, containers.Well):
this_container = placeable.get_parent()
elif isinstance(placeable, containers.WellSeries):
this_container = placeable.get_parent()
elif isinstance(placeable, containers.Container):
this_container = placeable
if this_container and self._prev_container == this_container:
# movements that stay within the same container do not need to
# avoid other containers on the deck, so the travel height of
# arced movements can be relative to just that one container
arc_top = self.max_placeable_height_on_deck(this_container)
arc_top += TIP_CLEARANCE_LABWARE
elif self._use_safest_height:
# bring the pipettes up as high as possible while calibrating
arc_top = inst._max_deck_height()
else:
# bring pipette up above the tallest container currently on deck
arc_top = self.max_deck_height() + TIP_CLEARANCE_DECK
self._prev_container = this_container
# if instrument is currently taller than arc_top, don't move down
_, _, pip_z = pose_tracker.absolute(self.poses, inst)
arc_top = max(arc_top, destination[2], pip_z)
arc_top = min(arc_top, inst._max_deck_height())
strategy = [
{'z': arc_top},
{'x': destination[0], 'y': destination[1]},
{'z': destination[2]}
]
return strategy | python | def _create_arc(self, inst, destination, placeable=None):
"""
Returns a list of coordinates to arrive to the destination coordinate
"""
this_container = None
if isinstance(placeable, containers.Well):
this_container = placeable.get_parent()
elif isinstance(placeable, containers.WellSeries):
this_container = placeable.get_parent()
elif isinstance(placeable, containers.Container):
this_container = placeable
if this_container and self._prev_container == this_container:
# movements that stay within the same container do not need to
# avoid other containers on the deck, so the travel height of
# arced movements can be relative to just that one container
arc_top = self.max_placeable_height_on_deck(this_container)
arc_top += TIP_CLEARANCE_LABWARE
elif self._use_safest_height:
# bring the pipettes up as high as possible while calibrating
arc_top = inst._max_deck_height()
else:
# bring pipette up above the tallest container currently on deck
arc_top = self.max_deck_height() + TIP_CLEARANCE_DECK
self._prev_container = this_container
# if instrument is currently taller than arc_top, don't move down
_, _, pip_z = pose_tracker.absolute(self.poses, inst)
arc_top = max(arc_top, destination[2], pip_z)
arc_top = min(arc_top, inst._max_deck_height())
strategy = [
{'z': arc_top},
{'x': destination[0], 'y': destination[1]},
{'z': destination[2]}
]
return strategy | [
"def",
"_create_arc",
"(",
"self",
",",
"inst",
",",
"destination",
",",
"placeable",
"=",
"None",
")",
":",
"this_container",
"=",
"None",
"if",
"isinstance",
"(",
"placeable",
",",
"containers",
".",
"Well",
")",
":",
"this_container",
"=",
"placeable",
... | Returns a list of coordinates to arrive to the destination coordinate | [
"Returns",
"a",
"list",
"of",
"coordinates",
"to",
"arrive",
"to",
"the",
"destination",
"coordinate"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/robot/robot.py#L625-L664 | train | 198,147 |
Opentrons/opentrons | api/src/opentrons/legacy_api/robot/robot.py | Robot.disconnect | def disconnect(self):
"""
Disconnects from the robot.
"""
if self._driver:
self._driver.disconnect()
self.axis_homed = {
'x': False, 'y': False, 'z': False, 'a': False, 'b': False} | python | def disconnect(self):
"""
Disconnects from the robot.
"""
if self._driver:
self._driver.disconnect()
self.axis_homed = {
'x': False, 'y': False, 'z': False, 'a': False, 'b': False} | [
"def",
"disconnect",
"(",
"self",
")",
":",
"if",
"self",
".",
"_driver",
":",
"self",
".",
"_driver",
".",
"disconnect",
"(",
")",
"self",
".",
"axis_homed",
"=",
"{",
"'x'",
":",
"False",
",",
"'y'",
":",
"False",
",",
"'z'",
":",
"False",
",",
... | Disconnects from the robot. | [
"Disconnects",
"from",
"the",
"robot",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/robot/robot.py#L666-L674 | train | 198,148 |
Opentrons/opentrons | api/src/opentrons/legacy_api/robot/robot.py | Robot.get_slot_offsets | def get_slot_offsets(self):
"""
col_offset
- from bottom left corner of 1 to bottom corner of 2
row_offset
- from bottom left corner of 1 to bottom corner of 4
TODO: figure out actual X and Y offsets (from origin)
"""
SLOT_OFFSETS = {
'slots': {
'col_offset': 132.50,
'row_offset': 90.5
}
}
slot_settings = SLOT_OFFSETS.get(self.get_deck_slot_types())
row_offset = slot_settings.get('row_offset')
col_offset = slot_settings.get('col_offset')
return (row_offset, col_offset) | python | def get_slot_offsets(self):
"""
col_offset
- from bottom left corner of 1 to bottom corner of 2
row_offset
- from bottom left corner of 1 to bottom corner of 4
TODO: figure out actual X and Y offsets (from origin)
"""
SLOT_OFFSETS = {
'slots': {
'col_offset': 132.50,
'row_offset': 90.5
}
}
slot_settings = SLOT_OFFSETS.get(self.get_deck_slot_types())
row_offset = slot_settings.get('row_offset')
col_offset = slot_settings.get('col_offset')
return (row_offset, col_offset) | [
"def",
"get_slot_offsets",
"(",
"self",
")",
":",
"SLOT_OFFSETS",
"=",
"{",
"'slots'",
":",
"{",
"'col_offset'",
":",
"132.50",
",",
"'row_offset'",
":",
"90.5",
"}",
"}",
"slot_settings",
"=",
"SLOT_OFFSETS",
".",
"get",
"(",
"self",
".",
"get_deck_slot_typ... | col_offset
- from bottom left corner of 1 to bottom corner of 2
row_offset
- from bottom left corner of 1 to bottom corner of 4
TODO: figure out actual X and Y offsets (from origin) | [
"col_offset",
"-",
"from",
"bottom",
"left",
"corner",
"of",
"1",
"to",
"bottom",
"corner",
"of",
"2"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/robot/robot.py#L679-L698 | train | 198,149 |
Opentrons/opentrons | api/src/opentrons/legacy_api/robot/robot.py | Robot.get_attached_pipettes | def get_attached_pipettes(self):
"""
Gets model names of attached pipettes
:return: :dict with keys 'left' and 'right' and a model string for each
mount, or 'uncommissioned' if no model string available
"""
left_data = {
'mount_axis': 'z',
'plunger_axis': 'b',
'model': self.model_by_mount['left']['model'],
'id': self.model_by_mount['left']['id']
}
left_model = left_data.get('model')
if left_model:
tip_length = pipette_config.load(
left_model, left_data['id']).tip_length
left_data.update({'tip_length': tip_length})
right_data = {
'mount_axis': 'a',
'plunger_axis': 'c',
'model': self.model_by_mount['right']['model'],
'id': self.model_by_mount['right']['id']
}
right_model = right_data.get('model')
if right_model:
tip_length = pipette_config.load(
right_model, right_data['id']).tip_length
right_data.update({'tip_length': tip_length})
return {
'left': left_data,
'right': right_data
} | python | def get_attached_pipettes(self):
"""
Gets model names of attached pipettes
:return: :dict with keys 'left' and 'right' and a model string for each
mount, or 'uncommissioned' if no model string available
"""
left_data = {
'mount_axis': 'z',
'plunger_axis': 'b',
'model': self.model_by_mount['left']['model'],
'id': self.model_by_mount['left']['id']
}
left_model = left_data.get('model')
if left_model:
tip_length = pipette_config.load(
left_model, left_data['id']).tip_length
left_data.update({'tip_length': tip_length})
right_data = {
'mount_axis': 'a',
'plunger_axis': 'c',
'model': self.model_by_mount['right']['model'],
'id': self.model_by_mount['right']['id']
}
right_model = right_data.get('model')
if right_model:
tip_length = pipette_config.load(
right_model, right_data['id']).tip_length
right_data.update({'tip_length': tip_length})
return {
'left': left_data,
'right': right_data
} | [
"def",
"get_attached_pipettes",
"(",
"self",
")",
":",
"left_data",
"=",
"{",
"'mount_axis'",
":",
"'z'",
",",
"'plunger_axis'",
":",
"'b'",
",",
"'model'",
":",
"self",
".",
"model_by_mount",
"[",
"'left'",
"]",
"[",
"'model'",
"]",
",",
"'id'",
":",
"s... | Gets model names of attached pipettes
:return: :dict with keys 'left' and 'right' and a model string for each
mount, or 'uncommissioned' if no model string available | [
"Gets",
"model",
"names",
"of",
"attached",
"pipettes"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/robot/robot.py#L850-L884 | train | 198,150 |
Opentrons/opentrons | api/src/opentrons/legacy_api/robot/robot.py | Robot.calibrate_container_with_instrument | def calibrate_container_with_instrument(self,
container: Container,
instrument,
save: bool
):
'''Calibrates a container using the bottom of the first well'''
well = container[0]
# Get the relative position of well with respect to instrument
delta = pose_tracker.change_base(
self.poses,
src=instrument,
dst=well
)
if fflags.calibrate_to_bottom():
delta_x = delta[0]
delta_y = delta[1]
if 'tiprack' in container.get_type():
delta_z = delta[2]
else:
delta_z = delta[2] + well.z_size()
else:
delta_x = delta[0]
delta_y = delta[1]
delta_z = delta[2]
self.poses = self._calibrate_container_with_delta(
self.poses,
container,
delta_x,
delta_y,
delta_z,
save
)
self.max_deck_height.cache_clear() | python | def calibrate_container_with_instrument(self,
container: Container,
instrument,
save: bool
):
'''Calibrates a container using the bottom of the first well'''
well = container[0]
# Get the relative position of well with respect to instrument
delta = pose_tracker.change_base(
self.poses,
src=instrument,
dst=well
)
if fflags.calibrate_to_bottom():
delta_x = delta[0]
delta_y = delta[1]
if 'tiprack' in container.get_type():
delta_z = delta[2]
else:
delta_z = delta[2] + well.z_size()
else:
delta_x = delta[0]
delta_y = delta[1]
delta_z = delta[2]
self.poses = self._calibrate_container_with_delta(
self.poses,
container,
delta_x,
delta_y,
delta_z,
save
)
self.max_deck_height.cache_clear() | [
"def",
"calibrate_container_with_instrument",
"(",
"self",
",",
"container",
":",
"Container",
",",
"instrument",
",",
"save",
":",
"bool",
")",
":",
"well",
"=",
"container",
"[",
"0",
"]",
"# Get the relative position of well with respect to instrument",
"delta",
"=... | Calibrates a container using the bottom of the first well | [
"Calibrates",
"a",
"container",
"using",
"the",
"bottom",
"of",
"the",
"first",
"well"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/robot/robot.py#L928-L965 | train | 198,151 |
Opentrons/opentrons | update-server/otupdate/buildroot/update.py | _begin_write | def _begin_write(session: UpdateSession,
loop: asyncio.AbstractEventLoop,
rootfs_file_path: str):
""" Start the write process. """
session.set_progress(0)
session.set_stage(Stages.WRITING)
write_future = asyncio.ensure_future(loop.run_in_executor(
None, file_actions.write_update, rootfs_file_path,
session.set_progress))
def write_done(fut):
exc = fut.exception()
if exc:
session.set_error(getattr(exc, 'short', str(type(exc))),
str(exc))
else:
session.set_stage(Stages.DONE)
write_future.add_done_callback(write_done) | python | def _begin_write(session: UpdateSession,
loop: asyncio.AbstractEventLoop,
rootfs_file_path: str):
""" Start the write process. """
session.set_progress(0)
session.set_stage(Stages.WRITING)
write_future = asyncio.ensure_future(loop.run_in_executor(
None, file_actions.write_update, rootfs_file_path,
session.set_progress))
def write_done(fut):
exc = fut.exception()
if exc:
session.set_error(getattr(exc, 'short', str(type(exc))),
str(exc))
else:
session.set_stage(Stages.DONE)
write_future.add_done_callback(write_done) | [
"def",
"_begin_write",
"(",
"session",
":",
"UpdateSession",
",",
"loop",
":",
"asyncio",
".",
"AbstractEventLoop",
",",
"rootfs_file_path",
":",
"str",
")",
":",
"session",
".",
"set_progress",
"(",
"0",
")",
"session",
".",
"set_stage",
"(",
"Stages",
".",... | Start the write process. | [
"Start",
"the",
"write",
"process",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/buildroot/update.py#L86-L104 | train | 198,152 |
Opentrons/opentrons | api/src/opentrons/legacy_api/modules/magdeck.py | MagDeck.calibrate | def calibrate(self):
'''
Calibration involves probing for top plate to get the plate height
'''
if self._driver and self._driver.is_connected():
self._driver.probe_plate()
# return if successful or not?
self._engaged = False | python | def calibrate(self):
'''
Calibration involves probing for top plate to get the plate height
'''
if self._driver and self._driver.is_connected():
self._driver.probe_plate()
# return if successful or not?
self._engaged = False | [
"def",
"calibrate",
"(",
"self",
")",
":",
"if",
"self",
".",
"_driver",
"and",
"self",
".",
"_driver",
".",
"is_connected",
"(",
")",
":",
"self",
".",
"_driver",
".",
"probe_plate",
"(",
")",
"# return if successful or not?",
"self",
".",
"_engaged",
"="... | Calibration involves probing for top plate to get the plate height | [
"Calibration",
"involves",
"probing",
"for",
"top",
"plate",
"to",
"get",
"the",
"plate",
"height"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/modules/magdeck.py#L28-L35 | train | 198,153 |
Opentrons/opentrons | api/src/opentrons/legacy_api/modules/magdeck.py | MagDeck.disengage | def disengage(self):
'''
Home the magnet
'''
if self._driver and self._driver.is_connected():
self._driver.home()
self._engaged = False | python | def disengage(self):
'''
Home the magnet
'''
if self._driver and self._driver.is_connected():
self._driver.home()
self._engaged = False | [
"def",
"disengage",
"(",
"self",
")",
":",
"if",
"self",
".",
"_driver",
"and",
"self",
".",
"_driver",
".",
"is_connected",
"(",
")",
":",
"self",
".",
"_driver",
".",
"home",
"(",
")",
"self",
".",
"_engaged",
"=",
"False"
] | Home the magnet | [
"Home",
"the",
"magnet"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/modules/magdeck.py#L68-L74 | train | 198,154 |
Opentrons/opentrons | api/src/opentrons/legacy_api/modules/magdeck.py | MagDeck.connect | def connect(self):
'''
Connect to the serial port
'''
if self._port:
self._driver = MagDeckDriver()
self._driver.connect(self._port)
self._device_info = self._driver.get_device_info()
else:
# Sanity check: Should never happen, because connect should
# never be called without a port on Module
raise MissingDevicePortError(
"MagDeck couldnt connect to port {}".format(self._port)
) | python | def connect(self):
'''
Connect to the serial port
'''
if self._port:
self._driver = MagDeckDriver()
self._driver.connect(self._port)
self._device_info = self._driver.get_device_info()
else:
# Sanity check: Should never happen, because connect should
# never be called without a port on Module
raise MissingDevicePortError(
"MagDeck couldnt connect to port {}".format(self._port)
) | [
"def",
"connect",
"(",
"self",
")",
":",
"if",
"self",
".",
"_port",
":",
"self",
".",
"_driver",
"=",
"MagDeckDriver",
"(",
")",
"self",
".",
"_driver",
".",
"connect",
"(",
"self",
".",
"_port",
")",
"self",
".",
"_device_info",
"=",
"self",
".",
... | Connect to the serial port | [
"Connect",
"to",
"the",
"serial",
"port"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/modules/magdeck.py#L125-L138 | train | 198,155 |
Opentrons/opentrons | api/src/opentrons/__init__.py | reset_globals | def reset_globals(version=None, loop=None):
""" Reinitialize the global singletons with a given API version.
:param version: 1 or 2. If `None`, pulled from the `useProtocolApiV2`
advanced setting.
"""
global containers
global instruments
global labware
global robot
global reset
global modules
global hardware
robot, reset, instruments, containers, labware, modules, hardware\
= build_globals(version, loop) | python | def reset_globals(version=None, loop=None):
""" Reinitialize the global singletons with a given API version.
:param version: 1 or 2. If `None`, pulled from the `useProtocolApiV2`
advanced setting.
"""
global containers
global instruments
global labware
global robot
global reset
global modules
global hardware
robot, reset, instruments, containers, labware, modules, hardware\
= build_globals(version, loop) | [
"def",
"reset_globals",
"(",
"version",
"=",
"None",
",",
"loop",
"=",
"None",
")",
":",
"global",
"containers",
"global",
"instruments",
"global",
"labware",
"global",
"robot",
"global",
"reset",
"global",
"modules",
"global",
"hardware",
"robot",
",",
"reset... | Reinitialize the global singletons with a given API version.
:param version: 1 or 2. If `None`, pulled from the `useProtocolApiV2`
advanced setting. | [
"Reinitialize",
"the",
"global",
"singletons",
"with",
"a",
"given",
"API",
"version",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/__init__.py#L58-L73 | train | 198,156 |
Opentrons/opentrons | api/src/opentrons/protocol_api/execute.py | _find_protocol_error | def _find_protocol_error(tb, proto_name):
"""Return the FrameInfo for the lowest frame in the traceback from the
protocol.
"""
tb_info = traceback.extract_tb(tb)
for frame in reversed(tb_info):
if frame.filename == proto_name:
return frame
else:
raise KeyError | python | def _find_protocol_error(tb, proto_name):
"""Return the FrameInfo for the lowest frame in the traceback from the
protocol.
"""
tb_info = traceback.extract_tb(tb)
for frame in reversed(tb_info):
if frame.filename == proto_name:
return frame
else:
raise KeyError | [
"def",
"_find_protocol_error",
"(",
"tb",
",",
"proto_name",
")",
":",
"tb_info",
"=",
"traceback",
".",
"extract_tb",
"(",
"tb",
")",
"for",
"frame",
"in",
"reversed",
"(",
"tb_info",
")",
":",
"if",
"frame",
".",
"filename",
"==",
"proto_name",
":",
"r... | Return the FrameInfo for the lowest frame in the traceback from the
protocol. | [
"Return",
"the",
"FrameInfo",
"for",
"the",
"lowest",
"frame",
"in",
"the",
"traceback",
"from",
"the",
"protocol",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/protocol_api/execute.py#L86-L95 | train | 198,157 |
Opentrons/opentrons | api/src/opentrons/protocol_api/execute.py | run_protocol | def run_protocol(protocol_code: Any = None,
protocol_json: Dict[Any, Any] = None,
simulate: bool = False,
context: ProtocolContext = None):
""" Create a ProtocolRunner instance from one of a variety of protocol
sources.
:param protocol_bytes: If the protocol is a Python protocol, pass the
file contents here.
:param protocol_json: If the protocol is a json file, pass the contents
here.
:param simulate: True to simulate; False to execute. If this is not an
OT2, ``simulate`` will be forced ``True``.
:param context: The context to use. If ``None``, create a new
ProtocolContext.
"""
if not config.IS_ROBOT:
simulate = True # noqa - will be used later
if None is context and simulate:
true_context = ProtocolContext()
true_context.home()
MODULE_LOG.info("Generating blank protocol context for simulate")
elif context:
true_context = context
else:
raise RuntimeError(
'Will not automatically generate hardware controller')
if None is not protocol_code:
_run_python(protocol_code, true_context)
elif None is not protocol_json:
protocol_version = get_protocol_schema_version(protocol_json)
if protocol_version > 3:
raise RuntimeError(
f'JSON Protocol version {protocol_version} is not yet ' +
'supported in this version of the API')
validate_protocol(protocol_json)
if protocol_version >= 3:
ins = execute_v3.load_pipettes_from_json(
true_context, protocol_json)
lw = execute_v3.load_labware_from_json_defs(
true_context, protocol_json)
execute_v3.dispatch_json(true_context, protocol_json, ins, lw)
else:
ins = execute_v1.load_pipettes_from_json(
true_context, protocol_json)
lw = execute_v1.load_labware_from_json_loadnames(
true_context, protocol_json)
execute_v1.dispatch_json(true_context, protocol_json, ins, lw)
else:
raise RuntimeError("run_protocol must have either code or json") | python | def run_protocol(protocol_code: Any = None,
protocol_json: Dict[Any, Any] = None,
simulate: bool = False,
context: ProtocolContext = None):
""" Create a ProtocolRunner instance from one of a variety of protocol
sources.
:param protocol_bytes: If the protocol is a Python protocol, pass the
file contents here.
:param protocol_json: If the protocol is a json file, pass the contents
here.
:param simulate: True to simulate; False to execute. If this is not an
OT2, ``simulate`` will be forced ``True``.
:param context: The context to use. If ``None``, create a new
ProtocolContext.
"""
if not config.IS_ROBOT:
simulate = True # noqa - will be used later
if None is context and simulate:
true_context = ProtocolContext()
true_context.home()
MODULE_LOG.info("Generating blank protocol context for simulate")
elif context:
true_context = context
else:
raise RuntimeError(
'Will not automatically generate hardware controller')
if None is not protocol_code:
_run_python(protocol_code, true_context)
elif None is not protocol_json:
protocol_version = get_protocol_schema_version(protocol_json)
if protocol_version > 3:
raise RuntimeError(
f'JSON Protocol version {protocol_version} is not yet ' +
'supported in this version of the API')
validate_protocol(protocol_json)
if protocol_version >= 3:
ins = execute_v3.load_pipettes_from_json(
true_context, protocol_json)
lw = execute_v3.load_labware_from_json_defs(
true_context, protocol_json)
execute_v3.dispatch_json(true_context, protocol_json, ins, lw)
else:
ins = execute_v1.load_pipettes_from_json(
true_context, protocol_json)
lw = execute_v1.load_labware_from_json_loadnames(
true_context, protocol_json)
execute_v1.dispatch_json(true_context, protocol_json, ins, lw)
else:
raise RuntimeError("run_protocol must have either code or json") | [
"def",
"run_protocol",
"(",
"protocol_code",
":",
"Any",
"=",
"None",
",",
"protocol_json",
":",
"Dict",
"[",
"Any",
",",
"Any",
"]",
"=",
"None",
",",
"simulate",
":",
"bool",
"=",
"False",
",",
"context",
":",
"ProtocolContext",
"=",
"None",
")",
":"... | Create a ProtocolRunner instance from one of a variety of protocol
sources.
:param protocol_bytes: If the protocol is a Python protocol, pass the
file contents here.
:param protocol_json: If the protocol is a json file, pass the contents
here.
:param simulate: True to simulate; False to execute. If this is not an
OT2, ``simulate`` will be forced ``True``.
:param context: The context to use. If ``None``, create a new
ProtocolContext. | [
"Create",
"a",
"ProtocolRunner",
"instance",
"from",
"one",
"of",
"a",
"variety",
"of",
"protocol",
"sources",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/protocol_api/execute.py#L185-L236 | train | 198,158 |
Opentrons/opentrons | api/src/opentrons/drivers/serial_communication.py | get_ports_by_name | def get_ports_by_name(device_name):
'''Returns all serial devices with a given name'''
filtered_devices = filter(
lambda device: device_name in device[1],
list_ports.comports()
)
device_ports = [device[0] for device in filtered_devices]
return device_ports | python | def get_ports_by_name(device_name):
'''Returns all serial devices with a given name'''
filtered_devices = filter(
lambda device: device_name in device[1],
list_ports.comports()
)
device_ports = [device[0] for device in filtered_devices]
return device_ports | [
"def",
"get_ports_by_name",
"(",
"device_name",
")",
":",
"filtered_devices",
"=",
"filter",
"(",
"lambda",
"device",
":",
"device_name",
"in",
"device",
"[",
"1",
"]",
",",
"list_ports",
".",
"comports",
"(",
")",
")",
"device_ports",
"=",
"[",
"device",
... | Returns all serial devices with a given name | [
"Returns",
"all",
"serial",
"devices",
"with",
"a",
"given",
"name"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/drivers/serial_communication.py#L17-L24 | train | 198,159 |
Opentrons/opentrons | api/src/opentrons/drivers/serial_communication.py | serial_with_temp_timeout | def serial_with_temp_timeout(serial_connection, timeout):
'''Implements a temporary timeout for a serial connection'''
saved_timeout = serial_connection.timeout
if timeout is not None:
serial_connection.timeout = timeout
yield serial_connection
serial_connection.timeout = saved_timeout | python | def serial_with_temp_timeout(serial_connection, timeout):
'''Implements a temporary timeout for a serial connection'''
saved_timeout = serial_connection.timeout
if timeout is not None:
serial_connection.timeout = timeout
yield serial_connection
serial_connection.timeout = saved_timeout | [
"def",
"serial_with_temp_timeout",
"(",
"serial_connection",
",",
"timeout",
")",
":",
"saved_timeout",
"=",
"serial_connection",
".",
"timeout",
"if",
"timeout",
"is",
"not",
"None",
":",
"serial_connection",
".",
"timeout",
"=",
"timeout",
"yield",
"serial_connect... | Implements a temporary timeout for a serial connection | [
"Implements",
"a",
"temporary",
"timeout",
"for",
"a",
"serial",
"connection"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/drivers/serial_communication.py#L35-L41 | train | 198,160 |
Opentrons/opentrons | api/src/opentrons/drivers/serial_communication.py | _write_to_device_and_return | def _write_to_device_and_return(cmd, ack, device_connection):
'''Writes to a serial device.
- Formats command
- Wait for ack return
- return parsed response'''
log.debug('Write -> {}'.format(cmd.encode()))
device_connection.write(cmd.encode())
response = device_connection.read_until(ack.encode())
log.debug('Read <- {}'.format(response))
if ack.encode() not in response:
raise SerialNoResponse(
'No response from serial port after {} second(s)'.format(
device_connection.timeout))
clean_response = _parse_serial_response(response, ack.encode())
if clean_response:
return clean_response.decode()
return '' | python | def _write_to_device_and_return(cmd, ack, device_connection):
'''Writes to a serial device.
- Formats command
- Wait for ack return
- return parsed response'''
log.debug('Write -> {}'.format(cmd.encode()))
device_connection.write(cmd.encode())
response = device_connection.read_until(ack.encode())
log.debug('Read <- {}'.format(response))
if ack.encode() not in response:
raise SerialNoResponse(
'No response from serial port after {} second(s)'.format(
device_connection.timeout))
clean_response = _parse_serial_response(response, ack.encode())
if clean_response:
return clean_response.decode()
return '' | [
"def",
"_write_to_device_and_return",
"(",
"cmd",
",",
"ack",
",",
"device_connection",
")",
":",
"log",
".",
"debug",
"(",
"'Write -> {}'",
".",
"format",
"(",
"cmd",
".",
"encode",
"(",
")",
")",
")",
"device_connection",
".",
"write",
"(",
"cmd",
".",
... | Writes to a serial device.
- Formats command
- Wait for ack return
- return parsed response | [
"Writes",
"to",
"a",
"serial",
"device",
".",
"-",
"Formats",
"command",
"-",
"Wait",
"for",
"ack",
"return",
"-",
"return",
"parsed",
"response"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/drivers/serial_communication.py#L56-L72 | train | 198,161 |
Opentrons/opentrons | api/src/opentrons/drivers/serial_communication.py | write_and_return | def write_and_return(
command, ack, serial_connection, timeout=DEFAULT_WRITE_TIMEOUT):
'''Write a command and return the response'''
clear_buffer(serial_connection)
with serial_with_temp_timeout(
serial_connection, timeout) as device_connection:
response = _write_to_device_and_return(command, ack, device_connection)
return response | python | def write_and_return(
command, ack, serial_connection, timeout=DEFAULT_WRITE_TIMEOUT):
'''Write a command and return the response'''
clear_buffer(serial_connection)
with serial_with_temp_timeout(
serial_connection, timeout) as device_connection:
response = _write_to_device_and_return(command, ack, device_connection)
return response | [
"def",
"write_and_return",
"(",
"command",
",",
"ack",
",",
"serial_connection",
",",
"timeout",
"=",
"DEFAULT_WRITE_TIMEOUT",
")",
":",
"clear_buffer",
"(",
"serial_connection",
")",
"with",
"serial_with_temp_timeout",
"(",
"serial_connection",
",",
"timeout",
")",
... | Write a command and return the response | [
"Write",
"a",
"command",
"and",
"return",
"the",
"response"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/drivers/serial_communication.py#L98-L105 | train | 198,162 |
Opentrons/opentrons | api/src/opentrons/server/endpoints/settings.py | get_advanced_settings | async def get_advanced_settings(request: web.Request) -> web.Response:
"""
Handles a GET request and returns a json body with the key "settings" and a
value that is a list of objects where each object has keys "id", "title",
"description", and "value"
"""
res = _get_adv_settings()
return web.json_response(res) | python | async def get_advanced_settings(request: web.Request) -> web.Response:
"""
Handles a GET request and returns a json body with the key "settings" and a
value that is a list of objects where each object has keys "id", "title",
"description", and "value"
"""
res = _get_adv_settings()
return web.json_response(res) | [
"async",
"def",
"get_advanced_settings",
"(",
"request",
":",
"web",
".",
"Request",
")",
"->",
"web",
".",
"Response",
":",
"res",
"=",
"_get_adv_settings",
"(",
")",
"return",
"web",
".",
"json_response",
"(",
"res",
")"
] | Handles a GET request and returns a json body with the key "settings" and a
value that is a list of objects where each object has keys "id", "title",
"description", and "value" | [
"Handles",
"a",
"GET",
"request",
"and",
"returns",
"a",
"json",
"body",
"with",
"the",
"key",
"settings",
"and",
"a",
"value",
"that",
"is",
"a",
"list",
"of",
"objects",
"where",
"each",
"object",
"has",
"keys",
"id",
"title",
"description",
"and",
"va... | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/server/endpoints/settings.py#L54-L61 | train | 198,163 |
Opentrons/opentrons | api/src/opentrons/server/endpoints/settings.py | set_advanced_setting | async def set_advanced_setting(request: web.Request) -> web.Response:
"""
Handles a POST request with a json body that has keys "id" and "value",
where the value of "id" must correspond to an id field of a setting in
`opentrons.config.advanced_settings.settings`. Saves the value of "value"
for the setting that matches the supplied id.
"""
data = await request.json()
key = data.get('id')
value = data.get('value')
if key and key in advs.settings_by_id.keys():
advs.set_adv_setting(key, value)
res = _get_adv_settings()
status = 200
else:
res = {'message': 'ID {} not found in settings list'.format(key)}
status = 400
return web.json_response(res, status=status) | python | async def set_advanced_setting(request: web.Request) -> web.Response:
"""
Handles a POST request with a json body that has keys "id" and "value",
where the value of "id" must correspond to an id field of a setting in
`opentrons.config.advanced_settings.settings`. Saves the value of "value"
for the setting that matches the supplied id.
"""
data = await request.json()
key = data.get('id')
value = data.get('value')
if key and key in advs.settings_by_id.keys():
advs.set_adv_setting(key, value)
res = _get_adv_settings()
status = 200
else:
res = {'message': 'ID {} not found in settings list'.format(key)}
status = 400
return web.json_response(res, status=status) | [
"async",
"def",
"set_advanced_setting",
"(",
"request",
":",
"web",
".",
"Request",
")",
"->",
"web",
".",
"Response",
":",
"data",
"=",
"await",
"request",
".",
"json",
"(",
")",
"key",
"=",
"data",
".",
"get",
"(",
"'id'",
")",
"value",
"=",
"data"... | Handles a POST request with a json body that has keys "id" and "value",
where the value of "id" must correspond to an id field of a setting in
`opentrons.config.advanced_settings.settings`. Saves the value of "value"
for the setting that matches the supplied id. | [
"Handles",
"a",
"POST",
"request",
"with",
"a",
"json",
"body",
"that",
"has",
"keys",
"id",
"and",
"value",
"where",
"the",
"value",
"of",
"id",
"must",
"correspond",
"to",
"an",
"id",
"field",
"of",
"a",
"setting",
"in",
"opentrons",
".",
"config",
"... | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/server/endpoints/settings.py#L69-L86 | train | 198,164 |
Opentrons/opentrons | api/src/opentrons/server/endpoints/settings.py | reset | async def reset(request: web.Request) -> web.Response:
""" Execute a reset of the requested parts of the user configuration.
"""
data = await request.json()
ok, bad_key = _check_reset(data)
if not ok:
return web.json_response(
{'message': '{} is not a valid reset option'
.format(bad_key)},
status=400)
log.info("Reset requested for {}".format(', '.join(data.keys())))
if data.get('tipProbe'):
config = rc.load()
if ff.use_protocol_api_v2():
config = config._replace(
instrument_offset=rc.build_fallback_instrument_offset({}))
else:
config.tip_length.clear()
rc.save_robot_settings(config)
if data.get('labwareCalibration'):
if ff.use_protocol_api_v2():
labware.clear_calibrations()
else:
db.reset()
if data.get('bootScripts'):
if IS_ROBOT:
if os.path.exists('/data/boot.d'):
shutil.rmtree('/data/boot.d')
else:
log.debug('Not on pi, not removing /data/boot.d')
return web.json_response({}, status=200) | python | async def reset(request: web.Request) -> web.Response:
""" Execute a reset of the requested parts of the user configuration.
"""
data = await request.json()
ok, bad_key = _check_reset(data)
if not ok:
return web.json_response(
{'message': '{} is not a valid reset option'
.format(bad_key)},
status=400)
log.info("Reset requested for {}".format(', '.join(data.keys())))
if data.get('tipProbe'):
config = rc.load()
if ff.use_protocol_api_v2():
config = config._replace(
instrument_offset=rc.build_fallback_instrument_offset({}))
else:
config.tip_length.clear()
rc.save_robot_settings(config)
if data.get('labwareCalibration'):
if ff.use_protocol_api_v2():
labware.clear_calibrations()
else:
db.reset()
if data.get('bootScripts'):
if IS_ROBOT:
if os.path.exists('/data/boot.d'):
shutil.rmtree('/data/boot.d')
else:
log.debug('Not on pi, not removing /data/boot.d')
return web.json_response({}, status=200) | [
"async",
"def",
"reset",
"(",
"request",
":",
"web",
".",
"Request",
")",
"->",
"web",
".",
"Response",
":",
"data",
"=",
"await",
"request",
".",
"json",
"(",
")",
"ok",
",",
"bad_key",
"=",
"_check_reset",
"(",
"data",
")",
"if",
"not",
"ok",
":"... | Execute a reset of the requested parts of the user configuration. | [
"Execute",
"a",
"reset",
"of",
"the",
"requested",
"parts",
"of",
"the",
"user",
"configuration",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/server/endpoints/settings.py#L98-L129 | train | 198,165 |
Opentrons/opentrons | api/src/opentrons/server/endpoints/settings.py | available_resets | async def available_resets(request: web.Request) -> web.Response:
""" Indicate what parts of the user configuration are available for reset.
"""
return web.json_response({'options': _settings_reset_options}, status=200) | python | async def available_resets(request: web.Request) -> web.Response:
""" Indicate what parts of the user configuration are available for reset.
"""
return web.json_response({'options': _settings_reset_options}, status=200) | [
"async",
"def",
"available_resets",
"(",
"request",
":",
"web",
".",
"Request",
")",
"->",
"web",
".",
"Response",
":",
"return",
"web",
".",
"json_response",
"(",
"{",
"'options'",
":",
"_settings_reset_options",
"}",
",",
"status",
"=",
"200",
")"
] | Indicate what parts of the user configuration are available for reset. | [
"Indicate",
"what",
"parts",
"of",
"the",
"user",
"configuration",
"are",
"available",
"for",
"reset",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/server/endpoints/settings.py#L132-L135 | train | 198,166 |
Opentrons/opentrons | api/src/opentrons/system/nmcli.py | connections | async def connections(
for_type: Optional[CONNECTION_TYPES] = None) -> List[Dict[str, str]]:
""" Return the list of configured connections.
This is all connections that nmcli knows about and manages.
Each connection is a dict containing some basic information - the
information retrievable from nmcli connection show. Further information
should be queried on a connection by connection basis.
If for_type is not None, it should be a str containing an element of
CONNECTION_TYPES, and results will be limited to that connection type.
"""
fields = ['name', 'type', 'active']
res, _ = await _call(['-t', '-f', ','.join(fields), 'connection', 'show'])
found = _dict_from_terse_tabular(
fields,
res,
# ’ethernet’ or ’wireless’ from ’802-11-wireless’ or ’802-4-ethernet’
# and bools from ’yes’ or ’no
transformers={'type': lambda s: s.split('-')[-1],
'active': lambda s: s.lower() == 'yes'}
)
if for_type is not None:
should_return = []
for c in found:
if c['type'] == for_type.value:
should_return.append(c)
return should_return
else:
return found | python | async def connections(
for_type: Optional[CONNECTION_TYPES] = None) -> List[Dict[str, str]]:
""" Return the list of configured connections.
This is all connections that nmcli knows about and manages.
Each connection is a dict containing some basic information - the
information retrievable from nmcli connection show. Further information
should be queried on a connection by connection basis.
If for_type is not None, it should be a str containing an element of
CONNECTION_TYPES, and results will be limited to that connection type.
"""
fields = ['name', 'type', 'active']
res, _ = await _call(['-t', '-f', ','.join(fields), 'connection', 'show'])
found = _dict_from_terse_tabular(
fields,
res,
# ’ethernet’ or ’wireless’ from ’802-11-wireless’ or ’802-4-ethernet’
# and bools from ’yes’ or ’no
transformers={'type': lambda s: s.split('-')[-1],
'active': lambda s: s.lower() == 'yes'}
)
if for_type is not None:
should_return = []
for c in found:
if c['type'] == for_type.value:
should_return.append(c)
return should_return
else:
return found | [
"async",
"def",
"connections",
"(",
"for_type",
":",
"Optional",
"[",
"CONNECTION_TYPES",
"]",
"=",
"None",
")",
"->",
"List",
"[",
"Dict",
"[",
"str",
",",
"str",
"]",
"]",
":",
"fields",
"=",
"[",
"'name'",
",",
"'type'",
",",
"'active'",
"]",
"res... | Return the list of configured connections.
This is all connections that nmcli knows about and manages.
Each connection is a dict containing some basic information - the
information retrievable from nmcli connection show. Further information
should be queried on a connection by connection basis.
If for_type is not None, it should be a str containing an element of
CONNECTION_TYPES, and results will be limited to that connection type. | [
"Return",
"the",
"list",
"of",
"configured",
"connections",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/system/nmcli.py#L293-L322 | train | 198,167 |
Opentrons/opentrons | api/src/opentrons/system/nmcli.py | connection_exists | async def connection_exists(ssid: str) -> Optional[str]:
""" If there is already a connection for this ssid, return the name of
the connection; if there is not, return None.
"""
nmcli_conns = await connections()
for wifi in [c['name']
for c in nmcli_conns if c['type'] == 'wireless']:
res, _ = await _call(['-t', '-f', '802-11-wireless.ssid',
'-m', 'tabular',
'connection', 'show', wifi])
if res == ssid:
return wifi
return None | python | async def connection_exists(ssid: str) -> Optional[str]:
""" If there is already a connection for this ssid, return the name of
the connection; if there is not, return None.
"""
nmcli_conns = await connections()
for wifi in [c['name']
for c in nmcli_conns if c['type'] == 'wireless']:
res, _ = await _call(['-t', '-f', '802-11-wireless.ssid',
'-m', 'tabular',
'connection', 'show', wifi])
if res == ssid:
return wifi
return None | [
"async",
"def",
"connection_exists",
"(",
"ssid",
":",
"str",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"nmcli_conns",
"=",
"await",
"connections",
"(",
")",
"for",
"wifi",
"in",
"[",
"c",
"[",
"'name'",
"]",
"for",
"c",
"in",
"nmcli_conns",
"if",
... | If there is already a connection for this ssid, return the name of
the connection; if there is not, return None. | [
"If",
"there",
"is",
"already",
"a",
"connection",
"for",
"this",
"ssid",
"return",
"the",
"name",
"of",
"the",
"connection",
";",
"if",
"there",
"is",
"not",
"return",
"None",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/system/nmcli.py#L325-L337 | train | 198,168 |
Opentrons/opentrons | api/src/opentrons/system/nmcli.py | _trim_old_connections | async def _trim_old_connections(
new_name: str, con_type: CONNECTION_TYPES) -> Tuple[bool, str]:
""" Delete all connections of con_type but the one specified.
"""
existing_cons = await connections(for_type=con_type)
not_us = [c['name'] for c in existing_cons if c['name'] != new_name]
ok = True
res = []
for c in not_us:
this_ok, remove_res = await remove(name=c)
ok = ok and this_ok
if not this_ok:
# This is not a failure case for connection, and indeed the new
# connection is already established, so just warn about it
log.warning("Could not remove wifi connection {}: {}"
.format(c, remove_res))
res.append(remove_res)
else:
log.debug("Removed old wifi connection {}".format(c))
return ok, ';'.join(res) | python | async def _trim_old_connections(
new_name: str, con_type: CONNECTION_TYPES) -> Tuple[bool, str]:
""" Delete all connections of con_type but the one specified.
"""
existing_cons = await connections(for_type=con_type)
not_us = [c['name'] for c in existing_cons if c['name'] != new_name]
ok = True
res = []
for c in not_us:
this_ok, remove_res = await remove(name=c)
ok = ok and this_ok
if not this_ok:
# This is not a failure case for connection, and indeed the new
# connection is already established, so just warn about it
log.warning("Could not remove wifi connection {}: {}"
.format(c, remove_res))
res.append(remove_res)
else:
log.debug("Removed old wifi connection {}".format(c))
return ok, ';'.join(res) | [
"async",
"def",
"_trim_old_connections",
"(",
"new_name",
":",
"str",
",",
"con_type",
":",
"CONNECTION_TYPES",
")",
"->",
"Tuple",
"[",
"bool",
",",
"str",
"]",
":",
"existing_cons",
"=",
"await",
"connections",
"(",
"for_type",
"=",
"con_type",
")",
"not_u... | Delete all connections of con_type but the one specified. | [
"Delete",
"all",
"connections",
"of",
"con_type",
"but",
"the",
"one",
"specified",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/system/nmcli.py#L340-L359 | train | 198,169 |
Opentrons/opentrons | api/src/opentrons/system/nmcli.py | _add_eap_args | def _add_eap_args(eap_args: Dict[str, str]) -> List[str]:
""" Add configuration options suitable for an nmcli con add command
for WPA-EAP configuration. These options are mostly in the
802-1x group.
The eap_args dict should be a flat structure of arguments. They
must contain at least 'eapType', specifying the EAP type to use
(the qualified_name() of one of the members of EAP_TYPES) and the
required arguments for that EAP type.
"""
args = ['wifi-sec.key-mgmt', 'wpa-eap']
eap_type = EAP_TYPES.by_qualified_name(eap_args['eapType'])
type_args = eap_type.args()
args += ['802-1x.eap', eap_type.outer.value.name]
if eap_type.inner:
args += ['802-1x.phase2-autheap', eap_type.inner.value.name]
for ta in type_args:
if ta['name'] in eap_args:
if ta['type'] == 'file':
# Keyfiles must be prepended with file:// so nm-cli
# knows that we’re not giving it DER-encoded blobs
_make_host_symlink_if_necessary()
path = _rewrite_key_path_to_host_path(eap_args[ta['name']])
val = 'file://' + path
else:
val = eap_args[ta['name']]
args += ['802-1x.' + ta['nmName'], val]
return args | python | def _add_eap_args(eap_args: Dict[str, str]) -> List[str]:
""" Add configuration options suitable for an nmcli con add command
for WPA-EAP configuration. These options are mostly in the
802-1x group.
The eap_args dict should be a flat structure of arguments. They
must contain at least 'eapType', specifying the EAP type to use
(the qualified_name() of one of the members of EAP_TYPES) and the
required arguments for that EAP type.
"""
args = ['wifi-sec.key-mgmt', 'wpa-eap']
eap_type = EAP_TYPES.by_qualified_name(eap_args['eapType'])
type_args = eap_type.args()
args += ['802-1x.eap', eap_type.outer.value.name]
if eap_type.inner:
args += ['802-1x.phase2-autheap', eap_type.inner.value.name]
for ta in type_args:
if ta['name'] in eap_args:
if ta['type'] == 'file':
# Keyfiles must be prepended with file:// so nm-cli
# knows that we’re not giving it DER-encoded blobs
_make_host_symlink_if_necessary()
path = _rewrite_key_path_to_host_path(eap_args[ta['name']])
val = 'file://' + path
else:
val = eap_args[ta['name']]
args += ['802-1x.' + ta['nmName'], val]
return args | [
"def",
"_add_eap_args",
"(",
"eap_args",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
")",
"->",
"List",
"[",
"str",
"]",
":",
"args",
"=",
"[",
"'wifi-sec.key-mgmt'",
",",
"'wpa-eap'",
"]",
"eap_type",
"=",
"EAP_TYPES",
".",
"by_qualified_name",
"(",
"eap_... | Add configuration options suitable for an nmcli con add command
for WPA-EAP configuration. These options are mostly in the
802-1x group.
The eap_args dict should be a flat structure of arguments. They
must contain at least 'eapType', specifying the EAP type to use
(the qualified_name() of one of the members of EAP_TYPES) and the
required arguments for that EAP type. | [
"Add",
"configuration",
"options",
"suitable",
"for",
"an",
"nmcli",
"con",
"add",
"command",
"for",
"WPA",
"-",
"EAP",
"configuration",
".",
"These",
"options",
"are",
"mostly",
"in",
"the",
"802",
"-",
"1x",
"group",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/system/nmcli.py#L362-L389 | train | 198,170 |
Opentrons/opentrons | api/src/opentrons/system/nmcli.py | _build_con_add_cmd | def _build_con_add_cmd(ssid: str, security_type: SECURITY_TYPES,
psk: Optional[str], hidden: bool,
eap_args: Optional[Dict[str, Any]]) -> List[str]:
""" Build the nmcli connection add command to configure the new network.
The parameters are the same as configure but without the defaults; this
should be called only by configure.
"""
configure_cmd = ['connection', 'add',
'save', 'yes',
'autoconnect', 'yes',
'ifname', 'wlan0',
'type', 'wifi',
'con-name', ssid,
'wifi.ssid', ssid]
if hidden:
configure_cmd += ['wifi.hidden', 'true']
if security_type == SECURITY_TYPES.WPA_PSK:
configure_cmd += ['wifi-sec.key-mgmt', security_type.value]
if psk is None:
raise ValueError('wpa-psk security type requires psk')
configure_cmd += ['wifi-sec.psk', psk]
elif security_type == SECURITY_TYPES.WPA_EAP:
if eap_args is None:
raise ValueError('wpa-eap security type requires eap_args')
configure_cmd += _add_eap_args(eap_args)
elif security_type == SECURITY_TYPES.NONE:
pass
else:
raise ValueError("Bad security_type {}".format(security_type))
return configure_cmd | python | def _build_con_add_cmd(ssid: str, security_type: SECURITY_TYPES,
psk: Optional[str], hidden: bool,
eap_args: Optional[Dict[str, Any]]) -> List[str]:
""" Build the nmcli connection add command to configure the new network.
The parameters are the same as configure but without the defaults; this
should be called only by configure.
"""
configure_cmd = ['connection', 'add',
'save', 'yes',
'autoconnect', 'yes',
'ifname', 'wlan0',
'type', 'wifi',
'con-name', ssid,
'wifi.ssid', ssid]
if hidden:
configure_cmd += ['wifi.hidden', 'true']
if security_type == SECURITY_TYPES.WPA_PSK:
configure_cmd += ['wifi-sec.key-mgmt', security_type.value]
if psk is None:
raise ValueError('wpa-psk security type requires psk')
configure_cmd += ['wifi-sec.psk', psk]
elif security_type == SECURITY_TYPES.WPA_EAP:
if eap_args is None:
raise ValueError('wpa-eap security type requires eap_args')
configure_cmd += _add_eap_args(eap_args)
elif security_type == SECURITY_TYPES.NONE:
pass
else:
raise ValueError("Bad security_type {}".format(security_type))
return configure_cmd | [
"def",
"_build_con_add_cmd",
"(",
"ssid",
":",
"str",
",",
"security_type",
":",
"SECURITY_TYPES",
",",
"psk",
":",
"Optional",
"[",
"str",
"]",
",",
"hidden",
":",
"bool",
",",
"eap_args",
":",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]"... | Build the nmcli connection add command to configure the new network.
The parameters are the same as configure but without the defaults; this
should be called only by configure. | [
"Build",
"the",
"nmcli",
"connection",
"add",
"command",
"to",
"configure",
"the",
"new",
"network",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/system/nmcli.py#L392-L423 | train | 198,171 |
Opentrons/opentrons | api/src/opentrons/system/nmcli.py | iface_info | async def iface_info(which_iface: NETWORK_IFACES) -> Dict[str, Optional[str]]:
""" Get the basic network configuration of an interface.
Returns a dict containing the info:
{
'ipAddress': 'xx.xx.xx.xx/yy' (ip4 addr with subnet as CIDR) or None
'macAddress': 'aa:bb:cc:dd:ee:ff' or None
'gatewayAddress: 'zz.zz.zz.zz' or None
}
which_iface should be a string in IFACE_NAMES.
"""
# example device info lines
# GENERAL.HWADDR:B8:27:EB:24:D1:D0
# IP4.ADDRESS[1]:10.10.2.221/22
# capture the field name (without the number in brackets) and the value
# using regex instead of split because there may be ":" in the value
_DEV_INFO_LINE_RE = re.compile(r'([\w.]+)(?:\[\d+])?:(.*)')
# example device info: 30 (disconnected)
# capture the string without the number
_IFACE_STATE_RE = re.compile(r'\d+ \((.+)\)')
info: Dict[str, Optional[str]] = {'ipAddress': None,
'macAddress': None,
'gatewayAddress': None,
'state': None,
'type': None}
fields = ['GENERAL.HWADDR', 'IP4.ADDRESS',
'IP4.GATEWAY', 'GENERAL.TYPE', 'GENERAL.STATE']
# Note on this specific command: Most nmcli commands default to a tabular
# output mode, where if there are multiple things to pull a couple specific
# fields from it you’ll get a table where rows are, say, connections, and
# columns are field name. However, specifically ‘con show <con-name>‘ and
# ‘dev show <dev-name>’ default to a multiline representation, and even if
# explicitly ask for it to be tabular, it’s not quite the same as the other
# commands. So we have to special-case the parsing.
res, err = await _call(['--mode', 'multiline',
'--escape', 'no',
'--terse', '--fields', ','.join(fields),
'dev', 'show', which_iface.value])
field_map = {}
for line in res.split('\n'):
# pull the key (without brackets) and the value out of the line
match = _DEV_INFO_LINE_RE.fullmatch(line)
if match is None:
raise ValueError(
"Bad nmcli result; out: {}; err: {}".format(res, err))
key, val = match.groups()
# nmcli can put "--" instead of "" for None
field_map[key] = None if val == '--' else val
info['macAddress'] = field_map.get('GENERAL.HWADDR')
info['ipAddress'] = field_map.get('IP4.ADDRESS')
info['gatewayAddress'] = field_map.get('IP4.GATEWAY')
info['type'] = field_map.get('GENERAL.TYPE')
state_val = field_map.get('GENERAL.STATE')
if state_val:
state_match = _IFACE_STATE_RE.fullmatch(state_val)
if state_match:
info['state'] = state_match.group(1)
return info | python | async def iface_info(which_iface: NETWORK_IFACES) -> Dict[str, Optional[str]]:
""" Get the basic network configuration of an interface.
Returns a dict containing the info:
{
'ipAddress': 'xx.xx.xx.xx/yy' (ip4 addr with subnet as CIDR) or None
'macAddress': 'aa:bb:cc:dd:ee:ff' or None
'gatewayAddress: 'zz.zz.zz.zz' or None
}
which_iface should be a string in IFACE_NAMES.
"""
# example device info lines
# GENERAL.HWADDR:B8:27:EB:24:D1:D0
# IP4.ADDRESS[1]:10.10.2.221/22
# capture the field name (without the number in brackets) and the value
# using regex instead of split because there may be ":" in the value
_DEV_INFO_LINE_RE = re.compile(r'([\w.]+)(?:\[\d+])?:(.*)')
# example device info: 30 (disconnected)
# capture the string without the number
_IFACE_STATE_RE = re.compile(r'\d+ \((.+)\)')
info: Dict[str, Optional[str]] = {'ipAddress': None,
'macAddress': None,
'gatewayAddress': None,
'state': None,
'type': None}
fields = ['GENERAL.HWADDR', 'IP4.ADDRESS',
'IP4.GATEWAY', 'GENERAL.TYPE', 'GENERAL.STATE']
# Note on this specific command: Most nmcli commands default to a tabular
# output mode, where if there are multiple things to pull a couple specific
# fields from it you’ll get a table where rows are, say, connections, and
# columns are field name. However, specifically ‘con show <con-name>‘ and
# ‘dev show <dev-name>’ default to a multiline representation, and even if
# explicitly ask for it to be tabular, it’s not quite the same as the other
# commands. So we have to special-case the parsing.
res, err = await _call(['--mode', 'multiline',
'--escape', 'no',
'--terse', '--fields', ','.join(fields),
'dev', 'show', which_iface.value])
field_map = {}
for line in res.split('\n'):
# pull the key (without brackets) and the value out of the line
match = _DEV_INFO_LINE_RE.fullmatch(line)
if match is None:
raise ValueError(
"Bad nmcli result; out: {}; err: {}".format(res, err))
key, val = match.groups()
# nmcli can put "--" instead of "" for None
field_map[key] = None if val == '--' else val
info['macAddress'] = field_map.get('GENERAL.HWADDR')
info['ipAddress'] = field_map.get('IP4.ADDRESS')
info['gatewayAddress'] = field_map.get('IP4.GATEWAY')
info['type'] = field_map.get('GENERAL.TYPE')
state_val = field_map.get('GENERAL.STATE')
if state_val:
state_match = _IFACE_STATE_RE.fullmatch(state_val)
if state_match:
info['state'] = state_match.group(1)
return info | [
"async",
"def",
"iface_info",
"(",
"which_iface",
":",
"NETWORK_IFACES",
")",
"->",
"Dict",
"[",
"str",
",",
"Optional",
"[",
"str",
"]",
"]",
":",
"# example device info lines",
"# GENERAL.HWADDR:B8:27:EB:24:D1:D0",
"# IP4.ADDRESS[1]:10.10.2.221/22",
"# capture the fie... | Get the basic network configuration of an interface.
Returns a dict containing the info:
{
'ipAddress': 'xx.xx.xx.xx/yy' (ip4 addr with subnet as CIDR) or None
'macAddress': 'aa:bb:cc:dd:ee:ff' or None
'gatewayAddress: 'zz.zz.zz.zz' or None
}
which_iface should be a string in IFACE_NAMES. | [
"Get",
"the",
"basic",
"network",
"configuration",
"of",
"an",
"interface",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/system/nmcli.py#L504-L567 | train | 198,172 |
Opentrons/opentrons | api/src/opentrons/system/nmcli.py | sanitize_args | def sanitize_args(cmd: List[str]) -> List[str]:
""" Filter the command so that it no longer contains passwords
"""
sanitized = []
for idx, fieldname in enumerate(cmd):
def _is_password(cmdstr):
return 'wifi-sec.psk' in cmdstr\
or 'password' in cmdstr.lower()
if idx > 0 and _is_password(cmd[idx-1]):
sanitized.append('****')
else:
sanitized.append(fieldname)
return sanitized | python | def sanitize_args(cmd: List[str]) -> List[str]:
""" Filter the command so that it no longer contains passwords
"""
sanitized = []
for idx, fieldname in enumerate(cmd):
def _is_password(cmdstr):
return 'wifi-sec.psk' in cmdstr\
or 'password' in cmdstr.lower()
if idx > 0 and _is_password(cmd[idx-1]):
sanitized.append('****')
else:
sanitized.append(fieldname)
return sanitized | [
"def",
"sanitize_args",
"(",
"cmd",
":",
"List",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"str",
"]",
":",
"sanitized",
"=",
"[",
"]",
"for",
"idx",
",",
"fieldname",
"in",
"enumerate",
"(",
"cmd",
")",
":",
"def",
"_is_password",
"(",
"cmdstr",
")... | Filter the command so that it no longer contains passwords | [
"Filter",
"the",
"command",
"so",
"that",
"it",
"no",
"longer",
"contains",
"passwords"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/system/nmcli.py#L595-L607 | train | 198,173 |
Opentrons/opentrons | api/src/opentrons/system/nmcli.py | _dict_from_terse_tabular | def _dict_from_terse_tabular(
names: List[str],
inp: str,
transformers: Dict[str, Callable[[str], Any]] = {})\
-> List[Dict[str, Any]]:
""" Parse NMCLI terse tabular output into a list of Python dict.
``names`` is a list of strings of field names to apply to the input data,
which is assumed to be colon separated.
``inp`` is the input as a string (i.e. already decode()d) from nmcli
``transformers`` is a dict mapping field names to callables of the form
f: str -> any. If a fieldname is in transformers, that callable will be
invoked on the field matching the name and the result stored.
The return value is a list with one element per valid line of input, where
each element is a dict with keys taken from names and values from the input
"""
res = []
for n in names:
if n not in transformers:
transformers[n] = lambda s: s
for line in inp.split('\n'):
if len(line) < 3:
continue
fields = line.split(':')
res.append(dict([
(elem[0], transformers[elem[0]](elem[1]))
for elem in zip(names, fields)]))
return res | python | def _dict_from_terse_tabular(
names: List[str],
inp: str,
transformers: Dict[str, Callable[[str], Any]] = {})\
-> List[Dict[str, Any]]:
""" Parse NMCLI terse tabular output into a list of Python dict.
``names`` is a list of strings of field names to apply to the input data,
which is assumed to be colon separated.
``inp`` is the input as a string (i.e. already decode()d) from nmcli
``transformers`` is a dict mapping field names to callables of the form
f: str -> any. If a fieldname is in transformers, that callable will be
invoked on the field matching the name and the result stored.
The return value is a list with one element per valid line of input, where
each element is a dict with keys taken from names and values from the input
"""
res = []
for n in names:
if n not in transformers:
transformers[n] = lambda s: s
for line in inp.split('\n'):
if len(line) < 3:
continue
fields = line.split(':')
res.append(dict([
(elem[0], transformers[elem[0]](elem[1]))
for elem in zip(names, fields)]))
return res | [
"def",
"_dict_from_terse_tabular",
"(",
"names",
":",
"List",
"[",
"str",
"]",
",",
"inp",
":",
"str",
",",
"transformers",
":",
"Dict",
"[",
"str",
",",
"Callable",
"[",
"[",
"str",
"]",
",",
"Any",
"]",
"]",
"=",
"{",
"}",
")",
"->",
"List",
"[... | Parse NMCLI terse tabular output into a list of Python dict.
``names`` is a list of strings of field names to apply to the input data,
which is assumed to be colon separated.
``inp`` is the input as a string (i.e. already decode()d) from nmcli
``transformers`` is a dict mapping field names to callables of the form
f: str -> any. If a fieldname is in transformers, that callable will be
invoked on the field matching the name and the result stored.
The return value is a list with one element per valid line of input, where
each element is a dict with keys taken from names and values from the input | [
"Parse",
"NMCLI",
"terse",
"tabular",
"output",
"into",
"a",
"list",
"of",
"Python",
"dict",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/system/nmcli.py#L610-L640 | train | 198,174 |
Opentrons/opentrons | api/src/opentrons/legacy_api/instruments/pipette.py | Pipette.reset | def reset(self):
"""
Resets the state of this pipette, removing associated placeables,
setting current volume to zero, and resetting tip tracking
"""
self.tip_attached = False
self.placeables = []
self.previous_placeable = None
self.current_volume = 0
self.reset_tip_tracking() | python | def reset(self):
"""
Resets the state of this pipette, removing associated placeables,
setting current volume to zero, and resetting tip tracking
"""
self.tip_attached = False
self.placeables = []
self.previous_placeable = None
self.current_volume = 0
self.reset_tip_tracking() | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"tip_attached",
"=",
"False",
"self",
".",
"placeables",
"=",
"[",
"]",
"self",
".",
"previous_placeable",
"=",
"None",
"self",
".",
"current_volume",
"=",
"0",
"self",
".",
"reset_tip_tracking",
"(",
"... | Resets the state of this pipette, removing associated placeables,
setting current volume to zero, and resetting tip tracking | [
"Resets",
"the",
"state",
"of",
"this",
"pipette",
"removing",
"associated",
"placeables",
"setting",
"current",
"volume",
"to",
"zero",
"and",
"resetting",
"tip",
"tracking"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/instruments/pipette.py#L231-L240 | train | 198,175 |
Opentrons/opentrons | api/src/opentrons/legacy_api/instruments/pipette.py | Pipette._associate_placeable | def _associate_placeable(self, location):
"""
Saves a reference to a placeable
"""
if not location:
return
placeable, _ = unpack_location(location)
self.previous_placeable = placeable
if not self.placeables or (placeable != self.placeables[-1]):
self.placeables.append(placeable) | python | def _associate_placeable(self, location):
"""
Saves a reference to a placeable
"""
if not location:
return
placeable, _ = unpack_location(location)
self.previous_placeable = placeable
if not self.placeables or (placeable != self.placeables[-1]):
self.placeables.append(placeable) | [
"def",
"_associate_placeable",
"(",
"self",
",",
"location",
")",
":",
"if",
"not",
"location",
":",
"return",
"placeable",
",",
"_",
"=",
"unpack_location",
"(",
"location",
")",
"self",
".",
"previous_placeable",
"=",
"placeable",
"if",
"not",
"self",
".",... | Saves a reference to a placeable | [
"Saves",
"a",
"reference",
"to",
"a",
"placeable"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/instruments/pipette.py#L294-L304 | train | 198,176 |
Opentrons/opentrons | api/src/opentrons/legacy_api/instruments/pipette.py | Pipette.retract | def retract(self, safety_margin=10):
'''
Move the pipette's mount upwards and away from the deck
Parameters
----------
safety_margin: int
Distance in millimeters awey from the limit switch,
used during the mount's `fast_home()` method
'''
self.previous_placeable = None # it is no longer inside a placeable
self.robot.poses = self.instrument_mover.fast_home(
self.robot.poses, safety_margin)
return self | python | def retract(self, safety_margin=10):
'''
Move the pipette's mount upwards and away from the deck
Parameters
----------
safety_margin: int
Distance in millimeters awey from the limit switch,
used during the mount's `fast_home()` method
'''
self.previous_placeable = None # it is no longer inside a placeable
self.robot.poses = self.instrument_mover.fast_home(
self.robot.poses, safety_margin)
return self | [
"def",
"retract",
"(",
"self",
",",
"safety_margin",
"=",
"10",
")",
":",
"self",
".",
"previous_placeable",
"=",
"None",
"# it is no longer inside a placeable",
"self",
".",
"robot",
".",
"poses",
"=",
"self",
".",
"instrument_mover",
".",
"fast_home",
"(",
"... | Move the pipette's mount upwards and away from the deck
Parameters
----------
safety_margin: int
Distance in millimeters awey from the limit switch,
used during the mount's `fast_home()` method | [
"Move",
"the",
"pipette",
"s",
"mount",
"upwards",
"and",
"away",
"from",
"the",
"deck"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/instruments/pipette.py#L592-L605 | train | 198,177 |
Opentrons/opentrons | api/src/opentrons/legacy_api/instruments/pipette.py | Pipette.blow_out | def blow_out(self, location=None):
"""
Force any remaining liquid to dispense, by moving
this pipette's plunger to the calibrated `blow_out` position
Notes
-----
If no `location` is passed, the pipette will blow_out
from it's current position.
Parameters
----------
location : :any:`Placeable` or tuple(:any:`Placeable`, :any:`Vector`)
The :any:`Placeable` (:any:`Well`) to perform the blow_out.
Can also be a tuple with first item :any:`Placeable`,
second item relative :any:`Vector`
Returns
-------
This instance of :class:`Pipette`.
Examples
--------
..
>>> from opentrons import instruments, robot # doctest: +SKIP
>>> robot.reset() # doctest: +SKIP
>>> p300 = instruments.P300_Single(mount='left') # doctest: +SKIP
>>> p300.aspirate(50).dispense().blow_out() # doctest: +SKIP
"""
if not self.tip_attached:
log.warning("Cannot 'blow out' without a tip attached.")
self.move_to(location)
self.instrument_actuator.set_active_current(self._plunger_current)
self.robot.poses = self.instrument_actuator.move(
self.robot.poses,
x=self._get_plunger_position('blow_out')
)
self.current_volume = 0
return self | python | def blow_out(self, location=None):
"""
Force any remaining liquid to dispense, by moving
this pipette's plunger to the calibrated `blow_out` position
Notes
-----
If no `location` is passed, the pipette will blow_out
from it's current position.
Parameters
----------
location : :any:`Placeable` or tuple(:any:`Placeable`, :any:`Vector`)
The :any:`Placeable` (:any:`Well`) to perform the blow_out.
Can also be a tuple with first item :any:`Placeable`,
second item relative :any:`Vector`
Returns
-------
This instance of :class:`Pipette`.
Examples
--------
..
>>> from opentrons import instruments, robot # doctest: +SKIP
>>> robot.reset() # doctest: +SKIP
>>> p300 = instruments.P300_Single(mount='left') # doctest: +SKIP
>>> p300.aspirate(50).dispense().blow_out() # doctest: +SKIP
"""
if not self.tip_attached:
log.warning("Cannot 'blow out' without a tip attached.")
self.move_to(location)
self.instrument_actuator.set_active_current(self._plunger_current)
self.robot.poses = self.instrument_actuator.move(
self.robot.poses,
x=self._get_plunger_position('blow_out')
)
self.current_volume = 0
return self | [
"def",
"blow_out",
"(",
"self",
",",
"location",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"tip_attached",
":",
"log",
".",
"warning",
"(",
"\"Cannot 'blow out' without a tip attached.\"",
")",
"self",
".",
"move_to",
"(",
"location",
")",
"self",
"."... | Force any remaining liquid to dispense, by moving
this pipette's plunger to the calibrated `blow_out` position
Notes
-----
If no `location` is passed, the pipette will blow_out
from it's current position.
Parameters
----------
location : :any:`Placeable` or tuple(:any:`Placeable`, :any:`Vector`)
The :any:`Placeable` (:any:`Well`) to perform the blow_out.
Can also be a tuple with first item :any:`Placeable`,
second item relative :any:`Vector`
Returns
-------
This instance of :class:`Pipette`.
Examples
--------
..
>>> from opentrons import instruments, robot # doctest: +SKIP
>>> robot.reset() # doctest: +SKIP
>>> p300 = instruments.P300_Single(mount='left') # doctest: +SKIP
>>> p300.aspirate(50).dispense().blow_out() # doctest: +SKIP | [
"Force",
"any",
"remaining",
"liquid",
"to",
"dispense",
"by",
"moving",
"this",
"pipette",
"s",
"plunger",
"to",
"the",
"calibrated",
"blow_out",
"position"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/instruments/pipette.py#L680-L721 | train | 198,178 |
Opentrons/opentrons | api/src/opentrons/legacy_api/instruments/pipette.py | Pipette.return_tip | def return_tip(self, home_after=True):
"""
Drop the pipette's current tip to it's originating tip rack
Notes
-----
This method requires one or more tip-rack :any:`Container`
to be in this Pipette's `tip_racks` list (see :any:`Pipette`)
Returns
-------
This instance of :class:`Pipette`.
Examples
--------
..
>>> from opentrons import instruments, labware, robot # doctest: +SKIP
>>> robot.reset() # doctest: +SKIP
>>> tiprack = labware.load('GEB-tiprack-300', '2') # doctest: +SKIP
>>> p300 = instruments.P300_Single(mount='left',
... tip_racks=[tiprack, tiprack2]) # doctest: +SKIP
>>> p300.pick_up_tip() # doctest: +SKIP
>>> p300.aspirate(50, plate[0]) # doctest: +SKIP
>>> p300.dispense(plate[1]) # doctest: +SKIP
>>> p300.return_tip() # doctest: +SKIP
"""
if not self.tip_attached:
log.warning("Cannot return tip without tip attached.")
if not self.current_tip():
self.robot.add_warning(
'Pipette has no tip to return, dropping in place')
self.drop_tip(self.current_tip(), home_after=home_after)
return self | python | def return_tip(self, home_after=True):
"""
Drop the pipette's current tip to it's originating tip rack
Notes
-----
This method requires one or more tip-rack :any:`Container`
to be in this Pipette's `tip_racks` list (see :any:`Pipette`)
Returns
-------
This instance of :class:`Pipette`.
Examples
--------
..
>>> from opentrons import instruments, labware, robot # doctest: +SKIP
>>> robot.reset() # doctest: +SKIP
>>> tiprack = labware.load('GEB-tiprack-300', '2') # doctest: +SKIP
>>> p300 = instruments.P300_Single(mount='left',
... tip_racks=[tiprack, tiprack2]) # doctest: +SKIP
>>> p300.pick_up_tip() # doctest: +SKIP
>>> p300.aspirate(50, plate[0]) # doctest: +SKIP
>>> p300.dispense(plate[1]) # doctest: +SKIP
>>> p300.return_tip() # doctest: +SKIP
"""
if not self.tip_attached:
log.warning("Cannot return tip without tip attached.")
if not self.current_tip():
self.robot.add_warning(
'Pipette has no tip to return, dropping in place')
self.drop_tip(self.current_tip(), home_after=home_after)
return self | [
"def",
"return_tip",
"(",
"self",
",",
"home_after",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"tip_attached",
":",
"log",
".",
"warning",
"(",
"\"Cannot return tip without tip attached.\"",
")",
"if",
"not",
"self",
".",
"current_tip",
"(",
")",
":",... | Drop the pipette's current tip to it's originating tip rack
Notes
-----
This method requires one or more tip-rack :any:`Container`
to be in this Pipette's `tip_racks` list (see :any:`Pipette`)
Returns
-------
This instance of :class:`Pipette`.
Examples
--------
..
>>> from opentrons import instruments, labware, robot # doctest: +SKIP
>>> robot.reset() # doctest: +SKIP
>>> tiprack = labware.load('GEB-tiprack-300', '2') # doctest: +SKIP
>>> p300 = instruments.P300_Single(mount='left',
... tip_racks=[tiprack, tiprack2]) # doctest: +SKIP
>>> p300.pick_up_tip() # doctest: +SKIP
>>> p300.aspirate(50, plate[0]) # doctest: +SKIP
>>> p300.dispense(plate[1]) # doctest: +SKIP
>>> p300.return_tip() # doctest: +SKIP | [
"Drop",
"the",
"pipette",
"s",
"current",
"tip",
"to",
"it",
"s",
"originating",
"tip",
"rack"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/instruments/pipette.py#L876-L911 | train | 198,179 |
Opentrons/opentrons | api/src/opentrons/legacy_api/instruments/pipette.py | Pipette.pick_up_tip | def pick_up_tip(self, location=None, presses=None, increment=None):
"""
Pick up a tip for the Pipette to run liquid-handling commands with
Notes
-----
A tip can be manually set by passing a `location`. If no location
is passed, the Pipette will pick up the next available tip in
it's `tip_racks` list (see :any:`Pipette`)
Parameters
----------
location : :any:`Placeable` or tuple(:any:`Placeable`, :any:`Vector`)
The :any:`Placeable` (:any:`Well`) to perform the pick_up_tip.
Can also be a tuple with first item :any:`Placeable`,
second item relative :any:`Vector`
presses : :any:int
The number of times to lower and then raise the pipette when
picking up a tip, to ensure a good seal (0 [zero] will result in
the pipette hovering over the tip but not picking it up--generally
not desireable, but could be used for dry-run). Default: 3 presses
increment: :int
The additional distance to travel on each successive press (e.g.:
if presses=3 and increment=1, then the first press will travel down
into the tip by 3.5mm, the second by 4.5mm, and the third by 5.5mm.
Default: 1mm
Returns
-------
This instance of :class:`Pipette`.
Examples
--------
..
>>> from opentrons import instruments, labware, robot # doctest: +SKIP
>>> robot.reset() # doctest: +SKIP
>>> tiprack = labware.load('GEB-tiprack-300', '2') # doctest: +SKIP
>>> p300 = instruments.P300_Single(mount='left',
... tip_racks=[tiprack]) # doctest: +SKIP
>>> p300.pick_up_tip(tiprack[0]) # doctest: +SKIP
>>> p300.return_tip() # doctest: +SKIP
# `pick_up_tip` will automatically go to tiprack[1]
>>> p300.pick_up_tip() # doctest: +SKIP
>>> p300.return_tip() # doctest: +SKIP
"""
if self.tip_attached:
log.warning("There is already a tip attached to this pipette.")
if not location:
location = self.get_next_tip()
self.current_tip(None)
if location:
placeable, _ = unpack_location(location)
self.current_tip(placeable)
presses = (self._pick_up_presses
if not helpers.is_number(presses)
else presses)
increment = (self._pick_up_increment
if not helpers.is_number(increment)
else increment)
def _pick_up_tip(
self, location, presses, increment):
self.instrument_actuator.set_active_current(self._plunger_current)
self.robot.poses = self.instrument_actuator.move(
self.robot.poses,
x=self._get_plunger_position('bottom')
)
self.current_volume = 0
self.move_to(self.current_tip().top(0))
for i in range(int(presses)):
# move nozzle down into the tip
self.instrument_mover.push_speed()
self.instrument_mover.push_active_current()
self.instrument_mover.set_active_current(self._pick_up_current)
self.instrument_mover.set_speed(self._pick_up_speed)
dist = (-1 * self._pick_up_distance) + (-1 * increment * i)
self.move_to(
self.current_tip().top(dist),
strategy='direct')
# move nozzle back up
self.instrument_mover.pop_active_current()
self.instrument_mover.pop_speed()
self.move_to(
self.current_tip().top(0),
strategy='direct')
self._add_tip(
length=self._tip_length
)
# neighboring tips tend to get stuck in the space between
# the volume chamber and the drop-tip sleeve on p1000.
# This extra shake ensures those tips are removed
if 'needs-pickup-shake' in self.quirks:
self._shake_off_tips(location)
self._shake_off_tips(location)
self.previous_placeable = None # no longer inside a placeable
self.robot.poses = self.instrument_mover.fast_home(
self.robot.poses, self._pick_up_distance)
return self
do_publish(self.broker, commands.pick_up_tip, self.pick_up_tip,
'before', None, None, self, location, presses, increment)
_pick_up_tip(
self, location=location, presses=presses, increment=increment)
do_publish(self.broker, commands.pick_up_tip, self.pick_up_tip,
'after', self, None, self, location, presses, increment)
return self | python | def pick_up_tip(self, location=None, presses=None, increment=None):
"""
Pick up a tip for the Pipette to run liquid-handling commands with
Notes
-----
A tip can be manually set by passing a `location`. If no location
is passed, the Pipette will pick up the next available tip in
it's `tip_racks` list (see :any:`Pipette`)
Parameters
----------
location : :any:`Placeable` or tuple(:any:`Placeable`, :any:`Vector`)
The :any:`Placeable` (:any:`Well`) to perform the pick_up_tip.
Can also be a tuple with first item :any:`Placeable`,
second item relative :any:`Vector`
presses : :any:int
The number of times to lower and then raise the pipette when
picking up a tip, to ensure a good seal (0 [zero] will result in
the pipette hovering over the tip but not picking it up--generally
not desireable, but could be used for dry-run). Default: 3 presses
increment: :int
The additional distance to travel on each successive press (e.g.:
if presses=3 and increment=1, then the first press will travel down
into the tip by 3.5mm, the second by 4.5mm, and the third by 5.5mm.
Default: 1mm
Returns
-------
This instance of :class:`Pipette`.
Examples
--------
..
>>> from opentrons import instruments, labware, robot # doctest: +SKIP
>>> robot.reset() # doctest: +SKIP
>>> tiprack = labware.load('GEB-tiprack-300', '2') # doctest: +SKIP
>>> p300 = instruments.P300_Single(mount='left',
... tip_racks=[tiprack]) # doctest: +SKIP
>>> p300.pick_up_tip(tiprack[0]) # doctest: +SKIP
>>> p300.return_tip() # doctest: +SKIP
# `pick_up_tip` will automatically go to tiprack[1]
>>> p300.pick_up_tip() # doctest: +SKIP
>>> p300.return_tip() # doctest: +SKIP
"""
if self.tip_attached:
log.warning("There is already a tip attached to this pipette.")
if not location:
location = self.get_next_tip()
self.current_tip(None)
if location:
placeable, _ = unpack_location(location)
self.current_tip(placeable)
presses = (self._pick_up_presses
if not helpers.is_number(presses)
else presses)
increment = (self._pick_up_increment
if not helpers.is_number(increment)
else increment)
def _pick_up_tip(
self, location, presses, increment):
self.instrument_actuator.set_active_current(self._plunger_current)
self.robot.poses = self.instrument_actuator.move(
self.robot.poses,
x=self._get_plunger_position('bottom')
)
self.current_volume = 0
self.move_to(self.current_tip().top(0))
for i in range(int(presses)):
# move nozzle down into the tip
self.instrument_mover.push_speed()
self.instrument_mover.push_active_current()
self.instrument_mover.set_active_current(self._pick_up_current)
self.instrument_mover.set_speed(self._pick_up_speed)
dist = (-1 * self._pick_up_distance) + (-1 * increment * i)
self.move_to(
self.current_tip().top(dist),
strategy='direct')
# move nozzle back up
self.instrument_mover.pop_active_current()
self.instrument_mover.pop_speed()
self.move_to(
self.current_tip().top(0),
strategy='direct')
self._add_tip(
length=self._tip_length
)
# neighboring tips tend to get stuck in the space between
# the volume chamber and the drop-tip sleeve on p1000.
# This extra shake ensures those tips are removed
if 'needs-pickup-shake' in self.quirks:
self._shake_off_tips(location)
self._shake_off_tips(location)
self.previous_placeable = None # no longer inside a placeable
self.robot.poses = self.instrument_mover.fast_home(
self.robot.poses, self._pick_up_distance)
return self
do_publish(self.broker, commands.pick_up_tip, self.pick_up_tip,
'before', None, None, self, location, presses, increment)
_pick_up_tip(
self, location=location, presses=presses, increment=increment)
do_publish(self.broker, commands.pick_up_tip, self.pick_up_tip,
'after', self, None, self, location, presses, increment)
return self | [
"def",
"pick_up_tip",
"(",
"self",
",",
"location",
"=",
"None",
",",
"presses",
"=",
"None",
",",
"increment",
"=",
"None",
")",
":",
"if",
"self",
".",
"tip_attached",
":",
"log",
".",
"warning",
"(",
"\"There is already a tip attached to this pipette.\"",
"... | Pick up a tip for the Pipette to run liquid-handling commands with
Notes
-----
A tip can be manually set by passing a `location`. If no location
is passed, the Pipette will pick up the next available tip in
it's `tip_racks` list (see :any:`Pipette`)
Parameters
----------
location : :any:`Placeable` or tuple(:any:`Placeable`, :any:`Vector`)
The :any:`Placeable` (:any:`Well`) to perform the pick_up_tip.
Can also be a tuple with first item :any:`Placeable`,
second item relative :any:`Vector`
presses : :any:int
The number of times to lower and then raise the pipette when
picking up a tip, to ensure a good seal (0 [zero] will result in
the pipette hovering over the tip but not picking it up--generally
not desireable, but could be used for dry-run). Default: 3 presses
increment: :int
The additional distance to travel on each successive press (e.g.:
if presses=3 and increment=1, then the first press will travel down
into the tip by 3.5mm, the second by 4.5mm, and the third by 5.5mm.
Default: 1mm
Returns
-------
This instance of :class:`Pipette`.
Examples
--------
..
>>> from opentrons import instruments, labware, robot # doctest: +SKIP
>>> robot.reset() # doctest: +SKIP
>>> tiprack = labware.load('GEB-tiprack-300', '2') # doctest: +SKIP
>>> p300 = instruments.P300_Single(mount='left',
... tip_racks=[tiprack]) # doctest: +SKIP
>>> p300.pick_up_tip(tiprack[0]) # doctest: +SKIP
>>> p300.return_tip() # doctest: +SKIP
# `pick_up_tip` will automatically go to tiprack[1]
>>> p300.pick_up_tip() # doctest: +SKIP
>>> p300.return_tip() # doctest: +SKIP | [
"Pick",
"up",
"a",
"tip",
"for",
"the",
"Pipette",
"to",
"run",
"liquid",
"-",
"handling",
"commands",
"with"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/instruments/pipette.py#L913-L1023 | train | 198,180 |
Opentrons/opentrons | api/src/opentrons/legacy_api/instruments/pipette.py | Pipette.drop_tip | def drop_tip(self, location=None, home_after=True):
"""
Drop the pipette's current tip
Notes
-----
If no location is passed, the pipette defaults to its `trash_container`
(see :any:`Pipette`)
Parameters
----------
location : :any:`Placeable` or tuple(:any:`Placeable`, :any:`Vector`)
The :any:`Placeable` (:any:`Well`) to perform the drop_tip.
Can also be a tuple with first item :any:`Placeable`,
second item relative :any:`Vector`
Returns
-------
This instance of :class:`Pipette`.
Examples
--------
..
>>> from opentrons import instruments, labware, robot # doctest: +SKIP
>>> robot.reset() # doctest: +SKIP
>>> tiprack = labware.load('tiprack-200ul', 'C2') # doctest: +SKIP
>>> trash = labware.load('point', 'A3') # doctest: +SKIP
>>> p300 = instruments.P300_Single(mount='left') # doctest: +SKIP
>>> p300.pick_up_tip(tiprack[0]) # doctest: +SKIP
# drops the tip in the fixed trash
>>> p300.drop_tip() # doctest: +SKIP
>>> p300.pick_up_tip(tiprack[1]) # doctest: +SKIP
# drops the tip back at its tip rack
>>> p300.drop_tip(tiprack[1]) # doctest: +SKIP
"""
if not self.tip_attached:
log.warning("Cannot drop tip without a tip attached.")
if not location and self.trash_container:
location = self.trash_container
if isinstance(location, Placeable):
# give space for the drop-tip mechanism
# @TODO (Laura & Andy 2018261)
# When container typing is implemented, make sure that
# when returning to a tiprack, tips are dropped within the rack
if 'rack' in location.get_parent().get_type():
half_tip_length = self._tip_length / 2
location = location.top(-half_tip_length)
elif 'trash' in location.get_parent().get_type():
loc, coords = location.top()
location = (loc, coords + (0, self.model_offset[1], 0))
else:
location = location.top()
def _drop_tip(location, instrument=self):
if location:
self.move_to(location)
pos_bottom = self._get_plunger_position('bottom')
pos_drop_tip = self._get_plunger_position('drop_tip')
self.instrument_actuator.set_active_current(self._plunger_current)
self.robot.poses = self.instrument_actuator.move(
self.robot.poses,
x=pos_bottom
)
self.instrument_actuator.set_active_current(self._drop_tip_current)
self.instrument_actuator.push_speed()
self.instrument_actuator.set_speed(self._drop_tip_speed)
self.robot.poses = self.instrument_actuator.move(
self.robot.poses,
x=pos_drop_tip
)
self.instrument_actuator.pop_speed()
self._shake_off_tips(location)
if home_after:
self._home_after_drop_tip()
self.current_volume = 0
self.current_tip(None)
self._remove_tip(
length=self._tip_length
)
do_publish(self.broker, commands.drop_tip, self.drop_tip,
'before', None, None, self, location)
_drop_tip(location)
do_publish(self.broker, commands.drop_tip, self.drop_tip,
'after', self, None, self, location)
return self | python | def drop_tip(self, location=None, home_after=True):
"""
Drop the pipette's current tip
Notes
-----
If no location is passed, the pipette defaults to its `trash_container`
(see :any:`Pipette`)
Parameters
----------
location : :any:`Placeable` or tuple(:any:`Placeable`, :any:`Vector`)
The :any:`Placeable` (:any:`Well`) to perform the drop_tip.
Can also be a tuple with first item :any:`Placeable`,
second item relative :any:`Vector`
Returns
-------
This instance of :class:`Pipette`.
Examples
--------
..
>>> from opentrons import instruments, labware, robot # doctest: +SKIP
>>> robot.reset() # doctest: +SKIP
>>> tiprack = labware.load('tiprack-200ul', 'C2') # doctest: +SKIP
>>> trash = labware.load('point', 'A3') # doctest: +SKIP
>>> p300 = instruments.P300_Single(mount='left') # doctest: +SKIP
>>> p300.pick_up_tip(tiprack[0]) # doctest: +SKIP
# drops the tip in the fixed trash
>>> p300.drop_tip() # doctest: +SKIP
>>> p300.pick_up_tip(tiprack[1]) # doctest: +SKIP
# drops the tip back at its tip rack
>>> p300.drop_tip(tiprack[1]) # doctest: +SKIP
"""
if not self.tip_attached:
log.warning("Cannot drop tip without a tip attached.")
if not location and self.trash_container:
location = self.trash_container
if isinstance(location, Placeable):
# give space for the drop-tip mechanism
# @TODO (Laura & Andy 2018261)
# When container typing is implemented, make sure that
# when returning to a tiprack, tips are dropped within the rack
if 'rack' in location.get_parent().get_type():
half_tip_length = self._tip_length / 2
location = location.top(-half_tip_length)
elif 'trash' in location.get_parent().get_type():
loc, coords = location.top()
location = (loc, coords + (0, self.model_offset[1], 0))
else:
location = location.top()
def _drop_tip(location, instrument=self):
if location:
self.move_to(location)
pos_bottom = self._get_plunger_position('bottom')
pos_drop_tip = self._get_plunger_position('drop_tip')
self.instrument_actuator.set_active_current(self._plunger_current)
self.robot.poses = self.instrument_actuator.move(
self.robot.poses,
x=pos_bottom
)
self.instrument_actuator.set_active_current(self._drop_tip_current)
self.instrument_actuator.push_speed()
self.instrument_actuator.set_speed(self._drop_tip_speed)
self.robot.poses = self.instrument_actuator.move(
self.robot.poses,
x=pos_drop_tip
)
self.instrument_actuator.pop_speed()
self._shake_off_tips(location)
if home_after:
self._home_after_drop_tip()
self.current_volume = 0
self.current_tip(None)
self._remove_tip(
length=self._tip_length
)
do_publish(self.broker, commands.drop_tip, self.drop_tip,
'before', None, None, self, location)
_drop_tip(location)
do_publish(self.broker, commands.drop_tip, self.drop_tip,
'after', self, None, self, location)
return self | [
"def",
"drop_tip",
"(",
"self",
",",
"location",
"=",
"None",
",",
"home_after",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"tip_attached",
":",
"log",
".",
"warning",
"(",
"\"Cannot drop tip without a tip attached.\"",
")",
"if",
"not",
"location",
"a... | Drop the pipette's current tip
Notes
-----
If no location is passed, the pipette defaults to its `trash_container`
(see :any:`Pipette`)
Parameters
----------
location : :any:`Placeable` or tuple(:any:`Placeable`, :any:`Vector`)
The :any:`Placeable` (:any:`Well`) to perform the drop_tip.
Can also be a tuple with first item :any:`Placeable`,
second item relative :any:`Vector`
Returns
-------
This instance of :class:`Pipette`.
Examples
--------
..
>>> from opentrons import instruments, labware, robot # doctest: +SKIP
>>> robot.reset() # doctest: +SKIP
>>> tiprack = labware.load('tiprack-200ul', 'C2') # doctest: +SKIP
>>> trash = labware.load('point', 'A3') # doctest: +SKIP
>>> p300 = instruments.P300_Single(mount='left') # doctest: +SKIP
>>> p300.pick_up_tip(tiprack[0]) # doctest: +SKIP
# drops the tip in the fixed trash
>>> p300.drop_tip() # doctest: +SKIP
>>> p300.pick_up_tip(tiprack[1]) # doctest: +SKIP
# drops the tip back at its tip rack
>>> p300.drop_tip(tiprack[1]) # doctest: +SKIP | [
"Drop",
"the",
"pipette",
"s",
"current",
"tip"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/instruments/pipette.py#L1025-L1116 | train | 198,181 |
Opentrons/opentrons | api/src/opentrons/legacy_api/instruments/pipette.py | Pipette.home | def home(self):
"""
Home the pipette's plunger axis during a protocol run
Notes
-----
`Pipette.home()` homes the `Robot`
Returns
-------
This instance of :class:`Pipette`.
Examples
--------
..
>>> from opentrons import instruments, robot # doctest: +SKIP
>>> robot.reset() # doctest: +SKIP
>>> p300 = instruments.P300_Single(mount='right') # doctest: +SKIP
>>> p300.home() # doctest: +SKIP
"""
def _home(mount):
self.current_volume = 0
self.instrument_actuator.set_active_current(self._plunger_current)
self.robot.poses = self.instrument_actuator.home(
self.robot.poses)
self.robot.poses = self.instrument_mover.home(self.robot.poses)
self.previous_placeable = None # no longer inside a placeable
do_publish(self.broker, commands.home, _home,
'before', None, None, self.mount)
_home(self.mount)
do_publish(self.broker, commands.home, _home,
'after', self, None, self.mount)
return self | python | def home(self):
"""
Home the pipette's plunger axis during a protocol run
Notes
-----
`Pipette.home()` homes the `Robot`
Returns
-------
This instance of :class:`Pipette`.
Examples
--------
..
>>> from opentrons import instruments, robot # doctest: +SKIP
>>> robot.reset() # doctest: +SKIP
>>> p300 = instruments.P300_Single(mount='right') # doctest: +SKIP
>>> p300.home() # doctest: +SKIP
"""
def _home(mount):
self.current_volume = 0
self.instrument_actuator.set_active_current(self._plunger_current)
self.robot.poses = self.instrument_actuator.home(
self.robot.poses)
self.robot.poses = self.instrument_mover.home(self.robot.poses)
self.previous_placeable = None # no longer inside a placeable
do_publish(self.broker, commands.home, _home,
'before', None, None, self.mount)
_home(self.mount)
do_publish(self.broker, commands.home, _home,
'after', self, None, self.mount)
return self | [
"def",
"home",
"(",
"self",
")",
":",
"def",
"_home",
"(",
"mount",
")",
":",
"self",
".",
"current_volume",
"=",
"0",
"self",
".",
"instrument_actuator",
".",
"set_active_current",
"(",
"self",
".",
"_plunger_current",
")",
"self",
".",
"robot",
".",
"p... | Home the pipette's plunger axis during a protocol run
Notes
-----
`Pipette.home()` homes the `Robot`
Returns
-------
This instance of :class:`Pipette`.
Examples
--------
..
>>> from opentrons import instruments, robot # doctest: +SKIP
>>> robot.reset() # doctest: +SKIP
>>> p300 = instruments.P300_Single(mount='right') # doctest: +SKIP
>>> p300.home() # doctest: +SKIP | [
"Home",
"the",
"pipette",
"s",
"plunger",
"axis",
"during",
"a",
"protocol",
"run"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/instruments/pipette.py#L1159-L1192 | train | 198,182 |
Opentrons/opentrons | api/src/opentrons/legacy_api/instruments/pipette.py | Pipette.calibrate_plunger | def calibrate_plunger(
self,
top=None,
bottom=None,
blow_out=None,
drop_tip=None):
"""Set calibration values for the pipette plunger.
This can be called multiple times as the user sets each value,
or you can set them all at once.
Parameters
----------
top : int
Touching but not engaging the plunger.
bottom: int
Must be above the pipette's physical hard-stop, while still
leaving enough room for 'blow_out'
blow_out : int
Plunger has been pushed down enough to expell all liquids.
drop_tip : int
This position that causes the tip to be released from the
pipette.
"""
if top is not None:
self.plunger_positions['top'] = top
if bottom is not None:
self.plunger_positions['bottom'] = bottom
if blow_out is not None:
self.plunger_positions['blow_out'] = blow_out
if drop_tip is not None:
self.plunger_positions['drop_tip'] = drop_tip
return self | python | def calibrate_plunger(
self,
top=None,
bottom=None,
blow_out=None,
drop_tip=None):
"""Set calibration values for the pipette plunger.
This can be called multiple times as the user sets each value,
or you can set them all at once.
Parameters
----------
top : int
Touching but not engaging the plunger.
bottom: int
Must be above the pipette's physical hard-stop, while still
leaving enough room for 'blow_out'
blow_out : int
Plunger has been pushed down enough to expell all liquids.
drop_tip : int
This position that causes the tip to be released from the
pipette.
"""
if top is not None:
self.plunger_positions['top'] = top
if bottom is not None:
self.plunger_positions['bottom'] = bottom
if blow_out is not None:
self.plunger_positions['blow_out'] = blow_out
if drop_tip is not None:
self.plunger_positions['drop_tip'] = drop_tip
return self | [
"def",
"calibrate_plunger",
"(",
"self",
",",
"top",
"=",
"None",
",",
"bottom",
"=",
"None",
",",
"blow_out",
"=",
"None",
",",
"drop_tip",
"=",
"None",
")",
":",
"if",
"top",
"is",
"not",
"None",
":",
"self",
".",
"plunger_positions",
"[",
"'top'",
... | Set calibration values for the pipette plunger.
This can be called multiple times as the user sets each value,
or you can set them all at once.
Parameters
----------
top : int
Touching but not engaging the plunger.
bottom: int
Must be above the pipette's physical hard-stop, while still
leaving enough room for 'blow_out'
blow_out : int
Plunger has been pushed down enough to expell all liquids.
drop_tip : int
This position that causes the tip to be released from the
pipette. | [
"Set",
"calibration",
"values",
"for",
"the",
"pipette",
"plunger",
"."
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/instruments/pipette.py#L1394-L1432 | train | 198,183 |
Opentrons/opentrons | api/src/opentrons/legacy_api/instruments/pipette.py | Pipette._get_plunger_position | def _get_plunger_position(self, position):
"""
Returns the calibrated coordinate of a given plunger position
Raises exception if the position has not been calibrated yet
"""
try:
value = self.plunger_positions[position]
if helpers.is_number(value):
return value
else:
raise RuntimeError(
'Plunger position "{}" not yet calibrated'.format(
position))
except KeyError:
raise RuntimeError(
'Plunger position "{}" does not exist'.format(
position)) | python | def _get_plunger_position(self, position):
"""
Returns the calibrated coordinate of a given plunger position
Raises exception if the position has not been calibrated yet
"""
try:
value = self.plunger_positions[position]
if helpers.is_number(value):
return value
else:
raise RuntimeError(
'Plunger position "{}" not yet calibrated'.format(
position))
except KeyError:
raise RuntimeError(
'Plunger position "{}" does not exist'.format(
position)) | [
"def",
"_get_plunger_position",
"(",
"self",
",",
"position",
")",
":",
"try",
":",
"value",
"=",
"self",
".",
"plunger_positions",
"[",
"position",
"]",
"if",
"helpers",
".",
"is_number",
"(",
"value",
")",
":",
"return",
"value",
"else",
":",
"raise",
... | Returns the calibrated coordinate of a given plunger position
Raises exception if the position has not been calibrated yet | [
"Returns",
"the",
"calibrated",
"coordinate",
"of",
"a",
"given",
"plunger",
"position"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/instruments/pipette.py#L1434-L1451 | train | 198,184 |
Opentrons/opentrons | api/src/opentrons/hardware_control/modules/magdeck.py | MagDeck.engage | def engage(self, height):
"""
Move the magnet to a specific height, in mm from home position
"""
if height > MAX_ENGAGE_HEIGHT or height < 0:
raise ValueError('Invalid engage height. Should be 0 to {}'.format(
MAX_ENGAGE_HEIGHT))
self._driver.move(height)
self._engaged = True | python | def engage(self, height):
"""
Move the magnet to a specific height, in mm from home position
"""
if height > MAX_ENGAGE_HEIGHT or height < 0:
raise ValueError('Invalid engage height. Should be 0 to {}'.format(
MAX_ENGAGE_HEIGHT))
self._driver.move(height)
self._engaged = True | [
"def",
"engage",
"(",
"self",
",",
"height",
")",
":",
"if",
"height",
">",
"MAX_ENGAGE_HEIGHT",
"or",
"height",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'Invalid engage height. Should be 0 to {}'",
".",
"format",
"(",
"MAX_ENGAGE_HEIGHT",
")",
")",
"self",
... | Move the magnet to a specific height, in mm from home position | [
"Move",
"the",
"magnet",
"to",
"a",
"specific",
"height",
"in",
"mm",
"from",
"home",
"position"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/hardware_control/modules/magdeck.py#L99-L107 | train | 198,185 |
Opentrons/opentrons | api/src/opentrons/helpers/helpers.py | break_down_travel | def break_down_travel(p1, target, increment=5, mode='absolute'):
"""
given two points p1 and target, this returns a list of
incremental positions or relative steps
"""
heading = target - p1
if mode == 'relative':
heading = target
length = heading.length()
length_steps = length / increment
length_remainder = length % increment
vector_step = Vector(0, 0, 0)
if length_steps > 0:
vector_step = heading / length_steps
vector_remainder = vector_step * (length_remainder / increment)
res = []
if mode == 'absolute':
for i in range(int(length_steps)):
p1 = p1 + vector_step
res.append(p1)
p1 = p1 + vector_remainder
res.append(p1)
else:
for i in range(int(length_steps)):
res.append(vector_step)
res.append(vector_remainder)
return res | python | def break_down_travel(p1, target, increment=5, mode='absolute'):
"""
given two points p1 and target, this returns a list of
incremental positions or relative steps
"""
heading = target - p1
if mode == 'relative':
heading = target
length = heading.length()
length_steps = length / increment
length_remainder = length % increment
vector_step = Vector(0, 0, 0)
if length_steps > 0:
vector_step = heading / length_steps
vector_remainder = vector_step * (length_remainder / increment)
res = []
if mode == 'absolute':
for i in range(int(length_steps)):
p1 = p1 + vector_step
res.append(p1)
p1 = p1 + vector_remainder
res.append(p1)
else:
for i in range(int(length_steps)):
res.append(vector_step)
res.append(vector_remainder)
return res | [
"def",
"break_down_travel",
"(",
"p1",
",",
"target",
",",
"increment",
"=",
"5",
",",
"mode",
"=",
"'absolute'",
")",
":",
"heading",
"=",
"target",
"-",
"p1",
"if",
"mode",
"==",
"'relative'",
":",
"heading",
"=",
"target",
"length",
"=",
"heading",
... | given two points p1 and target, this returns a list of
incremental positions or relative steps | [
"given",
"two",
"points",
"p1",
"and",
"target",
"this",
"returns",
"a",
"list",
"of",
"incremental",
"positions",
"or",
"relative",
"steps"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/helpers/helpers.py#L23-L53 | train | 198,186 |
Opentrons/opentrons | api/src/opentrons/helpers/helpers.py | _expand_for_carryover | def _expand_for_carryover(max_vol, plan, **kwargs):
"""
Divide volumes larger than maximum volume into separate transfers
"""
max_vol = float(max_vol)
carryover = kwargs.get('carryover', True)
if not carryover:
return plan
new_transfer_plan = []
for p in plan:
source = p['aspirate']['location']
target = p['dispense']['location']
volume = float(p['aspirate']['volume'])
while volume > max_vol * 2:
new_transfer_plan.append({
'aspirate': {'location': source, 'volume': max_vol},
'dispense': {'location': target, 'volume': max_vol}
})
volume -= max_vol
if volume > max_vol:
volume /= 2
new_transfer_plan.append({
'aspirate': {'location': source, 'volume': float(volume)},
'dispense': {'location': target, 'volume': float(volume)}
})
new_transfer_plan.append({
'aspirate': {'location': source, 'volume': float(volume)},
'dispense': {'location': target, 'volume': float(volume)}
})
return new_transfer_plan | python | def _expand_for_carryover(max_vol, plan, **kwargs):
"""
Divide volumes larger than maximum volume into separate transfers
"""
max_vol = float(max_vol)
carryover = kwargs.get('carryover', True)
if not carryover:
return plan
new_transfer_plan = []
for p in plan:
source = p['aspirate']['location']
target = p['dispense']['location']
volume = float(p['aspirate']['volume'])
while volume > max_vol * 2:
new_transfer_plan.append({
'aspirate': {'location': source, 'volume': max_vol},
'dispense': {'location': target, 'volume': max_vol}
})
volume -= max_vol
if volume > max_vol:
volume /= 2
new_transfer_plan.append({
'aspirate': {'location': source, 'volume': float(volume)},
'dispense': {'location': target, 'volume': float(volume)}
})
new_transfer_plan.append({
'aspirate': {'location': source, 'volume': float(volume)},
'dispense': {'location': target, 'volume': float(volume)}
})
return new_transfer_plan | [
"def",
"_expand_for_carryover",
"(",
"max_vol",
",",
"plan",
",",
"*",
"*",
"kwargs",
")",
":",
"max_vol",
"=",
"float",
"(",
"max_vol",
")",
"carryover",
"=",
"kwargs",
".",
"get",
"(",
"'carryover'",
",",
"True",
")",
"if",
"not",
"carryover",
":",
"... | Divide volumes larger than maximum volume into separate transfers | [
"Divide",
"volumes",
"larger",
"than",
"maximum",
"volume",
"into",
"separate",
"transfers"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/helpers/helpers.py#L112-L142 | train | 198,187 |
Opentrons/opentrons | api/src/opentrons/helpers/helpers.py | _compress_for_repeater | def _compress_for_repeater(max_vol, plan, **kwargs):
"""
Reduce size of transfer plan, if mode is distribute or consolidate
"""
max_vol = float(max_vol)
mode = kwargs.get('mode', 'transfer')
if mode == 'distribute': # combine target volumes into single aspirate
return _compress_for_distribute(max_vol, plan, **kwargs)
if mode == 'consolidate': # combine target volumes into multiple aspirates
return _compress_for_consolidate(max_vol, plan, **kwargs)
else:
return plan | python | def _compress_for_repeater(max_vol, plan, **kwargs):
"""
Reduce size of transfer plan, if mode is distribute or consolidate
"""
max_vol = float(max_vol)
mode = kwargs.get('mode', 'transfer')
if mode == 'distribute': # combine target volumes into single aspirate
return _compress_for_distribute(max_vol, plan, **kwargs)
if mode == 'consolidate': # combine target volumes into multiple aspirates
return _compress_for_consolidate(max_vol, plan, **kwargs)
else:
return plan | [
"def",
"_compress_for_repeater",
"(",
"max_vol",
",",
"plan",
",",
"*",
"*",
"kwargs",
")",
":",
"max_vol",
"=",
"float",
"(",
"max_vol",
")",
"mode",
"=",
"kwargs",
".",
"get",
"(",
"'mode'",
",",
"'transfer'",
")",
"if",
"mode",
"==",
"'distribute'",
... | Reduce size of transfer plan, if mode is distribute or consolidate | [
"Reduce",
"size",
"of",
"transfer",
"plan",
"if",
"mode",
"is",
"distribute",
"or",
"consolidate"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/helpers/helpers.py#L145-L156 | train | 198,188 |
Opentrons/opentrons | api/src/opentrons/helpers/helpers.py | _compress_for_distribute | def _compress_for_distribute(max_vol, plan, **kwargs):
"""
Combines as many dispenses as can fit within the maximum volume
"""
source = None
new_source = None
a_vol = 0
temp_dispenses = []
new_transfer_plan = []
disposal_vol = kwargs.get('disposal_vol', 0)
max_vol = max_vol - disposal_vol
def _append_dispenses():
nonlocal a_vol, temp_dispenses, new_transfer_plan, source
if not temp_dispenses:
return
added_volume = 0
if len(temp_dispenses) > 1:
added_volume = disposal_vol
new_transfer_plan.append({
'aspirate': {
'location': source,
'volume': a_vol + added_volume
}
})
for d in temp_dispenses:
new_transfer_plan.append({
'dispense': {
'location': d['location'],
'volume': d['volume']
}
})
a_vol = 0
temp_dispenses = []
for p in plan:
this_vol = p['aspirate']['volume']
new_source = p['aspirate']['location']
if (new_source is not source) or (this_vol + a_vol > max_vol):
_append_dispenses()
source = new_source
a_vol += this_vol
temp_dispenses.append(p['dispense'])
_append_dispenses()
return new_transfer_plan | python | def _compress_for_distribute(max_vol, plan, **kwargs):
"""
Combines as many dispenses as can fit within the maximum volume
"""
source = None
new_source = None
a_vol = 0
temp_dispenses = []
new_transfer_plan = []
disposal_vol = kwargs.get('disposal_vol', 0)
max_vol = max_vol - disposal_vol
def _append_dispenses():
nonlocal a_vol, temp_dispenses, new_transfer_plan, source
if not temp_dispenses:
return
added_volume = 0
if len(temp_dispenses) > 1:
added_volume = disposal_vol
new_transfer_plan.append({
'aspirate': {
'location': source,
'volume': a_vol + added_volume
}
})
for d in temp_dispenses:
new_transfer_plan.append({
'dispense': {
'location': d['location'],
'volume': d['volume']
}
})
a_vol = 0
temp_dispenses = []
for p in plan:
this_vol = p['aspirate']['volume']
new_source = p['aspirate']['location']
if (new_source is not source) or (this_vol + a_vol > max_vol):
_append_dispenses()
source = new_source
a_vol += this_vol
temp_dispenses.append(p['dispense'])
_append_dispenses()
return new_transfer_plan | [
"def",
"_compress_for_distribute",
"(",
"max_vol",
",",
"plan",
",",
"*",
"*",
"kwargs",
")",
":",
"source",
"=",
"None",
"new_source",
"=",
"None",
"a_vol",
"=",
"0",
"temp_dispenses",
"=",
"[",
"]",
"new_transfer_plan",
"=",
"[",
"]",
"disposal_vol",
"="... | Combines as many dispenses as can fit within the maximum volume | [
"Combines",
"as",
"many",
"dispenses",
"as",
"can",
"fit",
"within",
"the",
"maximum",
"volume"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/helpers/helpers.py#L159-L203 | train | 198,189 |
Opentrons/opentrons | api/src/opentrons/helpers/helpers.py | _compress_for_consolidate | def _compress_for_consolidate(max_vol, plan, **kwargs):
"""
Combines as many aspirates as can fit within the maximum volume
"""
target = None
new_target = None
d_vol = 0
temp_aspirates = []
new_transfer_plan = []
def _append_aspirates():
nonlocal d_vol, temp_aspirates, new_transfer_plan, target
if not temp_aspirates:
return
for a in temp_aspirates:
new_transfer_plan.append({
'aspirate': {
'location': a['location'], 'volume': a['volume']
}
})
new_transfer_plan.append({
'dispense': {
'location': target, 'volume': d_vol
}
})
d_vol = 0
temp_aspirates = []
for i, p in enumerate(plan):
this_vol = p['aspirate']['volume']
new_target = p['dispense']['location']
if (new_target is not target) or (this_vol + d_vol > max_vol):
_append_aspirates()
target = new_target
d_vol += this_vol
temp_aspirates.append(p['aspirate'])
_append_aspirates()
return new_transfer_plan | python | def _compress_for_consolidate(max_vol, plan, **kwargs):
"""
Combines as many aspirates as can fit within the maximum volume
"""
target = None
new_target = None
d_vol = 0
temp_aspirates = []
new_transfer_plan = []
def _append_aspirates():
nonlocal d_vol, temp_aspirates, new_transfer_plan, target
if not temp_aspirates:
return
for a in temp_aspirates:
new_transfer_plan.append({
'aspirate': {
'location': a['location'], 'volume': a['volume']
}
})
new_transfer_plan.append({
'dispense': {
'location': target, 'volume': d_vol
}
})
d_vol = 0
temp_aspirates = []
for i, p in enumerate(plan):
this_vol = p['aspirate']['volume']
new_target = p['dispense']['location']
if (new_target is not target) or (this_vol + d_vol > max_vol):
_append_aspirates()
target = new_target
d_vol += this_vol
temp_aspirates.append(p['aspirate'])
_append_aspirates()
return new_transfer_plan | [
"def",
"_compress_for_consolidate",
"(",
"max_vol",
",",
"plan",
",",
"*",
"*",
"kwargs",
")",
":",
"target",
"=",
"None",
"new_target",
"=",
"None",
"d_vol",
"=",
"0",
"temp_aspirates",
"=",
"[",
"]",
"new_transfer_plan",
"=",
"[",
"]",
"def",
"_append_as... | Combines as many aspirates as can fit within the maximum volume | [
"Combines",
"as",
"many",
"aspirates",
"as",
"can",
"fit",
"within",
"the",
"maximum",
"volume"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/helpers/helpers.py#L206-L243 | train | 198,190 |
Opentrons/opentrons | api/src/opentrons/config/advanced_settings.py | _migrate0to1 | def _migrate0to1(previous: Mapping[str, Any]) -> SettingsMap:
"""
Migrate to version 1 of the feature flags file. Replaces old IDs with new
IDs and sets any False values to None
"""
next: SettingsMap = {}
for s in settings:
id = s.id
old_id = s.old_id
if previous.get(id) is True:
next[id] = True
elif previous.get(old_id) is True:
next[id] = True
else:
next[id] = None
return next | python | def _migrate0to1(previous: Mapping[str, Any]) -> SettingsMap:
"""
Migrate to version 1 of the feature flags file. Replaces old IDs with new
IDs and sets any False values to None
"""
next: SettingsMap = {}
for s in settings:
id = s.id
old_id = s.old_id
if previous.get(id) is True:
next[id] = True
elif previous.get(old_id) is True:
next[id] = True
else:
next[id] = None
return next | [
"def",
"_migrate0to1",
"(",
"previous",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"SettingsMap",
":",
"next",
":",
"SettingsMap",
"=",
"{",
"}",
"for",
"s",
"in",
"settings",
":",
"id",
"=",
"s",
".",
"id",
"old_id",
"=",
"s",
".",
... | Migrate to version 1 of the feature flags file. Replaces old IDs with new
IDs and sets any False values to None | [
"Migrate",
"to",
"version",
"1",
"of",
"the",
"feature",
"flags",
"file",
".",
"Replaces",
"old",
"IDs",
"with",
"new",
"IDs",
"and",
"sets",
"any",
"False",
"values",
"to",
"None"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/config/advanced_settings.py#L172-L190 | train | 198,191 |
Opentrons/opentrons | api/src/opentrons/config/advanced_settings.py | _migrate | def _migrate(data: Mapping[str, Any]) -> SettingsData:
"""
Check the version integer of the JSON file data a run any necessary
migrations to get us to the latest file format. Returns dictionary of
settings and version migrated to
"""
next = dict(data)
version = next.pop('_version', 0)
target_version = len(_MIGRATIONS)
migrations = _MIGRATIONS[version:]
if len(migrations) > 0:
log.info(
"Migrating advanced settings from version {} to {}"
.format(version, target_version))
for m in migrations:
next = m(next)
return next, target_version | python | def _migrate(data: Mapping[str, Any]) -> SettingsData:
"""
Check the version integer of the JSON file data a run any necessary
migrations to get us to the latest file format. Returns dictionary of
settings and version migrated to
"""
next = dict(data)
version = next.pop('_version', 0)
target_version = len(_MIGRATIONS)
migrations = _MIGRATIONS[version:]
if len(migrations) > 0:
log.info(
"Migrating advanced settings from version {} to {}"
.format(version, target_version))
for m in migrations:
next = m(next)
return next, target_version | [
"def",
"_migrate",
"(",
"data",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"SettingsData",
":",
"next",
"=",
"dict",
"(",
"data",
")",
"version",
"=",
"next",
".",
"pop",
"(",
"'_version'",
",",
"0",
")",
"target_version",
"=",
"len",
... | Check the version integer of the JSON file data a run any necessary
migrations to get us to the latest file format. Returns dictionary of
settings and version migrated to | [
"Check",
"the",
"version",
"integer",
"of",
"the",
"JSON",
"file",
"data",
"a",
"run",
"any",
"necessary",
"migrations",
"to",
"get",
"us",
"to",
"the",
"latest",
"file",
"format",
".",
"Returns",
"dictionary",
"of",
"settings",
"and",
"version",
"migrated",... | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/config/advanced_settings.py#L201-L220 | train | 198,192 |
Opentrons/opentrons | update-server/otupdate/buildroot/config.py | _ensure_values | def _ensure_values(data: Mapping[str, Any]) -> Tuple[Dict[str, Any], bool]:
""" Make sure we have appropriate keys and say if we should write """
to_return = {}
should_write = False
for keyname, typekind, default in REQUIRED_DATA:
if keyname not in data:
LOG.debug(f"Defaulted config value {keyname} to {default}")
to_return[keyname] = default
should_write = True
elif not isinstance(data[keyname], typekind):
LOG.warning(
f"Config value {keyname} was {type(data[keyname])} not"
f" {typekind}, defaulted to {default}")
to_return[keyname] = default
should_write = True
else:
to_return[keyname] = data[keyname]
return to_return, should_write | python | def _ensure_values(data: Mapping[str, Any]) -> Tuple[Dict[str, Any], bool]:
""" Make sure we have appropriate keys and say if we should write """
to_return = {}
should_write = False
for keyname, typekind, default in REQUIRED_DATA:
if keyname not in data:
LOG.debug(f"Defaulted config value {keyname} to {default}")
to_return[keyname] = default
should_write = True
elif not isinstance(data[keyname], typekind):
LOG.warning(
f"Config value {keyname} was {type(data[keyname])} not"
f" {typekind}, defaulted to {default}")
to_return[keyname] = default
should_write = True
else:
to_return[keyname] = data[keyname]
return to_return, should_write | [
"def",
"_ensure_values",
"(",
"data",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Tuple",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"bool",
"]",
":",
"to_return",
"=",
"{",
"}",
"should_write",
"=",
"False",
"for",
"keyname",
",",... | Make sure we have appropriate keys and say if we should write | [
"Make",
"sure",
"we",
"have",
"appropriate",
"keys",
"and",
"say",
"if",
"we",
"should",
"write"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/buildroot/config.py#L58-L75 | train | 198,193 |
Opentrons/opentrons | update-server/otupdate/buildroot/config.py | load_from_path | def load_from_path(path: str) -> Config:
"""
Load a config from a file and ensure its structure.
Writes a default if necessary
"""
data = _ensure_load(path)
if not data:
data = {}
values, should_write = _ensure_values(data)
values.update({'path': path})
config = Config(**values)
if config.signature_required:
if not os.path.exists(config.update_cert_path):
LOG.warning(
f"No signing cert is present in {config.update_cert_path}, "
"code signature checking disabled")
config = config._replace(signature_required=False)
config = config._replace(update_cert_path=DEFAULT_CERT_PATH)
if should_write:
save_to_path(path, config)
return config | python | def load_from_path(path: str) -> Config:
"""
Load a config from a file and ensure its structure.
Writes a default if necessary
"""
data = _ensure_load(path)
if not data:
data = {}
values, should_write = _ensure_values(data)
values.update({'path': path})
config = Config(**values)
if config.signature_required:
if not os.path.exists(config.update_cert_path):
LOG.warning(
f"No signing cert is present in {config.update_cert_path}, "
"code signature checking disabled")
config = config._replace(signature_required=False)
config = config._replace(update_cert_path=DEFAULT_CERT_PATH)
if should_write:
save_to_path(path, config)
return config | [
"def",
"load_from_path",
"(",
"path",
":",
"str",
")",
"->",
"Config",
":",
"data",
"=",
"_ensure_load",
"(",
"path",
")",
"if",
"not",
"data",
":",
"data",
"=",
"{",
"}",
"values",
",",
"should_write",
"=",
"_ensure_values",
"(",
"data",
")",
"values"... | Load a config from a file and ensure its structure.
Writes a default if necessary | [
"Load",
"a",
"config",
"from",
"a",
"file",
"and",
"ensure",
"its",
"structure",
".",
"Writes",
"a",
"default",
"if",
"necessary"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/buildroot/config.py#L78-L98 | train | 198,194 |
Opentrons/opentrons | update-server/otupdate/buildroot/config.py | _get_path | def _get_path(args_path: Optional[str]) -> str:
""" Find the valid path from args then env then default """
env_path = os.getenv(PATH_ENVIRONMENT_VARIABLE)
for path, source in ((args_path, 'arg'),
(env_path, 'env')):
if not path:
LOG.debug(f"config.load: skipping {source} (path None)")
continue
else:
LOG.debug(f"config.load: using config path {path} from {source}")
return path
return DEFAULT_PATH | python | def _get_path(args_path: Optional[str]) -> str:
""" Find the valid path from args then env then default """
env_path = os.getenv(PATH_ENVIRONMENT_VARIABLE)
for path, source in ((args_path, 'arg'),
(env_path, 'env')):
if not path:
LOG.debug(f"config.load: skipping {source} (path None)")
continue
else:
LOG.debug(f"config.load: using config path {path} from {source}")
return path
return DEFAULT_PATH | [
"def",
"_get_path",
"(",
"args_path",
":",
"Optional",
"[",
"str",
"]",
")",
"->",
"str",
":",
"env_path",
"=",
"os",
".",
"getenv",
"(",
"PATH_ENVIRONMENT_VARIABLE",
")",
"for",
"path",
",",
"source",
"in",
"(",
"(",
"args_path",
",",
"'arg'",
")",
",... | Find the valid path from args then env then default | [
"Find",
"the",
"valid",
"path",
"from",
"args",
"then",
"env",
"then",
"default"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/buildroot/config.py#L101-L112 | train | 198,195 |
Opentrons/opentrons | update-server/otupdate/buildroot/update_session.py | UpdateSession.set_stage | def set_stage(self, stage: Stages):
""" Convenience method to set the stage and lookup message """
assert stage in Stages
LOG.info(f'Update session: stage {self._stage.name}->{stage.name}')
self._stage = stage | python | def set_stage(self, stage: Stages):
""" Convenience method to set the stage and lookup message """
assert stage in Stages
LOG.info(f'Update session: stage {self._stage.name}->{stage.name}')
self._stage = stage | [
"def",
"set_stage",
"(",
"self",
",",
"stage",
":",
"Stages",
")",
":",
"assert",
"stage",
"in",
"Stages",
"LOG",
".",
"info",
"(",
"f'Update session: stage {self._stage.name}->{stage.name}'",
")",
"self",
".",
"_stage",
"=",
"stage"
] | Convenience method to set the stage and lookup message | [
"Convenience",
"method",
"to",
"set",
"the",
"stage",
"and",
"lookup",
"message"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/buildroot/update_session.py#L51-L55 | train | 198,196 |
Opentrons/opentrons | update-server/otupdate/buildroot/update_session.py | UpdateSession.set_error | def set_error(self, error_shortmsg: str, error_longmsg: str):
""" Set the stage to error and add a message """
LOG.error(f"Update session: error in stage {self._stage.name}: "
f"{error_shortmsg}: {error_longmsg}")
self._error = Value(error_shortmsg, error_longmsg)
self.set_stage(Stages.ERROR) | python | def set_error(self, error_shortmsg: str, error_longmsg: str):
""" Set the stage to error and add a message """
LOG.error(f"Update session: error in stage {self._stage.name}: "
f"{error_shortmsg}: {error_longmsg}")
self._error = Value(error_shortmsg, error_longmsg)
self.set_stage(Stages.ERROR) | [
"def",
"set_error",
"(",
"self",
",",
"error_shortmsg",
":",
"str",
",",
"error_longmsg",
":",
"str",
")",
":",
"LOG",
".",
"error",
"(",
"f\"Update session: error in stage {self._stage.name}: \"",
"f\"{error_shortmsg}: {error_longmsg}\"",
")",
"self",
".",
"_error",
... | Set the stage to error and add a message | [
"Set",
"the",
"stage",
"to",
"error",
"and",
"add",
"a",
"message"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/buildroot/update_session.py#L57-L62 | train | 198,197 |
Opentrons/opentrons | update-server/otupdate/buildroot/update_session.py | UpdateSession.message | def message(self) -> str:
""" The human readable message of the current stage """
if self.is_error:
assert self._error
return self._error.human
else:
return self._stage.value.human | python | def message(self) -> str:
""" The human readable message of the current stage """
if self.is_error:
assert self._error
return self._error.human
else:
return self._stage.value.human | [
"def",
"message",
"(",
"self",
")",
"->",
"str",
":",
"if",
"self",
".",
"is_error",
":",
"assert",
"self",
".",
"_error",
"return",
"self",
".",
"_error",
".",
"human",
"else",
":",
"return",
"self",
".",
"_stage",
".",
"value",
".",
"human"
] | The human readable message of the current stage | [
"The",
"human",
"readable",
"message",
"of",
"the",
"current",
"stage"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/update-server/otupdate/buildroot/update_session.py#L100-L106 | train | 198,198 |
Opentrons/opentrons | api/src/opentrons/trackers/pose_tracker.py | descendants | def descendants(state, obj, level=0):
""" Returns a flattened list tuples of DFS traversal of subtree
from object that contains descendant object and it's depth """
return sum([
[(child, level)] + descendants(state, child, level + 1)
for child in state[obj].children
], []) | python | def descendants(state, obj, level=0):
""" Returns a flattened list tuples of DFS traversal of subtree
from object that contains descendant object and it's depth """
return sum([
[(child, level)] + descendants(state, child, level + 1)
for child in state[obj].children
], []) | [
"def",
"descendants",
"(",
"state",
",",
"obj",
",",
"level",
"=",
"0",
")",
":",
"return",
"sum",
"(",
"[",
"[",
"(",
"child",
",",
"level",
")",
"]",
"+",
"descendants",
"(",
"state",
",",
"child",
",",
"level",
"+",
"1",
")",
"for",
"child",
... | Returns a flattened list tuples of DFS traversal of subtree
from object that contains descendant object and it's depth | [
"Returns",
"a",
"flattened",
"list",
"tuples",
"of",
"DFS",
"traversal",
"of",
"subtree",
"from",
"object",
"that",
"contains",
"descendant",
"object",
"and",
"it",
"s",
"depth"
] | a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf | https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/trackers/pose_tracker.py#L112-L118 | train | 198,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.