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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
pyvisa/pyvisa | pyvisa/ctwrapper/functions.py | unmap_trigger | def unmap_trigger(library, session, trigger_source, trigger_destination):
"""Undo a previous map from the specified trigger source line to the specified destination line.
Corresponds to viUnmapTrigger function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param trigger_source: Source line used in previous map. (Constants.TRIG*)
:param trigger_destination: Destination line used in previous map. (Constants.TRIG*)
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
return library.viUnmapTrigger(session, trigger_source, trigger_destination) | python | def unmap_trigger(library, session, trigger_source, trigger_destination):
"""Undo a previous map from the specified trigger source line to the specified destination line.
Corresponds to viUnmapTrigger function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param trigger_source: Source line used in previous map. (Constants.TRIG*)
:param trigger_destination: Destination line used in previous map. (Constants.TRIG*)
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
return library.viUnmapTrigger(session, trigger_source, trigger_destination) | [
"def",
"unmap_trigger",
"(",
"library",
",",
"session",
",",
"trigger_source",
",",
"trigger_destination",
")",
":",
"return",
"library",
".",
"viUnmapTrigger",
"(",
"session",
",",
"trigger_source",
",",
"trigger_destination",
")"
] | Undo a previous map from the specified trigger source line to the specified destination line.
Corresponds to viUnmapTrigger function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param trigger_source: Source line used in previous map. (Constants.TRIG*)
:param trigger_destination: Destination line used in previous map. (Constants.TRIG*)
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode` | [
"Undo",
"a",
"previous",
"map",
"from",
"the",
"specified",
"trigger",
"source",
"line",
"to",
"the",
"specified",
"destination",
"line",
"."
] | b8b2d4371e1f00782856aa9176ff1ced6bcb3798 | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/ctwrapper/functions.py#L1745-L1757 | train | 228,900 |
pyvisa/pyvisa | pyvisa/ctwrapper/functions.py | usb_control_in | def usb_control_in(library, session, request_type_bitmap_field, request_id, request_value,
index, length=0):
"""Performs a USB control pipe transfer from the device.
Corresponds to viUsbControlIn function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param request_type_bitmap_field: bmRequestType parameter of the setup stage of a USB control transfer.
:param request_id: bRequest parameter of the setup stage of a USB control transfer.
:param request_value: wValue parameter of the setup stage of a USB control transfer.
:param index: wIndex parameter of the setup stage of a USB control transfer.
This is usually the index of the interface or endpoint.
:param length: wLength parameter of the setup stage of a USB control transfer.
This value also specifies the size of the data buffer to receive the data from the
optional data stage of the control transfer.
:return: - The data buffer that receives the data from the optional data stage of the control transfer
- return value of the library call.
:rtype: - bytes
- :class:`pyvisa.constants.StatusCode`
"""
buffer = create_string_buffer(length)
return_count = ViUInt16()
ret = library.viUsbControlIn(session, request_type_bitmap_field, request_id,
request_value, index, length, buffer,
byref(return_count))
return buffer.raw[:return_count.value], ret | python | def usb_control_in(library, session, request_type_bitmap_field, request_id, request_value,
index, length=0):
"""Performs a USB control pipe transfer from the device.
Corresponds to viUsbControlIn function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param request_type_bitmap_field: bmRequestType parameter of the setup stage of a USB control transfer.
:param request_id: bRequest parameter of the setup stage of a USB control transfer.
:param request_value: wValue parameter of the setup stage of a USB control transfer.
:param index: wIndex parameter of the setup stage of a USB control transfer.
This is usually the index of the interface or endpoint.
:param length: wLength parameter of the setup stage of a USB control transfer.
This value also specifies the size of the data buffer to receive the data from the
optional data stage of the control transfer.
:return: - The data buffer that receives the data from the optional data stage of the control transfer
- return value of the library call.
:rtype: - bytes
- :class:`pyvisa.constants.StatusCode`
"""
buffer = create_string_buffer(length)
return_count = ViUInt16()
ret = library.viUsbControlIn(session, request_type_bitmap_field, request_id,
request_value, index, length, buffer,
byref(return_count))
return buffer.raw[:return_count.value], ret | [
"def",
"usb_control_in",
"(",
"library",
",",
"session",
",",
"request_type_bitmap_field",
",",
"request_id",
",",
"request_value",
",",
"index",
",",
"length",
"=",
"0",
")",
":",
"buffer",
"=",
"create_string_buffer",
"(",
"length",
")",
"return_count",
"=",
... | Performs a USB control pipe transfer from the device.
Corresponds to viUsbControlIn function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param request_type_bitmap_field: bmRequestType parameter of the setup stage of a USB control transfer.
:param request_id: bRequest parameter of the setup stage of a USB control transfer.
:param request_value: wValue parameter of the setup stage of a USB control transfer.
:param index: wIndex parameter of the setup stage of a USB control transfer.
This is usually the index of the interface or endpoint.
:param length: wLength parameter of the setup stage of a USB control transfer.
This value also specifies the size of the data buffer to receive the data from the
optional data stage of the control transfer.
:return: - The data buffer that receives the data from the optional data stage of the control transfer
- return value of the library call.
:rtype: - bytes
- :class:`pyvisa.constants.StatusCode` | [
"Performs",
"a",
"USB",
"control",
"pipe",
"transfer",
"from",
"the",
"device",
"."
] | b8b2d4371e1f00782856aa9176ff1ced6bcb3798 | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/ctwrapper/functions.py#L1760-L1786 | train | 228,901 |
pyvisa/pyvisa | pyvisa/ctwrapper/functions.py | usb_control_out | def usb_control_out(library, session, request_type_bitmap_field, request_id, request_value,
index, data=""):
"""Performs a USB control pipe transfer to the device.
Corresponds to viUsbControlOut function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param request_type_bitmap_field: bmRequestType parameter of the setup stage of a USB control transfer.
:param request_id: bRequest parameter of the setup stage of a USB control transfer.
:param request_value: wValue parameter of the setup stage of a USB control transfer.
:param index: wIndex parameter of the setup stage of a USB control transfer.
This is usually the index of the interface or endpoint.
:param data: The data buffer that sends the data in the optional data stage of the control transfer.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
length = len(data)
return library.viUsbControlOut(session, request_type_bitmap_field, request_id,
request_value, index, length, data) | python | def usb_control_out(library, session, request_type_bitmap_field, request_id, request_value,
index, data=""):
"""Performs a USB control pipe transfer to the device.
Corresponds to viUsbControlOut function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param request_type_bitmap_field: bmRequestType parameter of the setup stage of a USB control transfer.
:param request_id: bRequest parameter of the setup stage of a USB control transfer.
:param request_value: wValue parameter of the setup stage of a USB control transfer.
:param index: wIndex parameter of the setup stage of a USB control transfer.
This is usually the index of the interface or endpoint.
:param data: The data buffer that sends the data in the optional data stage of the control transfer.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode`
"""
length = len(data)
return library.viUsbControlOut(session, request_type_bitmap_field, request_id,
request_value, index, length, data) | [
"def",
"usb_control_out",
"(",
"library",
",",
"session",
",",
"request_type_bitmap_field",
",",
"request_id",
",",
"request_value",
",",
"index",
",",
"data",
"=",
"\"\"",
")",
":",
"length",
"=",
"len",
"(",
"data",
")",
"return",
"library",
".",
"viUsbCon... | Performs a USB control pipe transfer to the device.
Corresponds to viUsbControlOut function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param request_type_bitmap_field: bmRequestType parameter of the setup stage of a USB control transfer.
:param request_id: bRequest parameter of the setup stage of a USB control transfer.
:param request_value: wValue parameter of the setup stage of a USB control transfer.
:param index: wIndex parameter of the setup stage of a USB control transfer.
This is usually the index of the interface or endpoint.
:param data: The data buffer that sends the data in the optional data stage of the control transfer.
:return: return value of the library call.
:rtype: :class:`pyvisa.constants.StatusCode` | [
"Performs",
"a",
"USB",
"control",
"pipe",
"transfer",
"to",
"the",
"device",
"."
] | b8b2d4371e1f00782856aa9176ff1ced6bcb3798 | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/ctwrapper/functions.py#L1789-L1808 | train | 228,902 |
pyvisa/pyvisa | pyvisa/ctwrapper/functions.py | wait_on_event | def wait_on_event(library, session, in_event_type, timeout):
"""Waits for an occurrence of the specified event for a given session.
Corresponds to viWaitOnEvent function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param in_event_type: Logical identifier of the event(s) to wait for.
:param timeout: Absolute time period in time units that the resource shall wait for a specified event to
occur before returning the time elapsed error. The time unit is in milliseconds.
:return: - Logical identifier of the event actually received
- A handle specifying the unique occurrence of an event
- return value of the library call.
:rtype: - eventtype
- event
- :class:`pyvisa.constants.StatusCode`
"""
out_event_type = ViEventType()
out_context = ViEvent()
ret = library.viWaitOnEvent(session, in_event_type, timeout,
byref(out_event_type), byref(out_context))
return out_event_type.value, out_context, ret | python | def wait_on_event(library, session, in_event_type, timeout):
"""Waits for an occurrence of the specified event for a given session.
Corresponds to viWaitOnEvent function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param in_event_type: Logical identifier of the event(s) to wait for.
:param timeout: Absolute time period in time units that the resource shall wait for a specified event to
occur before returning the time elapsed error. The time unit is in milliseconds.
:return: - Logical identifier of the event actually received
- A handle specifying the unique occurrence of an event
- return value of the library call.
:rtype: - eventtype
- event
- :class:`pyvisa.constants.StatusCode`
"""
out_event_type = ViEventType()
out_context = ViEvent()
ret = library.viWaitOnEvent(session, in_event_type, timeout,
byref(out_event_type), byref(out_context))
return out_event_type.value, out_context, ret | [
"def",
"wait_on_event",
"(",
"library",
",",
"session",
",",
"in_event_type",
",",
"timeout",
")",
":",
"out_event_type",
"=",
"ViEventType",
"(",
")",
"out_context",
"=",
"ViEvent",
"(",
")",
"ret",
"=",
"library",
".",
"viWaitOnEvent",
"(",
"session",
",",... | Waits for an occurrence of the specified event for a given session.
Corresponds to viWaitOnEvent function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param in_event_type: Logical identifier of the event(s) to wait for.
:param timeout: Absolute time period in time units that the resource shall wait for a specified event to
occur before returning the time elapsed error. The time unit is in milliseconds.
:return: - Logical identifier of the event actually received
- A handle specifying the unique occurrence of an event
- return value of the library call.
:rtype: - eventtype
- event
- :class:`pyvisa.constants.StatusCode` | [
"Waits",
"for",
"an",
"occurrence",
"of",
"the",
"specified",
"event",
"for",
"a",
"given",
"session",
"."
] | b8b2d4371e1f00782856aa9176ff1ced6bcb3798 | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/ctwrapper/functions.py#L1828-L1849 | train | 228,903 |
pyvisa/pyvisa | pyvisa/ctwrapper/functions.py | write_asynchronously | def write_asynchronously(library, session, data):
"""Writes data to device or interface asynchronously.
Corresponds to viWriteAsync function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param data: data to be written.
:return: Job ID of this asynchronous write operation, return value of the library call.
:rtype: jobid, :class:`pyvisa.constants.StatusCode`
"""
job_id = ViJobId()
# [ViSession, ViBuf, ViUInt32, ViPJobId]
ret = library.viWriteAsync(session, data, len(data), byref(job_id))
return job_id, ret | python | def write_asynchronously(library, session, data):
"""Writes data to device or interface asynchronously.
Corresponds to viWriteAsync function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param data: data to be written.
:return: Job ID of this asynchronous write operation, return value of the library call.
:rtype: jobid, :class:`pyvisa.constants.StatusCode`
"""
job_id = ViJobId()
# [ViSession, ViBuf, ViUInt32, ViPJobId]
ret = library.viWriteAsync(session, data, len(data), byref(job_id))
return job_id, ret | [
"def",
"write_asynchronously",
"(",
"library",
",",
"session",
",",
"data",
")",
":",
"job_id",
"=",
"ViJobId",
"(",
")",
"# [ViSession, ViBuf, ViUInt32, ViPJobId]",
"ret",
"=",
"library",
".",
"viWriteAsync",
"(",
"session",
",",
"data",
",",
"len",
"(",
"dat... | Writes data to device or interface asynchronously.
Corresponds to viWriteAsync function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param data: data to be written.
:return: Job ID of this asynchronous write operation, return value of the library call.
:rtype: jobid, :class:`pyvisa.constants.StatusCode` | [
"Writes",
"data",
"to",
"device",
"or",
"interface",
"asynchronously",
"."
] | b8b2d4371e1f00782856aa9176ff1ced6bcb3798 | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/ctwrapper/functions.py#L1870-L1884 | train | 228,904 |
pyvisa/pyvisa | pyvisa/ctwrapper/functions.py | write_from_file | def write_from_file(library, session, filename, count):
"""Take data from a file and write it out synchronously.
Corresponds to viWriteFromFile function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param filename: Name of file from which data will be read.
:param count: Number of bytes to be written.
:return: Number of bytes actually transferred, return value of the library call.
:rtype: int, :class:`pyvisa.constants.StatusCode`
"""
return_count = ViUInt32()
ret = library.viWriteFromFile(session, filename, count, return_count)
return return_count, ret | python | def write_from_file(library, session, filename, count):
"""Take data from a file and write it out synchronously.
Corresponds to viWriteFromFile function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param filename: Name of file from which data will be read.
:param count: Number of bytes to be written.
:return: Number of bytes actually transferred, return value of the library call.
:rtype: int, :class:`pyvisa.constants.StatusCode`
"""
return_count = ViUInt32()
ret = library.viWriteFromFile(session, filename, count, return_count)
return return_count, ret | [
"def",
"write_from_file",
"(",
"library",
",",
"session",
",",
"filename",
",",
"count",
")",
":",
"return_count",
"=",
"ViUInt32",
"(",
")",
"ret",
"=",
"library",
".",
"viWriteFromFile",
"(",
"session",
",",
"filename",
",",
"count",
",",
"return_count",
... | Take data from a file and write it out synchronously.
Corresponds to viWriteFromFile function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param filename: Name of file from which data will be read.
:param count: Number of bytes to be written.
:return: Number of bytes actually transferred, return value of the library call.
:rtype: int, :class:`pyvisa.constants.StatusCode` | [
"Take",
"data",
"from",
"a",
"file",
"and",
"write",
"it",
"out",
"synchronously",
"."
] | b8b2d4371e1f00782856aa9176ff1ced6bcb3798 | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/ctwrapper/functions.py#L1887-L1901 | train | 228,905 |
pyvisa/pyvisa | pyvisa/attributes.py | Attribute.in_resource | def in_resource(cls, session_type):
"""Returns True if the attribute is part of a given session type.
The session_type is a tuple with the interface type and resource_class
:type session_type: (constants.InterfaceType, str)
:rtype: bool
"""
if cls.resources is AllSessionTypes:
return True
return session_type in cls.resources | python | def in_resource(cls, session_type):
"""Returns True if the attribute is part of a given session type.
The session_type is a tuple with the interface type and resource_class
:type session_type: (constants.InterfaceType, str)
:rtype: bool
"""
if cls.resources is AllSessionTypes:
return True
return session_type in cls.resources | [
"def",
"in_resource",
"(",
"cls",
",",
"session_type",
")",
":",
"if",
"cls",
".",
"resources",
"is",
"AllSessionTypes",
":",
"return",
"True",
"return",
"session_type",
"in",
"cls",
".",
"resources"
] | Returns True if the attribute is part of a given session type.
The session_type is a tuple with the interface type and resource_class
:type session_type: (constants.InterfaceType, str)
:rtype: bool | [
"Returns",
"True",
"if",
"the",
"attribute",
"is",
"part",
"of",
"a",
"given",
"session",
"type",
"."
] | b8b2d4371e1f00782856aa9176ff1ced6bcb3798 | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/attributes.py#L116-L126 | train | 228,906 |
pyvisa/pyvisa | pyvisa/shell.py | VisaShell.do_list | def do_list(self, args):
"""List all connected resources."""
try:
resources = self.resource_manager.list_resources_info()
except Exception as e:
print(e)
else:
self.resources = []
for ndx, (resource_name, value) in enumerate(resources.items()):
if not args:
print('({0:2d}) {1}'.format(ndx, resource_name))
if value.alias:
print(' alias: {}'.format(value.alias))
self.resources.append((resource_name, value.alias or None)) | python | def do_list(self, args):
"""List all connected resources."""
try:
resources = self.resource_manager.list_resources_info()
except Exception as e:
print(e)
else:
self.resources = []
for ndx, (resource_name, value) in enumerate(resources.items()):
if not args:
print('({0:2d}) {1}'.format(ndx, resource_name))
if value.alias:
print(' alias: {}'.format(value.alias))
self.resources.append((resource_name, value.alias or None)) | [
"def",
"do_list",
"(",
"self",
",",
"args",
")",
":",
"try",
":",
"resources",
"=",
"self",
".",
"resource_manager",
".",
"list_resources_info",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"e",
")",
"else",
":",
"self",
".",
"resourc... | List all connected resources. | [
"List",
"all",
"connected",
"resources",
"."
] | b8b2d4371e1f00782856aa9176ff1ced6bcb3798 | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/shell.py#L121-L136 | train | 228,907 |
pyvisa/pyvisa | pyvisa/shell.py | VisaShell.do_close | def do_close(self, args):
"""Close resource in use."""
if not self.current:
print('There are no resources in use. Use the command "open".')
return
try:
self.current.close()
except Exception as e:
print(e)
else:
print('The resource has been closed.')
self.current = None
self.prompt = self.default_prompt | python | def do_close(self, args):
"""Close resource in use."""
if not self.current:
print('There are no resources in use. Use the command "open".')
return
try:
self.current.close()
except Exception as e:
print(e)
else:
print('The resource has been closed.')
self.current = None
self.prompt = self.default_prompt | [
"def",
"do_close",
"(",
"self",
",",
"args",
")",
":",
"if",
"not",
"self",
".",
"current",
":",
"print",
"(",
"'There are no resources in use. Use the command \"open\".'",
")",
"return",
"try",
":",
"self",
".",
"current",
".",
"close",
"(",
")",
"except",
... | Close resource in use. | [
"Close",
"resource",
"in",
"use",
"."
] | b8b2d4371e1f00782856aa9176ff1ced6bcb3798 | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/shell.py#L179-L193 | train | 228,908 |
pyvisa/pyvisa | pyvisa/shell.py | VisaShell.do_read | def do_read(self, args):
"""Receive from the resource in use."""
if not self.current:
print('There are no resources in use. Use the command "open".')
return
try:
print(self.current.read())
except Exception as e:
print(e) | python | def do_read(self, args):
"""Receive from the resource in use."""
if not self.current:
print('There are no resources in use. Use the command "open".')
return
try:
print(self.current.read())
except Exception as e:
print(e) | [
"def",
"do_read",
"(",
"self",
",",
"args",
")",
":",
"if",
"not",
"self",
".",
"current",
":",
"print",
"(",
"'There are no resources in use. Use the command \"open\".'",
")",
"return",
"try",
":",
"print",
"(",
"self",
".",
"current",
".",
"read",
"(",
")"... | Receive from the resource in use. | [
"Receive",
"from",
"the",
"resource",
"in",
"use",
"."
] | b8b2d4371e1f00782856aa9176ff1ced6bcb3798 | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/shell.py#L207-L217 | train | 228,909 |
pyvisa/pyvisa | pyvisa/shell.py | VisaShell.do_attr | def do_attr(self, args):
"""Get or set the state for a visa attribute.
List all attributes:
attr
Get an attribute state:
attr <name>
Set an attribute state:
attr <name> <state>
"""
if not self.current:
print('There are no resources in use. Use the command "open".')
return
args = args.strip()
if not args:
self.print_attribute_list()
return
args = args.split(' ')
if len(args) > 2:
print('Invalid syntax, use `attr <name>` to get; or `attr <name> <value>` to set')
elif len(args) == 1:
# Get
attr_name = args[0]
if attr_name.startswith('VI_'):
try:
print(self.current.get_visa_attribute(getattr(constants, attr_name)))
except Exception as e:
print(e)
else:
try:
print(getattr(self.current, attr_name))
except Exception as e:
print(e)
else:
attr_name, attr_state = args[0], args[1]
if attr_name.startswith('VI_'):
try:
attributeId = getattr(constants, attr_name)
attr = attributes.AttributesByID[attributeId]
datatype = attr.visa_type
retcode = None
if datatype == 'ViBoolean':
if attr_state == 'True':
attr_state = True
elif attr_state == 'False':
attr_state = False
else:
retcode = constants.StatusCode.error_nonsupported_attribute_state
elif datatype in ['ViUInt8', 'ViUInt16', 'ViUInt32', 'ViInt8', 'ViInt16', 'ViInt32']:
try:
attr_state = int(attr_state)
except ValueError:
retcode = constants.StatusCode.error_nonsupported_attribute_state
if not retcode:
retcode = self.current.set_visa_attribute(attributeId, attr_state)
if retcode:
print('Error {}'.format(str(retcode)))
else:
print('Done')
except Exception as e:
print(e)
else:
print('Setting Resource Attributes by python name is not yet supported.')
return
try:
print(getattr(self.current, attr_name))
print('Done')
except Exception as e:
print(e) | python | def do_attr(self, args):
"""Get or set the state for a visa attribute.
List all attributes:
attr
Get an attribute state:
attr <name>
Set an attribute state:
attr <name> <state>
"""
if not self.current:
print('There are no resources in use. Use the command "open".')
return
args = args.strip()
if not args:
self.print_attribute_list()
return
args = args.split(' ')
if len(args) > 2:
print('Invalid syntax, use `attr <name>` to get; or `attr <name> <value>` to set')
elif len(args) == 1:
# Get
attr_name = args[0]
if attr_name.startswith('VI_'):
try:
print(self.current.get_visa_attribute(getattr(constants, attr_name)))
except Exception as e:
print(e)
else:
try:
print(getattr(self.current, attr_name))
except Exception as e:
print(e)
else:
attr_name, attr_state = args[0], args[1]
if attr_name.startswith('VI_'):
try:
attributeId = getattr(constants, attr_name)
attr = attributes.AttributesByID[attributeId]
datatype = attr.visa_type
retcode = None
if datatype == 'ViBoolean':
if attr_state == 'True':
attr_state = True
elif attr_state == 'False':
attr_state = False
else:
retcode = constants.StatusCode.error_nonsupported_attribute_state
elif datatype in ['ViUInt8', 'ViUInt16', 'ViUInt32', 'ViInt8', 'ViInt16', 'ViInt32']:
try:
attr_state = int(attr_state)
except ValueError:
retcode = constants.StatusCode.error_nonsupported_attribute_state
if not retcode:
retcode = self.current.set_visa_attribute(attributeId, attr_state)
if retcode:
print('Error {}'.format(str(retcode)))
else:
print('Done')
except Exception as e:
print(e)
else:
print('Setting Resource Attributes by python name is not yet supported.')
return
try:
print(getattr(self.current, attr_name))
print('Done')
except Exception as e:
print(e) | [
"def",
"do_attr",
"(",
"self",
",",
"args",
")",
":",
"if",
"not",
"self",
".",
"current",
":",
"print",
"(",
"'There are no resources in use. Use the command \"open\".'",
")",
"return",
"args",
"=",
"args",
".",
"strip",
"(",
")",
"if",
"not",
"args",
":",
... | Get or set the state for a visa attribute.
List all attributes:
attr
Get an attribute state:
attr <name>
Set an attribute state:
attr <name> <state> | [
"Get",
"or",
"set",
"the",
"state",
"for",
"a",
"visa",
"attribute",
"."
] | b8b2d4371e1f00782856aa9176ff1ced6bcb3798 | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/shell.py#L278-L356 | train | 228,910 |
pyvisa/pyvisa | pyvisa/shell.py | VisaShell.do_exit | def do_exit(self, arg):
"""Exit the shell session."""
if self.current:
self.current.close()
self.resource_manager.close()
del self.resource_manager
return True | python | def do_exit(self, arg):
"""Exit the shell session."""
if self.current:
self.current.close()
self.resource_manager.close()
del self.resource_manager
return True | [
"def",
"do_exit",
"(",
"self",
",",
"arg",
")",
":",
"if",
"self",
".",
"current",
":",
"self",
".",
"current",
".",
"close",
"(",
")",
"self",
".",
"resource_manager",
".",
"close",
"(",
")",
"del",
"self",
".",
"resource_manager",
"return",
"True"
] | Exit the shell session. | [
"Exit",
"the",
"shell",
"session",
"."
] | b8b2d4371e1f00782856aa9176ff1ced6bcb3798 | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/shell.py#L411-L418 | train | 228,911 |
pyvisa/pyvisa | pyvisa/resources/resource.py | Resource.resource_info | def resource_info(self):
"""Get the extended information of this resource.
:param resource_name: Unique symbolic name of a resource.
:rtype: :class:`pyvisa.highlevel.ResourceInfo`
"""
return self.visalib.parse_resource_extended(self._resource_manager.session, self.resource_name) | python | def resource_info(self):
"""Get the extended information of this resource.
:param resource_name: Unique symbolic name of a resource.
:rtype: :class:`pyvisa.highlevel.ResourceInfo`
"""
return self.visalib.parse_resource_extended(self._resource_manager.session, self.resource_name) | [
"def",
"resource_info",
"(",
"self",
")",
":",
"return",
"self",
".",
"visalib",
".",
"parse_resource_extended",
"(",
"self",
".",
"_resource_manager",
".",
"session",
",",
"self",
".",
"resource_name",
")"
] | Get the extended information of this resource.
:param resource_name: Unique symbolic name of a resource.
:rtype: :class:`pyvisa.highlevel.ResourceInfo` | [
"Get",
"the",
"extended",
"information",
"of",
"this",
"resource",
"."
] | b8b2d4371e1f00782856aa9176ff1ced6bcb3798 | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/resources/resource.py#L176-L183 | train | 228,912 |
pyvisa/pyvisa | pyvisa/resources/resource.py | Resource.interface_type | def interface_type(self):
"""The interface type of the resource as a number.
"""
return self.visalib.parse_resource(self._resource_manager.session,
self.resource_name)[0].interface_type | python | def interface_type(self):
"""The interface type of the resource as a number.
"""
return self.visalib.parse_resource(self._resource_manager.session,
self.resource_name)[0].interface_type | [
"def",
"interface_type",
"(",
"self",
")",
":",
"return",
"self",
".",
"visalib",
".",
"parse_resource",
"(",
"self",
".",
"_resource_manager",
".",
"session",
",",
"self",
".",
"resource_name",
")",
"[",
"0",
"]",
".",
"interface_type"
] | The interface type of the resource as a number. | [
"The",
"interface",
"type",
"of",
"the",
"resource",
"as",
"a",
"number",
"."
] | b8b2d4371e1f00782856aa9176ff1ced6bcb3798 | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/resources/resource.py#L186-L190 | train | 228,913 |
pyvisa/pyvisa | pyvisa/resources/resource.py | Resource.close | def close(self):
"""Closes the VISA session and marks the handle as invalid.
"""
try:
logger.debug('%s - closing', self._resource_name,
extra=self._logging_extra)
self.before_close()
self.visalib.close(self.session)
logger.debug('%s - is closed', self._resource_name,
extra=self._logging_extra)
self.session = None
except errors.InvalidSession:
pass | python | def close(self):
"""Closes the VISA session and marks the handle as invalid.
"""
try:
logger.debug('%s - closing', self._resource_name,
extra=self._logging_extra)
self.before_close()
self.visalib.close(self.session)
logger.debug('%s - is closed', self._resource_name,
extra=self._logging_extra)
self.session = None
except errors.InvalidSession:
pass | [
"def",
"close",
"(",
"self",
")",
":",
"try",
":",
"logger",
".",
"debug",
"(",
"'%s - closing'",
",",
"self",
".",
"_resource_name",
",",
"extra",
"=",
"self",
".",
"_logging_extra",
")",
"self",
".",
"before_close",
"(",
")",
"self",
".",
"visalib",
... | Closes the VISA session and marks the handle as invalid. | [
"Closes",
"the",
"VISA",
"session",
"and",
"marks",
"the",
"handle",
"as",
"invalid",
"."
] | b8b2d4371e1f00782856aa9176ff1ced6bcb3798 | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/resources/resource.py#L238-L250 | train | 228,914 |
pyvisa/pyvisa | pyvisa/resources/resource.py | Resource.install_handler | def install_handler(self, event_type, handler, user_handle=None):
"""Installs handlers for event callbacks in this resource.
:param event_type: Logical event identifier.
:param handler: Interpreted as a valid reference to a handler to be installed by a client application.
:param user_handle: A value specified by an application that can be used for identifying handlers
uniquely for an event type.
:returns: user handle (a ctypes object)
"""
return self.visalib.install_visa_handler(self.session, event_type, handler, user_handle) | python | def install_handler(self, event_type, handler, user_handle=None):
"""Installs handlers for event callbacks in this resource.
:param event_type: Logical event identifier.
:param handler: Interpreted as a valid reference to a handler to be installed by a client application.
:param user_handle: A value specified by an application that can be used for identifying handlers
uniquely for an event type.
:returns: user handle (a ctypes object)
"""
return self.visalib.install_visa_handler(self.session, event_type, handler, user_handle) | [
"def",
"install_handler",
"(",
"self",
",",
"event_type",
",",
"handler",
",",
"user_handle",
"=",
"None",
")",
":",
"return",
"self",
".",
"visalib",
".",
"install_visa_handler",
"(",
"self",
".",
"session",
",",
"event_type",
",",
"handler",
",",
"user_han... | Installs handlers for event callbacks in this resource.
:param event_type: Logical event identifier.
:param handler: Interpreted as a valid reference to a handler to be installed by a client application.
:param user_handle: A value specified by an application that can be used for identifying handlers
uniquely for an event type.
:returns: user handle (a ctypes object) | [
"Installs",
"handlers",
"for",
"event",
"callbacks",
"in",
"this",
"resource",
"."
] | b8b2d4371e1f00782856aa9176ff1ced6bcb3798 | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/resources/resource.py#L281-L291 | train | 228,915 |
pyvisa/pyvisa | pyvisa/resources/resource.py | Resource.uninstall_handler | def uninstall_handler(self, event_type, handler, user_handle=None):
"""Uninstalls handlers for events in this resource.
:param event_type: Logical event identifier.
:param handler: Interpreted as a valid reference to a handler to be uninstalled by a client application.
:param user_handle: The user handle (ctypes object or None) returned by install_handler.
"""
self.visalib.uninstall_visa_handler(self.session, event_type, handler, user_handle) | python | def uninstall_handler(self, event_type, handler, user_handle=None):
"""Uninstalls handlers for events in this resource.
:param event_type: Logical event identifier.
:param handler: Interpreted as a valid reference to a handler to be uninstalled by a client application.
:param user_handle: The user handle (ctypes object or None) returned by install_handler.
"""
self.visalib.uninstall_visa_handler(self.session, event_type, handler, user_handle) | [
"def",
"uninstall_handler",
"(",
"self",
",",
"event_type",
",",
"handler",
",",
"user_handle",
"=",
"None",
")",
":",
"self",
".",
"visalib",
".",
"uninstall_visa_handler",
"(",
"self",
".",
"session",
",",
"event_type",
",",
"handler",
",",
"user_handle",
... | Uninstalls handlers for events in this resource.
:param event_type: Logical event identifier.
:param handler: Interpreted as a valid reference to a handler to be uninstalled by a client application.
:param user_handle: The user handle (ctypes object or None) returned by install_handler. | [
"Uninstalls",
"handlers",
"for",
"events",
"in",
"this",
"resource",
"."
] | b8b2d4371e1f00782856aa9176ff1ced6bcb3798 | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/resources/resource.py#L293-L301 | train | 228,916 |
pyvisa/pyvisa | pyvisa/resources/resource.py | Resource.discard_events | def discard_events(self, event_type, mechanism):
"""Discards event occurrences for specified event types and mechanisms in this resource.
:param event_type: Logical event identifier.
:param mechanism: Specifies event handling mechanisms to be dicarded.
(Constants.VI_QUEUE, .VI_HNDLR, .VI_SUSPEND_HNDLR, .VI_ALL_MECH)
"""
self.visalib.discard_events(self.session, event_type, mechanism) | python | def discard_events(self, event_type, mechanism):
"""Discards event occurrences for specified event types and mechanisms in this resource.
:param event_type: Logical event identifier.
:param mechanism: Specifies event handling mechanisms to be dicarded.
(Constants.VI_QUEUE, .VI_HNDLR, .VI_SUSPEND_HNDLR, .VI_ALL_MECH)
"""
self.visalib.discard_events(self.session, event_type, mechanism) | [
"def",
"discard_events",
"(",
"self",
",",
"event_type",
",",
"mechanism",
")",
":",
"self",
".",
"visalib",
".",
"discard_events",
"(",
"self",
".",
"session",
",",
"event_type",
",",
"mechanism",
")"
] | Discards event occurrences for specified event types and mechanisms in this resource.
:param event_type: Logical event identifier.
:param mechanism: Specifies event handling mechanisms to be dicarded.
(Constants.VI_QUEUE, .VI_HNDLR, .VI_SUSPEND_HNDLR, .VI_ALL_MECH) | [
"Discards",
"event",
"occurrences",
"for",
"specified",
"event",
"types",
"and",
"mechanisms",
"in",
"this",
"resource",
"."
] | b8b2d4371e1f00782856aa9176ff1ced6bcb3798 | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/resources/resource.py#L312-L319 | train | 228,917 |
pyvisa/pyvisa | pyvisa/resources/resource.py | Resource.enable_event | def enable_event(self, event_type, mechanism, context=None):
"""Enable event occurrences for specified event types and mechanisms in this resource.
:param event_type: Logical event identifier.
:param mechanism: Specifies event handling mechanisms to be enabled.
(Constants.VI_QUEUE, .VI_HNDLR, .VI_SUSPEND_HNDLR)
:param context: Not currently used, leave as None.
"""
self.visalib.enable_event(self.session, event_type, mechanism, context) | python | def enable_event(self, event_type, mechanism, context=None):
"""Enable event occurrences for specified event types and mechanisms in this resource.
:param event_type: Logical event identifier.
:param mechanism: Specifies event handling mechanisms to be enabled.
(Constants.VI_QUEUE, .VI_HNDLR, .VI_SUSPEND_HNDLR)
:param context: Not currently used, leave as None.
"""
self.visalib.enable_event(self.session, event_type, mechanism, context) | [
"def",
"enable_event",
"(",
"self",
",",
"event_type",
",",
"mechanism",
",",
"context",
"=",
"None",
")",
":",
"self",
".",
"visalib",
".",
"enable_event",
"(",
"self",
".",
"session",
",",
"event_type",
",",
"mechanism",
",",
"context",
")"
] | Enable event occurrences for specified event types and mechanisms in this resource.
:param event_type: Logical event identifier.
:param mechanism: Specifies event handling mechanisms to be enabled.
(Constants.VI_QUEUE, .VI_HNDLR, .VI_SUSPEND_HNDLR)
:param context: Not currently used, leave as None. | [
"Enable",
"event",
"occurrences",
"for",
"specified",
"event",
"types",
"and",
"mechanisms",
"in",
"this",
"resource",
"."
] | b8b2d4371e1f00782856aa9176ff1ced6bcb3798 | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/resources/resource.py#L321-L329 | train | 228,918 |
pyvisa/pyvisa | pyvisa/resources/resource.py | Resource.wait_on_event | def wait_on_event(self, in_event_type, timeout, capture_timeout=False):
"""Waits for an occurrence of the specified event in this resource.
:param in_event_type: Logical identifier of the event(s) to wait for.
:param timeout: Absolute time period in time units that the resource shall wait for a specified event to
occur before returning the time elapsed error. The time unit is in milliseconds.
None means waiting forever if necessary.
:param capture_timeout: When True will not produce a VisaIOError(VI_ERROR_TMO) but
instead return a WaitResponse with timed_out=True
:return: A WaitResponse object that contains event_type, context and ret value.
"""
try:
event_type, context, ret = self.visalib.wait_on_event(self.session, in_event_type, timeout)
except errors.VisaIOError as exc:
if capture_timeout and exc.error_code == constants.StatusCode.error_timeout:
return WaitResponse(in_event_type, None, exc.error_code, self.visalib, timed_out=True)
raise
return WaitResponse(event_type, context, ret, self.visalib) | python | def wait_on_event(self, in_event_type, timeout, capture_timeout=False):
"""Waits for an occurrence of the specified event in this resource.
:param in_event_type: Logical identifier of the event(s) to wait for.
:param timeout: Absolute time period in time units that the resource shall wait for a specified event to
occur before returning the time elapsed error. The time unit is in milliseconds.
None means waiting forever if necessary.
:param capture_timeout: When True will not produce a VisaIOError(VI_ERROR_TMO) but
instead return a WaitResponse with timed_out=True
:return: A WaitResponse object that contains event_type, context and ret value.
"""
try:
event_type, context, ret = self.visalib.wait_on_event(self.session, in_event_type, timeout)
except errors.VisaIOError as exc:
if capture_timeout and exc.error_code == constants.StatusCode.error_timeout:
return WaitResponse(in_event_type, None, exc.error_code, self.visalib, timed_out=True)
raise
return WaitResponse(event_type, context, ret, self.visalib) | [
"def",
"wait_on_event",
"(",
"self",
",",
"in_event_type",
",",
"timeout",
",",
"capture_timeout",
"=",
"False",
")",
":",
"try",
":",
"event_type",
",",
"context",
",",
"ret",
"=",
"self",
".",
"visalib",
".",
"wait_on_event",
"(",
"self",
".",
"session",... | Waits for an occurrence of the specified event in this resource.
:param in_event_type: Logical identifier of the event(s) to wait for.
:param timeout: Absolute time period in time units that the resource shall wait for a specified event to
occur before returning the time elapsed error. The time unit is in milliseconds.
None means waiting forever if necessary.
:param capture_timeout: When True will not produce a VisaIOError(VI_ERROR_TMO) but
instead return a WaitResponse with timed_out=True
:return: A WaitResponse object that contains event_type, context and ret value. | [
"Waits",
"for",
"an",
"occurrence",
"of",
"the",
"specified",
"event",
"in",
"this",
"resource",
"."
] | b8b2d4371e1f00782856aa9176ff1ced6bcb3798 | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/resources/resource.py#L331-L348 | train | 228,919 |
pyvisa/pyvisa | pyvisa/resources/resource.py | Resource.lock | def lock(self, timeout='default', requested_key=None):
"""Establish a shared lock to the resource.
:param timeout: Absolute time period (in milliseconds) that a resource
waits to get unlocked by the locking session before
returning an error. (Defaults to self.timeout)
:param requested_key: Access key used by another session with which you
want your session to share a lock or None to generate
a new shared access key.
:returns: A new shared access key if requested_key is None,
otherwise, same value as the requested_key
"""
timeout = self.timeout if timeout == 'default' else timeout
timeout = self._cleanup_timeout(timeout)
return self.visalib.lock(self.session, constants.AccessModes.shared_lock, timeout, requested_key)[0] | python | def lock(self, timeout='default', requested_key=None):
"""Establish a shared lock to the resource.
:param timeout: Absolute time period (in milliseconds) that a resource
waits to get unlocked by the locking session before
returning an error. (Defaults to self.timeout)
:param requested_key: Access key used by another session with which you
want your session to share a lock or None to generate
a new shared access key.
:returns: A new shared access key if requested_key is None,
otherwise, same value as the requested_key
"""
timeout = self.timeout if timeout == 'default' else timeout
timeout = self._cleanup_timeout(timeout)
return self.visalib.lock(self.session, constants.AccessModes.shared_lock, timeout, requested_key)[0] | [
"def",
"lock",
"(",
"self",
",",
"timeout",
"=",
"'default'",
",",
"requested_key",
"=",
"None",
")",
":",
"timeout",
"=",
"self",
".",
"timeout",
"if",
"timeout",
"==",
"'default'",
"else",
"timeout",
"timeout",
"=",
"self",
".",
"_cleanup_timeout",
"(",
... | Establish a shared lock to the resource.
:param timeout: Absolute time period (in milliseconds) that a resource
waits to get unlocked by the locking session before
returning an error. (Defaults to self.timeout)
:param requested_key: Access key used by another session with which you
want your session to share a lock or None to generate
a new shared access key.
:returns: A new shared access key if requested_key is None,
otherwise, same value as the requested_key | [
"Establish",
"a",
"shared",
"lock",
"to",
"the",
"resource",
"."
] | b8b2d4371e1f00782856aa9176ff1ced6bcb3798 | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/resources/resource.py#L350-L365 | train | 228,920 |
pyvisa/pyvisa | pyvisa/resources/resource.py | Resource.lock_excl | def lock_excl(self, timeout='default'):
"""Establish an exclusive lock to the resource.
:param timeout: Absolute time period (in milliseconds) that a resource
waits to get unlocked by the locking session before
returning an error. (Defaults to self.timeout)
"""
timeout = self.timeout if timeout == 'default' else timeout
timeout = self._cleanup_timeout(timeout)
self.visalib.lock(self.session, constants.AccessModes.exclusive_lock, timeout, None) | python | def lock_excl(self, timeout='default'):
"""Establish an exclusive lock to the resource.
:param timeout: Absolute time period (in milliseconds) that a resource
waits to get unlocked by the locking session before
returning an error. (Defaults to self.timeout)
"""
timeout = self.timeout if timeout == 'default' else timeout
timeout = self._cleanup_timeout(timeout)
self.visalib.lock(self.session, constants.AccessModes.exclusive_lock, timeout, None) | [
"def",
"lock_excl",
"(",
"self",
",",
"timeout",
"=",
"'default'",
")",
":",
"timeout",
"=",
"self",
".",
"timeout",
"if",
"timeout",
"==",
"'default'",
"else",
"timeout",
"timeout",
"=",
"self",
".",
"_cleanup_timeout",
"(",
"timeout",
")",
"self",
".",
... | Establish an exclusive lock to the resource.
:param timeout: Absolute time period (in milliseconds) that a resource
waits to get unlocked by the locking session before
returning an error. (Defaults to self.timeout) | [
"Establish",
"an",
"exclusive",
"lock",
"to",
"the",
"resource",
"."
] | b8b2d4371e1f00782856aa9176ff1ced6bcb3798 | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/resources/resource.py#L367-L377 | train | 228,921 |
pyvisa/pyvisa | pyvisa/resources/resource.py | Resource.lock_context | def lock_context(self, timeout='default', requested_key='exclusive'):
"""A context that locks
:param timeout: Absolute time period (in milliseconds) that a resource
waits to get unlocked by the locking session before
returning an error. (Defaults to self.timeout)
:param requested_key: When using default of 'exclusive' the lock
is an exclusive lock.
Otherwise it is the access key for the shared lock or
None to generate a new shared access key.
The returned context is the access_key if applicable.
"""
if requested_key == 'exclusive':
self.lock_excl(timeout)
access_key = None
else:
access_key = self.lock(timeout, requested_key)
try:
yield access_key
finally:
self.unlock() | python | def lock_context(self, timeout='default', requested_key='exclusive'):
"""A context that locks
:param timeout: Absolute time period (in milliseconds) that a resource
waits to get unlocked by the locking session before
returning an error. (Defaults to self.timeout)
:param requested_key: When using default of 'exclusive' the lock
is an exclusive lock.
Otherwise it is the access key for the shared lock or
None to generate a new shared access key.
The returned context is the access_key if applicable.
"""
if requested_key == 'exclusive':
self.lock_excl(timeout)
access_key = None
else:
access_key = self.lock(timeout, requested_key)
try:
yield access_key
finally:
self.unlock() | [
"def",
"lock_context",
"(",
"self",
",",
"timeout",
"=",
"'default'",
",",
"requested_key",
"=",
"'exclusive'",
")",
":",
"if",
"requested_key",
"==",
"'exclusive'",
":",
"self",
".",
"lock_excl",
"(",
"timeout",
")",
"access_key",
"=",
"None",
"else",
":",
... | A context that locks
:param timeout: Absolute time period (in milliseconds) that a resource
waits to get unlocked by the locking session before
returning an error. (Defaults to self.timeout)
:param requested_key: When using default of 'exclusive' the lock
is an exclusive lock.
Otherwise it is the access key for the shared lock or
None to generate a new shared access key.
The returned context is the access_key if applicable. | [
"A",
"context",
"that",
"locks"
] | b8b2d4371e1f00782856aa9176ff1ced6bcb3798 | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/resources/resource.py#L385-L407 | train | 228,922 |
pyvisa/pyvisa | pyvisa/thirdparty/prettytable.py | PrettyTable.del_row | def del_row(self, row_index):
"""Delete a row to the table
Arguments:
row_index - The index of the row you want to delete. Indexing starts at 0."""
if row_index > len(self._rows)-1:
raise Exception("Cant delete row at index %d, table only has %d rows!" % (row_index, len(self._rows)))
del self._rows[row_index] | python | def del_row(self, row_index):
"""Delete a row to the table
Arguments:
row_index - The index of the row you want to delete. Indexing starts at 0."""
if row_index > len(self._rows)-1:
raise Exception("Cant delete row at index %d, table only has %d rows!" % (row_index, len(self._rows)))
del self._rows[row_index] | [
"def",
"del_row",
"(",
"self",
",",
"row_index",
")",
":",
"if",
"row_index",
">",
"len",
"(",
"self",
".",
"_rows",
")",
"-",
"1",
":",
"raise",
"Exception",
"(",
"\"Cant delete row at index %d, table only has %d rows!\"",
"%",
"(",
"row_index",
",",
"len",
... | Delete a row to the table
Arguments:
row_index - The index of the row you want to delete. Indexing starts at 0. | [
"Delete",
"a",
"row",
"to",
"the",
"table"
] | b8b2d4371e1f00782856aa9176ff1ced6bcb3798 | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/thirdparty/prettytable.py#L823-L833 | train | 228,923 |
pyvisa/pyvisa | pyvisa/thirdparty/prettytable.py | PrettyTable.get_html_string | def get_html_string(self, **kwargs):
"""Return string representation of HTML formatted version of table in current state.
Arguments:
start - index of first data row to include in output
end - index of last data row to include in output PLUS ONE (list slice style)
fields - names of fields (columns) to include
header - print a header showing field names (True or False)
border - print a border around the table (True or False)
hrules - controls printing of horizontal rules after rows. Allowed values: ALL, FRAME, HEADER, NONE
vrules - controls printing of vertical rules between columns. Allowed values: FRAME, ALL, NONE
int_format - controls formatting of integer data
float_format - controls formatting of floating point data
padding_width - number of spaces on either side of column data (only used if left and right paddings are None)
left_padding_width - number of spaces on left hand side of column data
right_padding_width - number of spaces on right hand side of column data
sortby - name of field to sort rows by
sort_key - sorting key function, applied to data points before sorting
attributes - dictionary of name/value pairs to include as HTML attributes in the <table> tag
xhtml - print <br/> tags if True, <br> tags if false"""
options = self._get_options(kwargs)
if options["format"]:
string = self._get_formatted_html_string(options)
else:
string = self._get_simple_html_string(options)
return string | python | def get_html_string(self, **kwargs):
"""Return string representation of HTML formatted version of table in current state.
Arguments:
start - index of first data row to include in output
end - index of last data row to include in output PLUS ONE (list slice style)
fields - names of fields (columns) to include
header - print a header showing field names (True or False)
border - print a border around the table (True or False)
hrules - controls printing of horizontal rules after rows. Allowed values: ALL, FRAME, HEADER, NONE
vrules - controls printing of vertical rules between columns. Allowed values: FRAME, ALL, NONE
int_format - controls formatting of integer data
float_format - controls formatting of floating point data
padding_width - number of spaces on either side of column data (only used if left and right paddings are None)
left_padding_width - number of spaces on left hand side of column data
right_padding_width - number of spaces on right hand side of column data
sortby - name of field to sort rows by
sort_key - sorting key function, applied to data points before sorting
attributes - dictionary of name/value pairs to include as HTML attributes in the <table> tag
xhtml - print <br/> tags if True, <br> tags if false"""
options = self._get_options(kwargs)
if options["format"]:
string = self._get_formatted_html_string(options)
else:
string = self._get_simple_html_string(options)
return string | [
"def",
"get_html_string",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"options",
"=",
"self",
".",
"_get_options",
"(",
"kwargs",
")",
"if",
"options",
"[",
"\"format\"",
"]",
":",
"string",
"=",
"self",
".",
"_get_formatted_html_string",
"(",
"options... | Return string representation of HTML formatted version of table in current state.
Arguments:
start - index of first data row to include in output
end - index of last data row to include in output PLUS ONE (list slice style)
fields - names of fields (columns) to include
header - print a header showing field names (True or False)
border - print a border around the table (True or False)
hrules - controls printing of horizontal rules after rows. Allowed values: ALL, FRAME, HEADER, NONE
vrules - controls printing of vertical rules between columns. Allowed values: FRAME, ALL, NONE
int_format - controls formatting of integer data
float_format - controls formatting of floating point data
padding_width - number of spaces on either side of column data (only used if left and right paddings are None)
left_padding_width - number of spaces on left hand side of column data
right_padding_width - number of spaces on right hand side of column data
sortby - name of field to sort rows by
sort_key - sorting key function, applied to data points before sorting
attributes - dictionary of name/value pairs to include as HTML attributes in the <table> tag
xhtml - print <br/> tags if True, <br> tags if false | [
"Return",
"string",
"representation",
"of",
"HTML",
"formatted",
"version",
"of",
"table",
"in",
"current",
"state",
"."
] | b8b2d4371e1f00782856aa9176ff1ced6bcb3798 | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/thirdparty/prettytable.py#L1158-L1188 | train | 228,924 |
pyvisa/pyvisa | pyvisa/thirdparty/prettytable.py | TableHandler.make_fields_unique | def make_fields_unique(self, fields):
"""
iterates over the row and make each field unique
"""
for i in range(0, len(fields)):
for j in range(i+1, len(fields)):
if fields[i] == fields[j]:
fields[j] += "'" | python | def make_fields_unique(self, fields):
"""
iterates over the row and make each field unique
"""
for i in range(0, len(fields)):
for j in range(i+1, len(fields)):
if fields[i] == fields[j]:
fields[j] += "'" | [
"def",
"make_fields_unique",
"(",
"self",
",",
"fields",
")",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"fields",
")",
")",
":",
"for",
"j",
"in",
"range",
"(",
"i",
"+",
"1",
",",
"len",
"(",
"fields",
")",
")",
":",
"if",
"... | iterates over the row and make each field unique | [
"iterates",
"over",
"the",
"row",
"and",
"make",
"each",
"field",
"unique"
] | b8b2d4371e1f00782856aa9176ff1ced6bcb3798 | https://github.com/pyvisa/pyvisa/blob/b8b2d4371e1f00782856aa9176ff1ced6bcb3798/pyvisa/thirdparty/prettytable.py#L1421-L1428 | train | 228,925 |
openshift/openshift-restclient-python | openshift/dynamic/client.py | meta_request | def meta_request(func):
""" Handles parsing response structure and translating API Exceptions """
def inner(self, resource, *args, **kwargs):
serialize_response = kwargs.pop('serialize', True)
try:
resp = func(self, resource, *args, **kwargs)
except ApiException as e:
raise api_exception(e)
if serialize_response:
return serialize(resource, resp)
return resp
return inner | python | def meta_request(func):
""" Handles parsing response structure and translating API Exceptions """
def inner(self, resource, *args, **kwargs):
serialize_response = kwargs.pop('serialize', True)
try:
resp = func(self, resource, *args, **kwargs)
except ApiException as e:
raise api_exception(e)
if serialize_response:
return serialize(resource, resp)
return resp
return inner | [
"def",
"meta_request",
"(",
"func",
")",
":",
"def",
"inner",
"(",
"self",
",",
"resource",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"serialize_response",
"=",
"kwargs",
".",
"pop",
"(",
"'serialize'",
",",
"True",
")",
"try",
":",
"resp"... | Handles parsing response structure and translating API Exceptions | [
"Handles",
"parsing",
"response",
"structure",
"and",
"translating",
"API",
"Exceptions"
] | 5d86bf5ba4e723bcc4d33ad47077aca01edca0f6 | https://github.com/openshift/openshift-restclient-python/blob/5d86bf5ba4e723bcc4d33ad47077aca01edca0f6/openshift/dynamic/client.py#L71-L83 | train | 228,926 |
openshift/openshift-restclient-python | openshift/dynamic/client.py | DynamicClient.watch | def watch(self, resource, namespace=None, name=None, label_selector=None, field_selector=None, resource_version=None, timeout=None):
"""
Stream events for a resource from the Kubernetes API
:param resource: The API resource object that will be used to query the API
:param namespace: The namespace to query
:param name: The name of the resource instance to query
:param label_selector: The label selector with which to filter results
:param field_selector: The field selector with which to filter results
:param resource_version: The version with which to filter results. Only events with
a resource_version greater than this value will be returned
:param timeout: The amount of time in seconds to wait before terminating the stream
:return: Event object with these keys:
'type': The type of event such as "ADDED", "DELETED", etc.
'raw_object': a dict representing the watched object.
'object': A ResourceInstance wrapping raw_object.
Example:
client = DynamicClient(k8s_client)
v1_pods = client.resources.get(api_version='v1', kind='Pod')
for e in v1_pods.watch(resource_version=0, namespace=default, timeout=5):
print(e['type'])
print(e['object'].metadata)
"""
watcher = watch.Watch()
for event in watcher.stream(
resource.get,
namespace=namespace,
name=name,
field_selector=field_selector,
label_selector=label_selector,
resource_version=resource_version,
serialize=False,
timeout_seconds=timeout
):
event['object'] = ResourceInstance(resource, event['object'])
yield event | python | def watch(self, resource, namespace=None, name=None, label_selector=None, field_selector=None, resource_version=None, timeout=None):
"""
Stream events for a resource from the Kubernetes API
:param resource: The API resource object that will be used to query the API
:param namespace: The namespace to query
:param name: The name of the resource instance to query
:param label_selector: The label selector with which to filter results
:param field_selector: The field selector with which to filter results
:param resource_version: The version with which to filter results. Only events with
a resource_version greater than this value will be returned
:param timeout: The amount of time in seconds to wait before terminating the stream
:return: Event object with these keys:
'type': The type of event such as "ADDED", "DELETED", etc.
'raw_object': a dict representing the watched object.
'object': A ResourceInstance wrapping raw_object.
Example:
client = DynamicClient(k8s_client)
v1_pods = client.resources.get(api_version='v1', kind='Pod')
for e in v1_pods.watch(resource_version=0, namespace=default, timeout=5):
print(e['type'])
print(e['object'].metadata)
"""
watcher = watch.Watch()
for event in watcher.stream(
resource.get,
namespace=namespace,
name=name,
field_selector=field_selector,
label_selector=label_selector,
resource_version=resource_version,
serialize=False,
timeout_seconds=timeout
):
event['object'] = ResourceInstance(resource, event['object'])
yield event | [
"def",
"watch",
"(",
"self",
",",
"resource",
",",
"namespace",
"=",
"None",
",",
"name",
"=",
"None",
",",
"label_selector",
"=",
"None",
",",
"field_selector",
"=",
"None",
",",
"resource_version",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
... | Stream events for a resource from the Kubernetes API
:param resource: The API resource object that will be used to query the API
:param namespace: The namespace to query
:param name: The name of the resource instance to query
:param label_selector: The label selector with which to filter results
:param field_selector: The field selector with which to filter results
:param resource_version: The version with which to filter results. Only events with
a resource_version greater than this value will be returned
:param timeout: The amount of time in seconds to wait before terminating the stream
:return: Event object with these keys:
'type': The type of event such as "ADDED", "DELETED", etc.
'raw_object': a dict representing the watched object.
'object': A ResourceInstance wrapping raw_object.
Example:
client = DynamicClient(k8s_client)
v1_pods = client.resources.get(api_version='v1', kind='Pod')
for e in v1_pods.watch(resource_version=0, namespace=default, timeout=5):
print(e['type'])
print(e['object'].metadata) | [
"Stream",
"events",
"for",
"a",
"resource",
"from",
"the",
"Kubernetes",
"API"
] | 5d86bf5ba4e723bcc4d33ad47077aca01edca0f6 | https://github.com/openshift/openshift-restclient-python/blob/5d86bf5ba4e723bcc4d33ad47077aca01edca0f6/openshift/dynamic/client.py#L179-L217 | train | 228,927 |
openshift/openshift-restclient-python | openshift/dynamic/client.py | DynamicClient.validate | def validate(self, definition, version=None, strict=False):
"""validate checks a kubernetes resource definition
Args:
definition (dict): resource definition
version (str): version of kubernetes to validate against
strict (bool): whether unexpected additional properties should be considered errors
Returns:
warnings (list), errors (list): warnings are missing validations, errors are validation failures
"""
if not HAS_KUBERNETES_VALIDATE:
raise KubernetesValidateMissing()
errors = list()
warnings = list()
try:
if version is None:
try:
version = self.version['kubernetes']['gitVersion']
except KeyError:
version = kubernetes_validate.latest_version()
kubernetes_validate.validate(definition, version, strict)
except kubernetes_validate.utils.ValidationError as e:
errors.append("resource definition validation error at %s: %s" % ('.'.join([str(item) for item in e.path]), e.message)) # noqa: B306
except VersionNotSupportedError as e:
errors.append("Kubernetes version %s is not supported by kubernetes-validate" % version)
except kubernetes_validate.utils.SchemaNotFoundError as e:
warnings.append("Could not find schema for object kind %s with API version %s in Kubernetes version %s (possibly Custom Resource?)" %
(e.kind, e.api_version, e.version))
return warnings, errors | python | def validate(self, definition, version=None, strict=False):
"""validate checks a kubernetes resource definition
Args:
definition (dict): resource definition
version (str): version of kubernetes to validate against
strict (bool): whether unexpected additional properties should be considered errors
Returns:
warnings (list), errors (list): warnings are missing validations, errors are validation failures
"""
if not HAS_KUBERNETES_VALIDATE:
raise KubernetesValidateMissing()
errors = list()
warnings = list()
try:
if version is None:
try:
version = self.version['kubernetes']['gitVersion']
except KeyError:
version = kubernetes_validate.latest_version()
kubernetes_validate.validate(definition, version, strict)
except kubernetes_validate.utils.ValidationError as e:
errors.append("resource definition validation error at %s: %s" % ('.'.join([str(item) for item in e.path]), e.message)) # noqa: B306
except VersionNotSupportedError as e:
errors.append("Kubernetes version %s is not supported by kubernetes-validate" % version)
except kubernetes_validate.utils.SchemaNotFoundError as e:
warnings.append("Could not find schema for object kind %s with API version %s in Kubernetes version %s (possibly Custom Resource?)" %
(e.kind, e.api_version, e.version))
return warnings, errors | [
"def",
"validate",
"(",
"self",
",",
"definition",
",",
"version",
"=",
"None",
",",
"strict",
"=",
"False",
")",
":",
"if",
"not",
"HAS_KUBERNETES_VALIDATE",
":",
"raise",
"KubernetesValidateMissing",
"(",
")",
"errors",
"=",
"list",
"(",
")",
"warnings",
... | validate checks a kubernetes resource definition
Args:
definition (dict): resource definition
version (str): version of kubernetes to validate against
strict (bool): whether unexpected additional properties should be considered errors
Returns:
warnings (list), errors (list): warnings are missing validations, errors are validation failures | [
"validate",
"checks",
"a",
"kubernetes",
"resource",
"definition"
] | 5d86bf5ba4e723bcc4d33ad47077aca01edca0f6 | https://github.com/openshift/openshift-restclient-python/blob/5d86bf5ba4e723bcc4d33ad47077aca01edca0f6/openshift/dynamic/client.py#L278-L308 | train | 228,928 |
openshift/openshift-restclient-python | openshift/dynamic/client.py | Discoverer.parse_api_groups | def parse_api_groups(self, request_resources=False, update=False):
""" Discovers all API groups present in the cluster """
if not self._cache.get('resources') or update:
self._cache['resources'] = self._cache.get('resources', {})
groups_response = load_json(self.client.request('GET', '/{}'.format(DISCOVERY_PREFIX)))['groups']
groups = self.default_groups(request_resources=request_resources)
for group in groups_response:
new_group = {}
for version_raw in group['versions']:
version = version_raw['version']
resource_group = self._cache.get('resources', {}).get(DISCOVERY_PREFIX, {}).get(group['name'], {}).get(version)
preferred = version_raw == group['preferredVersion']
resources = resource_group.resources if resource_group else {}
if request_resources:
resources = self.get_resources_for_api_version(DISCOVERY_PREFIX, group['name'], version, preferred)
new_group[version] = ResourceGroup(preferred, resources=resources)
groups[DISCOVERY_PREFIX][group['name']] = new_group
self._cache['resources'].update(groups)
self._write_cache()
return self._cache['resources'] | python | def parse_api_groups(self, request_resources=False, update=False):
""" Discovers all API groups present in the cluster """
if not self._cache.get('resources') or update:
self._cache['resources'] = self._cache.get('resources', {})
groups_response = load_json(self.client.request('GET', '/{}'.format(DISCOVERY_PREFIX)))['groups']
groups = self.default_groups(request_resources=request_resources)
for group in groups_response:
new_group = {}
for version_raw in group['versions']:
version = version_raw['version']
resource_group = self._cache.get('resources', {}).get(DISCOVERY_PREFIX, {}).get(group['name'], {}).get(version)
preferred = version_raw == group['preferredVersion']
resources = resource_group.resources if resource_group else {}
if request_resources:
resources = self.get_resources_for_api_version(DISCOVERY_PREFIX, group['name'], version, preferred)
new_group[version] = ResourceGroup(preferred, resources=resources)
groups[DISCOVERY_PREFIX][group['name']] = new_group
self._cache['resources'].update(groups)
self._write_cache()
return self._cache['resources'] | [
"def",
"parse_api_groups",
"(",
"self",
",",
"request_resources",
"=",
"False",
",",
"update",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"_cache",
".",
"get",
"(",
"'resources'",
")",
"or",
"update",
":",
"self",
".",
"_cache",
"[",
"'resources'"... | Discovers all API groups present in the cluster | [
"Discovers",
"all",
"API",
"groups",
"present",
"in",
"the",
"cluster"
] | 5d86bf5ba4e723bcc4d33ad47077aca01edca0f6 | https://github.com/openshift/openshift-restclient-python/blob/5d86bf5ba4e723bcc4d33ad47077aca01edca0f6/openshift/dynamic/client.py#L656-L678 | train | 228,929 |
openshift/openshift-restclient-python | openshift/dynamic/client.py | Discoverer.get | def get(self, **kwargs):
""" Same as search, but will throw an error if there are multiple or no
results. If there are multiple results and only one is an exact match
on api_version, that resource will be returned.
"""
results = self.search(**kwargs)
# If there are multiple matches, prefer exact matches on api_version
if len(results) > 1 and kwargs.get('api_version'):
results = [
result for result in results if result.group_version == kwargs['api_version']
]
# If there are multiple matches, prefer non-List kinds
if len(results) > 1 and not all([isinstance(x, ResourceList) for x in results]):
results = [result for result in results if not isinstance(result, ResourceList)]
if len(results) == 1:
return results[0]
elif not results:
raise ResourceNotFoundError('No matches found for {}'.format(kwargs))
else:
raise ResourceNotUniqueError('Multiple matches found for {}: {}'.format(kwargs, results)) | python | def get(self, **kwargs):
""" Same as search, but will throw an error if there are multiple or no
results. If there are multiple results and only one is an exact match
on api_version, that resource will be returned.
"""
results = self.search(**kwargs)
# If there are multiple matches, prefer exact matches on api_version
if len(results) > 1 and kwargs.get('api_version'):
results = [
result for result in results if result.group_version == kwargs['api_version']
]
# If there are multiple matches, prefer non-List kinds
if len(results) > 1 and not all([isinstance(x, ResourceList) for x in results]):
results = [result for result in results if not isinstance(result, ResourceList)]
if len(results) == 1:
return results[0]
elif not results:
raise ResourceNotFoundError('No matches found for {}'.format(kwargs))
else:
raise ResourceNotUniqueError('Multiple matches found for {}: {}'.format(kwargs, results)) | [
"def",
"get",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"results",
"=",
"self",
".",
"search",
"(",
"*",
"*",
"kwargs",
")",
"# If there are multiple matches, prefer exact matches on api_version",
"if",
"len",
"(",
"results",
")",
">",
"1",
"and",
"kwa... | Same as search, but will throw an error if there are multiple or no
results. If there are multiple results and only one is an exact match
on api_version, that resource will be returned. | [
"Same",
"as",
"search",
"but",
"will",
"throw",
"an",
"error",
"if",
"there",
"are",
"multiple",
"or",
"no",
"results",
".",
"If",
"there",
"are",
"multiple",
"results",
"and",
"only",
"one",
"is",
"an",
"exact",
"match",
"on",
"api_version",
"that",
"re... | 5d86bf5ba4e723bcc4d33ad47077aca01edca0f6 | https://github.com/openshift/openshift-restclient-python/blob/5d86bf5ba4e723bcc4d33ad47077aca01edca0f6/openshift/dynamic/client.py#L735-L754 | train | 228,930 |
dhylands/rshell | rshell/main.py | add_device | def add_device(dev):
"""Adds a device to the list of devices we know about."""
global DEV_IDX, DEFAULT_DEV
with DEV_LOCK:
for idx in range(len(DEVS)):
test_dev = DEVS[idx]
if test_dev.dev_name_short == dev.dev_name_short:
# This device is already in our list. Delete the old one
if test_dev is DEFAULT_DEV:
DEFAULT_DEV = None
del DEVS[idx]
break
if find_device_by_name(dev.name):
# This name is taken - make it unique
dev.name += '-%d' % DEV_IDX
dev.name_path = '/' + dev.name + '/'
DEVS.append(dev)
DEV_IDX += 1
if DEFAULT_DEV is None:
DEFAULT_DEV = dev | python | def add_device(dev):
"""Adds a device to the list of devices we know about."""
global DEV_IDX, DEFAULT_DEV
with DEV_LOCK:
for idx in range(len(DEVS)):
test_dev = DEVS[idx]
if test_dev.dev_name_short == dev.dev_name_short:
# This device is already in our list. Delete the old one
if test_dev is DEFAULT_DEV:
DEFAULT_DEV = None
del DEVS[idx]
break
if find_device_by_name(dev.name):
# This name is taken - make it unique
dev.name += '-%d' % DEV_IDX
dev.name_path = '/' + dev.name + '/'
DEVS.append(dev)
DEV_IDX += 1
if DEFAULT_DEV is None:
DEFAULT_DEV = dev | [
"def",
"add_device",
"(",
"dev",
")",
":",
"global",
"DEV_IDX",
",",
"DEFAULT_DEV",
"with",
"DEV_LOCK",
":",
"for",
"idx",
"in",
"range",
"(",
"len",
"(",
"DEVS",
")",
")",
":",
"test_dev",
"=",
"DEVS",
"[",
"idx",
"]",
"if",
"test_dev",
".",
"dev_na... | Adds a device to the list of devices we know about. | [
"Adds",
"a",
"device",
"to",
"the",
"list",
"of",
"devices",
"we",
"know",
"about",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L176-L195 | train | 228,931 |
dhylands/rshell | rshell/main.py | find_device_by_name | def find_device_by_name(name):
"""Tries to find a board by board name."""
if not name:
return DEFAULT_DEV
with DEV_LOCK:
for dev in DEVS:
if dev.name == name:
return dev
return None | python | def find_device_by_name(name):
"""Tries to find a board by board name."""
if not name:
return DEFAULT_DEV
with DEV_LOCK:
for dev in DEVS:
if dev.name == name:
return dev
return None | [
"def",
"find_device_by_name",
"(",
"name",
")",
":",
"if",
"not",
"name",
":",
"return",
"DEFAULT_DEV",
"with",
"DEV_LOCK",
":",
"for",
"dev",
"in",
"DEVS",
":",
"if",
"dev",
".",
"name",
"==",
"name",
":",
"return",
"dev",
"return",
"None"
] | Tries to find a board by board name. | [
"Tries",
"to",
"find",
"a",
"board",
"by",
"board",
"name",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L198-L206 | train | 228,932 |
dhylands/rshell | rshell/main.py | is_micropython_usb_device | def is_micropython_usb_device(port):
"""Checks a USB device to see if it looks like a MicroPython device.
"""
if type(port).__name__ == 'Device':
# Assume its a pyudev.device.Device
if ('ID_BUS' not in port or port['ID_BUS'] != 'usb' or
'SUBSYSTEM' not in port or port['SUBSYSTEM'] != 'tty'):
return False
usb_id = 'usb vid:pid={}:{}'.format(port['ID_VENDOR_ID'], port['ID_MODEL_ID'])
else:
# Assume its a port from serial.tools.list_ports.comports()
usb_id = port[2].lower()
# We don't check the last digit of the PID since there are 3 possible
# values.
if usb_id.startswith('usb vid:pid=f055:980'):
return True
# Check for Teensy VID:PID
if usb_id.startswith('usb vid:pid=16c0:0483'):
return True
return False | python | def is_micropython_usb_device(port):
"""Checks a USB device to see if it looks like a MicroPython device.
"""
if type(port).__name__ == 'Device':
# Assume its a pyudev.device.Device
if ('ID_BUS' not in port or port['ID_BUS'] != 'usb' or
'SUBSYSTEM' not in port or port['SUBSYSTEM'] != 'tty'):
return False
usb_id = 'usb vid:pid={}:{}'.format(port['ID_VENDOR_ID'], port['ID_MODEL_ID'])
else:
# Assume its a port from serial.tools.list_ports.comports()
usb_id = port[2].lower()
# We don't check the last digit of the PID since there are 3 possible
# values.
if usb_id.startswith('usb vid:pid=f055:980'):
return True
# Check for Teensy VID:PID
if usb_id.startswith('usb vid:pid=16c0:0483'):
return True
return False | [
"def",
"is_micropython_usb_device",
"(",
"port",
")",
":",
"if",
"type",
"(",
"port",
")",
".",
"__name__",
"==",
"'Device'",
":",
"# Assume its a pyudev.device.Device",
"if",
"(",
"'ID_BUS'",
"not",
"in",
"port",
"or",
"port",
"[",
"'ID_BUS'",
"]",
"!=",
"'... | Checks a USB device to see if it looks like a MicroPython device. | [
"Checks",
"a",
"USB",
"device",
"to",
"see",
"if",
"it",
"looks",
"like",
"a",
"MicroPython",
"device",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L222-L241 | train | 228,933 |
dhylands/rshell | rshell/main.py | is_micropython_usb_port | def is_micropython_usb_port(portName):
"""Checks to see if the indicated portname is a MicroPython device
or not.
"""
for port in serial.tools.list_ports.comports():
if port.device == portName:
return is_micropython_usb_device(port)
return False | python | def is_micropython_usb_port(portName):
"""Checks to see if the indicated portname is a MicroPython device
or not.
"""
for port in serial.tools.list_ports.comports():
if port.device == portName:
return is_micropython_usb_device(port)
return False | [
"def",
"is_micropython_usb_port",
"(",
"portName",
")",
":",
"for",
"port",
"in",
"serial",
".",
"tools",
".",
"list_ports",
".",
"comports",
"(",
")",
":",
"if",
"port",
".",
"device",
"==",
"portName",
":",
"return",
"is_micropython_usb_device",
"(",
"port... | Checks to see if the indicated portname is a MicroPython device
or not. | [
"Checks",
"to",
"see",
"if",
"the",
"indicated",
"portname",
"is",
"a",
"MicroPython",
"device",
"or",
"not",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L244-L251 | train | 228,934 |
dhylands/rshell | rshell/main.py | autoconnect | def autoconnect():
"""Sets up a thread to detect when USB devices are plugged and unplugged.
If the device looks like a MicroPython board, then it will automatically
connect to it.
"""
if not USE_AUTOCONNECT:
return
try:
import pyudev
except ImportError:
return
context = pyudev.Context()
monitor = pyudev.Monitor.from_netlink(context)
connect_thread = threading.Thread(target=autoconnect_thread, args=(monitor,), name='AutoConnect')
connect_thread.daemon = True
connect_thread.start() | python | def autoconnect():
"""Sets up a thread to detect when USB devices are plugged and unplugged.
If the device looks like a MicroPython board, then it will automatically
connect to it.
"""
if not USE_AUTOCONNECT:
return
try:
import pyudev
except ImportError:
return
context = pyudev.Context()
monitor = pyudev.Monitor.from_netlink(context)
connect_thread = threading.Thread(target=autoconnect_thread, args=(monitor,), name='AutoConnect')
connect_thread.daemon = True
connect_thread.start() | [
"def",
"autoconnect",
"(",
")",
":",
"if",
"not",
"USE_AUTOCONNECT",
":",
"return",
"try",
":",
"import",
"pyudev",
"except",
"ImportError",
":",
"return",
"context",
"=",
"pyudev",
".",
"Context",
"(",
")",
"monitor",
"=",
"pyudev",
".",
"Monitor",
".",
... | Sets up a thread to detect when USB devices are plugged and unplugged.
If the device looks like a MicroPython board, then it will automatically
connect to it. | [
"Sets",
"up",
"a",
"thread",
"to",
"detect",
"when",
"USB",
"devices",
"are",
"plugged",
"and",
"unplugged",
".",
"If",
"the",
"device",
"looks",
"like",
"a",
"MicroPython",
"board",
"then",
"it",
"will",
"automatically",
"connect",
"to",
"it",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L254-L269 | train | 228,935 |
dhylands/rshell | rshell/main.py | autoconnect_thread | def autoconnect_thread(monitor):
"""Thread which detects USB Serial devices connecting and disconnecting."""
monitor.start()
monitor.filter_by('tty')
epoll = select.epoll()
epoll.register(monitor.fileno(), select.POLLIN)
while True:
try:
events = epoll.poll()
except InterruptedError:
continue
for fileno, _ in events:
if fileno == monitor.fileno():
usb_dev = monitor.poll()
print('autoconnect: {} action: {}'.format(usb_dev.device_node, usb_dev.action))
dev = find_serial_device_by_port(usb_dev.device_node)
if usb_dev.action == 'add':
# Try connecting a few times. Sometimes the serial port
# reports itself as busy, which causes the connection to fail.
for i in range(8):
if dev:
connected = connect_serial(dev.port, dev.baud, dev.wait)
elif is_micropython_usb_device(usb_dev):
connected = connect_serial(usb_dev.device_node)
else:
connected = False
if connected:
break
time.sleep(0.25)
elif usb_dev.action == 'remove':
print('')
print("USB Serial device '%s' disconnected" % usb_dev.device_node)
if dev:
dev.close()
break | python | def autoconnect_thread(monitor):
"""Thread which detects USB Serial devices connecting and disconnecting."""
monitor.start()
monitor.filter_by('tty')
epoll = select.epoll()
epoll.register(monitor.fileno(), select.POLLIN)
while True:
try:
events = epoll.poll()
except InterruptedError:
continue
for fileno, _ in events:
if fileno == monitor.fileno():
usb_dev = monitor.poll()
print('autoconnect: {} action: {}'.format(usb_dev.device_node, usb_dev.action))
dev = find_serial_device_by_port(usb_dev.device_node)
if usb_dev.action == 'add':
# Try connecting a few times. Sometimes the serial port
# reports itself as busy, which causes the connection to fail.
for i in range(8):
if dev:
connected = connect_serial(dev.port, dev.baud, dev.wait)
elif is_micropython_usb_device(usb_dev):
connected = connect_serial(usb_dev.device_node)
else:
connected = False
if connected:
break
time.sleep(0.25)
elif usb_dev.action == 'remove':
print('')
print("USB Serial device '%s' disconnected" % usb_dev.device_node)
if dev:
dev.close()
break | [
"def",
"autoconnect_thread",
"(",
"monitor",
")",
":",
"monitor",
".",
"start",
"(",
")",
"monitor",
".",
"filter_by",
"(",
"'tty'",
")",
"epoll",
"=",
"select",
".",
"epoll",
"(",
")",
"epoll",
".",
"register",
"(",
"monitor",
".",
"fileno",
"(",
")",... | Thread which detects USB Serial devices connecting and disconnecting. | [
"Thread",
"which",
"detects",
"USB",
"Serial",
"devices",
"connecting",
"and",
"disconnecting",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L272-L308 | train | 228,936 |
dhylands/rshell | rshell/main.py | extra_info | def extra_info(port):
"""Collects the serial nunber and manufacturer into a string, if
the fields are available."""
extra_items = []
if port.manufacturer:
extra_items.append("vendor '{}'".format(port.manufacturer))
if port.serial_number:
extra_items.append("serial '{}'".format(port.serial_number))
if port.interface:
extra_items.append("intf '{}'".format(port.interface))
if extra_items:
return ' with ' + ' '.join(extra_items)
return '' | python | def extra_info(port):
"""Collects the serial nunber and manufacturer into a string, if
the fields are available."""
extra_items = []
if port.manufacturer:
extra_items.append("vendor '{}'".format(port.manufacturer))
if port.serial_number:
extra_items.append("serial '{}'".format(port.serial_number))
if port.interface:
extra_items.append("intf '{}'".format(port.interface))
if extra_items:
return ' with ' + ' '.join(extra_items)
return '' | [
"def",
"extra_info",
"(",
"port",
")",
":",
"extra_items",
"=",
"[",
"]",
"if",
"port",
".",
"manufacturer",
":",
"extra_items",
".",
"append",
"(",
"\"vendor '{}'\"",
".",
"format",
"(",
"port",
".",
"manufacturer",
")",
")",
"if",
"port",
".",
"serial_... | Collects the serial nunber and manufacturer into a string, if
the fields are available. | [
"Collects",
"the",
"serial",
"nunber",
"and",
"manufacturer",
"into",
"a",
"string",
"if",
"the",
"fields",
"are",
"available",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L320-L332 | train | 228,937 |
dhylands/rshell | rshell/main.py | listports | def listports():
"""listports will display a list of all of the serial ports.
"""
detected = False
for port in serial.tools.list_ports.comports():
detected = True
if port.vid:
micropythonPort = ''
if is_micropython_usb_device(port):
micropythonPort = ' *'
print('USB Serial Device {:04x}:{:04x}{} found @{}{}\r'.format(
port.vid, port.pid,
extra_info(port), port.device, micropythonPort))
else:
print('Serial Device:', port.device)
if not detected:
print('No serial devices detected') | python | def listports():
"""listports will display a list of all of the serial ports.
"""
detected = False
for port in serial.tools.list_ports.comports():
detected = True
if port.vid:
micropythonPort = ''
if is_micropython_usb_device(port):
micropythonPort = ' *'
print('USB Serial Device {:04x}:{:04x}{} found @{}{}\r'.format(
port.vid, port.pid,
extra_info(port), port.device, micropythonPort))
else:
print('Serial Device:', port.device)
if not detected:
print('No serial devices detected') | [
"def",
"listports",
"(",
")",
":",
"detected",
"=",
"False",
"for",
"port",
"in",
"serial",
".",
"tools",
".",
"list_ports",
".",
"comports",
"(",
")",
":",
"detected",
"=",
"True",
"if",
"port",
".",
"vid",
":",
"micropythonPort",
"=",
"''",
"if",
"... | listports will display a list of all of the serial ports. | [
"listports",
"will",
"display",
"a",
"list",
"of",
"all",
"of",
"the",
"serial",
"ports",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L335-L351 | train | 228,938 |
dhylands/rshell | rshell/main.py | escape | def escape(str):
"""Precede all special characters with a backslash."""
out = ''
for char in str:
if char in '\\ ':
out += '\\'
out += char
return out | python | def escape(str):
"""Precede all special characters with a backslash."""
out = ''
for char in str:
if char in '\\ ':
out += '\\'
out += char
return out | [
"def",
"escape",
"(",
"str",
")",
":",
"out",
"=",
"''",
"for",
"char",
"in",
"str",
":",
"if",
"char",
"in",
"'\\\\ '",
":",
"out",
"+=",
"'\\\\'",
"out",
"+=",
"char",
"return",
"out"
] | Precede all special characters with a backslash. | [
"Precede",
"all",
"special",
"characters",
"with",
"a",
"backslash",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L354-L361 | train | 228,939 |
dhylands/rshell | rshell/main.py | align_cell | def align_cell(fmt, elem, width):
"""Returns an aligned element."""
if fmt == "<":
return elem + ' ' * (width - len(elem))
if fmt == ">":
return ' ' * (width - len(elem)) + elem
return elem | python | def align_cell(fmt, elem, width):
"""Returns an aligned element."""
if fmt == "<":
return elem + ' ' * (width - len(elem))
if fmt == ">":
return ' ' * (width - len(elem)) + elem
return elem | [
"def",
"align_cell",
"(",
"fmt",
",",
"elem",
",",
"width",
")",
":",
"if",
"fmt",
"==",
"\"<\"",
":",
"return",
"elem",
"+",
"' '",
"*",
"(",
"width",
"-",
"len",
"(",
"elem",
")",
")",
"if",
"fmt",
"==",
"\">\"",
":",
"return",
"' '",
"*",
"(... | Returns an aligned element. | [
"Returns",
"an",
"aligned",
"element",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L377-L383 | train | 228,940 |
dhylands/rshell | rshell/main.py | print_err | def print_err(*args, end='\n'):
"""Similar to print, but prints to stderr.
"""
print(*args, end=end, file=sys.stderr)
sys.stderr.flush() | python | def print_err(*args, end='\n'):
"""Similar to print, but prints to stderr.
"""
print(*args, end=end, file=sys.stderr)
sys.stderr.flush() | [
"def",
"print_err",
"(",
"*",
"args",
",",
"end",
"=",
"'\\n'",
")",
":",
"print",
"(",
"*",
"args",
",",
"end",
"=",
"end",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"sys",
".",
"stderr",
".",
"flush",
"(",
")"
] | Similar to print, but prints to stderr. | [
"Similar",
"to",
"print",
"but",
"prints",
"to",
"stderr",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L421-L425 | train | 228,941 |
dhylands/rshell | rshell/main.py | validate_pattern | def validate_pattern(fn):
"""On success return an absolute path and a pattern.
Otherwise print a message and return None, None
"""
directory, pattern = parse_pattern(fn)
if directory is None:
print_err("Invalid pattern {}.".format(fn))
return None, None
target = resolve_path(directory)
mode = auto(get_mode, target)
if not mode_exists(mode):
print_err("cannot access '{}': No such file or directory".format(fn))
return None, None
if not mode_isdir(mode):
print_err("cannot access '{}': Not a directory".format(fn))
return None, None
return target, pattern | python | def validate_pattern(fn):
"""On success return an absolute path and a pattern.
Otherwise print a message and return None, None
"""
directory, pattern = parse_pattern(fn)
if directory is None:
print_err("Invalid pattern {}.".format(fn))
return None, None
target = resolve_path(directory)
mode = auto(get_mode, target)
if not mode_exists(mode):
print_err("cannot access '{}': No such file or directory".format(fn))
return None, None
if not mode_isdir(mode):
print_err("cannot access '{}': Not a directory".format(fn))
return None, None
return target, pattern | [
"def",
"validate_pattern",
"(",
"fn",
")",
":",
"directory",
",",
"pattern",
"=",
"parse_pattern",
"(",
"fn",
")",
"if",
"directory",
"is",
"None",
":",
"print_err",
"(",
"\"Invalid pattern {}.\"",
".",
"format",
"(",
"fn",
")",
")",
"return",
"None",
",",... | On success return an absolute path and a pattern.
Otherwise print a message and return None, None | [
"On",
"success",
"return",
"an",
"absolute",
"path",
"and",
"a",
"pattern",
".",
"Otherwise",
"print",
"a",
"message",
"and",
"return",
"None",
"None"
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L463-L479 | train | 228,942 |
dhylands/rshell | rshell/main.py | resolve_path | def resolve_path(path):
"""Resolves path and converts it into an absolute path."""
if path[0] == '~':
# ~ or ~user
path = os.path.expanduser(path)
if path[0] != '/':
# Relative path
if cur_dir[-1] == '/':
path = cur_dir + path
else:
path = cur_dir + '/' + path
comps = path.split('/')
new_comps = []
for comp in comps:
# We strip out xxx/./xxx and xxx//xxx, except that we want to keep the
# leading / for absolute paths. This also removes the trailing slash
# that autocompletion adds to a directory.
if comp == '.' or (comp == '' and len(new_comps) > 0):
continue
if comp == '..':
if len(new_comps) > 1:
new_comps.pop()
else:
new_comps.append(comp)
if len(new_comps) == 1 and new_comps[0] == '':
return '/'
return '/'.join(new_comps) | python | def resolve_path(path):
"""Resolves path and converts it into an absolute path."""
if path[0] == '~':
# ~ or ~user
path = os.path.expanduser(path)
if path[0] != '/':
# Relative path
if cur_dir[-1] == '/':
path = cur_dir + path
else:
path = cur_dir + '/' + path
comps = path.split('/')
new_comps = []
for comp in comps:
# We strip out xxx/./xxx and xxx//xxx, except that we want to keep the
# leading / for absolute paths. This also removes the trailing slash
# that autocompletion adds to a directory.
if comp == '.' or (comp == '' and len(new_comps) > 0):
continue
if comp == '..':
if len(new_comps) > 1:
new_comps.pop()
else:
new_comps.append(comp)
if len(new_comps) == 1 and new_comps[0] == '':
return '/'
return '/'.join(new_comps) | [
"def",
"resolve_path",
"(",
"path",
")",
":",
"if",
"path",
"[",
"0",
"]",
"==",
"'~'",
":",
"# ~ or ~user",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
"if",
"path",
"[",
"0",
"]",
"!=",
"'/'",
":",
"# Relative path",
"if"... | Resolves path and converts it into an absolute path. | [
"Resolves",
"path",
"and",
"converts",
"it",
"into",
"an",
"absolute",
"path",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L494-L520 | train | 228,943 |
dhylands/rshell | rshell/main.py | print_bytes | def print_bytes(byte_str):
"""Prints a string or converts bytes to a string and then prints."""
if isinstance(byte_str, str):
print(byte_str)
else:
print(str(byte_str, encoding='utf8')) | python | def print_bytes(byte_str):
"""Prints a string or converts bytes to a string and then prints."""
if isinstance(byte_str, str):
print(byte_str)
else:
print(str(byte_str, encoding='utf8')) | [
"def",
"print_bytes",
"(",
"byte_str",
")",
":",
"if",
"isinstance",
"(",
"byte_str",
",",
"str",
")",
":",
"print",
"(",
"byte_str",
")",
"else",
":",
"print",
"(",
"str",
"(",
"byte_str",
",",
"encoding",
"=",
"'utf8'",
")",
")"
] | Prints a string or converts bytes to a string and then prints. | [
"Prints",
"a",
"string",
"or",
"converts",
"bytes",
"to",
"a",
"string",
"and",
"then",
"prints",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L559-L564 | train | 228,944 |
dhylands/rshell | rshell/main.py | extra_funcs | def extra_funcs(*funcs):
"""Decorator which adds extra functions to be downloaded to the pyboard."""
def extra_funcs_decorator(real_func):
def wrapper(*args, **kwargs):
return real_func(*args, **kwargs)
wrapper.extra_funcs = list(funcs)
wrapper.source = inspect.getsource(real_func)
wrapper.name = real_func.__name__
return wrapper
return extra_funcs_decorator | python | def extra_funcs(*funcs):
"""Decorator which adds extra functions to be downloaded to the pyboard."""
def extra_funcs_decorator(real_func):
def wrapper(*args, **kwargs):
return real_func(*args, **kwargs)
wrapper.extra_funcs = list(funcs)
wrapper.source = inspect.getsource(real_func)
wrapper.name = real_func.__name__
return wrapper
return extra_funcs_decorator | [
"def",
"extra_funcs",
"(",
"*",
"funcs",
")",
":",
"def",
"extra_funcs_decorator",
"(",
"real_func",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"real_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")... | Decorator which adds extra functions to be downloaded to the pyboard. | [
"Decorator",
"which",
"adds",
"extra",
"functions",
"to",
"be",
"downloaded",
"to",
"the",
"pyboard",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L567-L576 | train | 228,945 |
dhylands/rshell | rshell/main.py | auto | def auto(func, filename, *args, **kwargs):
"""If `filename` is a remote file, then this function calls func on the
micropython board, otherwise it calls it locally.
"""
dev, dev_filename = get_dev_and_path(filename)
if dev is None:
if len(dev_filename) > 0 and dev_filename[0] == '~':
dev_filename = os.path.expanduser(dev_filename)
return func(dev_filename, *args, **kwargs)
return dev.remote_eval(func, dev_filename, *args, **kwargs) | python | def auto(func, filename, *args, **kwargs):
"""If `filename` is a remote file, then this function calls func on the
micropython board, otherwise it calls it locally.
"""
dev, dev_filename = get_dev_and_path(filename)
if dev is None:
if len(dev_filename) > 0 and dev_filename[0] == '~':
dev_filename = os.path.expanduser(dev_filename)
return func(dev_filename, *args, **kwargs)
return dev.remote_eval(func, dev_filename, *args, **kwargs) | [
"def",
"auto",
"(",
"func",
",",
"filename",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"dev",
",",
"dev_filename",
"=",
"get_dev_and_path",
"(",
"filename",
")",
"if",
"dev",
"is",
"None",
":",
"if",
"len",
"(",
"dev_filename",
")",
">",
... | If `filename` is a remote file, then this function calls func on the
micropython board, otherwise it calls it locally. | [
"If",
"filename",
"is",
"a",
"remote",
"file",
"then",
"this",
"function",
"calls",
"func",
"on",
"the",
"micropython",
"board",
"otherwise",
"it",
"calls",
"it",
"locally",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L579-L588 | train | 228,946 |
dhylands/rshell | rshell/main.py | cat | def cat(src_filename, dst_file):
"""Copies the contents of the indicated file to an already opened file."""
(dev, dev_filename) = get_dev_and_path(src_filename)
if dev is None:
with open(dev_filename, 'rb') as txtfile:
for line in txtfile:
dst_file.write(line)
else:
filesize = dev.remote_eval(get_filesize, dev_filename)
return dev.remote(send_file_to_host, dev_filename, dst_file, filesize,
xfer_func=recv_file_from_remote) | python | def cat(src_filename, dst_file):
"""Copies the contents of the indicated file to an already opened file."""
(dev, dev_filename) = get_dev_and_path(src_filename)
if dev is None:
with open(dev_filename, 'rb') as txtfile:
for line in txtfile:
dst_file.write(line)
else:
filesize = dev.remote_eval(get_filesize, dev_filename)
return dev.remote(send_file_to_host, dev_filename, dst_file, filesize,
xfer_func=recv_file_from_remote) | [
"def",
"cat",
"(",
"src_filename",
",",
"dst_file",
")",
":",
"(",
"dev",
",",
"dev_filename",
")",
"=",
"get_dev_and_path",
"(",
"src_filename",
")",
"if",
"dev",
"is",
"None",
":",
"with",
"open",
"(",
"dev_filename",
",",
"'rb'",
")",
"as",
"txtfile",... | Copies the contents of the indicated file to an already opened file. | [
"Copies",
"the",
"contents",
"of",
"the",
"indicated",
"file",
"to",
"an",
"already",
"opened",
"file",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L612-L622 | train | 228,947 |
dhylands/rshell | rshell/main.py | copy_file | def copy_file(src_filename, dst_filename):
"""Copies a file from one place to another. Both the source and destination
files must exist on the same machine.
"""
try:
with open(src_filename, 'rb') as src_file:
with open(dst_filename, 'wb') as dst_file:
while True:
buf = src_file.read(BUFFER_SIZE)
if len(buf) > 0:
dst_file.write(buf)
if len(buf) < BUFFER_SIZE:
break
return True
except:
return False | python | def copy_file(src_filename, dst_filename):
"""Copies a file from one place to another. Both the source and destination
files must exist on the same machine.
"""
try:
with open(src_filename, 'rb') as src_file:
with open(dst_filename, 'wb') as dst_file:
while True:
buf = src_file.read(BUFFER_SIZE)
if len(buf) > 0:
dst_file.write(buf)
if len(buf) < BUFFER_SIZE:
break
return True
except:
return False | [
"def",
"copy_file",
"(",
"src_filename",
",",
"dst_filename",
")",
":",
"try",
":",
"with",
"open",
"(",
"src_filename",
",",
"'rb'",
")",
"as",
"src_file",
":",
"with",
"open",
"(",
"dst_filename",
",",
"'wb'",
")",
"as",
"dst_file",
":",
"while",
"True... | Copies a file from one place to another. Both the source and destination
files must exist on the same machine. | [
"Copies",
"a",
"file",
"from",
"one",
"place",
"to",
"another",
".",
"Both",
"the",
"source",
"and",
"destination",
"files",
"must",
"exist",
"on",
"the",
"same",
"machine",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L631-L646 | train | 228,948 |
dhylands/rshell | rshell/main.py | cp | def cp(src_filename, dst_filename):
"""Copies one file to another. The source file may be local or remote and
the destination file may be local or remote.
"""
src_dev, src_dev_filename = get_dev_and_path(src_filename)
dst_dev, dst_dev_filename = get_dev_and_path(dst_filename)
if src_dev is dst_dev:
# src and dst are either on the same remote, or both are on the host
return auto(copy_file, src_filename, dst_dev_filename)
filesize = auto(get_filesize, src_filename)
if dst_dev is None:
# Copying from remote to host
with open(dst_dev_filename, 'wb') as dst_file:
return src_dev.remote(send_file_to_host, src_dev_filename, dst_file,
filesize, xfer_func=recv_file_from_remote)
if src_dev is None:
# Copying from host to remote
with open(src_dev_filename, 'rb') as src_file:
return dst_dev.remote(recv_file_from_host, src_file, dst_dev_filename,
filesize, xfer_func=send_file_to_remote)
# Copying from remote A to remote B. We first copy the file
# from remote A to the host and then from the host to remote B
host_temp_file = tempfile.TemporaryFile()
if src_dev.remote(send_file_to_host, src_dev_filename, host_temp_file,
filesize, xfer_func=recv_file_from_remote):
host_temp_file.seek(0)
return dst_dev.remote(recv_file_from_host, host_temp_file, dst_dev_filename,
filesize, xfer_func=send_file_to_remote)
return False | python | def cp(src_filename, dst_filename):
"""Copies one file to another. The source file may be local or remote and
the destination file may be local or remote.
"""
src_dev, src_dev_filename = get_dev_and_path(src_filename)
dst_dev, dst_dev_filename = get_dev_and_path(dst_filename)
if src_dev is dst_dev:
# src and dst are either on the same remote, or both are on the host
return auto(copy_file, src_filename, dst_dev_filename)
filesize = auto(get_filesize, src_filename)
if dst_dev is None:
# Copying from remote to host
with open(dst_dev_filename, 'wb') as dst_file:
return src_dev.remote(send_file_to_host, src_dev_filename, dst_file,
filesize, xfer_func=recv_file_from_remote)
if src_dev is None:
# Copying from host to remote
with open(src_dev_filename, 'rb') as src_file:
return dst_dev.remote(recv_file_from_host, src_file, dst_dev_filename,
filesize, xfer_func=send_file_to_remote)
# Copying from remote A to remote B. We first copy the file
# from remote A to the host and then from the host to remote B
host_temp_file = tempfile.TemporaryFile()
if src_dev.remote(send_file_to_host, src_dev_filename, host_temp_file,
filesize, xfer_func=recv_file_from_remote):
host_temp_file.seek(0)
return dst_dev.remote(recv_file_from_host, host_temp_file, dst_dev_filename,
filesize, xfer_func=send_file_to_remote)
return False | [
"def",
"cp",
"(",
"src_filename",
",",
"dst_filename",
")",
":",
"src_dev",
",",
"src_dev_filename",
"=",
"get_dev_and_path",
"(",
"src_filename",
")",
"dst_dev",
",",
"dst_dev_filename",
"=",
"get_dev_and_path",
"(",
"dst_filename",
")",
"if",
"src_dev",
"is",
... | Copies one file to another. The source file may be local or remote and
the destination file may be local or remote. | [
"Copies",
"one",
"file",
"to",
"another",
".",
"The",
"source",
"file",
"may",
"be",
"local",
"or",
"remote",
"and",
"the",
"destination",
"file",
"may",
"be",
"local",
"or",
"remote",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L649-L680 | train | 228,949 |
dhylands/rshell | rshell/main.py | stat | def stat(filename):
"""Returns os.stat for a given file, adjusting the timestamps as appropriate."""
import os
try:
# on the host, lstat won't try to follow symlinks
rstat = os.lstat(filename)
except:
rstat = os.stat(filename)
return rstat[:7] + tuple(tim + TIME_OFFSET for tim in rstat[7:]) | python | def stat(filename):
"""Returns os.stat for a given file, adjusting the timestamps as appropriate."""
import os
try:
# on the host, lstat won't try to follow symlinks
rstat = os.lstat(filename)
except:
rstat = os.stat(filename)
return rstat[:7] + tuple(tim + TIME_OFFSET for tim in rstat[7:]) | [
"def",
"stat",
"(",
"filename",
")",
":",
"import",
"os",
"try",
":",
"# on the host, lstat won't try to follow symlinks",
"rstat",
"=",
"os",
".",
"lstat",
"(",
"filename",
")",
"except",
":",
"rstat",
"=",
"os",
".",
"stat",
"(",
"filename",
")",
"return",... | Returns os.stat for a given file, adjusting the timestamps as appropriate. | [
"Returns",
"os",
".",
"stat",
"for",
"a",
"given",
"file",
"adjusting",
"the",
"timestamps",
"as",
"appropriate",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L713-L721 | train | 228,950 |
dhylands/rshell | rshell/main.py | listdir_matches | def listdir_matches(match):
"""Returns a list of filenames contained in the named directory.
Only filenames which start with `match` will be returned.
Directories will have a trailing slash.
"""
import os
last_slash = match.rfind('/')
if last_slash == -1:
dirname = '.'
match_prefix = match
result_prefix = ''
else:
match_prefix = match[last_slash + 1:]
if last_slash == 0:
dirname = '/'
result_prefix = '/'
else:
dirname = match[0:last_slash]
result_prefix = dirname + '/'
def add_suffix_if_dir(filename):
try:
if (os.stat(filename)[0] & 0x4000) != 0:
return filename + '/'
except FileNotFoundError:
# This can happen when a symlink points to a non-existant file.
pass
return filename
matches = [add_suffix_if_dir(result_prefix + filename)
for filename in os.listdir(dirname) if filename.startswith(match_prefix)]
return matches | python | def listdir_matches(match):
"""Returns a list of filenames contained in the named directory.
Only filenames which start with `match` will be returned.
Directories will have a trailing slash.
"""
import os
last_slash = match.rfind('/')
if last_slash == -1:
dirname = '.'
match_prefix = match
result_prefix = ''
else:
match_prefix = match[last_slash + 1:]
if last_slash == 0:
dirname = '/'
result_prefix = '/'
else:
dirname = match[0:last_slash]
result_prefix = dirname + '/'
def add_suffix_if_dir(filename):
try:
if (os.stat(filename)[0] & 0x4000) != 0:
return filename + '/'
except FileNotFoundError:
# This can happen when a symlink points to a non-existant file.
pass
return filename
matches = [add_suffix_if_dir(result_prefix + filename)
for filename in os.listdir(dirname) if filename.startswith(match_prefix)]
return matches | [
"def",
"listdir_matches",
"(",
"match",
")",
":",
"import",
"os",
"last_slash",
"=",
"match",
".",
"rfind",
"(",
"'/'",
")",
"if",
"last_slash",
"==",
"-",
"1",
":",
"dirname",
"=",
"'.'",
"match_prefix",
"=",
"match",
"result_prefix",
"=",
"''",
"else",... | Returns a list of filenames contained in the named directory.
Only filenames which start with `match` will be returned.
Directories will have a trailing slash. | [
"Returns",
"a",
"list",
"of",
"filenames",
"contained",
"in",
"the",
"named",
"directory",
".",
"Only",
"filenames",
"which",
"start",
"with",
"match",
"will",
"be",
"returned",
".",
"Directories",
"will",
"have",
"a",
"trailing",
"slash",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L746-L775 | train | 228,951 |
dhylands/rshell | rshell/main.py | listdir_stat | def listdir_stat(dirname, show_hidden=True):
"""Returns a list of tuples for each file contained in the named
directory, or None if the directory does not exist. Each tuple
contains the filename, followed by the tuple returned by
calling os.stat on the filename.
"""
import os
try:
files = os.listdir(dirname)
except OSError:
return None
if dirname == '/':
return list((file, stat('/' + file)) for file in files if is_visible(file) or show_hidden)
return list((file, stat(dirname + '/' + file)) for file in files if is_visible(file) or show_hidden) | python | def listdir_stat(dirname, show_hidden=True):
"""Returns a list of tuples for each file contained in the named
directory, or None if the directory does not exist. Each tuple
contains the filename, followed by the tuple returned by
calling os.stat on the filename.
"""
import os
try:
files = os.listdir(dirname)
except OSError:
return None
if dirname == '/':
return list((file, stat('/' + file)) for file in files if is_visible(file) or show_hidden)
return list((file, stat(dirname + '/' + file)) for file in files if is_visible(file) or show_hidden) | [
"def",
"listdir_stat",
"(",
"dirname",
",",
"show_hidden",
"=",
"True",
")",
":",
"import",
"os",
"try",
":",
"files",
"=",
"os",
".",
"listdir",
"(",
"dirname",
")",
"except",
"OSError",
":",
"return",
"None",
"if",
"dirname",
"==",
"'/'",
":",
"retur... | Returns a list of tuples for each file contained in the named
directory, or None if the directory does not exist. Each tuple
contains the filename, followed by the tuple returned by
calling os.stat on the filename. | [
"Returns",
"a",
"list",
"of",
"tuples",
"for",
"each",
"file",
"contained",
"in",
"the",
"named",
"directory",
"or",
"None",
"if",
"the",
"directory",
"does",
"not",
"exist",
".",
"Each",
"tuple",
"contains",
"the",
"filename",
"followed",
"by",
"the",
"tu... | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L779-L792 | train | 228,952 |
dhylands/rshell | rshell/main.py | remove_file | def remove_file(filename, recursive=False, force=False):
"""Removes a file or directory."""
import os
try:
mode = os.stat(filename)[0]
if mode & 0x4000 != 0:
# directory
if recursive:
for file in os.listdir(filename):
success = remove_file(filename + '/' + file, recursive, force)
if not success and not force:
return False
os.rmdir(filename) # PGH Work like Unix: require recursive
else:
if not force:
return False
else:
os.remove(filename)
except:
if not force:
return False
return True | python | def remove_file(filename, recursive=False, force=False):
"""Removes a file or directory."""
import os
try:
mode = os.stat(filename)[0]
if mode & 0x4000 != 0:
# directory
if recursive:
for file in os.listdir(filename):
success = remove_file(filename + '/' + file, recursive, force)
if not success and not force:
return False
os.rmdir(filename) # PGH Work like Unix: require recursive
else:
if not force:
return False
else:
os.remove(filename)
except:
if not force:
return False
return True | [
"def",
"remove_file",
"(",
"filename",
",",
"recursive",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"import",
"os",
"try",
":",
"mode",
"=",
"os",
".",
"stat",
"(",
"filename",
")",
"[",
"0",
"]",
"if",
"mode",
"&",
"0x4000",
"!=",
"0",
... | Removes a file or directory. | [
"Removes",
"a",
"file",
"or",
"directory",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L810-L831 | train | 228,953 |
dhylands/rshell | rshell/main.py | rm | def rm(filename, recursive=False, force=False):
"""Removes a file or directory tree."""
return auto(remove_file, filename, recursive, force) | python | def rm(filename, recursive=False, force=False):
"""Removes a file or directory tree."""
return auto(remove_file, filename, recursive, force) | [
"def",
"rm",
"(",
"filename",
",",
"recursive",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"return",
"auto",
"(",
"remove_file",
",",
"filename",
",",
"recursive",
",",
"force",
")"
] | Removes a file or directory tree. | [
"Removes",
"a",
"file",
"or",
"directory",
"tree",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L834-L836 | train | 228,954 |
dhylands/rshell | rshell/main.py | make_dir | def make_dir(dst_dir, dry_run, print_func, recursed):
"""Creates a directory. Produces information in case of dry run.
Issues error where necessary.
"""
parent = os.path.split(dst_dir.rstrip('/'))[0] # Check for nonexistent parent
parent_files = auto(listdir_stat, parent) if parent else True # Relative dir
if dry_run:
if recursed: # Assume success: parent not actually created yet
print_func("Creating directory {}".format(dst_dir))
elif parent_files is None:
print_func("Unable to create {}".format(dst_dir))
return True
if not mkdir(dst_dir):
print_err("Unable to create {}".format(dst_dir))
return False
return True | python | def make_dir(dst_dir, dry_run, print_func, recursed):
"""Creates a directory. Produces information in case of dry run.
Issues error where necessary.
"""
parent = os.path.split(dst_dir.rstrip('/'))[0] # Check for nonexistent parent
parent_files = auto(listdir_stat, parent) if parent else True # Relative dir
if dry_run:
if recursed: # Assume success: parent not actually created yet
print_func("Creating directory {}".format(dst_dir))
elif parent_files is None:
print_func("Unable to create {}".format(dst_dir))
return True
if not mkdir(dst_dir):
print_err("Unable to create {}".format(dst_dir))
return False
return True | [
"def",
"make_dir",
"(",
"dst_dir",
",",
"dry_run",
",",
"print_func",
",",
"recursed",
")",
":",
"parent",
"=",
"os",
".",
"path",
".",
"split",
"(",
"dst_dir",
".",
"rstrip",
"(",
"'/'",
")",
")",
"[",
"0",
"]",
"# Check for nonexistent parent",
"parent... | Creates a directory. Produces information in case of dry run.
Issues error where necessary. | [
"Creates",
"a",
"directory",
".",
"Produces",
"information",
"in",
"case",
"of",
"dry",
"run",
".",
"Issues",
"error",
"where",
"necessary",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L839-L854 | train | 228,955 |
dhylands/rshell | rshell/main.py | recv_file_from_host | def recv_file_from_host(src_file, dst_filename, filesize, dst_mode='wb'):
"""Function which runs on the pyboard. Matches up with send_file_to_remote."""
import sys
import ubinascii
if HAS_BUFFER:
try:
import pyb
usb = pyb.USB_VCP()
except:
try:
import machine
usb = machine.USB_VCP()
except:
usb = None
if usb and usb.isconnected():
# We don't want 0x03 bytes in the data to be interpreted as a Control-C
# This gets reset each time the REPL runs a line, so we don't need to
# worry about resetting it ourselves
usb.setinterrupt(-1)
try:
with open(dst_filename, dst_mode) as dst_file:
bytes_remaining = filesize
if not HAS_BUFFER:
bytes_remaining *= 2 # hexlify makes each byte into 2
buf_size = BUFFER_SIZE
write_buf = bytearray(buf_size)
read_buf = bytearray(buf_size)
while bytes_remaining > 0:
# Send back an ack as a form of flow control
sys.stdout.write('\x06')
read_size = min(bytes_remaining, buf_size)
buf_remaining = read_size
buf_index = 0
while buf_remaining > 0:
if HAS_BUFFER:
bytes_read = sys.stdin.buffer.readinto(read_buf, read_size)
else:
bytes_read = sys.stdin.readinto(read_buf, read_size)
if bytes_read > 0:
write_buf[buf_index:bytes_read] = read_buf[0:bytes_read]
buf_index += bytes_read
buf_remaining -= bytes_read
if HAS_BUFFER:
dst_file.write(write_buf[0:read_size])
else:
dst_file.write(ubinascii.unhexlify(write_buf[0:read_size]))
bytes_remaining -= read_size
return True
except:
return False | python | def recv_file_from_host(src_file, dst_filename, filesize, dst_mode='wb'):
"""Function which runs on the pyboard. Matches up with send_file_to_remote."""
import sys
import ubinascii
if HAS_BUFFER:
try:
import pyb
usb = pyb.USB_VCP()
except:
try:
import machine
usb = machine.USB_VCP()
except:
usb = None
if usb and usb.isconnected():
# We don't want 0x03 bytes in the data to be interpreted as a Control-C
# This gets reset each time the REPL runs a line, so we don't need to
# worry about resetting it ourselves
usb.setinterrupt(-1)
try:
with open(dst_filename, dst_mode) as dst_file:
bytes_remaining = filesize
if not HAS_BUFFER:
bytes_remaining *= 2 # hexlify makes each byte into 2
buf_size = BUFFER_SIZE
write_buf = bytearray(buf_size)
read_buf = bytearray(buf_size)
while bytes_remaining > 0:
# Send back an ack as a form of flow control
sys.stdout.write('\x06')
read_size = min(bytes_remaining, buf_size)
buf_remaining = read_size
buf_index = 0
while buf_remaining > 0:
if HAS_BUFFER:
bytes_read = sys.stdin.buffer.readinto(read_buf, read_size)
else:
bytes_read = sys.stdin.readinto(read_buf, read_size)
if bytes_read > 0:
write_buf[buf_index:bytes_read] = read_buf[0:bytes_read]
buf_index += bytes_read
buf_remaining -= bytes_read
if HAS_BUFFER:
dst_file.write(write_buf[0:read_size])
else:
dst_file.write(ubinascii.unhexlify(write_buf[0:read_size]))
bytes_remaining -= read_size
return True
except:
return False | [
"def",
"recv_file_from_host",
"(",
"src_file",
",",
"dst_filename",
",",
"filesize",
",",
"dst_mode",
"=",
"'wb'",
")",
":",
"import",
"sys",
"import",
"ubinascii",
"if",
"HAS_BUFFER",
":",
"try",
":",
"import",
"pyb",
"usb",
"=",
"pyb",
".",
"USB_VCP",
"(... | Function which runs on the pyboard. Matches up with send_file_to_remote. | [
"Function",
"which",
"runs",
"on",
"the",
"pyboard",
".",
"Matches",
"up",
"with",
"send_file_to_remote",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L968-L1017 | train | 228,956 |
dhylands/rshell | rshell/main.py | send_file_to_remote | def send_file_to_remote(dev, src_file, dst_filename, filesize, dst_mode='wb'):
"""Intended to be passed to the `remote` function as the xfer_func argument.
Matches up with recv_file_from_host.
"""
bytes_remaining = filesize
save_timeout = dev.timeout
dev.timeout = 1
while bytes_remaining > 0:
# Wait for ack so we don't get too far ahead of the remote
ack = dev.read(1)
if ack is None or ack != b'\x06':
sys.stderr.write("timed out or error in transfer to remote\n")
sys.exit(2)
if HAS_BUFFER:
buf_size = BUFFER_SIZE
else:
buf_size = BUFFER_SIZE // 2
read_size = min(bytes_remaining, buf_size)
buf = src_file.read(read_size)
#sys.stdout.write('\r%d/%d' % (filesize - bytes_remaining, filesize))
#sys.stdout.flush()
if HAS_BUFFER:
dev.write(buf)
else:
dev.write(binascii.hexlify(buf))
bytes_remaining -= read_size
#sys.stdout.write('\r')
dev.timeout = save_timeout | python | def send_file_to_remote(dev, src_file, dst_filename, filesize, dst_mode='wb'):
"""Intended to be passed to the `remote` function as the xfer_func argument.
Matches up with recv_file_from_host.
"""
bytes_remaining = filesize
save_timeout = dev.timeout
dev.timeout = 1
while bytes_remaining > 0:
# Wait for ack so we don't get too far ahead of the remote
ack = dev.read(1)
if ack is None or ack != b'\x06':
sys.stderr.write("timed out or error in transfer to remote\n")
sys.exit(2)
if HAS_BUFFER:
buf_size = BUFFER_SIZE
else:
buf_size = BUFFER_SIZE // 2
read_size = min(bytes_remaining, buf_size)
buf = src_file.read(read_size)
#sys.stdout.write('\r%d/%d' % (filesize - bytes_remaining, filesize))
#sys.stdout.flush()
if HAS_BUFFER:
dev.write(buf)
else:
dev.write(binascii.hexlify(buf))
bytes_remaining -= read_size
#sys.stdout.write('\r')
dev.timeout = save_timeout | [
"def",
"send_file_to_remote",
"(",
"dev",
",",
"src_file",
",",
"dst_filename",
",",
"filesize",
",",
"dst_mode",
"=",
"'wb'",
")",
":",
"bytes_remaining",
"=",
"filesize",
"save_timeout",
"=",
"dev",
".",
"timeout",
"dev",
".",
"timeout",
"=",
"1",
"while",... | Intended to be passed to the `remote` function as the xfer_func argument.
Matches up with recv_file_from_host. | [
"Intended",
"to",
"be",
"passed",
"to",
"the",
"remote",
"function",
"as",
"the",
"xfer_func",
"argument",
".",
"Matches",
"up",
"with",
"recv_file_from_host",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L1020-L1048 | train | 228,957 |
dhylands/rshell | rshell/main.py | recv_file_from_remote | def recv_file_from_remote(dev, src_filename, dst_file, filesize):
"""Intended to be passed to the `remote` function as the xfer_func argument.
Matches up with send_file_to_host.
"""
bytes_remaining = filesize
if not HAS_BUFFER:
bytes_remaining *= 2 # hexlify makes each byte into 2
buf_size = BUFFER_SIZE
write_buf = bytearray(buf_size)
while bytes_remaining > 0:
read_size = min(bytes_remaining, buf_size)
buf_remaining = read_size
buf_index = 0
while buf_remaining > 0:
read_buf = dev.read(buf_remaining)
bytes_read = len(read_buf)
if bytes_read:
write_buf[buf_index:bytes_read] = read_buf[0:bytes_read]
buf_index += bytes_read
buf_remaining -= bytes_read
if HAS_BUFFER:
dst_file.write(write_buf[0:read_size])
else:
dst_file.write(binascii.unhexlify(write_buf[0:read_size]))
# Send an ack to the remote as a form of flow control
dev.write(b'\x06') # ASCII ACK is 0x06
bytes_remaining -= read_size | python | def recv_file_from_remote(dev, src_filename, dst_file, filesize):
"""Intended to be passed to the `remote` function as the xfer_func argument.
Matches up with send_file_to_host.
"""
bytes_remaining = filesize
if not HAS_BUFFER:
bytes_remaining *= 2 # hexlify makes each byte into 2
buf_size = BUFFER_SIZE
write_buf = bytearray(buf_size)
while bytes_remaining > 0:
read_size = min(bytes_remaining, buf_size)
buf_remaining = read_size
buf_index = 0
while buf_remaining > 0:
read_buf = dev.read(buf_remaining)
bytes_read = len(read_buf)
if bytes_read:
write_buf[buf_index:bytes_read] = read_buf[0:bytes_read]
buf_index += bytes_read
buf_remaining -= bytes_read
if HAS_BUFFER:
dst_file.write(write_buf[0:read_size])
else:
dst_file.write(binascii.unhexlify(write_buf[0:read_size]))
# Send an ack to the remote as a form of flow control
dev.write(b'\x06') # ASCII ACK is 0x06
bytes_remaining -= read_size | [
"def",
"recv_file_from_remote",
"(",
"dev",
",",
"src_filename",
",",
"dst_file",
",",
"filesize",
")",
":",
"bytes_remaining",
"=",
"filesize",
"if",
"not",
"HAS_BUFFER",
":",
"bytes_remaining",
"*=",
"2",
"# hexlify makes each byte into 2",
"buf_size",
"=",
"BUFFE... | Intended to be passed to the `remote` function as the xfer_func argument.
Matches up with send_file_to_host. | [
"Intended",
"to",
"be",
"passed",
"to",
"the",
"remote",
"function",
"as",
"the",
"xfer_func",
"argument",
".",
"Matches",
"up",
"with",
"send_file_to_host",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L1051-L1077 | train | 228,958 |
dhylands/rshell | rshell/main.py | send_file_to_host | def send_file_to_host(src_filename, dst_file, filesize):
"""Function which runs on the pyboard. Matches up with recv_file_from_remote."""
import sys
import ubinascii
try:
with open(src_filename, 'rb') as src_file:
bytes_remaining = filesize
if HAS_BUFFER:
buf_size = BUFFER_SIZE
else:
buf_size = BUFFER_SIZE // 2
while bytes_remaining > 0:
read_size = min(bytes_remaining, buf_size)
buf = src_file.read(read_size)
if HAS_BUFFER:
sys.stdout.buffer.write(buf)
else:
sys.stdout.write(ubinascii.hexlify(buf))
bytes_remaining -= read_size
# Wait for an ack so we don't get ahead of the remote
while True:
char = sys.stdin.read(1)
if char:
if char == '\x06':
break
# This should only happen if an error occurs
sys.stdout.write(char)
return True
except:
return False | python | def send_file_to_host(src_filename, dst_file, filesize):
"""Function which runs on the pyboard. Matches up with recv_file_from_remote."""
import sys
import ubinascii
try:
with open(src_filename, 'rb') as src_file:
bytes_remaining = filesize
if HAS_BUFFER:
buf_size = BUFFER_SIZE
else:
buf_size = BUFFER_SIZE // 2
while bytes_remaining > 0:
read_size = min(bytes_remaining, buf_size)
buf = src_file.read(read_size)
if HAS_BUFFER:
sys.stdout.buffer.write(buf)
else:
sys.stdout.write(ubinascii.hexlify(buf))
bytes_remaining -= read_size
# Wait for an ack so we don't get ahead of the remote
while True:
char = sys.stdin.read(1)
if char:
if char == '\x06':
break
# This should only happen if an error occurs
sys.stdout.write(char)
return True
except:
return False | [
"def",
"send_file_to_host",
"(",
"src_filename",
",",
"dst_file",
",",
"filesize",
")",
":",
"import",
"sys",
"import",
"ubinascii",
"try",
":",
"with",
"open",
"(",
"src_filename",
",",
"'rb'",
")",
"as",
"src_file",
":",
"bytes_remaining",
"=",
"filesize",
... | Function which runs on the pyboard. Matches up with recv_file_from_remote. | [
"Function",
"which",
"runs",
"on",
"the",
"pyboard",
".",
"Matches",
"up",
"with",
"recv_file_from_remote",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L1080-L1109 | train | 228,959 |
dhylands/rshell | rshell/main.py | print_cols | def print_cols(words, print_func, termwidth=79):
"""Takes a single column of words, and prints it as multiple columns that
will fit in termwidth columns.
"""
width = max([word_len(word) for word in words])
nwords = len(words)
ncols = max(1, (termwidth + 1) // (width + 1))
nrows = (nwords + ncols - 1) // ncols
for row in range(nrows):
for i in range(row, nwords, nrows):
word = words[i]
if word[0] == '\x1b':
print_func('%-*s' % (width + 11, words[i]),
end='\n' if i + nrows >= nwords else ' ')
else:
print_func('%-*s' % (width, words[i]),
end='\n' if i + nrows >= nwords else ' ') | python | def print_cols(words, print_func, termwidth=79):
"""Takes a single column of words, and prints it as multiple columns that
will fit in termwidth columns.
"""
width = max([word_len(word) for word in words])
nwords = len(words)
ncols = max(1, (termwidth + 1) // (width + 1))
nrows = (nwords + ncols - 1) // ncols
for row in range(nrows):
for i in range(row, nwords, nrows):
word = words[i]
if word[0] == '\x1b':
print_func('%-*s' % (width + 11, words[i]),
end='\n' if i + nrows >= nwords else ' ')
else:
print_func('%-*s' % (width, words[i]),
end='\n' if i + nrows >= nwords else ' ') | [
"def",
"print_cols",
"(",
"words",
",",
"print_func",
",",
"termwidth",
"=",
"79",
")",
":",
"width",
"=",
"max",
"(",
"[",
"word_len",
"(",
"word",
")",
"for",
"word",
"in",
"words",
"]",
")",
"nwords",
"=",
"len",
"(",
"words",
")",
"ncols",
"=",... | Takes a single column of words, and prints it as multiple columns that
will fit in termwidth columns. | [
"Takes",
"a",
"single",
"column",
"of",
"words",
"and",
"prints",
"it",
"as",
"multiple",
"columns",
"that",
"will",
"fit",
"in",
"termwidth",
"columns",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L1190-L1206 | train | 228,960 |
dhylands/rshell | rshell/main.py | print_long | def print_long(filename, stat, print_func):
"""Prints detailed information about the file passed in."""
size = stat_size(stat)
mtime = stat_mtime(stat)
file_mtime = time.localtime(mtime)
curr_time = time.time()
if mtime > (curr_time + SIX_MONTHS) or mtime < (curr_time - SIX_MONTHS):
print_func('%6d %s %2d %04d %s' % (size, MONTH[file_mtime[1]],
file_mtime[2], file_mtime[0],
decorated_filename(filename, stat)))
else:
print_func('%6d %s %2d %02d:%02d %s' % (size, MONTH[file_mtime[1]],
file_mtime[2], file_mtime[3], file_mtime[4],
decorated_filename(filename, stat))) | python | def print_long(filename, stat, print_func):
"""Prints detailed information about the file passed in."""
size = stat_size(stat)
mtime = stat_mtime(stat)
file_mtime = time.localtime(mtime)
curr_time = time.time()
if mtime > (curr_time + SIX_MONTHS) or mtime < (curr_time - SIX_MONTHS):
print_func('%6d %s %2d %04d %s' % (size, MONTH[file_mtime[1]],
file_mtime[2], file_mtime[0],
decorated_filename(filename, stat)))
else:
print_func('%6d %s %2d %02d:%02d %s' % (size, MONTH[file_mtime[1]],
file_mtime[2], file_mtime[3], file_mtime[4],
decorated_filename(filename, stat))) | [
"def",
"print_long",
"(",
"filename",
",",
"stat",
",",
"print_func",
")",
":",
"size",
"=",
"stat_size",
"(",
"stat",
")",
"mtime",
"=",
"stat_mtime",
"(",
"stat",
")",
"file_mtime",
"=",
"time",
".",
"localtime",
"(",
"mtime",
")",
"curr_time",
"=",
... | Prints detailed information about the file passed in. | [
"Prints",
"detailed",
"information",
"about",
"the",
"file",
"passed",
"in",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L1224-L1237 | train | 228,961 |
dhylands/rshell | rshell/main.py | connect | def connect(port, baud=115200, user='micro', password='python', wait=0):
"""Tries to connect automagically via network or serial."""
try:
ip_address = socket.gethostbyname(port)
#print('Connecting to ip', ip_address)
connect_telnet(port, ip_address, user=user, password=password)
except socket.gaierror:
# Doesn't look like a hostname or IP-address, assume its a serial port
#print('connecting to serial', port)
connect_serial(port, baud=baud, wait=wait) | python | def connect(port, baud=115200, user='micro', password='python', wait=0):
"""Tries to connect automagically via network or serial."""
try:
ip_address = socket.gethostbyname(port)
#print('Connecting to ip', ip_address)
connect_telnet(port, ip_address, user=user, password=password)
except socket.gaierror:
# Doesn't look like a hostname or IP-address, assume its a serial port
#print('connecting to serial', port)
connect_serial(port, baud=baud, wait=wait) | [
"def",
"connect",
"(",
"port",
",",
"baud",
"=",
"115200",
",",
"user",
"=",
"'micro'",
",",
"password",
"=",
"'python'",
",",
"wait",
"=",
"0",
")",
":",
"try",
":",
"ip_address",
"=",
"socket",
".",
"gethostbyname",
"(",
"port",
")",
"#print('Connect... | Tries to connect automagically via network or serial. | [
"Tries",
"to",
"connect",
"automagically",
"via",
"network",
"or",
"serial",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L1276-L1285 | train | 228,962 |
dhylands/rshell | rshell/main.py | connect_telnet | def connect_telnet(name, ip_address=None, user='micro', password='python'):
"""Connect to a MicroPython board via telnet."""
if ip_address is None:
try:
ip_address = socket.gethostbyname(name)
except socket.gaierror:
ip_address = name
if not QUIET:
if name == ip_address:
print('Connecting to (%s) ...' % ip_address)
else:
print('Connecting to %s (%s) ...' % (name, ip_address))
dev = DeviceNet(name, ip_address, user, password)
add_device(dev) | python | def connect_telnet(name, ip_address=None, user='micro', password='python'):
"""Connect to a MicroPython board via telnet."""
if ip_address is None:
try:
ip_address = socket.gethostbyname(name)
except socket.gaierror:
ip_address = name
if not QUIET:
if name == ip_address:
print('Connecting to (%s) ...' % ip_address)
else:
print('Connecting to %s (%s) ...' % (name, ip_address))
dev = DeviceNet(name, ip_address, user, password)
add_device(dev) | [
"def",
"connect_telnet",
"(",
"name",
",",
"ip_address",
"=",
"None",
",",
"user",
"=",
"'micro'",
",",
"password",
"=",
"'python'",
")",
":",
"if",
"ip_address",
"is",
"None",
":",
"try",
":",
"ip_address",
"=",
"socket",
".",
"gethostbyname",
"(",
"nam... | Connect to a MicroPython board via telnet. | [
"Connect",
"to",
"a",
"MicroPython",
"board",
"via",
"telnet",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L1288-L1301 | train | 228,963 |
dhylands/rshell | rshell/main.py | connect_serial | def connect_serial(port, baud=115200, wait=0):
"""Connect to a MicroPython board via a serial port."""
if not QUIET:
print('Connecting to %s (buffer-size %d)...' % (port, BUFFER_SIZE))
try:
dev = DeviceSerial(port, baud, wait)
except DeviceError as err:
sys.stderr.write(str(err))
sys.stderr.write('\n')
return False
add_device(dev)
return True | python | def connect_serial(port, baud=115200, wait=0):
"""Connect to a MicroPython board via a serial port."""
if not QUIET:
print('Connecting to %s (buffer-size %d)...' % (port, BUFFER_SIZE))
try:
dev = DeviceSerial(port, baud, wait)
except DeviceError as err:
sys.stderr.write(str(err))
sys.stderr.write('\n')
return False
add_device(dev)
return True | [
"def",
"connect_serial",
"(",
"port",
",",
"baud",
"=",
"115200",
",",
"wait",
"=",
"0",
")",
":",
"if",
"not",
"QUIET",
":",
"print",
"(",
"'Connecting to %s (buffer-size %d)...'",
"%",
"(",
"port",
",",
"BUFFER_SIZE",
")",
")",
"try",
":",
"dev",
"=",
... | Connect to a MicroPython board via a serial port. | [
"Connect",
"to",
"a",
"MicroPython",
"board",
"via",
"a",
"serial",
"port",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L1304-L1315 | train | 228,964 |
dhylands/rshell | rshell/main.py | main | def main():
"""This main function saves the stdin termios settings, calls real_main,
and restores stdin termios settings when it returns.
"""
save_settings = None
stdin_fd = -1
try:
import termios
stdin_fd = sys.stdin.fileno()
save_settings = termios.tcgetattr(stdin_fd)
except:
pass
try:
real_main()
finally:
if save_settings:
termios.tcsetattr(stdin_fd, termios.TCSANOW, save_settings) | python | def main():
"""This main function saves the stdin termios settings, calls real_main,
and restores stdin termios settings when it returns.
"""
save_settings = None
stdin_fd = -1
try:
import termios
stdin_fd = sys.stdin.fileno()
save_settings = termios.tcgetattr(stdin_fd)
except:
pass
try:
real_main()
finally:
if save_settings:
termios.tcsetattr(stdin_fd, termios.TCSANOW, save_settings) | [
"def",
"main",
"(",
")",
":",
"save_settings",
"=",
"None",
"stdin_fd",
"=",
"-",
"1",
"try",
":",
"import",
"termios",
"stdin_fd",
"=",
"sys",
".",
"stdin",
".",
"fileno",
"(",
")",
"save_settings",
"=",
"termios",
".",
"tcgetattr",
"(",
"stdin_fd",
"... | This main function saves the stdin termios settings, calls real_main,
and restores stdin termios settings when it returns. | [
"This",
"main",
"function",
"saves",
"the",
"stdin",
"termios",
"settings",
"calls",
"real_main",
"and",
"restores",
"stdin",
"termios",
"settings",
"when",
"it",
"returns",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L2888-L2904 | train | 228,965 |
dhylands/rshell | rshell/main.py | Device.close | def close(self):
"""Closes the serial port."""
if self.pyb and self.pyb.serial:
self.pyb.serial.close()
self.pyb = None | python | def close(self):
"""Closes the serial port."""
if self.pyb and self.pyb.serial:
self.pyb.serial.close()
self.pyb = None | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"pyb",
"and",
"self",
".",
"pyb",
".",
"serial",
":",
"self",
".",
"pyb",
".",
"serial",
".",
"close",
"(",
")",
"self",
".",
"pyb",
"=",
"None"
] | Closes the serial port. | [
"Closes",
"the",
"serial",
"port",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L1398-L1402 | train | 228,966 |
dhylands/rshell | rshell/main.py | Device.is_root_path | def is_root_path(self, filename):
"""Determines if 'filename' corresponds to a directory on this device."""
test_filename = filename + '/'
for root_dir in self.root_dirs:
if test_filename.startswith(root_dir):
return True
return False | python | def is_root_path(self, filename):
"""Determines if 'filename' corresponds to a directory on this device."""
test_filename = filename + '/'
for root_dir in self.root_dirs:
if test_filename.startswith(root_dir):
return True
return False | [
"def",
"is_root_path",
"(",
"self",
",",
"filename",
")",
":",
"test_filename",
"=",
"filename",
"+",
"'/'",
"for",
"root_dir",
"in",
"self",
".",
"root_dirs",
":",
"if",
"test_filename",
".",
"startswith",
"(",
"root_dir",
")",
":",
"return",
"True",
"ret... | Determines if 'filename' corresponds to a directory on this device. | [
"Determines",
"if",
"filename",
"corresponds",
"to",
"a",
"directory",
"on",
"this",
"device",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L1407-L1413 | train | 228,967 |
dhylands/rshell | rshell/main.py | Device.read | def read(self, num_bytes):
"""Reads data from the pyboard over the serial port."""
self.check_pyb()
try:
return self.pyb.serial.read(num_bytes)
except (serial.serialutil.SerialException, TypeError):
# Write failed - assume that we got disconnected
self.close()
raise DeviceError('serial port %s closed' % self.dev_name_short) | python | def read(self, num_bytes):
"""Reads data from the pyboard over the serial port."""
self.check_pyb()
try:
return self.pyb.serial.read(num_bytes)
except (serial.serialutil.SerialException, TypeError):
# Write failed - assume that we got disconnected
self.close()
raise DeviceError('serial port %s closed' % self.dev_name_short) | [
"def",
"read",
"(",
"self",
",",
"num_bytes",
")",
":",
"self",
".",
"check_pyb",
"(",
")",
"try",
":",
"return",
"self",
".",
"pyb",
".",
"serial",
".",
"read",
"(",
"num_bytes",
")",
"except",
"(",
"serial",
".",
"serialutil",
".",
"SerialException",... | Reads data from the pyboard over the serial port. | [
"Reads",
"data",
"from",
"the",
"pyboard",
"over",
"the",
"serial",
"port",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L1418-L1426 | train | 228,968 |
dhylands/rshell | rshell/main.py | Device.remote | def remote(self, func, *args, xfer_func=None, **kwargs):
"""Calls func with the indicated args on the micropython board."""
global HAS_BUFFER
HAS_BUFFER = self.has_buffer
if hasattr(func, 'extra_funcs'):
func_name = func.name
func_lines = []
for extra_func in func.extra_funcs:
func_lines += inspect.getsource(extra_func).split('\n')
func_lines += ['']
func_lines += filter(lambda line: line[:1] != '@', func.source.split('\n'))
func_src = '\n'.join(func_lines)
else:
func_name = func.__name__
func_src = inspect.getsource(func)
args_arr = [remote_repr(i) for i in args]
kwargs_arr = ["{}={}".format(k, remote_repr(v)) for k, v in kwargs.items()]
func_src += 'output = ' + func_name + '('
func_src += ', '.join(args_arr + kwargs_arr)
func_src += ')\n'
func_src += 'if output is None:\n'
func_src += ' print("None")\n'
func_src += 'else:\n'
func_src += ' print(output)\n'
time_offset = self.time_offset
if self.adjust_for_timezone:
time_offset -= time.localtime().tm_gmtoff
func_src = func_src.replace('TIME_OFFSET', '{}'.format(time_offset))
func_src = func_src.replace('HAS_BUFFER', '{}'.format(HAS_BUFFER))
func_src = func_src.replace('BUFFER_SIZE', '{}'.format(BUFFER_SIZE))
func_src = func_src.replace('IS_UPY', 'True')
if DEBUG:
print('----- About to send %d bytes of code to the pyboard -----' % len(func_src))
print(func_src)
print('-----')
self.check_pyb()
try:
self.pyb.enter_raw_repl()
self.check_pyb()
output = self.pyb.exec_raw_no_follow(func_src)
if xfer_func:
xfer_func(self, *args, **kwargs)
self.check_pyb()
output, _ = self.pyb.follow(timeout=20)
self.check_pyb()
self.pyb.exit_raw_repl()
except (serial.serialutil.SerialException, TypeError):
self.close()
raise DeviceError('serial port %s closed' % self.dev_name_short)
if DEBUG:
print('-----Response-----')
print(output)
print('-----')
return output | python | def remote(self, func, *args, xfer_func=None, **kwargs):
"""Calls func with the indicated args on the micropython board."""
global HAS_BUFFER
HAS_BUFFER = self.has_buffer
if hasattr(func, 'extra_funcs'):
func_name = func.name
func_lines = []
for extra_func in func.extra_funcs:
func_lines += inspect.getsource(extra_func).split('\n')
func_lines += ['']
func_lines += filter(lambda line: line[:1] != '@', func.source.split('\n'))
func_src = '\n'.join(func_lines)
else:
func_name = func.__name__
func_src = inspect.getsource(func)
args_arr = [remote_repr(i) for i in args]
kwargs_arr = ["{}={}".format(k, remote_repr(v)) for k, v in kwargs.items()]
func_src += 'output = ' + func_name + '('
func_src += ', '.join(args_arr + kwargs_arr)
func_src += ')\n'
func_src += 'if output is None:\n'
func_src += ' print("None")\n'
func_src += 'else:\n'
func_src += ' print(output)\n'
time_offset = self.time_offset
if self.adjust_for_timezone:
time_offset -= time.localtime().tm_gmtoff
func_src = func_src.replace('TIME_OFFSET', '{}'.format(time_offset))
func_src = func_src.replace('HAS_BUFFER', '{}'.format(HAS_BUFFER))
func_src = func_src.replace('BUFFER_SIZE', '{}'.format(BUFFER_SIZE))
func_src = func_src.replace('IS_UPY', 'True')
if DEBUG:
print('----- About to send %d bytes of code to the pyboard -----' % len(func_src))
print(func_src)
print('-----')
self.check_pyb()
try:
self.pyb.enter_raw_repl()
self.check_pyb()
output = self.pyb.exec_raw_no_follow(func_src)
if xfer_func:
xfer_func(self, *args, **kwargs)
self.check_pyb()
output, _ = self.pyb.follow(timeout=20)
self.check_pyb()
self.pyb.exit_raw_repl()
except (serial.serialutil.SerialException, TypeError):
self.close()
raise DeviceError('serial port %s closed' % self.dev_name_short)
if DEBUG:
print('-----Response-----')
print(output)
print('-----')
return output | [
"def",
"remote",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"xfer_func",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"HAS_BUFFER",
"HAS_BUFFER",
"=",
"self",
".",
"has_buffer",
"if",
"hasattr",
"(",
"func",
",",
"'extra_funcs'",
")"... | Calls func with the indicated args on the micropython board. | [
"Calls",
"func",
"with",
"the",
"indicated",
"args",
"on",
"the",
"micropython",
"board",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L1428-L1481 | train | 228,969 |
dhylands/rshell | rshell/main.py | Device.sync_time | def sync_time(self):
"""Sets the time on the pyboard to match the time on the host."""
now = time.localtime(time.time())
self.remote(set_time, (now.tm_year, now.tm_mon, now.tm_mday, now.tm_wday + 1,
now.tm_hour, now.tm_min, now.tm_sec, 0))
return now | python | def sync_time(self):
"""Sets the time on the pyboard to match the time on the host."""
now = time.localtime(time.time())
self.remote(set_time, (now.tm_year, now.tm_mon, now.tm_mday, now.tm_wday + 1,
now.tm_hour, now.tm_min, now.tm_sec, 0))
return now | [
"def",
"sync_time",
"(",
"self",
")",
":",
"now",
"=",
"time",
".",
"localtime",
"(",
"time",
".",
"time",
"(",
")",
")",
"self",
".",
"remote",
"(",
"set_time",
",",
"(",
"now",
".",
"tm_year",
",",
"now",
".",
"tm_mon",
",",
"now",
".",
"tm_mda... | Sets the time on the pyboard to match the time on the host. | [
"Sets",
"the",
"time",
"on",
"the",
"pyboard",
"to",
"match",
"the",
"time",
"on",
"the",
"host",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L1506-L1511 | train | 228,970 |
dhylands/rshell | rshell/main.py | Device.write | def write(self, buf):
"""Writes data to the pyboard over the serial port."""
self.check_pyb()
try:
return self.pyb.serial.write(buf)
except (serial.serialutil.SerialException, BrokenPipeError, TypeError):
# Write failed - assume that we got disconnected
self.close()
raise DeviceError('{} closed'.format(self.dev_name_short)) | python | def write(self, buf):
"""Writes data to the pyboard over the serial port."""
self.check_pyb()
try:
return self.pyb.serial.write(buf)
except (serial.serialutil.SerialException, BrokenPipeError, TypeError):
# Write failed - assume that we got disconnected
self.close()
raise DeviceError('{} closed'.format(self.dev_name_short)) | [
"def",
"write",
"(",
"self",
",",
"buf",
")",
":",
"self",
".",
"check_pyb",
"(",
")",
"try",
":",
"return",
"self",
".",
"pyb",
".",
"serial",
".",
"write",
"(",
"buf",
")",
"except",
"(",
"serial",
".",
"serialutil",
".",
"SerialException",
",",
... | Writes data to the pyboard over the serial port. | [
"Writes",
"data",
"to",
"the",
"pyboard",
"over",
"the",
"serial",
"port",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L1513-L1521 | train | 228,971 |
dhylands/rshell | rshell/main.py | DeviceSerial.timeout | def timeout(self, value):
"""Sets the timeout associated with the serial port."""
self.check_pyb()
try:
self.pyb.serial.timeout = value
except:
# timeout is a property so it calls code, and that can fail
# if the serial port is closed.
pass | python | def timeout(self, value):
"""Sets the timeout associated with the serial port."""
self.check_pyb()
try:
self.pyb.serial.timeout = value
except:
# timeout is a property so it calls code, and that can fail
# if the serial port is closed.
pass | [
"def",
"timeout",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"check_pyb",
"(",
")",
"try",
":",
"self",
".",
"pyb",
".",
"serial",
".",
"timeout",
"=",
"value",
"except",
":",
"# timeout is a property so it calls code, and that can fail",
"# if the serial... | Sets the timeout associated with the serial port. | [
"Sets",
"the",
"timeout",
"associated",
"with",
"the",
"serial",
"port",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L1611-L1619 | train | 228,972 |
dhylands/rshell | rshell/main.py | Shell.onecmd | def onecmd(self, line):
"""Override onecmd.
1 - So we don't have to have a do_EOF method.
2 - So we can strip comments
3 - So we can track line numbers
"""
if DEBUG:
print('Executing "%s"' % line)
self.line_num += 1
if line == "EOF" or line == 'exit':
if cmd.Cmd.use_rawinput:
# This means that we printed a prompt, and we'll want to
# print a newline to pretty things up for the caller.
self.print('')
return True
# Strip comments
comment_idx = line.find("#")
if comment_idx >= 0:
line = line[0:comment_idx]
line = line.strip()
# search multiple commands on the same line
lexer = shlex.shlex(line)
lexer.whitespace = ''
for issemicolon, group in itertools.groupby(lexer, lambda x: x == ";"):
if not issemicolon:
self.onecmd_exec("".join(group)) | python | def onecmd(self, line):
"""Override onecmd.
1 - So we don't have to have a do_EOF method.
2 - So we can strip comments
3 - So we can track line numbers
"""
if DEBUG:
print('Executing "%s"' % line)
self.line_num += 1
if line == "EOF" or line == 'exit':
if cmd.Cmd.use_rawinput:
# This means that we printed a prompt, and we'll want to
# print a newline to pretty things up for the caller.
self.print('')
return True
# Strip comments
comment_idx = line.find("#")
if comment_idx >= 0:
line = line[0:comment_idx]
line = line.strip()
# search multiple commands on the same line
lexer = shlex.shlex(line)
lexer.whitespace = ''
for issemicolon, group in itertools.groupby(lexer, lambda x: x == ";"):
if not issemicolon:
self.onecmd_exec("".join(group)) | [
"def",
"onecmd",
"(",
"self",
",",
"line",
")",
":",
"if",
"DEBUG",
":",
"print",
"(",
"'Executing \"%s\"'",
"%",
"line",
")",
"self",
".",
"line_num",
"+=",
"1",
"if",
"line",
"==",
"\"EOF\"",
"or",
"line",
"==",
"'exit'",
":",
"if",
"cmd",
".",
"... | Override onecmd.
1 - So we don't have to have a do_EOF method.
2 - So we can strip comments
3 - So we can track line numbers | [
"Override",
"onecmd",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L1725-L1753 | train | 228,973 |
dhylands/rshell | rshell/main.py | Shell.print | def print(self, *args, end='\n', file=None):
"""Convenience function so you don't need to remember to put the \n
at the end of the line.
"""
if file is None:
file = self.stdout
s = ' '.join(str(arg) for arg in args) + end
file.write(s) | python | def print(self, *args, end='\n', file=None):
"""Convenience function so you don't need to remember to put the \n
at the end of the line.
"""
if file is None:
file = self.stdout
s = ' '.join(str(arg) for arg in args) + end
file.write(s) | [
"def",
"print",
"(",
"self",
",",
"*",
"args",
",",
"end",
"=",
"'\\n'",
",",
"file",
"=",
"None",
")",
":",
"if",
"file",
"is",
"None",
":",
"file",
"=",
"self",
".",
"stdout",
"s",
"=",
"' '",
".",
"join",
"(",
"str",
"(",
"arg",
")",
"for"... | Convenience function so you don't need to remember to put the \n
at the end of the line. | [
"Convenience",
"function",
"so",
"you",
"don",
"t",
"need",
"to",
"remember",
"to",
"put",
"the",
"\\",
"n",
"at",
"the",
"end",
"of",
"the",
"line",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L1808-L1815 | train | 228,974 |
dhylands/rshell | rshell/main.py | Shell.filename_complete | def filename_complete(self, text, line, begidx, endidx):
"""Wrapper for catching exceptions since cmd seems to silently
absorb them.
"""
try:
return self.real_filename_complete(text, line, begidx, endidx)
except:
traceback.print_exc() | python | def filename_complete(self, text, line, begidx, endidx):
"""Wrapper for catching exceptions since cmd seems to silently
absorb them.
"""
try:
return self.real_filename_complete(text, line, begidx, endidx)
except:
traceback.print_exc() | [
"def",
"filename_complete",
"(",
"self",
",",
"text",
",",
"line",
",",
"begidx",
",",
"endidx",
")",
":",
"try",
":",
"return",
"self",
".",
"real_filename_complete",
"(",
"text",
",",
"line",
",",
"begidx",
",",
"endidx",
")",
"except",
":",
"traceback... | Wrapper for catching exceptions since cmd seems to silently
absorb them. | [
"Wrapper",
"for",
"catching",
"exceptions",
"since",
"cmd",
"seems",
"to",
"silently",
"absorb",
"them",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L1839-L1846 | train | 228,975 |
dhylands/rshell | rshell/main.py | Shell.real_filename_complete | def real_filename_complete(self, text, line, begidx, endidx):
"""Figure out what filenames match the completion."""
# line contains the full command line that's been entered so far.
# text contains the portion of the line that readline is trying to complete
# text should correspond to line[begidx:endidx]
#
# The way the completer works text will start after one of the characters
# in DELIMS. So if the filename entered so far was "embedded\ sp" then
# text will point to the s in sp.
#
# The following bit of logic backs up to find the real beginning of the
# filename.
if begidx >= len(line):
# This happens when you hit TAB on an empty filename
before_match = begidx
else:
for before_match in range(begidx, 0, -1):
if line[before_match] in DELIMS and before_match >= 1 and line[before_match - 1] != '\\':
break
# We set fixed to be the portion of the filename which is before text
# and match is the full portion of the filename that's been entered so
# far (that's the part we use for matching files).
#
# When we return a list of completions, the bit that we return should
# just be the portion that we replace 'text' with.
fixed = unescape(line[before_match+1:begidx]) # fixed portion of the match
match = unescape(line[before_match+1:endidx]) # portion to match filenames against
# We do the following to cover the case that the current directory
# is / and the path being entered is relative.
strip = ''
if len(match) > 0 and match[0] == '/':
abs_match = match
elif cur_dir == '/':
abs_match = cur_dir + match
strip = cur_dir
else:
abs_match = cur_dir + '/' + match
strip = cur_dir + '/'
completions = []
prepend = ''
if abs_match.rfind('/') == 0: # match is in the root directory
# This means that we're looking for matches in the root directory
# (i.e. abs_match is /foo and the user hit TAB).
# So we'll supply the matching board names as possible completions.
# Since they're all treated as directories we leave the trailing slash.
with DEV_LOCK:
if match[0] == '/':
completions += [dev.name_path for dev in DEVS if dev.name_path.startswith(abs_match)]
else:
completions += [dev.name_path[1:] for dev in DEVS if dev.name_path.startswith(abs_match)]
if DEFAULT_DEV:
# Add root directories of the default device (i.e. /flash/ and /sd/)
if match[0] == '/':
completions += [root_dir for root_dir in DEFAULT_DEV.root_dirs if root_dir.startswith(match)]
else:
completions += [root_dir[1:] for root_dir in DEFAULT_DEV.root_dirs if root_dir[1:].startswith(match)]
else:
# This means that there are at least 2 slashes in abs_match. If one
# of them matches a board name then we need to remove the board
# name from fixed. Since the results from listdir_matches won't
# contain the board name, we need to prepend each of the completions.
with DEV_LOCK:
for dev in DEVS:
if abs_match.startswith(dev.name_path):
prepend = dev.name_path[:-1]
break
paths = sorted(auto(listdir_matches, abs_match))
for path in paths:
path = prepend + path
if path.startswith(strip):
path = path[len(strip):]
completions.append(escape(path.replace(fixed, '', 1)))
return completions | python | def real_filename_complete(self, text, line, begidx, endidx):
"""Figure out what filenames match the completion."""
# line contains the full command line that's been entered so far.
# text contains the portion of the line that readline is trying to complete
# text should correspond to line[begidx:endidx]
#
# The way the completer works text will start after one of the characters
# in DELIMS. So if the filename entered so far was "embedded\ sp" then
# text will point to the s in sp.
#
# The following bit of logic backs up to find the real beginning of the
# filename.
if begidx >= len(line):
# This happens when you hit TAB on an empty filename
before_match = begidx
else:
for before_match in range(begidx, 0, -1):
if line[before_match] in DELIMS and before_match >= 1 and line[before_match - 1] != '\\':
break
# We set fixed to be the portion of the filename which is before text
# and match is the full portion of the filename that's been entered so
# far (that's the part we use for matching files).
#
# When we return a list of completions, the bit that we return should
# just be the portion that we replace 'text' with.
fixed = unescape(line[before_match+1:begidx]) # fixed portion of the match
match = unescape(line[before_match+1:endidx]) # portion to match filenames against
# We do the following to cover the case that the current directory
# is / and the path being entered is relative.
strip = ''
if len(match) > 0 and match[0] == '/':
abs_match = match
elif cur_dir == '/':
abs_match = cur_dir + match
strip = cur_dir
else:
abs_match = cur_dir + '/' + match
strip = cur_dir + '/'
completions = []
prepend = ''
if abs_match.rfind('/') == 0: # match is in the root directory
# This means that we're looking for matches in the root directory
# (i.e. abs_match is /foo and the user hit TAB).
# So we'll supply the matching board names as possible completions.
# Since they're all treated as directories we leave the trailing slash.
with DEV_LOCK:
if match[0] == '/':
completions += [dev.name_path for dev in DEVS if dev.name_path.startswith(abs_match)]
else:
completions += [dev.name_path[1:] for dev in DEVS if dev.name_path.startswith(abs_match)]
if DEFAULT_DEV:
# Add root directories of the default device (i.e. /flash/ and /sd/)
if match[0] == '/':
completions += [root_dir for root_dir in DEFAULT_DEV.root_dirs if root_dir.startswith(match)]
else:
completions += [root_dir[1:] for root_dir in DEFAULT_DEV.root_dirs if root_dir[1:].startswith(match)]
else:
# This means that there are at least 2 slashes in abs_match. If one
# of them matches a board name then we need to remove the board
# name from fixed. Since the results from listdir_matches won't
# contain the board name, we need to prepend each of the completions.
with DEV_LOCK:
for dev in DEVS:
if abs_match.startswith(dev.name_path):
prepend = dev.name_path[:-1]
break
paths = sorted(auto(listdir_matches, abs_match))
for path in paths:
path = prepend + path
if path.startswith(strip):
path = path[len(strip):]
completions.append(escape(path.replace(fixed, '', 1)))
return completions | [
"def",
"real_filename_complete",
"(",
"self",
",",
"text",
",",
"line",
",",
"begidx",
",",
"endidx",
")",
":",
"# line contains the full command line that's been entered so far.",
"# text contains the portion of the line that readline is trying to complete",
"# text should correspon... | Figure out what filenames match the completion. | [
"Figure",
"out",
"what",
"filenames",
"match",
"the",
"completion",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L1848-L1927 | train | 228,976 |
dhylands/rshell | rshell/main.py | Shell.directory_complete | def directory_complete(self, text, line, begidx, endidx):
"""Figure out what directories match the completion."""
return [filename for filename in self.filename_complete(text, line, begidx, endidx) if filename[-1] == '/'] | python | def directory_complete(self, text, line, begidx, endidx):
"""Figure out what directories match the completion."""
return [filename for filename in self.filename_complete(text, line, begidx, endidx) if filename[-1] == '/'] | [
"def",
"directory_complete",
"(",
"self",
",",
"text",
",",
"line",
",",
"begidx",
",",
"endidx",
")",
":",
"return",
"[",
"filename",
"for",
"filename",
"in",
"self",
".",
"filename_complete",
"(",
"text",
",",
"line",
",",
"begidx",
",",
"endidx",
")",... | Figure out what directories match the completion. | [
"Figure",
"out",
"what",
"directories",
"match",
"the",
"completion",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L1929-L1931 | train | 228,977 |
dhylands/rshell | rshell/main.py | Shell.line_to_args | def line_to_args(self, line):
"""This will convert the line passed into the do_xxx functions into
an array of arguments and handle the Output Redirection Operator.
"""
# Note: using shlex.split causes quoted substrings to stay together.
args = shlex.split(line)
self.redirect_filename = ''
self.redirect_dev = None
redirect_index = -1
if '>' in args:
redirect_index = args.index('>')
elif '>>' in args:
redirect_index = args.index('>>')
if redirect_index >= 0:
if redirect_index + 1 >= len(args):
raise ShellError("> requires a filename")
self.redirect_filename = resolve_path(args[redirect_index + 1])
rmode = auto(get_mode, os.path.dirname(self.redirect_filename))
if not mode_isdir(rmode):
raise ShellError("Unable to redirect to '%s', directory doesn't exist" %
self.redirect_filename)
if args[redirect_index] == '>':
self.redirect_mode = 'w'
if DEBUG:
print('Redirecting (write) to', self.redirect_filename)
else:
self.redirect_mode = 'a'
if DEBUG:
print('Redirecting (append) to', self.redirect_filename)
self.redirect_dev, self.redirect_filename = get_dev_and_path(self.redirect_filename)
try:
if self.redirect_dev is None:
self.stdout = SmartFile(open(self.redirect_filename, self.redirect_mode))
else:
# Redirecting to a remote device. We collect the results locally
# and copy them to the remote device at the end of the command.
self.stdout = SmartFile(tempfile.TemporaryFile(mode='w+'))
except OSError as err:
raise ShellError(err)
del args[redirect_index + 1]
del args[redirect_index]
curr_cmd, _, _ = self.parseline(self.lastcmd)
parser = self.create_argparser(curr_cmd)
if parser:
args = parser.parse_args(args)
return args | python | def line_to_args(self, line):
"""This will convert the line passed into the do_xxx functions into
an array of arguments and handle the Output Redirection Operator.
"""
# Note: using shlex.split causes quoted substrings to stay together.
args = shlex.split(line)
self.redirect_filename = ''
self.redirect_dev = None
redirect_index = -1
if '>' in args:
redirect_index = args.index('>')
elif '>>' in args:
redirect_index = args.index('>>')
if redirect_index >= 0:
if redirect_index + 1 >= len(args):
raise ShellError("> requires a filename")
self.redirect_filename = resolve_path(args[redirect_index + 1])
rmode = auto(get_mode, os.path.dirname(self.redirect_filename))
if not mode_isdir(rmode):
raise ShellError("Unable to redirect to '%s', directory doesn't exist" %
self.redirect_filename)
if args[redirect_index] == '>':
self.redirect_mode = 'w'
if DEBUG:
print('Redirecting (write) to', self.redirect_filename)
else:
self.redirect_mode = 'a'
if DEBUG:
print('Redirecting (append) to', self.redirect_filename)
self.redirect_dev, self.redirect_filename = get_dev_and_path(self.redirect_filename)
try:
if self.redirect_dev is None:
self.stdout = SmartFile(open(self.redirect_filename, self.redirect_mode))
else:
# Redirecting to a remote device. We collect the results locally
# and copy them to the remote device at the end of the command.
self.stdout = SmartFile(tempfile.TemporaryFile(mode='w+'))
except OSError as err:
raise ShellError(err)
del args[redirect_index + 1]
del args[redirect_index]
curr_cmd, _, _ = self.parseline(self.lastcmd)
parser = self.create_argparser(curr_cmd)
if parser:
args = parser.parse_args(args)
return args | [
"def",
"line_to_args",
"(",
"self",
",",
"line",
")",
":",
"# Note: using shlex.split causes quoted substrings to stay together.",
"args",
"=",
"shlex",
".",
"split",
"(",
"line",
")",
"self",
".",
"redirect_filename",
"=",
"''",
"self",
".",
"redirect_dev",
"=",
... | This will convert the line passed into the do_xxx functions into
an array of arguments and handle the Output Redirection Operator. | [
"This",
"will",
"convert",
"the",
"line",
"passed",
"into",
"the",
"do_xxx",
"functions",
"into",
"an",
"array",
"of",
"arguments",
"and",
"handle",
"the",
"Output",
"Redirection",
"Operator",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L1933-L1979 | train | 228,978 |
dhylands/rshell | rshell/main.py | Shell.do_cat | def do_cat(self, line):
"""cat FILENAME...
Concatenates files and sends to stdout.
"""
# note: when we get around to supporting cat from stdin, we'll need
# to write stdin to a temp file, and then copy the file
# since we need to know the filesize when copying to the pyboard.
args = self.line_to_args(line)
for filename in args:
filename = resolve_path(filename)
mode = auto(get_mode, filename)
if not mode_exists(mode):
print_err("Cannot access '%s': No such file" % filename)
continue
if not mode_isfile(mode):
print_err("'%s': is not a file" % filename)
continue
cat(filename, self.stdout) | python | def do_cat(self, line):
"""cat FILENAME...
Concatenates files and sends to stdout.
"""
# note: when we get around to supporting cat from stdin, we'll need
# to write stdin to a temp file, and then copy the file
# since we need to know the filesize when copying to the pyboard.
args = self.line_to_args(line)
for filename in args:
filename = resolve_path(filename)
mode = auto(get_mode, filename)
if not mode_exists(mode):
print_err("Cannot access '%s': No such file" % filename)
continue
if not mode_isfile(mode):
print_err("'%s': is not a file" % filename)
continue
cat(filename, self.stdout) | [
"def",
"do_cat",
"(",
"self",
",",
"line",
")",
":",
"# note: when we get around to supporting cat from stdin, we'll need",
"# to write stdin to a temp file, and then copy the file",
"# since we need to know the filesize when copying to the pyboard.",
"args",
"=",
"self",
"."... | cat FILENAME...
Concatenates files and sends to stdout. | [
"cat",
"FILENAME",
"..."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L2015-L2033 | train | 228,979 |
dhylands/rshell | rshell/main.py | Shell.do_echo | def do_echo(self, line):
"""echo TEXT...
Display a line of text.
"""
args = self.line_to_args(line)
self.print(*args) | python | def do_echo(self, line):
"""echo TEXT...
Display a line of text.
"""
args = self.line_to_args(line)
self.print(*args) | [
"def",
"do_echo",
"(",
"self",
",",
"line",
")",
":",
"args",
"=",
"self",
".",
"line_to_args",
"(",
"line",
")",
"self",
".",
"print",
"(",
"*",
"args",
")"
] | echo TEXT...
Display a line of text. | [
"echo",
"TEXT",
"..."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L2181-L2187 | train | 228,980 |
dhylands/rshell | rshell/main.py | Shell.do_mkdir | def do_mkdir(self, line):
"""mkdir DIRECTORY...
Creates one or more directories.
"""
args = self.line_to_args(line)
for filename in args:
filename = resolve_path(filename)
if not mkdir(filename):
print_err('Unable to create %s' % filename) | python | def do_mkdir(self, line):
"""mkdir DIRECTORY...
Creates one or more directories.
"""
args = self.line_to_args(line)
for filename in args:
filename = resolve_path(filename)
if not mkdir(filename):
print_err('Unable to create %s' % filename) | [
"def",
"do_mkdir",
"(",
"self",
",",
"line",
")",
":",
"args",
"=",
"self",
".",
"line_to_args",
"(",
"line",
")",
"for",
"filename",
"in",
"args",
":",
"filename",
"=",
"resolve_path",
"(",
"filename",
")",
"if",
"not",
"mkdir",
"(",
"filename",
")",
... | mkdir DIRECTORY...
Creates one or more directories. | [
"mkdir",
"DIRECTORY",
"..."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L2379-L2388 | train | 228,981 |
dhylands/rshell | rshell/main.py | Shell.repl_serial_to_stdout | def repl_serial_to_stdout(self, dev):
"""Runs as a thread which has a sole purpose of readding bytes from
the serial port and writing them to stdout. Used by do_repl.
"""
with self.serial_reader_running:
try:
save_timeout = dev.timeout
# Set a timeout so that the read returns periodically with no data
# and allows us to check whether the main thread wants us to quit.
dev.timeout = 1
while not self.quit_serial_reader:
try:
char = dev.read(1)
except serial.serialutil.SerialException:
# This happens if the pyboard reboots, or a USB port
# goes away.
return
except TypeError:
# This is a bug in serialposix.py starting with python 3.3
# which causes a TypeError during the handling of the
# select.error. So we treat this the same as
# serial.serialutil.SerialException:
return
except ConnectionResetError:
# This happens over a telnet session, if it resets
return
if not char:
# This means that the read timed out. We'll check the quit
# flag and return if needed
if self.quit_when_no_output:
break
continue
self.stdout.write(char)
self.stdout.flush()
dev.timeout = save_timeout
except DeviceError:
# The device is no longer present.
return | python | def repl_serial_to_stdout(self, dev):
"""Runs as a thread which has a sole purpose of readding bytes from
the serial port and writing them to stdout. Used by do_repl.
"""
with self.serial_reader_running:
try:
save_timeout = dev.timeout
# Set a timeout so that the read returns periodically with no data
# and allows us to check whether the main thread wants us to quit.
dev.timeout = 1
while not self.quit_serial_reader:
try:
char = dev.read(1)
except serial.serialutil.SerialException:
# This happens if the pyboard reboots, or a USB port
# goes away.
return
except TypeError:
# This is a bug in serialposix.py starting with python 3.3
# which causes a TypeError during the handling of the
# select.error. So we treat this the same as
# serial.serialutil.SerialException:
return
except ConnectionResetError:
# This happens over a telnet session, if it resets
return
if not char:
# This means that the read timed out. We'll check the quit
# flag and return if needed
if self.quit_when_no_output:
break
continue
self.stdout.write(char)
self.stdout.flush()
dev.timeout = save_timeout
except DeviceError:
# The device is no longer present.
return | [
"def",
"repl_serial_to_stdout",
"(",
"self",
",",
"dev",
")",
":",
"with",
"self",
".",
"serial_reader_running",
":",
"try",
":",
"save_timeout",
"=",
"dev",
".",
"timeout",
"# Set a timeout so that the read returns periodically with no data",
"# and allows us to check whet... | Runs as a thread which has a sole purpose of readding bytes from
the serial port and writing them to stdout. Used by do_repl. | [
"Runs",
"as",
"a",
"thread",
"which",
"has",
"a",
"sole",
"purpose",
"of",
"readding",
"bytes",
"from",
"the",
"serial",
"port",
"and",
"writing",
"them",
"to",
"stdout",
".",
"Used",
"by",
"do_repl",
"."
] | a92a8fa8074ac792241c83c640a51b394667c324 | https://github.com/dhylands/rshell/blob/a92a8fa8074ac792241c83c640a51b394667c324/rshell/main.py#L2390-L2427 | train | 228,982 |
hyperledger/indy-plenum | stp_core/loop/motor.py | Motor.set_status | def set_status(self, value):
"""
Set the status of the motor to the specified value if not already set.
"""
if not self._status == value:
old = self._status
self._status = value
logger.info("{} changing status from {} to {}".format(self, old.name, value.name))
self._statusChanged(old, value) | python | def set_status(self, value):
"""
Set the status of the motor to the specified value if not already set.
"""
if not self._status == value:
old = self._status
self._status = value
logger.info("{} changing status from {} to {}".format(self, old.name, value.name))
self._statusChanged(old, value) | [
"def",
"set_status",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"self",
".",
"_status",
"==",
"value",
":",
"old",
"=",
"self",
".",
"_status",
"self",
".",
"_status",
"=",
"value",
"logger",
".",
"info",
"(",
"\"{} changing status from {} to {}\"",... | Set the status of the motor to the specified value if not already set. | [
"Set",
"the",
"status",
"of",
"the",
"motor",
"to",
"the",
"specified",
"value",
"if",
"not",
"already",
"set",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_core/loop/motor.py#L28-L36 | train | 228,983 |
hyperledger/indy-plenum | stp_core/loop/motor.py | Motor.stop | def stop(self, *args, **kwargs):
"""
Set the status to Status.stopping and also call `onStopping`
with the provided args and kwargs.
"""
if self.status in (Status.stopping, Status.stopped):
logger.debug("{} is already {}".format(self, self.status.name))
else:
self.status = Status.stopping
self.onStopping(*args, **kwargs)
self.status = Status.stopped | python | def stop(self, *args, **kwargs):
"""
Set the status to Status.stopping and also call `onStopping`
with the provided args and kwargs.
"""
if self.status in (Status.stopping, Status.stopped):
logger.debug("{} is already {}".format(self, self.status.name))
else:
self.status = Status.stopping
self.onStopping(*args, **kwargs)
self.status = Status.stopped | [
"def",
"stop",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"status",
"in",
"(",
"Status",
".",
"stopping",
",",
"Status",
".",
"stopped",
")",
":",
"logger",
".",
"debug",
"(",
"\"{} is already {}\"",
".",
"... | Set the status to Status.stopping and also call `onStopping`
with the provided args and kwargs. | [
"Set",
"the",
"status",
"to",
"Status",
".",
"stopping",
"and",
"also",
"call",
"onStopping",
"with",
"the",
"provided",
"args",
"and",
"kwargs",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_core/loop/motor.py#L58-L68 | train | 228,984 |
hyperledger/indy-plenum | plenum/server/primary_selector.py | PrimarySelector.next_primary_replica_name_for_master | def next_primary_replica_name_for_master(self, node_reg, node_ids):
"""
Returns name and corresponding instance name of the next node which
is supposed to be a new Primary. In fact it is not round-robin on
this abstraction layer as currently the primary of master instance is
pointed directly depending on view number, instance id and total
number of nodes.
But since the view number is incremented by 1 before primary selection
then current approach may be treated as round robin.
"""
name = self._next_primary_node_name_for_master(node_reg, node_ids)
return name, Replica.generateName(nodeName=name, instId=0) | python | def next_primary_replica_name_for_master(self, node_reg, node_ids):
"""
Returns name and corresponding instance name of the next node which
is supposed to be a new Primary. In fact it is not round-robin on
this abstraction layer as currently the primary of master instance is
pointed directly depending on view number, instance id and total
number of nodes.
But since the view number is incremented by 1 before primary selection
then current approach may be treated as round robin.
"""
name = self._next_primary_node_name_for_master(node_reg, node_ids)
return name, Replica.generateName(nodeName=name, instId=0) | [
"def",
"next_primary_replica_name_for_master",
"(",
"self",
",",
"node_reg",
",",
"node_ids",
")",
":",
"name",
"=",
"self",
".",
"_next_primary_node_name_for_master",
"(",
"node_reg",
",",
"node_ids",
")",
"return",
"name",
",",
"Replica",
".",
"generateName",
"(... | Returns name and corresponding instance name of the next node which
is supposed to be a new Primary. In fact it is not round-robin on
this abstraction layer as currently the primary of master instance is
pointed directly depending on view number, instance id and total
number of nodes.
But since the view number is incremented by 1 before primary selection
then current approach may be treated as round robin. | [
"Returns",
"name",
"and",
"corresponding",
"instance",
"name",
"of",
"the",
"next",
"node",
"which",
"is",
"supposed",
"to",
"be",
"a",
"new",
"Primary",
".",
"In",
"fact",
"it",
"is",
"not",
"round",
"-",
"robin",
"on",
"this",
"abstraction",
"layer",
"... | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/primary_selector.py#L61-L72 | train | 228,985 |
hyperledger/indy-plenum | plenum/server/primary_selector.py | PrimarySelector.next_primary_replica_name_for_backup | def next_primary_replica_name_for_backup(self, instance_id, master_primary_rank,
primaries, node_reg, node_ids):
"""
Returns name and corresponding instance name of the next node which
is supposed to be a new Primary for backup instance in round-robin
fashion starting from primary of master instance.
"""
if node_reg is None:
node_reg = self.node.nodeReg
total_nodes = len(node_reg)
rank = (master_primary_rank + 1) % total_nodes
name = self.node.get_name_by_rank(rank, node_reg, node_ids)
while name in primaries:
rank = (rank + 1) % total_nodes
name = self.node.get_name_by_rank(rank, node_reg, node_ids)
return name, Replica.generateName(nodeName=name, instId=instance_id) | python | def next_primary_replica_name_for_backup(self, instance_id, master_primary_rank,
primaries, node_reg, node_ids):
"""
Returns name and corresponding instance name of the next node which
is supposed to be a new Primary for backup instance in round-robin
fashion starting from primary of master instance.
"""
if node_reg is None:
node_reg = self.node.nodeReg
total_nodes = len(node_reg)
rank = (master_primary_rank + 1) % total_nodes
name = self.node.get_name_by_rank(rank, node_reg, node_ids)
while name in primaries:
rank = (rank + 1) % total_nodes
name = self.node.get_name_by_rank(rank, node_reg, node_ids)
return name, Replica.generateName(nodeName=name, instId=instance_id) | [
"def",
"next_primary_replica_name_for_backup",
"(",
"self",
",",
"instance_id",
",",
"master_primary_rank",
",",
"primaries",
",",
"node_reg",
",",
"node_ids",
")",
":",
"if",
"node_reg",
"is",
"None",
":",
"node_reg",
"=",
"self",
".",
"node",
".",
"nodeReg",
... | Returns name and corresponding instance name of the next node which
is supposed to be a new Primary for backup instance in round-robin
fashion starting from primary of master instance. | [
"Returns",
"name",
"and",
"corresponding",
"instance",
"name",
"of",
"the",
"next",
"node",
"which",
"is",
"supposed",
"to",
"be",
"a",
"new",
"Primary",
"for",
"backup",
"instance",
"in",
"round",
"-",
"robin",
"fashion",
"starting",
"from",
"primary",
"of"... | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/primary_selector.py#L74-L89 | train | 228,986 |
hyperledger/indy-plenum | plenum/server/primary_selector.py | PrimarySelector.process_selection | def process_selection(self, instance_count, node_reg, node_ids):
# Select primaries for current view_no
if instance_count == 0:
return []
'''
Build a set of names of primaries, it is needed to avoid
duplicates of primary nodes for different replicas.
'''
primaries = []
primary_rank = None
for i in range(instance_count):
if i == 0:
primary_name = self._next_primary_node_name_for_master(node_reg, node_ids)
primary_rank = self.node.get_rank_by_name(primary_name, node_reg, node_ids)
if primary_rank is None:
raise LogicError('primary_rank must not be None')
else:
primary_name, _ = self.next_primary_replica_name_for_backup(
i, primary_rank, primaries, node_reg, node_ids)
primaries.append(primary_name)
logger.display("{} selected primary {} for instance {} (view {})"
.format(PRIMARY_SELECTION_PREFIX,
primary_name, i, self.viewNo),
extra={"cli": "ANNOUNCE",
"tags": ["node-election"]})
if len(primaries) != instance_count:
raise LogicError('instances inconsistency')
if len(primaries) != len(set(primaries)):
raise LogicError('repeating instances')
return primaries | python | def process_selection(self, instance_count, node_reg, node_ids):
# Select primaries for current view_no
if instance_count == 0:
return []
'''
Build a set of names of primaries, it is needed to avoid
duplicates of primary nodes for different replicas.
'''
primaries = []
primary_rank = None
for i in range(instance_count):
if i == 0:
primary_name = self._next_primary_node_name_for_master(node_reg, node_ids)
primary_rank = self.node.get_rank_by_name(primary_name, node_reg, node_ids)
if primary_rank is None:
raise LogicError('primary_rank must not be None')
else:
primary_name, _ = self.next_primary_replica_name_for_backup(
i, primary_rank, primaries, node_reg, node_ids)
primaries.append(primary_name)
logger.display("{} selected primary {} for instance {} (view {})"
.format(PRIMARY_SELECTION_PREFIX,
primary_name, i, self.viewNo),
extra={"cli": "ANNOUNCE",
"tags": ["node-election"]})
if len(primaries) != instance_count:
raise LogicError('instances inconsistency')
if len(primaries) != len(set(primaries)):
raise LogicError('repeating instances')
return primaries | [
"def",
"process_selection",
"(",
"self",
",",
"instance_count",
",",
"node_reg",
",",
"node_ids",
")",
":",
"# Select primaries for current view_no",
"if",
"instance_count",
"==",
"0",
":",
"return",
"[",
"]",
"primaries",
"=",
"[",
"]",
"primary_rank",
"=",
"No... | Build a set of names of primaries, it is needed to avoid
duplicates of primary nodes for different replicas. | [
"Build",
"a",
"set",
"of",
"names",
"of",
"primaries",
"it",
"is",
"needed",
"to",
"avoid",
"duplicates",
"of",
"primary",
"nodes",
"for",
"different",
"replicas",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/primary_selector.py#L147-L182 | train | 228,987 |
hyperledger/indy-plenum | plenum/server/replicas.py | Replicas.take_ordereds_out_of_turn | def take_ordereds_out_of_turn(self) -> tuple:
"""
Takes all Ordered messages from outbox out of turn
"""
for replica in self._replicas.values():
yield replica.instId, replica._remove_ordered_from_queue() | python | def take_ordereds_out_of_turn(self) -> tuple:
"""
Takes all Ordered messages from outbox out of turn
"""
for replica in self._replicas.values():
yield replica.instId, replica._remove_ordered_from_queue() | [
"def",
"take_ordereds_out_of_turn",
"(",
"self",
")",
"->",
"tuple",
":",
"for",
"replica",
"in",
"self",
".",
"_replicas",
".",
"values",
"(",
")",
":",
"yield",
"replica",
".",
"instId",
",",
"replica",
".",
"_remove_ordered_from_queue",
"(",
")"
] | Takes all Ordered messages from outbox out of turn | [
"Takes",
"all",
"Ordered",
"messages",
"from",
"outbox",
"out",
"of",
"turn"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/replicas.py#L131-L136 | train | 228,988 |
hyperledger/indy-plenum | plenum/server/replicas.py | Replicas._new_replica | def _new_replica(self, instance_id: int, is_master: bool, bls_bft: BlsBft) -> Replica:
"""
Create a new replica with the specified parameters.
"""
return self._replica_class(self._node, instance_id, self._config, is_master, bls_bft, self._metrics) | python | def _new_replica(self, instance_id: int, is_master: bool, bls_bft: BlsBft) -> Replica:
"""
Create a new replica with the specified parameters.
"""
return self._replica_class(self._node, instance_id, self._config, is_master, bls_bft, self._metrics) | [
"def",
"_new_replica",
"(",
"self",
",",
"instance_id",
":",
"int",
",",
"is_master",
":",
"bool",
",",
"bls_bft",
":",
"BlsBft",
")",
"->",
"Replica",
":",
"return",
"self",
".",
"_replica_class",
"(",
"self",
".",
"_node",
",",
"instance_id",
",",
"sel... | Create a new replica with the specified parameters. | [
"Create",
"a",
"new",
"replica",
"with",
"the",
"specified",
"parameters",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/replicas.py#L138-L142 | train | 228,989 |
hyperledger/indy-plenum | plenum/common/throttler.py | Throttler.acquire | def acquire(self):
"""
Acquires lock for action.
:return: True and 0.0 if lock successfully acquired or False and number of seconds to wait before the next try
"""
now = self.get_current_time()
logger.debug("now: {}, len(actionsLog): {}".format(
now, len(self.actionsLog)))
self._trimActionsLog(now)
logger.debug("after trim, len(actionsLog): {}".format(
len(self.actionsLog)))
if len(self.actionsLog) == 0:
self.actionsLog.append(now)
logger.debug("len(actionsLog) was 0, after append, len(actionsLog):"
" {}".format(len(self.actionsLog)))
return True, 0.0
timeToWaitAfterPreviousTry = self.delayFunction(len(self.actionsLog))
timePassed = now - self.actionsLog[-1]
logger.debug("timeToWaitAfterPreviousTry: {}, timePassed: {}".
format(timeToWaitAfterPreviousTry, timePassed))
if timeToWaitAfterPreviousTry < timePassed:
self.actionsLog.append(now)
logger.debug(
"timeToWaitAfterPreviousTry < timePassed was true, after "
"append, len(actionsLog): {}".format(len(self.actionsLog)))
return True, 0.0
else:
logger.debug(
"timeToWaitAfterPreviousTry < timePassed was false, "
"len(actionsLog): {}".format(len(self.actionsLog)))
return False, timeToWaitAfterPreviousTry - timePassed | python | def acquire(self):
"""
Acquires lock for action.
:return: True and 0.0 if lock successfully acquired or False and number of seconds to wait before the next try
"""
now = self.get_current_time()
logger.debug("now: {}, len(actionsLog): {}".format(
now, len(self.actionsLog)))
self._trimActionsLog(now)
logger.debug("after trim, len(actionsLog): {}".format(
len(self.actionsLog)))
if len(self.actionsLog) == 0:
self.actionsLog.append(now)
logger.debug("len(actionsLog) was 0, after append, len(actionsLog):"
" {}".format(len(self.actionsLog)))
return True, 0.0
timeToWaitAfterPreviousTry = self.delayFunction(len(self.actionsLog))
timePassed = now - self.actionsLog[-1]
logger.debug("timeToWaitAfterPreviousTry: {}, timePassed: {}".
format(timeToWaitAfterPreviousTry, timePassed))
if timeToWaitAfterPreviousTry < timePassed:
self.actionsLog.append(now)
logger.debug(
"timeToWaitAfterPreviousTry < timePassed was true, after "
"append, len(actionsLog): {}".format(len(self.actionsLog)))
return True, 0.0
else:
logger.debug(
"timeToWaitAfterPreviousTry < timePassed was false, "
"len(actionsLog): {}".format(len(self.actionsLog)))
return False, timeToWaitAfterPreviousTry - timePassed | [
"def",
"acquire",
"(",
"self",
")",
":",
"now",
"=",
"self",
".",
"get_current_time",
"(",
")",
"logger",
".",
"debug",
"(",
"\"now: {}, len(actionsLog): {}\"",
".",
"format",
"(",
"now",
",",
"len",
"(",
"self",
".",
"actionsLog",
")",
")",
")",
"self",... | Acquires lock for action.
:return: True and 0.0 if lock successfully acquired or False and number of seconds to wait before the next try | [
"Acquires",
"lock",
"for",
"action",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/common/throttler.py#L28-L60 | train | 228,990 |
hyperledger/indy-plenum | plenum/common/tools.py | lazy_field | def lazy_field(prop):
"""
Decorator which helps in creating lazy properties
"""
@property
def wrapper(self):
if self not in _lazy_value_cache:
_lazy_value_cache[self] = {}
self_cache = _lazy_value_cache[self]
if prop in self_cache:
return self_cache[prop]
prop_value = prop(self)
self_cache[prop] = prop_value
return prop_value
return wrapper | python | def lazy_field(prop):
"""
Decorator which helps in creating lazy properties
"""
@property
def wrapper(self):
if self not in _lazy_value_cache:
_lazy_value_cache[self] = {}
self_cache = _lazy_value_cache[self]
if prop in self_cache:
return self_cache[prop]
prop_value = prop(self)
self_cache[prop] = prop_value
return prop_value
return wrapper | [
"def",
"lazy_field",
"(",
"prop",
")",
":",
"@",
"property",
"def",
"wrapper",
"(",
"self",
")",
":",
"if",
"self",
"not",
"in",
"_lazy_value_cache",
":",
"_lazy_value_cache",
"[",
"self",
"]",
"=",
"{",
"}",
"self_cache",
"=",
"_lazy_value_cache",
"[",
... | Decorator which helps in creating lazy properties | [
"Decorator",
"which",
"helps",
"in",
"creating",
"lazy",
"properties"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/common/tools.py#L6-L20 | train | 228,991 |
hyperledger/indy-plenum | stp_core/network/network_interface.py | NetworkInterface.getRemote | def getRemote(self, name: str = None, ha: HA = None):
"""
Find the remote by name or ha.
:param name: the name of the remote to find
:param ha: host address pair the remote to find
:raises: RemoteNotFound
"""
return self.findInRemotesByName(name) if name else \
self.findInRemotesByHA(ha) | python | def getRemote(self, name: str = None, ha: HA = None):
"""
Find the remote by name or ha.
:param name: the name of the remote to find
:param ha: host address pair the remote to find
:raises: RemoteNotFound
"""
return self.findInRemotesByName(name) if name else \
self.findInRemotesByHA(ha) | [
"def",
"getRemote",
"(",
"self",
",",
"name",
":",
"str",
"=",
"None",
",",
"ha",
":",
"HA",
"=",
"None",
")",
":",
"return",
"self",
".",
"findInRemotesByName",
"(",
"name",
")",
"if",
"name",
"else",
"self",
".",
"findInRemotesByHA",
"(",
"ha",
")"... | Find the remote by name or ha.
:param name: the name of the remote to find
:param ha: host address pair the remote to find
:raises: RemoteNotFound | [
"Find",
"the",
"remote",
"by",
"name",
"or",
"ha",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_core/network/network_interface.py#L135-L144 | train | 228,992 |
hyperledger/indy-plenum | stp_core/network/network_interface.py | NetworkInterface.findInRemotesByName | def findInRemotesByName(self, name: str):
"""
Find the remote by name.
:param name: the name of the remote to find
:raises: RemoteNotFound
"""
remotes = [r for r in self.remotes.values()
if r.name == name]
if len(remotes) > 1:
raise DuplicateRemotes(remotes)
if not remotes:
raise RemoteNotFound(name)
return remotes[0] | python | def findInRemotesByName(self, name: str):
"""
Find the remote by name.
:param name: the name of the remote to find
:raises: RemoteNotFound
"""
remotes = [r for r in self.remotes.values()
if r.name == name]
if len(remotes) > 1:
raise DuplicateRemotes(remotes)
if not remotes:
raise RemoteNotFound(name)
return remotes[0] | [
"def",
"findInRemotesByName",
"(",
"self",
",",
"name",
":",
"str",
")",
":",
"remotes",
"=",
"[",
"r",
"for",
"r",
"in",
"self",
".",
"remotes",
".",
"values",
"(",
")",
"if",
"r",
".",
"name",
"==",
"name",
"]",
"if",
"len",
"(",
"remotes",
")"... | Find the remote by name.
:param name: the name of the remote to find
:raises: RemoteNotFound | [
"Find",
"the",
"remote",
"by",
"name",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_core/network/network_interface.py#L155-L168 | train | 228,993 |
hyperledger/indy-plenum | stp_core/network/network_interface.py | NetworkInterface.removeRemoteByName | def removeRemoteByName(self, name: str) -> int:
"""
Remove the remote by name.
:param name: the name of the remote to remove
:raises: RemoteNotFound
"""
remote = self.getRemote(name)
rid = remote.uid
self.removeRemote(remote)
return rid | python | def removeRemoteByName(self, name: str) -> int:
"""
Remove the remote by name.
:param name: the name of the remote to remove
:raises: RemoteNotFound
"""
remote = self.getRemote(name)
rid = remote.uid
self.removeRemote(remote)
return rid | [
"def",
"removeRemoteByName",
"(",
"self",
",",
"name",
":",
"str",
")",
"->",
"int",
":",
"remote",
"=",
"self",
".",
"getRemote",
"(",
"name",
")",
"rid",
"=",
"remote",
".",
"uid",
"self",
".",
"removeRemote",
"(",
"remote",
")",
"return",
"rid"
] | Remove the remote by name.
:param name: the name of the remote to remove
:raises: RemoteNotFound | [
"Remove",
"the",
"remote",
"by",
"name",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_core/network/network_interface.py#L177-L187 | train | 228,994 |
hyperledger/indy-plenum | stp_core/network/network_interface.py | NetworkInterface.sameAddr | def sameAddr(self, ha, ha2) -> bool:
"""
Check whether the two arguments correspond to the same address
"""
if ha == ha2:
return True
if ha[1] != ha2[1]:
return False
return ha[0] in self.localips and ha2[0] in self.localips | python | def sameAddr(self, ha, ha2) -> bool:
"""
Check whether the two arguments correspond to the same address
"""
if ha == ha2:
return True
if ha[1] != ha2[1]:
return False
return ha[0] in self.localips and ha2[0] in self.localips | [
"def",
"sameAddr",
"(",
"self",
",",
"ha",
",",
"ha2",
")",
"->",
"bool",
":",
"if",
"ha",
"==",
"ha2",
":",
"return",
"True",
"if",
"ha",
"[",
"1",
"]",
"!=",
"ha2",
"[",
"1",
"]",
":",
"return",
"False",
"return",
"ha",
"[",
"0",
"]",
"in",... | Check whether the two arguments correspond to the same address | [
"Check",
"whether",
"the",
"two",
"arguments",
"correspond",
"to",
"the",
"same",
"address"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_core/network/network_interface.py#L196-L204 | train | 228,995 |
hyperledger/indy-plenum | stp_core/network/network_interface.py | NetworkInterface.remotesByConnected | def remotesByConnected(self):
"""
Partitions the remotes into connected and disconnected
:return: tuple(connected remotes, disconnected remotes)
"""
conns, disconns = [], []
for r in self.remotes.values():
array = conns if self.isRemoteConnected(r) else disconns
array.append(r)
return conns, disconns | python | def remotesByConnected(self):
"""
Partitions the remotes into connected and disconnected
:return: tuple(connected remotes, disconnected remotes)
"""
conns, disconns = [], []
for r in self.remotes.values():
array = conns if self.isRemoteConnected(r) else disconns
array.append(r)
return conns, disconns | [
"def",
"remotesByConnected",
"(",
"self",
")",
":",
"conns",
",",
"disconns",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"r",
"in",
"self",
".",
"remotes",
".",
"values",
"(",
")",
":",
"array",
"=",
"conns",
"if",
"self",
".",
"isRemoteConnected",
"(",
... | Partitions the remotes into connected and disconnected
:return: tuple(connected remotes, disconnected remotes) | [
"Partitions",
"the",
"remotes",
"into",
"connected",
"and",
"disconnected"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_core/network/network_interface.py#L206-L216 | train | 228,996 |
hyperledger/indy-plenum | plenum/client/wallet.py | Wallet.addIdentifier | def addIdentifier(self,
identifier=None,
seed=None,
signer=None,
alias=None,
didMethodName=None):
"""
Adds signer to the wallet.
Requires complete signer, identifier or seed.
:param identifier: signer identifier or None to use random one
:param seed: signer key seed or None to use random one
:param signer: signer to add
:param alias: a friendly readable name for the signer
:param didMethodName: name of DID Method if not the default
:return:
"""
dm = self.didMethods.get(didMethodName)
signer = signer or dm.newSigner(identifier=identifier, seed=seed)
self.idsToSigners[signer.identifier] = signer
if self.defaultId is None:
# setting this signer as default signer to let use sign* methods
# without explicit specification of signer
self.defaultId = signer.identifier
if alias:
signer.alias = alias
if signer.alias:
self.aliasesToIds[signer.alias] = signer.identifier
return signer.identifier, signer | python | def addIdentifier(self,
identifier=None,
seed=None,
signer=None,
alias=None,
didMethodName=None):
"""
Adds signer to the wallet.
Requires complete signer, identifier or seed.
:param identifier: signer identifier or None to use random one
:param seed: signer key seed or None to use random one
:param signer: signer to add
:param alias: a friendly readable name for the signer
:param didMethodName: name of DID Method if not the default
:return:
"""
dm = self.didMethods.get(didMethodName)
signer = signer or dm.newSigner(identifier=identifier, seed=seed)
self.idsToSigners[signer.identifier] = signer
if self.defaultId is None:
# setting this signer as default signer to let use sign* methods
# without explicit specification of signer
self.defaultId = signer.identifier
if alias:
signer.alias = alias
if signer.alias:
self.aliasesToIds[signer.alias] = signer.identifier
return signer.identifier, signer | [
"def",
"addIdentifier",
"(",
"self",
",",
"identifier",
"=",
"None",
",",
"seed",
"=",
"None",
",",
"signer",
"=",
"None",
",",
"alias",
"=",
"None",
",",
"didMethodName",
"=",
"None",
")",
":",
"dm",
"=",
"self",
".",
"didMethods",
".",
"get",
"(",
... | Adds signer to the wallet.
Requires complete signer, identifier or seed.
:param identifier: signer identifier or None to use random one
:param seed: signer key seed or None to use random one
:param signer: signer to add
:param alias: a friendly readable name for the signer
:param didMethodName: name of DID Method if not the default
:return: | [
"Adds",
"signer",
"to",
"the",
"wallet",
".",
"Requires",
"complete",
"signer",
"identifier",
"or",
"seed",
"."
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/client/wallet.py#L82-L111 | train | 228,997 |
hyperledger/indy-plenum | plenum/client/wallet.py | Wallet.requiredIdr | def requiredIdr(self,
idr: Identifier=None,
alias: str=None):
"""
Checks whether signer identifier specified, or can it be
inferred from alias or can be default used instead
:param idr:
:param alias:
:param other:
:return: signer identifier
"""
# TODO Need to create a new Identifier type that supports DIDs and CIDs
if idr:
if ':' in idr:
idr = idr.split(':')[1]
else:
idr = self.aliasesToIds[alias] if alias else self.defaultId
if not idr:
raise EmptyIdentifier
return idr | python | def requiredIdr(self,
idr: Identifier=None,
alias: str=None):
"""
Checks whether signer identifier specified, or can it be
inferred from alias or can be default used instead
:param idr:
:param alias:
:param other:
:return: signer identifier
"""
# TODO Need to create a new Identifier type that supports DIDs and CIDs
if idr:
if ':' in idr:
idr = idr.split(':')[1]
else:
idr = self.aliasesToIds[alias] if alias else self.defaultId
if not idr:
raise EmptyIdentifier
return idr | [
"def",
"requiredIdr",
"(",
"self",
",",
"idr",
":",
"Identifier",
"=",
"None",
",",
"alias",
":",
"str",
"=",
"None",
")",
":",
"# TODO Need to create a new Identifier type that supports DIDs and CIDs",
"if",
"idr",
":",
"if",
"':'",
"in",
"idr",
":",
"idr",
"... | Checks whether signer identifier specified, or can it be
inferred from alias or can be default used instead
:param idr:
:param alias:
:param other:
:return: signer identifier | [
"Checks",
"whether",
"signer",
"identifier",
"specified",
"or",
"can",
"it",
"be",
"inferred",
"from",
"alias",
"or",
"can",
"be",
"default",
"used",
"instead"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/client/wallet.py#L139-L161 | train | 228,998 |
hyperledger/indy-plenum | plenum/client/wallet.py | Wallet.signMsg | def signMsg(self,
msg: Dict,
identifier: Identifier=None,
otherIdentifier: Identifier=None):
"""
Creates signature for message using specified signer
:param msg: message to sign
:param identifier: signer identifier
:param otherIdentifier:
:return: signature that then can be assigned to request
"""
idr = self.requiredIdr(idr=identifier or otherIdentifier)
signer = self._signerById(idr)
signature = signer.sign(msg)
return signature | python | def signMsg(self,
msg: Dict,
identifier: Identifier=None,
otherIdentifier: Identifier=None):
"""
Creates signature for message using specified signer
:param msg: message to sign
:param identifier: signer identifier
:param otherIdentifier:
:return: signature that then can be assigned to request
"""
idr = self.requiredIdr(idr=identifier or otherIdentifier)
signer = self._signerById(idr)
signature = signer.sign(msg)
return signature | [
"def",
"signMsg",
"(",
"self",
",",
"msg",
":",
"Dict",
",",
"identifier",
":",
"Identifier",
"=",
"None",
",",
"otherIdentifier",
":",
"Identifier",
"=",
"None",
")",
":",
"idr",
"=",
"self",
".",
"requiredIdr",
"(",
"idr",
"=",
"identifier",
"or",
"o... | Creates signature for message using specified signer
:param msg: message to sign
:param identifier: signer identifier
:param otherIdentifier:
:return: signature that then can be assigned to request | [
"Creates",
"signature",
"for",
"message",
"using",
"specified",
"signer"
] | dcd144e238af7f17a869ffc9412f13dc488b7020 | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/client/wallet.py#L163-L178 | train | 228,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.