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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
NASA-AMMOS/AIT-Core | ait/core/bsc.py | SocketStreamCapturer.capture_packet | def capture_packet(self):
''' Write packet data to the logger's log file. '''
data = self.socket.recv(self._buffer_size)
for h in self.capture_handlers:
h['reads'] += 1
h['data_read'] += len(data)
d = data
if 'pre_write_transforms' in h:
for data_transform in h['pre_write_transforms']:
d = data_transform(d)
h['logger'].write(d) | python | def capture_packet(self):
''' Write packet data to the logger's log file. '''
data = self.socket.recv(self._buffer_size)
for h in self.capture_handlers:
h['reads'] += 1
h['data_read'] += len(data)
d = data
if 'pre_write_transforms' in h:
for data_transform in h['pre_write_transforms']:
d = data_transform(d)
h['logger'].write(d) | [
"def",
"capture_packet",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"socket",
".",
"recv",
"(",
"self",
".",
"_buffer_size",
")",
"for",
"h",
"in",
"self",
".",
"capture_handlers",
":",
"h",
"[",
"'reads'",
"]",
"+=",
"1",
"h",
"[",
"'data_read... | Write packet data to the logger's log file. | [
"Write",
"packet",
"data",
"to",
"the",
"logger",
"s",
"log",
"file",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/bsc.py#L209-L221 | train | 42,700 |
NASA-AMMOS/AIT-Core | ait/core/bsc.py | SocketStreamCapturer.clean_up | def clean_up(self):
''' Clean up the socket and log file handles. '''
self.socket.close()
for h in self.capture_handlers:
h['logger'].close() | python | def clean_up(self):
''' Clean up the socket and log file handles. '''
self.socket.close()
for h in self.capture_handlers:
h['logger'].close() | [
"def",
"clean_up",
"(",
"self",
")",
":",
"self",
".",
"socket",
".",
"close",
"(",
")",
"for",
"h",
"in",
"self",
".",
"capture_handlers",
":",
"h",
"[",
"'logger'",
"]",
".",
"close",
"(",
")"
] | Clean up the socket and log file handles. | [
"Clean",
"up",
"the",
"socket",
"and",
"log",
"file",
"handles",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/bsc.py#L223-L227 | train | 42,701 |
NASA-AMMOS/AIT-Core | ait/core/bsc.py | SocketStreamCapturer.socket_monitor_loop | def socket_monitor_loop(self):
''' Monitor the socket and log captured data. '''
try:
while True:
gevent.socket.wait_read(self.socket.fileno())
self._handle_log_rotations()
self.capture_packet()
finally:
self.clean_up() | python | def socket_monitor_loop(self):
''' Monitor the socket and log captured data. '''
try:
while True:
gevent.socket.wait_read(self.socket.fileno())
self._handle_log_rotations()
self.capture_packet()
finally:
self.clean_up() | [
"def",
"socket_monitor_loop",
"(",
"self",
")",
":",
"try",
":",
"while",
"True",
":",
"gevent",
".",
"socket",
".",
"wait_read",
"(",
"self",
".",
"socket",
".",
"fileno",
"(",
")",
")",
"self",
".",
"_handle_log_rotations",
"(",
")",
"self",
".",
"ca... | Monitor the socket and log captured data. | [
"Monitor",
"the",
"socket",
"and",
"log",
"captured",
"data",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/bsc.py#L229-L238 | train | 42,702 |
NASA-AMMOS/AIT-Core | ait/core/bsc.py | SocketStreamCapturer.add_handler | def add_handler(self, handler):
''' Add an additional handler
Args:
handler:
A dictionary of handler configuration for the handler
that should be added. See :func:`__init__` for details
on valid parameters.
'''
handler['logger'] = self._get_logger(handler)
handler['reads'] = 0
handler['data_read'] = 0
self.capture_handlers.append(handler) | python | def add_handler(self, handler):
''' Add an additional handler
Args:
handler:
A dictionary of handler configuration for the handler
that should be added. See :func:`__init__` for details
on valid parameters.
'''
handler['logger'] = self._get_logger(handler)
handler['reads'] = 0
handler['data_read'] = 0
self.capture_handlers.append(handler) | [
"def",
"add_handler",
"(",
"self",
",",
"handler",
")",
":",
"handler",
"[",
"'logger'",
"]",
"=",
"self",
".",
"_get_logger",
"(",
"handler",
")",
"handler",
"[",
"'reads'",
"]",
"=",
"0",
"handler",
"[",
"'data_read'",
"]",
"=",
"0",
"self",
".",
"... | Add an additional handler
Args:
handler:
A dictionary of handler configuration for the handler
that should be added. See :func:`__init__` for details
on valid parameters. | [
"Add",
"an",
"additional",
"handler"
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/bsc.py#L240-L253 | train | 42,703 |
NASA-AMMOS/AIT-Core | ait/core/bsc.py | SocketStreamCapturer.remove_handler | def remove_handler(self, name):
''' Remove a handler given a name
Note, if multiple handlers have the same name the last matching
instance in the handler list will be removed.
Args:
name:
The name of the handler to remove
'''
index = None
for i, h in enumerate(self.capture_handlers):
if h['name'] == name:
index = i
if index is not None:
self.capture_handlers[index]['logger'].close()
del self.capture_handlers[index] | python | def remove_handler(self, name):
''' Remove a handler given a name
Note, if multiple handlers have the same name the last matching
instance in the handler list will be removed.
Args:
name:
The name of the handler to remove
'''
index = None
for i, h in enumerate(self.capture_handlers):
if h['name'] == name:
index = i
if index is not None:
self.capture_handlers[index]['logger'].close()
del self.capture_handlers[index] | [
"def",
"remove_handler",
"(",
"self",
",",
"name",
")",
":",
"index",
"=",
"None",
"for",
"i",
",",
"h",
"in",
"enumerate",
"(",
"self",
".",
"capture_handlers",
")",
":",
"if",
"h",
"[",
"'name'",
"]",
"==",
"name",
":",
"index",
"=",
"i",
"if",
... | Remove a handler given a name
Note, if multiple handlers have the same name the last matching
instance in the handler list will be removed.
Args:
name:
The name of the handler to remove | [
"Remove",
"a",
"handler",
"given",
"a",
"name"
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/bsc.py#L255-L272 | train | 42,704 |
NASA-AMMOS/AIT-Core | ait/core/bsc.py | SocketStreamCapturer.dump_handler_config_data | def dump_handler_config_data(self):
''' Return capture handler configuration data.
Return a dictionary of capture handler configuration data of the form:
.. code-block:: none
[{
'handler': <handler configuration dictionary>,
'log_file_path': <Path to the current log file that the logger
is writing. Note that if rotation is used it\'s possible
this data will be stale eventually.>,
'conn_type': <The string defining the connection type of the
logger.>,
'address': <The list containing address info that the logger is
using for its connection.>
}, ...]
'''
ignored_keys = ['logger', 'log_rot_time', 'reads', 'data_read']
config_data = []
for h in self.capture_handlers:
config_data.append({
'handler': {
k:v for k, v in h.iteritems()
if k not in ignored_keys
},
'log_file_path': h['logger']._stream.name,
'conn_type': self.conn_type,
'address': self.address,
})
return config_data | python | def dump_handler_config_data(self):
''' Return capture handler configuration data.
Return a dictionary of capture handler configuration data of the form:
.. code-block:: none
[{
'handler': <handler configuration dictionary>,
'log_file_path': <Path to the current log file that the logger
is writing. Note that if rotation is used it\'s possible
this data will be stale eventually.>,
'conn_type': <The string defining the connection type of the
logger.>,
'address': <The list containing address info that the logger is
using for its connection.>
}, ...]
'''
ignored_keys = ['logger', 'log_rot_time', 'reads', 'data_read']
config_data = []
for h in self.capture_handlers:
config_data.append({
'handler': {
k:v for k, v in h.iteritems()
if k not in ignored_keys
},
'log_file_path': h['logger']._stream.name,
'conn_type': self.conn_type,
'address': self.address,
})
return config_data | [
"def",
"dump_handler_config_data",
"(",
"self",
")",
":",
"ignored_keys",
"=",
"[",
"'logger'",
",",
"'log_rot_time'",
",",
"'reads'",
",",
"'data_read'",
"]",
"config_data",
"=",
"[",
"]",
"for",
"h",
"in",
"self",
".",
"capture_handlers",
":",
"config_data",... | Return capture handler configuration data.
Return a dictionary of capture handler configuration data of the form:
.. code-block:: none
[{
'handler': <handler configuration dictionary>,
'log_file_path': <Path to the current log file that the logger
is writing. Note that if rotation is used it\'s possible
this data will be stale eventually.>,
'conn_type': <The string defining the connection type of the
logger.>,
'address': <The list containing address info that the logger is
using for its connection.>
}, ...] | [
"Return",
"capture",
"handler",
"configuration",
"data",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/bsc.py#L274-L308 | train | 42,705 |
NASA-AMMOS/AIT-Core | ait/core/bsc.py | SocketStreamCapturer.dump_all_handler_stats | def dump_all_handler_stats(self):
''' Return handler capture statistics
Return a dictionary of capture handler statistics of the form:
.. code-block:: none
[{
'name': The handler's name,
'reads': The number of packet reads this handler has received
'data_read_length': The total length of the data received
'approx_data_rate': The approximate data rate for this handler
}, ...]
'''
stats = []
for h in self.capture_handlers:
now = calendar.timegm(time.gmtime())
rot_time = calendar.timegm(h['log_rot_time'])
time_delta = now - rot_time
approx_data_rate = '{} bytes/second'.format(h['data_read'] / float(time_delta))
stats.append({
'name': h['name'],
'reads': h['reads'],
'data_read_length': '{} bytes'.format(h['data_read']),
'approx_data_rate': approx_data_rate
})
return stats | python | def dump_all_handler_stats(self):
''' Return handler capture statistics
Return a dictionary of capture handler statistics of the form:
.. code-block:: none
[{
'name': The handler's name,
'reads': The number of packet reads this handler has received
'data_read_length': The total length of the data received
'approx_data_rate': The approximate data rate for this handler
}, ...]
'''
stats = []
for h in self.capture_handlers:
now = calendar.timegm(time.gmtime())
rot_time = calendar.timegm(h['log_rot_time'])
time_delta = now - rot_time
approx_data_rate = '{} bytes/second'.format(h['data_read'] / float(time_delta))
stats.append({
'name': h['name'],
'reads': h['reads'],
'data_read_length': '{} bytes'.format(h['data_read']),
'approx_data_rate': approx_data_rate
})
return stats | [
"def",
"dump_all_handler_stats",
"(",
"self",
")",
":",
"stats",
"=",
"[",
"]",
"for",
"h",
"in",
"self",
".",
"capture_handlers",
":",
"now",
"=",
"calendar",
".",
"timegm",
"(",
"time",
".",
"gmtime",
"(",
")",
")",
"rot_time",
"=",
"calendar",
".",
... | Return handler capture statistics
Return a dictionary of capture handler statistics of the form:
.. code-block:: none
[{
'name': The handler's name,
'reads': The number of packet reads this handler has received
'data_read_length': The total length of the data received
'approx_data_rate': The approximate data rate for this handler
}, ...] | [
"Return",
"handler",
"capture",
"statistics"
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/bsc.py#L310-L342 | train | 42,706 |
NASA-AMMOS/AIT-Core | ait/core/bsc.py | SocketStreamCapturer._handle_log_rotations | def _handle_log_rotations(self):
''' Rotate each handler's log file if necessary '''
for h in self.capture_handlers:
if self._should_rotate_log(h):
self._rotate_log(h) | python | def _handle_log_rotations(self):
''' Rotate each handler's log file if necessary '''
for h in self.capture_handlers:
if self._should_rotate_log(h):
self._rotate_log(h) | [
"def",
"_handle_log_rotations",
"(",
"self",
")",
":",
"for",
"h",
"in",
"self",
".",
"capture_handlers",
":",
"if",
"self",
".",
"_should_rotate_log",
"(",
"h",
")",
":",
"self",
".",
"_rotate_log",
"(",
"h",
")"
] | Rotate each handler's log file if necessary | [
"Rotate",
"each",
"handler",
"s",
"log",
"file",
"if",
"necessary"
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/bsc.py#L344-L348 | train | 42,707 |
NASA-AMMOS/AIT-Core | ait/core/bsc.py | SocketStreamCapturer._should_rotate_log | def _should_rotate_log(self, handler):
''' Determine if a log file rotation is necessary '''
if handler['rotate_log']:
rotate_time_index = handler.get('rotate_log_index', 'day')
try:
rotate_time_index = self._decode_time_rotation_index(rotate_time_index)
except ValueError:
rotate_time_index = 2
rotate_time_delta = handler.get('rotate_log_delta', 1)
cur_t = time.gmtime()
first_different_index = 9
for i in range(9):
if cur_t[i] != handler['log_rot_time'][i]:
first_different_index = i
break
if first_different_index < rotate_time_index:
# If the time deltas differ by a time step greater than what we
# have set for the rotation (I.e., months instead of days) we will
# automatically rotate.
return True
else:
time_delta = cur_t[rotate_time_index] - handler['log_rot_time'][rotate_time_index]
return time_delta >= rotate_time_delta
return False | python | def _should_rotate_log(self, handler):
''' Determine if a log file rotation is necessary '''
if handler['rotate_log']:
rotate_time_index = handler.get('rotate_log_index', 'day')
try:
rotate_time_index = self._decode_time_rotation_index(rotate_time_index)
except ValueError:
rotate_time_index = 2
rotate_time_delta = handler.get('rotate_log_delta', 1)
cur_t = time.gmtime()
first_different_index = 9
for i in range(9):
if cur_t[i] != handler['log_rot_time'][i]:
first_different_index = i
break
if first_different_index < rotate_time_index:
# If the time deltas differ by a time step greater than what we
# have set for the rotation (I.e., months instead of days) we will
# automatically rotate.
return True
else:
time_delta = cur_t[rotate_time_index] - handler['log_rot_time'][rotate_time_index]
return time_delta >= rotate_time_delta
return False | [
"def",
"_should_rotate_log",
"(",
"self",
",",
"handler",
")",
":",
"if",
"handler",
"[",
"'rotate_log'",
"]",
":",
"rotate_time_index",
"=",
"handler",
".",
"get",
"(",
"'rotate_log_index'",
",",
"'day'",
")",
"try",
":",
"rotate_time_index",
"=",
"self",
"... | Determine if a log file rotation is necessary | [
"Determine",
"if",
"a",
"log",
"file",
"rotation",
"is",
"necessary"
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/bsc.py#L350-L377 | train | 42,708 |
NASA-AMMOS/AIT-Core | ait/core/bsc.py | SocketStreamCapturer._decode_time_rotation_index | def _decode_time_rotation_index(self, time_rot_index):
''' Return the time struct index to use for log rotation checks '''
time_index_decode_table = {
'year': 0, 'years': 0, 'tm_year': 0,
'month': 1, 'months': 1, 'tm_mon': 1,
'day': 2, 'days': 2, 'tm_mday': 2,
'hour': 3, 'hours': 3, 'tm_hour': 3,
'minute': 4, 'minutes': 4, 'tm_min': 4,
'second': 5, 'seconds': 5, 'tm_sec': 5,
}
if time_rot_index not in time_index_decode_table.keys():
raise ValueError('Invalid time option specified for log rotation')
return time_index_decode_table[time_rot_index] | python | def _decode_time_rotation_index(self, time_rot_index):
''' Return the time struct index to use for log rotation checks '''
time_index_decode_table = {
'year': 0, 'years': 0, 'tm_year': 0,
'month': 1, 'months': 1, 'tm_mon': 1,
'day': 2, 'days': 2, 'tm_mday': 2,
'hour': 3, 'hours': 3, 'tm_hour': 3,
'minute': 4, 'minutes': 4, 'tm_min': 4,
'second': 5, 'seconds': 5, 'tm_sec': 5,
}
if time_rot_index not in time_index_decode_table.keys():
raise ValueError('Invalid time option specified for log rotation')
return time_index_decode_table[time_rot_index] | [
"def",
"_decode_time_rotation_index",
"(",
"self",
",",
"time_rot_index",
")",
":",
"time_index_decode_table",
"=",
"{",
"'year'",
":",
"0",
",",
"'years'",
":",
"0",
",",
"'tm_year'",
":",
"0",
",",
"'month'",
":",
"1",
",",
"'months'",
":",
"1",
",",
"... | Return the time struct index to use for log rotation checks | [
"Return",
"the",
"time",
"struct",
"index",
"to",
"use",
"for",
"log",
"rotation",
"checks"
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/bsc.py#L379-L393 | train | 42,709 |
NASA-AMMOS/AIT-Core | ait/core/bsc.py | SocketStreamCapturer._get_log_file | def _get_log_file(self, handler):
''' Generate log file path for a given handler
Args:
handler:
The handler configuration dictionary for which a log file
path should be generated.
'''
if 'file_name_pattern' not in handler:
filename = '%Y-%m-%d-%H-%M-%S-{name}.pcap'
else:
filename = handler['file_name_pattern']
log_file = handler['log_dir']
if 'path' in handler:
log_file = os.path.join(log_file, handler['path'], filename)
else:
log_file = os.path.join(log_file, filename)
log_file = time.strftime(log_file, time.gmtime())
log_file = log_file.format(**handler)
return log_file | python | def _get_log_file(self, handler):
''' Generate log file path for a given handler
Args:
handler:
The handler configuration dictionary for which a log file
path should be generated.
'''
if 'file_name_pattern' not in handler:
filename = '%Y-%m-%d-%H-%M-%S-{name}.pcap'
else:
filename = handler['file_name_pattern']
log_file = handler['log_dir']
if 'path' in handler:
log_file = os.path.join(log_file, handler['path'], filename)
else:
log_file = os.path.join(log_file, filename)
log_file = time.strftime(log_file, time.gmtime())
log_file = log_file.format(**handler)
return log_file | [
"def",
"_get_log_file",
"(",
"self",
",",
"handler",
")",
":",
"if",
"'file_name_pattern'",
"not",
"in",
"handler",
":",
"filename",
"=",
"'%Y-%m-%d-%H-%M-%S-{name}.pcap'",
"else",
":",
"filename",
"=",
"handler",
"[",
"'file_name_pattern'",
"]",
"log_file",
"=",
... | Generate log file path for a given handler
Args:
handler:
The handler configuration dictionary for which a log file
path should be generated. | [
"Generate",
"log",
"file",
"path",
"for",
"a",
"given",
"handler"
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/bsc.py#L400-L422 | train | 42,710 |
NASA-AMMOS/AIT-Core | ait/core/bsc.py | SocketStreamCapturer._get_logger | def _get_logger(self, handler):
''' Initialize a PCAP stream for logging data '''
log_file = self._get_log_file(handler)
if not os.path.isdir(os.path.dirname(log_file)):
os.makedirs(os.path.dirname(log_file))
handler['log_rot_time'] = time.gmtime()
return pcap.open(log_file, mode='a') | python | def _get_logger(self, handler):
''' Initialize a PCAP stream for logging data '''
log_file = self._get_log_file(handler)
if not os.path.isdir(os.path.dirname(log_file)):
os.makedirs(os.path.dirname(log_file))
handler['log_rot_time'] = time.gmtime()
return pcap.open(log_file, mode='a') | [
"def",
"_get_logger",
"(",
"self",
",",
"handler",
")",
":",
"log_file",
"=",
"self",
".",
"_get_log_file",
"(",
"handler",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"log_file",
")",
")",
":",
"... | Initialize a PCAP stream for logging data | [
"Initialize",
"a",
"PCAP",
"stream",
"for",
"logging",
"data"
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/bsc.py#L424-L432 | train | 42,711 |
NASA-AMMOS/AIT-Core | ait/core/bsc.py | StreamCaptureManager.add_logger | def add_logger(self, name, address, conn_type, log_dir_path=None, **kwargs):
''' Add a new stream capturer to the manager.
Add a new stream capturer to the manager with the provided configuration
details. If an existing capturer is monitoring the same address the
new handler will be added to it.
Args:
name:
A string defining the new capturer's name.
address:
A tuple containing address data for the capturer. Check the
:class:`SocketStreamCapturer` documentation for what is
required.
conn_type:
A string defining the connection type. Check the
:class:`SocketStreamCapturer` documentation for a list of valid
options.
log_dir_path:
An optional path defining the directory where the
capturer should write its files. If this isn't provided the root
log directory from the manager configuration is used.
'''
capture_handler_conf = kwargs
if not log_dir_path:
log_dir_path = self._mngr_conf['root_log_directory']
log_dir_path = os.path.normpath(os.path.expanduser(log_dir_path))
capture_handler_conf['log_dir'] = log_dir_path
capture_handler_conf['name'] = name
if 'rotate_log' not in capture_handler_conf:
capture_handler_conf['rotate_log'] = True
transforms = []
if 'pre_write_transforms' in capture_handler_conf:
for transform in capture_handler_conf['pre_write_transforms']:
if isinstance(transform, str):
if globals().has_key(transform):
transforms.append(globals().get(transform))
else:
msg = (
'Unable to load data transformation '
'"{}" for handler "{}"'
).format(
transform,
capture_handler_conf['name']
)
log.warn(msg)
elif hasattr(transform, '__call__'):
transforms.append(transform)
else:
msg = (
'Unable to determine how to load data transform "{}"'
).format(transform)
log.warn(msg)
capture_handler_conf['pre_write_transforms'] = transforms
address_key = str(address)
if address_key in self._stream_capturers:
capturer = self._stream_capturers[address_key][0]
capturer.add_handler(capture_handler_conf)
return
socket_logger = SocketStreamCapturer(capture_handler_conf,
address,
conn_type)
greenlet = gevent.spawn(socket_logger.socket_monitor_loop)
self._stream_capturers[address_key] = (
socket_logger,
greenlet
)
self._pool.add(greenlet) | python | def add_logger(self, name, address, conn_type, log_dir_path=None, **kwargs):
''' Add a new stream capturer to the manager.
Add a new stream capturer to the manager with the provided configuration
details. If an existing capturer is monitoring the same address the
new handler will be added to it.
Args:
name:
A string defining the new capturer's name.
address:
A tuple containing address data for the capturer. Check the
:class:`SocketStreamCapturer` documentation for what is
required.
conn_type:
A string defining the connection type. Check the
:class:`SocketStreamCapturer` documentation for a list of valid
options.
log_dir_path:
An optional path defining the directory where the
capturer should write its files. If this isn't provided the root
log directory from the manager configuration is used.
'''
capture_handler_conf = kwargs
if not log_dir_path:
log_dir_path = self._mngr_conf['root_log_directory']
log_dir_path = os.path.normpath(os.path.expanduser(log_dir_path))
capture_handler_conf['log_dir'] = log_dir_path
capture_handler_conf['name'] = name
if 'rotate_log' not in capture_handler_conf:
capture_handler_conf['rotate_log'] = True
transforms = []
if 'pre_write_transforms' in capture_handler_conf:
for transform in capture_handler_conf['pre_write_transforms']:
if isinstance(transform, str):
if globals().has_key(transform):
transforms.append(globals().get(transform))
else:
msg = (
'Unable to load data transformation '
'"{}" for handler "{}"'
).format(
transform,
capture_handler_conf['name']
)
log.warn(msg)
elif hasattr(transform, '__call__'):
transforms.append(transform)
else:
msg = (
'Unable to determine how to load data transform "{}"'
).format(transform)
log.warn(msg)
capture_handler_conf['pre_write_transforms'] = transforms
address_key = str(address)
if address_key in self._stream_capturers:
capturer = self._stream_capturers[address_key][0]
capturer.add_handler(capture_handler_conf)
return
socket_logger = SocketStreamCapturer(capture_handler_conf,
address,
conn_type)
greenlet = gevent.spawn(socket_logger.socket_monitor_loop)
self._stream_capturers[address_key] = (
socket_logger,
greenlet
)
self._pool.add(greenlet) | [
"def",
"add_logger",
"(",
"self",
",",
"name",
",",
"address",
",",
"conn_type",
",",
"log_dir_path",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"capture_handler_conf",
"=",
"kwargs",
"if",
"not",
"log_dir_path",
":",
"log_dir_path",
"=",
"self",
".",... | Add a new stream capturer to the manager.
Add a new stream capturer to the manager with the provided configuration
details. If an existing capturer is monitoring the same address the
new handler will be added to it.
Args:
name:
A string defining the new capturer's name.
address:
A tuple containing address data for the capturer. Check the
:class:`SocketStreamCapturer` documentation for what is
required.
conn_type:
A string defining the connection type. Check the
:class:`SocketStreamCapturer` documentation for a list of valid
options.
log_dir_path:
An optional path defining the directory where the
capturer should write its files. If this isn't provided the root
log directory from the manager configuration is used. | [
"Add",
"a",
"new",
"stream",
"capturer",
"to",
"the",
"manager",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/bsc.py#L480-L558 | train | 42,712 |
NASA-AMMOS/AIT-Core | ait/core/bsc.py | StreamCaptureManager.stop_capture_handler | def stop_capture_handler(self, name):
''' Remove all handlers with a given name
Args:
name:
The name of the handler(s) to remove.
'''
empty_capturers_indeces = []
for k, sc in self._stream_capturers.iteritems():
stream_capturer = sc[0]
stream_capturer.remove_handler(name)
if stream_capturer.handler_count == 0:
self._pool.killone(sc[1])
empty_capturers_indeces.append(k)
for i in empty_capturers_indeces:
del self._stream_capturers[i] | python | def stop_capture_handler(self, name):
''' Remove all handlers with a given name
Args:
name:
The name of the handler(s) to remove.
'''
empty_capturers_indeces = []
for k, sc in self._stream_capturers.iteritems():
stream_capturer = sc[0]
stream_capturer.remove_handler(name)
if stream_capturer.handler_count == 0:
self._pool.killone(sc[1])
empty_capturers_indeces.append(k)
for i in empty_capturers_indeces:
del self._stream_capturers[i] | [
"def",
"stop_capture_handler",
"(",
"self",
",",
"name",
")",
":",
"empty_capturers_indeces",
"=",
"[",
"]",
"for",
"k",
",",
"sc",
"in",
"self",
".",
"_stream_capturers",
".",
"iteritems",
"(",
")",
":",
"stream_capturer",
"=",
"sc",
"[",
"0",
"]",
"str... | Remove all handlers with a given name
Args:
name:
The name of the handler(s) to remove. | [
"Remove",
"all",
"handlers",
"with",
"a",
"given",
"name"
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/bsc.py#L560-L577 | train | 42,713 |
NASA-AMMOS/AIT-Core | ait/core/bsc.py | StreamCaptureManager.stop_stream_capturer | def stop_stream_capturer(self, address):
''' Stop a capturer that the manager controls.
Args:
address:
An address array of the form ['host', 'port'] or similar
depending on the connection type of the stream capturer being
terminated. The capturer for the address will be terminated
along with all handlers for that capturer if the address is
that of a managed capturer.
Raises:
ValueError:
The provided address doesn't match a capturer that is
currently managed.
'''
address = str(address)
if address not in self._stream_capturers:
raise ValueError('Capturer address does not match a managed capturer')
stream_cap = self._stream_capturers[address]
self._pool.killone(stream_cap[1])
del self._stream_capturers[address] | python | def stop_stream_capturer(self, address):
''' Stop a capturer that the manager controls.
Args:
address:
An address array of the form ['host', 'port'] or similar
depending on the connection type of the stream capturer being
terminated. The capturer for the address will be terminated
along with all handlers for that capturer if the address is
that of a managed capturer.
Raises:
ValueError:
The provided address doesn't match a capturer that is
currently managed.
'''
address = str(address)
if address not in self._stream_capturers:
raise ValueError('Capturer address does not match a managed capturer')
stream_cap = self._stream_capturers[address]
self._pool.killone(stream_cap[1])
del self._stream_capturers[address] | [
"def",
"stop_stream_capturer",
"(",
"self",
",",
"address",
")",
":",
"address",
"=",
"str",
"(",
"address",
")",
"if",
"address",
"not",
"in",
"self",
".",
"_stream_capturers",
":",
"raise",
"ValueError",
"(",
"'Capturer address does not match a managed capturer'",... | Stop a capturer that the manager controls.
Args:
address:
An address array of the form ['host', 'port'] or similar
depending on the connection type of the stream capturer being
terminated. The capturer for the address will be terminated
along with all handlers for that capturer if the address is
that of a managed capturer.
Raises:
ValueError:
The provided address doesn't match a capturer that is
currently managed. | [
"Stop",
"a",
"capturer",
"that",
"the",
"manager",
"controls",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/bsc.py#L579-L601 | train | 42,714 |
NASA-AMMOS/AIT-Core | ait/core/bsc.py | StreamCaptureManager.rotate_capture_handler_log | def rotate_capture_handler_log(self, name):
''' Force a rotation of a handler's log file
Args:
name:
The name of the handler who's log file should be rotated.
'''
for sc_key, sc in self._stream_capturers.iteritems():
for h in sc[0].capture_handlers:
if h['name'] == name:
sc[0]._rotate_log(h) | python | def rotate_capture_handler_log(self, name):
''' Force a rotation of a handler's log file
Args:
name:
The name of the handler who's log file should be rotated.
'''
for sc_key, sc in self._stream_capturers.iteritems():
for h in sc[0].capture_handlers:
if h['name'] == name:
sc[0]._rotate_log(h) | [
"def",
"rotate_capture_handler_log",
"(",
"self",
",",
"name",
")",
":",
"for",
"sc_key",
",",
"sc",
"in",
"self",
".",
"_stream_capturers",
".",
"iteritems",
"(",
")",
":",
"for",
"h",
"in",
"sc",
"[",
"0",
"]",
".",
"capture_handlers",
":",
"if",
"h"... | Force a rotation of a handler's log file
Args:
name:
The name of the handler who's log file should be rotated. | [
"Force",
"a",
"rotation",
"of",
"a",
"handler",
"s",
"log",
"file"
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/bsc.py#L603-L613 | train | 42,715 |
NASA-AMMOS/AIT-Core | ait/core/bsc.py | StreamCaptureManager.get_logger_data | def get_logger_data(self):
''' Return data on managed loggers.
Returns a dictionary of managed logger configuration data. The format
is primarily controlled by the
:func:`SocketStreamCapturer.dump_handler_config_data` function::
{
<capture address>: <list of handler config for data capturers>
}
'''
return {
address : stream_capturer[0].dump_handler_config_data()
for address, stream_capturer in self._stream_capturers.iteritems()
} | python | def get_logger_data(self):
''' Return data on managed loggers.
Returns a dictionary of managed logger configuration data. The format
is primarily controlled by the
:func:`SocketStreamCapturer.dump_handler_config_data` function::
{
<capture address>: <list of handler config for data capturers>
}
'''
return {
address : stream_capturer[0].dump_handler_config_data()
for address, stream_capturer in self._stream_capturers.iteritems()
} | [
"def",
"get_logger_data",
"(",
"self",
")",
":",
"return",
"{",
"address",
":",
"stream_capturer",
"[",
"0",
"]",
".",
"dump_handler_config_data",
"(",
")",
"for",
"address",
",",
"stream_capturer",
"in",
"self",
".",
"_stream_capturers",
".",
"iteritems",
"("... | Return data on managed loggers.
Returns a dictionary of managed logger configuration data. The format
is primarily controlled by the
:func:`SocketStreamCapturer.dump_handler_config_data` function::
{
<capture address>: <list of handler config for data capturers>
} | [
"Return",
"data",
"on",
"managed",
"loggers",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/bsc.py#L615-L630 | train | 42,716 |
NASA-AMMOS/AIT-Core | ait/core/bsc.py | StreamCaptureManager.get_handler_stats | def get_handler_stats(self):
''' Return handler read statistics
Returns a dictionary of managed handler data read statistics. The
format is primarily controlled by the
:func:`SocketStreamCapturer.dump_all_handler_stats` function::
{
<capture address>: <list of handler capture statistics>
}
'''
return {
address : stream_capturer[0].dump_all_handler_stats()
for address, stream_capturer in self._stream_capturers.iteritems()
} | python | def get_handler_stats(self):
''' Return handler read statistics
Returns a dictionary of managed handler data read statistics. The
format is primarily controlled by the
:func:`SocketStreamCapturer.dump_all_handler_stats` function::
{
<capture address>: <list of handler capture statistics>
}
'''
return {
address : stream_capturer[0].dump_all_handler_stats()
for address, stream_capturer in self._stream_capturers.iteritems()
} | [
"def",
"get_handler_stats",
"(",
"self",
")",
":",
"return",
"{",
"address",
":",
"stream_capturer",
"[",
"0",
"]",
".",
"dump_all_handler_stats",
"(",
")",
"for",
"address",
",",
"stream_capturer",
"in",
"self",
".",
"_stream_capturers",
".",
"iteritems",
"("... | Return handler read statistics
Returns a dictionary of managed handler data read statistics. The
format is primarily controlled by the
:func:`SocketStreamCapturer.dump_all_handler_stats` function::
{
<capture address>: <list of handler capture statistics>
} | [
"Return",
"handler",
"read",
"statistics"
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/bsc.py#L632-L647 | train | 42,717 |
NASA-AMMOS/AIT-Core | ait/core/bsc.py | StreamCaptureManager.get_capture_handler_config_by_name | def get_capture_handler_config_by_name(self, name):
''' Return data for handlers of a given name.
Args:
name:
Name of the capture handler(s) to return config data for.
Returns:
Dictionary dump from the named capture handler as given by
the :func:`SocketStreamCapturer.dump_handler_config_data` method.
'''
handler_confs = []
for address, stream_capturer in self._stream_capturers.iteritems():
handler_data = stream_capturer[0].dump_handler_config_data()
for h in handler_data:
if h['handler']['name'] == name:
handler_confs.append(h)
return handler_confs | python | def get_capture_handler_config_by_name(self, name):
''' Return data for handlers of a given name.
Args:
name:
Name of the capture handler(s) to return config data for.
Returns:
Dictionary dump from the named capture handler as given by
the :func:`SocketStreamCapturer.dump_handler_config_data` method.
'''
handler_confs = []
for address, stream_capturer in self._stream_capturers.iteritems():
handler_data = stream_capturer[0].dump_handler_config_data()
for h in handler_data:
if h['handler']['name'] == name:
handler_confs.append(h)
return handler_confs | [
"def",
"get_capture_handler_config_by_name",
"(",
"self",
",",
"name",
")",
":",
"handler_confs",
"=",
"[",
"]",
"for",
"address",
",",
"stream_capturer",
"in",
"self",
".",
"_stream_capturers",
".",
"iteritems",
"(",
")",
":",
"handler_data",
"=",
"stream_captu... | Return data for handlers of a given name.
Args:
name:
Name of the capture handler(s) to return config data for.
Returns:
Dictionary dump from the named capture handler as given by
the :func:`SocketStreamCapturer.dump_handler_config_data` method. | [
"Return",
"data",
"for",
"handlers",
"of",
"a",
"given",
"name",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/bsc.py#L649-L667 | train | 42,718 |
NASA-AMMOS/AIT-Core | ait/core/bsc.py | StreamCaptureManager.run_socket_event_loop | def run_socket_event_loop(self):
''' Start monitoring managed loggers. '''
try:
while True:
self._pool.join()
# If we have no loggers we'll sleep briefly to ensure that we
# allow other processes (I.e., the webserver) to do their work.
if len(self._logger_data.keys()) == 0:
time.sleep(0.5)
except KeyboardInterrupt:
pass
finally:
self._pool.kill() | python | def run_socket_event_loop(self):
''' Start monitoring managed loggers. '''
try:
while True:
self._pool.join()
# If we have no loggers we'll sleep briefly to ensure that we
# allow other processes (I.e., the webserver) to do their work.
if len(self._logger_data.keys()) == 0:
time.sleep(0.5)
except KeyboardInterrupt:
pass
finally:
self._pool.kill() | [
"def",
"run_socket_event_loop",
"(",
"self",
")",
":",
"try",
":",
"while",
"True",
":",
"self",
".",
"_pool",
".",
"join",
"(",
")",
"# If we have no loggers we'll sleep briefly to ensure that we",
"# allow other processes (I.e., the webserver) to do their work.",
"if",
"l... | Start monitoring managed loggers. | [
"Start",
"monitoring",
"managed",
"loggers",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/bsc.py#L669-L683 | train | 42,719 |
NASA-AMMOS/AIT-Core | ait/core/bsc.py | StreamCaptureManagerServer._route | def _route(self):
''' Handles server route instantiation. '''
self._app.route('/',
method='GET',
callback=self._get_logger_list)
self._app.route('/stats',
method='GET',
callback=self._fetch_handler_stats)
self._app.route('/<name>/start',
method='POST',
callback=self._add_logger_by_name)
self._app.route('/<name>/stop',
method='DELETE',
callback=self._stop_logger_by_name)
self._app.route('/<name>/config',
method='GET',
callback=self._get_logger_conf)
self._app.route('/<name>/rotate',
method='POST',
callback=self._rotate_capturer_log) | python | def _route(self):
''' Handles server route instantiation. '''
self._app.route('/',
method='GET',
callback=self._get_logger_list)
self._app.route('/stats',
method='GET',
callback=self._fetch_handler_stats)
self._app.route('/<name>/start',
method='POST',
callback=self._add_logger_by_name)
self._app.route('/<name>/stop',
method='DELETE',
callback=self._stop_logger_by_name)
self._app.route('/<name>/config',
method='GET',
callback=self._get_logger_conf)
self._app.route('/<name>/rotate',
method='POST',
callback=self._rotate_capturer_log) | [
"def",
"_route",
"(",
"self",
")",
":",
"self",
".",
"_app",
".",
"route",
"(",
"'/'",
",",
"method",
"=",
"'GET'",
",",
"callback",
"=",
"self",
".",
"_get_logger_list",
")",
"self",
".",
"_app",
".",
"route",
"(",
"'/stats'",
",",
"method",
"=",
... | Handles server route instantiation. | [
"Handles",
"server",
"route",
"instantiation",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/bsc.py#L712-L731 | train | 42,720 |
NASA-AMMOS/AIT-Core | ait/core/bsc.py | StreamCaptureManagerServer._add_logger_by_name | def _add_logger_by_name(self, name):
''' Handles POST requests for adding a new logger.
Expects logger configuration to be passed in the request's query string.
The logger name is included in the URL and the address components and
connection type should be included as well. The loc attribute is
defaulted to "localhost" when making the socket connection if not
defined.
loc = IP / interface
port = port / protocol
conn_type = udp or ethernet
Raises:
ValueError:
if the port or connection type are not supplied.
'''
data = dict(request.forms)
loc = data.pop('loc', '')
port = data.pop('port', None)
conn_type = data.pop('conn_type', None)
if not port or not conn_type:
e = 'Port and/or conn_type not set'
raise ValueError(e)
address = [loc, int(port)]
if 'rotate_log' in data:
data['rotate_log'] = True if data == 'true' else False
if 'rotate_log_delta' in data:
data['rotate_log_delta'] = int(data['rotate_log_delta'])
self._logger_manager.add_logger(name, address, conn_type, **data) | python | def _add_logger_by_name(self, name):
''' Handles POST requests for adding a new logger.
Expects logger configuration to be passed in the request's query string.
The logger name is included in the URL and the address components and
connection type should be included as well. The loc attribute is
defaulted to "localhost" when making the socket connection if not
defined.
loc = IP / interface
port = port / protocol
conn_type = udp or ethernet
Raises:
ValueError:
if the port or connection type are not supplied.
'''
data = dict(request.forms)
loc = data.pop('loc', '')
port = data.pop('port', None)
conn_type = data.pop('conn_type', None)
if not port or not conn_type:
e = 'Port and/or conn_type not set'
raise ValueError(e)
address = [loc, int(port)]
if 'rotate_log' in data:
data['rotate_log'] = True if data == 'true' else False
if 'rotate_log_delta' in data:
data['rotate_log_delta'] = int(data['rotate_log_delta'])
self._logger_manager.add_logger(name, address, conn_type, **data) | [
"def",
"_add_logger_by_name",
"(",
"self",
",",
"name",
")",
":",
"data",
"=",
"dict",
"(",
"request",
".",
"forms",
")",
"loc",
"=",
"data",
".",
"pop",
"(",
"'loc'",
",",
"''",
")",
"port",
"=",
"data",
".",
"pop",
"(",
"'port'",
",",
"None",
"... | Handles POST requests for adding a new logger.
Expects logger configuration to be passed in the request's query string.
The logger name is included in the URL and the address components and
connection type should be included as well. The loc attribute is
defaulted to "localhost" when making the socket connection if not
defined.
loc = IP / interface
port = port / protocol
conn_type = udp or ethernet
Raises:
ValueError:
if the port or connection type are not supplied. | [
"Handles",
"POST",
"requests",
"for",
"adding",
"a",
"new",
"logger",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/bsc.py#L733-L766 | train | 42,721 |
NASA-AMMOS/AIT-Core | ait/core/tlm.py | handle_includes | def handle_includes(defns):
'''Recursive handling of includes for any input list of defns.
The assumption here is that when an include is handled by the
pyyaml reader, it adds them as a list, which is stands apart from the rest
of the expected YAML definitions.
'''
newdefns = []
for d in defns:
if isinstance(d,list):
newdefns.extend(handle_includes(d))
else:
newdefns.append(d)
return newdefns | python | def handle_includes(defns):
'''Recursive handling of includes for any input list of defns.
The assumption here is that when an include is handled by the
pyyaml reader, it adds them as a list, which is stands apart from the rest
of the expected YAML definitions.
'''
newdefns = []
for d in defns:
if isinstance(d,list):
newdefns.extend(handle_includes(d))
else:
newdefns.append(d)
return newdefns | [
"def",
"handle_includes",
"(",
"defns",
")",
":",
"newdefns",
"=",
"[",
"]",
"for",
"d",
"in",
"defns",
":",
"if",
"isinstance",
"(",
"d",
",",
"list",
")",
":",
"newdefns",
".",
"extend",
"(",
"handle_includes",
"(",
"d",
")",
")",
"else",
":",
"n... | Recursive handling of includes for any input list of defns.
The assumption here is that when an include is handled by the
pyyaml reader, it adds them as a list, which is stands apart from the rest
of the expected YAML definitions. | [
"Recursive",
"handling",
"of",
"includes",
"for",
"any",
"input",
"list",
"of",
"defns",
".",
"The",
"assumption",
"here",
"is",
"that",
"when",
"an",
"include",
"is",
"handled",
"by",
"the",
"pyyaml",
"reader",
"it",
"adds",
"them",
"as",
"a",
"list",
"... | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/tlm.py#L1124-L1137 | train | 42,722 |
NASA-AMMOS/AIT-Core | ait/core/tlm.py | DNToEUConversion.eval | def eval(self, packet):
"""Returns the result of evaluating this DNToEUConversion in the
context of the given Packet.
"""
result = None
terms = None
if self._when is None or self._when.eval(packet):
result = self._equation.eval(packet)
return result | python | def eval(self, packet):
"""Returns the result of evaluating this DNToEUConversion in the
context of the given Packet.
"""
result = None
terms = None
if self._when is None or self._when.eval(packet):
result = self._equation.eval(packet)
return result | [
"def",
"eval",
"(",
"self",
",",
"packet",
")",
":",
"result",
"=",
"None",
"terms",
"=",
"None",
"if",
"self",
".",
"_when",
"is",
"None",
"or",
"self",
".",
"_when",
".",
"eval",
"(",
"packet",
")",
":",
"result",
"=",
"self",
".",
"_equation",
... | Returns the result of evaluating this DNToEUConversion in the
context of the given Packet. | [
"Returns",
"the",
"result",
"of",
"evaluating",
"this",
"DNToEUConversion",
"in",
"the",
"context",
"of",
"the",
"given",
"Packet",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/tlm.py#L95-L105 | train | 42,723 |
NASA-AMMOS/AIT-Core | ait/core/tlm.py | DerivationDefinition.validate | def validate(self, value, messages=None):
"""Returns True if the given field value is valid, False otherwise.
Validation error messages are appended to an optional messages
array.
"""
valid = True
primitive = value
def log(msg):
if messages is not None:
messages.append(msg)
if self.enum:
if value not in self.enum.values():
valid = False
flds = (self.name, str(value))
log("%s value '%s' not in allowed enumerated values." % flds)
else:
primitive = int(self.enum.keys()[self.enum.values().index(value)])
if self.type:
if self.type.validate(primitive, messages, self.name) is False:
valid = False
return valid | python | def validate(self, value, messages=None):
"""Returns True if the given field value is valid, False otherwise.
Validation error messages are appended to an optional messages
array.
"""
valid = True
primitive = value
def log(msg):
if messages is not None:
messages.append(msg)
if self.enum:
if value not in self.enum.values():
valid = False
flds = (self.name, str(value))
log("%s value '%s' not in allowed enumerated values." % flds)
else:
primitive = int(self.enum.keys()[self.enum.values().index(value)])
if self.type:
if self.type.validate(primitive, messages, self.name) is False:
valid = False
return valid | [
"def",
"validate",
"(",
"self",
",",
"value",
",",
"messages",
"=",
"None",
")",
":",
"valid",
"=",
"True",
"primitive",
"=",
"value",
"def",
"log",
"(",
"msg",
")",
":",
"if",
"messages",
"is",
"not",
"None",
":",
"messages",
".",
"append",
"(",
"... | Returns True if the given field value is valid, False otherwise.
Validation error messages are appended to an optional messages
array. | [
"Returns",
"True",
"if",
"the",
"given",
"field",
"value",
"is",
"valid",
"False",
"otherwise",
".",
"Validation",
"error",
"messages",
"are",
"appended",
"to",
"an",
"optional",
"messages",
"array",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/tlm.py#L190-L214 | train | 42,724 |
NASA-AMMOS/AIT-Core | ait/core/tlm.py | FieldDefinition.decode | def decode(self, bytes, raw=False, index=None):
"""Decodes the given bytes according to this Field Definition.
If raw is True, no enumeration substitutions will be applied
to the data returned.
If index is an integer or slice (and the type of this
FieldDefinition is an ArrayType), then only the element(s) at
the specified position(s) will be decoded.
"""
if index is not None and isinstance(self.type, dtype.ArrayType):
value = self.type.decode( bytes[self.slice()], index, raw )
else:
value = self.type.decode( bytes[self.slice()], raw )
# Apply bit mask if needed
if self.mask is not None:
value &= self.mask
if self.shift > 0:
value >>= self.shift
if not raw and self.enum is not None:
value = self.enum.get(value, value)
return value | python | def decode(self, bytes, raw=False, index=None):
"""Decodes the given bytes according to this Field Definition.
If raw is True, no enumeration substitutions will be applied
to the data returned.
If index is an integer or slice (and the type of this
FieldDefinition is an ArrayType), then only the element(s) at
the specified position(s) will be decoded.
"""
if index is not None and isinstance(self.type, dtype.ArrayType):
value = self.type.decode( bytes[self.slice()], index, raw )
else:
value = self.type.decode( bytes[self.slice()], raw )
# Apply bit mask if needed
if self.mask is not None:
value &= self.mask
if self.shift > 0:
value >>= self.shift
if not raw and self.enum is not None:
value = self.enum.get(value, value)
return value | [
"def",
"decode",
"(",
"self",
",",
"bytes",
",",
"raw",
"=",
"False",
",",
"index",
"=",
"None",
")",
":",
"if",
"index",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"self",
".",
"type",
",",
"dtype",
".",
"ArrayType",
")",
":",
"value",
"=",
... | Decodes the given bytes according to this Field Definition.
If raw is True, no enumeration substitutions will be applied
to the data returned.
If index is an integer or slice (and the type of this
FieldDefinition is an ArrayType), then only the element(s) at
the specified position(s) will be decoded. | [
"Decodes",
"the",
"given",
"bytes",
"according",
"to",
"this",
"Field",
"Definition",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/tlm.py#L313-L339 | train | 42,725 |
NASA-AMMOS/AIT-Core | ait/core/tlm.py | FieldDefinition.encode | def encode(self, value):
"""Encodes the given value according to this FieldDefinition."""
if type(value) == str and self.enum and value in self.enum:
value = self.enum[value]
if type(value) == int:
if self.shift > 0:
value <<= self.shift
if self.mask is not None:
value &= self.mask
return self.type.encode(value) if self.type else bytearray() | python | def encode(self, value):
"""Encodes the given value according to this FieldDefinition."""
if type(value) == str and self.enum and value in self.enum:
value = self.enum[value]
if type(value) == int:
if self.shift > 0:
value <<= self.shift
if self.mask is not None:
value &= self.mask
return self.type.encode(value) if self.type else bytearray() | [
"def",
"encode",
"(",
"self",
",",
"value",
")",
":",
"if",
"type",
"(",
"value",
")",
"==",
"str",
"and",
"self",
".",
"enum",
"and",
"value",
"in",
"self",
".",
"enum",
":",
"value",
"=",
"self",
".",
"enum",
"[",
"value",
"]",
"if",
"type",
... | Encodes the given value according to this FieldDefinition. | [
"Encodes",
"the",
"given",
"value",
"according",
"to",
"this",
"FieldDefinition",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/tlm.py#L342-L353 | train | 42,726 |
NASA-AMMOS/AIT-Core | ait/core/tlm.py | Packet._assertField | def _assertField(self, fieldname):
"""Raise AttributeError when Packet has no field with the given
name."""
if not self._hasattr(fieldname):
values = self._defn.name, fieldname
raise AttributeError("Packet '%s' has no field '%s'" % values) | python | def _assertField(self, fieldname):
"""Raise AttributeError when Packet has no field with the given
name."""
if not self._hasattr(fieldname):
values = self._defn.name, fieldname
raise AttributeError("Packet '%s' has no field '%s'" % values) | [
"def",
"_assertField",
"(",
"self",
",",
"fieldname",
")",
":",
"if",
"not",
"self",
".",
"_hasattr",
"(",
"fieldname",
")",
":",
"values",
"=",
"self",
".",
"_defn",
".",
"name",
",",
"fieldname",
"raise",
"AttributeError",
"(",
"\"Packet '%s' has no field ... | Raise AttributeError when Packet has no field with the given
name. | [
"Raise",
"AttributeError",
"when",
"Packet",
"has",
"no",
"field",
"with",
"the",
"given",
"name",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/tlm.py#L465-L470 | train | 42,727 |
NASA-AMMOS/AIT-Core | ait/core/tlm.py | Packet._getattr | def _getattr (self, fieldname, raw=False, index=None):
"""Returns the value of the given packet field name.
If raw is True, the field value is only decoded. That is no
enumeration substituions or DN to EU conversions are applied.
"""
self._assertField(fieldname)
value = None
if fieldname == 'raw':
value = createRawPacket(self)
elif fieldname == 'history':
value = self._defn.history
else:
if fieldname in self._defn.derivationmap:
defn = self._defn.derivationmap[fieldname]
else:
defn = self._defn.fieldmap[fieldname]
if isinstance(defn.type, dtype.ArrayType) and index is None:
return createFieldList(self, defn, raw)
if defn.when is None or defn.when.eval(self):
if isinstance(defn, DerivationDefinition):
value = defn.equation.eval(self)
elif raw or (defn.dntoeu is None and defn.expr is None):
value = defn.decode(self._data, raw, index)
elif defn.dntoeu is not None:
value = defn.dntoeu.eval(self)
elif defn.expr is not None:
value = defn.expr.eval(self)
return value | python | def _getattr (self, fieldname, raw=False, index=None):
"""Returns the value of the given packet field name.
If raw is True, the field value is only decoded. That is no
enumeration substituions or DN to EU conversions are applied.
"""
self._assertField(fieldname)
value = None
if fieldname == 'raw':
value = createRawPacket(self)
elif fieldname == 'history':
value = self._defn.history
else:
if fieldname in self._defn.derivationmap:
defn = self._defn.derivationmap[fieldname]
else:
defn = self._defn.fieldmap[fieldname]
if isinstance(defn.type, dtype.ArrayType) and index is None:
return createFieldList(self, defn, raw)
if defn.when is None or defn.when.eval(self):
if isinstance(defn, DerivationDefinition):
value = defn.equation.eval(self)
elif raw or (defn.dntoeu is None and defn.expr is None):
value = defn.decode(self._data, raw, index)
elif defn.dntoeu is not None:
value = defn.dntoeu.eval(self)
elif defn.expr is not None:
value = defn.expr.eval(self)
return value | [
"def",
"_getattr",
"(",
"self",
",",
"fieldname",
",",
"raw",
"=",
"False",
",",
"index",
"=",
"None",
")",
":",
"self",
".",
"_assertField",
"(",
"fieldname",
")",
"value",
"=",
"None",
"if",
"fieldname",
"==",
"'raw'",
":",
"value",
"=",
"createRawPa... | Returns the value of the given packet field name.
If raw is True, the field value is only decoded. That is no
enumeration substituions or DN to EU conversions are applied. | [
"Returns",
"the",
"value",
"of",
"the",
"given",
"packet",
"field",
"name",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/tlm.py#L473-L505 | train | 42,728 |
NASA-AMMOS/AIT-Core | ait/core/tlm.py | Packet._hasattr | def _hasattr(self, fieldname):
"""Returns True if this packet contains fieldname, False otherwise."""
special = 'history', 'raw'
return (fieldname in special or
fieldname in self._defn.fieldmap or
fieldname in self._defn.derivationmap) | python | def _hasattr(self, fieldname):
"""Returns True if this packet contains fieldname, False otherwise."""
special = 'history', 'raw'
return (fieldname in special or
fieldname in self._defn.fieldmap or
fieldname in self._defn.derivationmap) | [
"def",
"_hasattr",
"(",
"self",
",",
"fieldname",
")",
":",
"special",
"=",
"'history'",
",",
"'raw'",
"return",
"(",
"fieldname",
"in",
"special",
"or",
"fieldname",
"in",
"self",
".",
"_defn",
".",
"fieldmap",
"or",
"fieldname",
"in",
"self",
".",
"_de... | Returns True if this packet contains fieldname, False otherwise. | [
"Returns",
"True",
"if",
"this",
"packet",
"contains",
"fieldname",
"False",
"otherwise",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/tlm.py#L508-L513 | train | 42,729 |
NASA-AMMOS/AIT-Core | ait/core/tlm.py | PacketDefinition._update_bytes | def _update_bytes(self, defns, start=0):
"""Updates the 'bytes' field in all FieldDefinition.
Any FieldDefinition.bytes which is undefined (None) or '@prev'
will have its bytes field computed based on its data type size
and where the previous FieldDefinition ended (or the start
parameter in the case of very first FieldDefinition). If
bytes is set to '@prev', this has the effect of *starting* the
FieldDefinition at the same place as the *previous*
FieldDefinition. This reads well in YAML, e.g.:
bytes: '@prev'
Returns the end of the very last FieldDefinition in Python
slice notation, i.e. [start, stop). This would correspond to
the *start* of the next FieldDefinition, if it existed.
"""
pos = slice(start, start)
for fd in defns:
if fd.bytes == '@prev' or fd.bytes is None:
if fd.bytes == '@prev':
fd.bytes = None
pos = fd.slice(pos.start)
elif fd.bytes is None:
pos = fd.slice(pos.stop)
if pos.start == pos.stop - 1:
fd.bytes = pos.start
else:
fd.bytes = [ pos.start, pos.stop - 1 ]
pos = fd.slice()
return pos.stop | python | def _update_bytes(self, defns, start=0):
"""Updates the 'bytes' field in all FieldDefinition.
Any FieldDefinition.bytes which is undefined (None) or '@prev'
will have its bytes field computed based on its data type size
and where the previous FieldDefinition ended (or the start
parameter in the case of very first FieldDefinition). If
bytes is set to '@prev', this has the effect of *starting* the
FieldDefinition at the same place as the *previous*
FieldDefinition. This reads well in YAML, e.g.:
bytes: '@prev'
Returns the end of the very last FieldDefinition in Python
slice notation, i.e. [start, stop). This would correspond to
the *start* of the next FieldDefinition, if it existed.
"""
pos = slice(start, start)
for fd in defns:
if fd.bytes == '@prev' or fd.bytes is None:
if fd.bytes == '@prev':
fd.bytes = None
pos = fd.slice(pos.start)
elif fd.bytes is None:
pos = fd.slice(pos.stop)
if pos.start == pos.stop - 1:
fd.bytes = pos.start
else:
fd.bytes = [ pos.start, pos.stop - 1 ]
pos = fd.slice()
return pos.stop | [
"def",
"_update_bytes",
"(",
"self",
",",
"defns",
",",
"start",
"=",
"0",
")",
":",
"pos",
"=",
"slice",
"(",
"start",
",",
"start",
")",
"for",
"fd",
"in",
"defns",
":",
"if",
"fd",
".",
"bytes",
"==",
"'@prev'",
"or",
"fd",
".",
"bytes",
"is",... | Updates the 'bytes' field in all FieldDefinition.
Any FieldDefinition.bytes which is undefined (None) or '@prev'
will have its bytes field computed based on its data type size
and where the previous FieldDefinition ended (or the start
parameter in the case of very first FieldDefinition). If
bytes is set to '@prev', this has the effect of *starting* the
FieldDefinition at the same place as the *previous*
FieldDefinition. This reads well in YAML, e.g.:
bytes: '@prev'
Returns the end of the very last FieldDefinition in Python
slice notation, i.e. [start, stop). This would correspond to
the *start* of the next FieldDefinition, if it existed. | [
"Updates",
"the",
"bytes",
"field",
"in",
"all",
"FieldDefinition",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/tlm.py#L640-L671 | train | 42,730 |
NASA-AMMOS/AIT-Core | ait/core/tlm.py | PacketDefinition.nbytes | def nbytes(self):
"""The number of bytes for this telemetry packet"""
max_byte = -1
for defn in self.fields:
byte = defn.bytes if type(defn.bytes) is int else max(defn.bytes)
max_byte = max(max_byte, byte)
return max_byte + 1 | python | def nbytes(self):
"""The number of bytes for this telemetry packet"""
max_byte = -1
for defn in self.fields:
byte = defn.bytes if type(defn.bytes) is int else max(defn.bytes)
max_byte = max(max_byte, byte)
return max_byte + 1 | [
"def",
"nbytes",
"(",
"self",
")",
":",
"max_byte",
"=",
"-",
"1",
"for",
"defn",
"in",
"self",
".",
"fields",
":",
"byte",
"=",
"defn",
".",
"bytes",
"if",
"type",
"(",
"defn",
".",
"bytes",
")",
"is",
"int",
"else",
"max",
"(",
"defn",
".",
"... | The number of bytes for this telemetry packet | [
"The",
"number",
"of",
"bytes",
"for",
"this",
"telemetry",
"packet"
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/tlm.py#L693-L701 | train | 42,731 |
NASA-AMMOS/AIT-Core | ait/core/tlm.py | PacketDefinition.validate | def validate(self, pkt, messages=None):
"""Returns True if the given Packet is valid, False otherwise.
Validation error messages are appended to an optional messages
array.
"""
valid = True
for f in self.fields:
try:
value = getattr(pkt, f.name)
except AttributeError:
valid = False
if messages is not None:
msg = "Telemetry field mismatch for packet '%s'. "
msg += "Unable to retrieve value for %s in Packet."
values = self.name, f.name
messages.append(msg % values)
break
if f.validate(value, messages) is False:
valid = False
return valid | python | def validate(self, pkt, messages=None):
"""Returns True if the given Packet is valid, False otherwise.
Validation error messages are appended to an optional messages
array.
"""
valid = True
for f in self.fields:
try:
value = getattr(pkt, f.name)
except AttributeError:
valid = False
if messages is not None:
msg = "Telemetry field mismatch for packet '%s'. "
msg += "Unable to retrieve value for %s in Packet."
values = self.name, f.name
messages.append(msg % values)
break
if f.validate(value, messages) is False:
valid = False
return valid | [
"def",
"validate",
"(",
"self",
",",
"pkt",
",",
"messages",
"=",
"None",
")",
":",
"valid",
"=",
"True",
"for",
"f",
"in",
"self",
".",
"fields",
":",
"try",
":",
"value",
"=",
"getattr",
"(",
"pkt",
",",
"f",
".",
"name",
")",
"except",
"Attrib... | Returns True if the given Packet is valid, False otherwise.
Validation error messages are appended to an optional messages
array. | [
"Returns",
"True",
"if",
"the",
"given",
"Packet",
"is",
"valid",
"False",
"otherwise",
".",
"Validation",
"error",
"messages",
"are",
"appended",
"to",
"an",
"optional",
"messages",
"array",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/tlm.py#L704-L726 | train | 42,732 |
NASA-AMMOS/AIT-Core | ait/core/tlm.py | PacketExpression.eval | def eval(self, packet):
"""Returns the result of evaluating this PacketExpression in the
context of the given Packet.
"""
try:
context = createPacketContext(packet)
result = eval(self._code, packet._defn.globals, context)
except ZeroDivisionError:
result = None
return result | python | def eval(self, packet):
"""Returns the result of evaluating this PacketExpression in the
context of the given Packet.
"""
try:
context = createPacketContext(packet)
result = eval(self._code, packet._defn.globals, context)
except ZeroDivisionError:
result = None
return result | [
"def",
"eval",
"(",
"self",
",",
"packet",
")",
":",
"try",
":",
"context",
"=",
"createPacketContext",
"(",
"packet",
")",
"result",
"=",
"eval",
"(",
"self",
".",
"_code",
",",
"packet",
".",
"_defn",
".",
"globals",
",",
"context",
")",
"except",
... | Returns the result of evaluating this PacketExpression in the
context of the given Packet. | [
"Returns",
"the",
"result",
"of",
"evaluating",
"this",
"PacketExpression",
"in",
"the",
"context",
"of",
"the",
"given",
"Packet",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/tlm.py#L793-L803 | train | 42,733 |
NASA-AMMOS/AIT-Core | ait/core/tlm.py | PacketHistory._assertField | def _assertField(self, name):
"""Raise AttributeError when PacketHistory has no field with the given
name.
"""
if name not in self._names:
msg = 'PacketHistory "%s" has no field "%s"'
values = self._defn.name, name
raise AttributeError(msg % values) | python | def _assertField(self, name):
"""Raise AttributeError when PacketHistory has no field with the given
name.
"""
if name not in self._names:
msg = 'PacketHistory "%s" has no field "%s"'
values = self._defn.name, name
raise AttributeError(msg % values) | [
"def",
"_assertField",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"_names",
":",
"msg",
"=",
"'PacketHistory \"%s\" has no field \"%s\"'",
"values",
"=",
"self",
".",
"_defn",
".",
"name",
",",
"name",
"raise",
"AttributeErro... | Raise AttributeError when PacketHistory has no field with the given
name. | [
"Raise",
"AttributeError",
"when",
"PacketHistory",
"has",
"no",
"field",
"with",
"the",
"given",
"name",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/tlm.py#L960-L967 | train | 42,734 |
NASA-AMMOS/AIT-Core | ait/core/tlm.py | PacketHistory.add | def add(self, packet):
"""Add the given Packet to this PacketHistory."""
for name in self._names:
value = getattr(packet, name)
if value is not None:
self._dict[name] = value | python | def add(self, packet):
"""Add the given Packet to this PacketHistory."""
for name in self._names:
value = getattr(packet, name)
if value is not None:
self._dict[name] = value | [
"def",
"add",
"(",
"self",
",",
"packet",
")",
":",
"for",
"name",
"in",
"self",
".",
"_names",
":",
"value",
"=",
"getattr",
"(",
"packet",
",",
"name",
")",
"if",
"value",
"is",
"not",
"None",
":",
"self",
".",
"_dict",
"[",
"name",
"]",
"=",
... | Add the given Packet to this PacketHistory. | [
"Add",
"the",
"given",
"Packet",
"to",
"this",
"PacketHistory",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/tlm.py#L969-L974 | train | 42,735 |
NASA-AMMOS/AIT-Core | ait/core/tlm.py | TlmDict.add | def add(self, defn):
"""Adds the given Packet Definition to this Telemetry Dictionary."""
if defn.name not in self:
self[defn.name] = defn
else:
msg = "Duplicate packet name '%s'" % defn.name
log.error(msg)
raise util.YAMLError(msg) | python | def add(self, defn):
"""Adds the given Packet Definition to this Telemetry Dictionary."""
if defn.name not in self:
self[defn.name] = defn
else:
msg = "Duplicate packet name '%s'" % defn.name
log.error(msg)
raise util.YAMLError(msg) | [
"def",
"add",
"(",
"self",
",",
"defn",
")",
":",
"if",
"defn",
".",
"name",
"not",
"in",
"self",
":",
"self",
"[",
"defn",
".",
"name",
"]",
"=",
"defn",
"else",
":",
"msg",
"=",
"\"Duplicate packet name '%s'\"",
"%",
"defn",
".",
"name",
"log",
"... | Adds the given Packet Definition to this Telemetry Dictionary. | [
"Adds",
"the",
"given",
"Packet",
"Definition",
"to",
"this",
"Telemetry",
"Dictionary",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/tlm.py#L1026-L1033 | train | 42,736 |
NASA-AMMOS/AIT-Core | ait/core/tlm.py | TlmDict.create | def create(self, name, data=None):
"""Creates a new packet with the given definition and raw data.
"""
return createPacket(self[name], data) if name in self else None | python | def create(self, name, data=None):
"""Creates a new packet with the given definition and raw data.
"""
return createPacket(self[name], data) if name in self else None | [
"def",
"create",
"(",
"self",
",",
"name",
",",
"data",
"=",
"None",
")",
":",
"return",
"createPacket",
"(",
"self",
"[",
"name",
"]",
",",
"data",
")",
"if",
"name",
"in",
"self",
"else",
"None"
] | Creates a new packet with the given definition and raw data. | [
"Creates",
"a",
"new",
"packet",
"with",
"the",
"given",
"definition",
"and",
"raw",
"data",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/tlm.py#L1035-L1038 | train | 42,737 |
NASA-AMMOS/AIT-Core | ait/core/tlm.py | TlmDict.load | def load(self, content):
"""Loads Packet Definitions from the given YAML content into this
Telemetry Dictionary. Content may be either a filename
containing YAML content or a YAML string.
Load has no effect if this Command Dictionary was already
instantiated with a filename or YAML content.
"""
if self.filename is None:
if os.path.isfile(content):
self.filename = content
stream = open(self.filename, 'rb')
else:
stream = content
pkts = yaml.load(stream)
pkts = handle_includes(pkts)
for pkt in pkts:
self.add(pkt)
if type(stream) is file:
stream.close() | python | def load(self, content):
"""Loads Packet Definitions from the given YAML content into this
Telemetry Dictionary. Content may be either a filename
containing YAML content or a YAML string.
Load has no effect if this Command Dictionary was already
instantiated with a filename or YAML content.
"""
if self.filename is None:
if os.path.isfile(content):
self.filename = content
stream = open(self.filename, 'rb')
else:
stream = content
pkts = yaml.load(stream)
pkts = handle_includes(pkts)
for pkt in pkts:
self.add(pkt)
if type(stream) is file:
stream.close() | [
"def",
"load",
"(",
"self",
",",
"content",
")",
":",
"if",
"self",
".",
"filename",
"is",
"None",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"content",
")",
":",
"self",
".",
"filename",
"=",
"content",
"stream",
"=",
"open",
"(",
"self",
... | Loads Packet Definitions from the given YAML content into this
Telemetry Dictionary. Content may be either a filename
containing YAML content or a YAML string.
Load has no effect if this Command Dictionary was already
instantiated with a filename or YAML content. | [
"Loads",
"Packet",
"Definitions",
"from",
"the",
"given",
"YAML",
"content",
"into",
"this",
"Telemetry",
"Dictionary",
".",
"Content",
"may",
"be",
"either",
"a",
"filename",
"containing",
"YAML",
"content",
"or",
"a",
"YAML",
"string",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/tlm.py#L1040-L1061 | train | 42,738 |
NASA-AMMOS/AIT-Core | ait/core/tlm.py | TlmDictWriter.writeToCSV | def writeToCSV(self, output_path=None):
'''writeToCSV - write the telemetry dictionary to csv
'''
header = ['Name', 'First Byte', 'Last Byte', 'Bit Mask', 'Endian',
'Type', 'Description', 'Values']
if output_path is None:
output_path = ait.config._directory
for pkt_name in self.tlmdict:
filename = os.path.join(output_path, pkt_name + '.csv')
with open(filename, 'wb') as output:
csvwriter = csv.writer(output, quoting=csv.QUOTE_ALL)
csvwriter.writerow(header)
for fld in self.tlmdict[pkt_name].fields:
# Pre-process some fields
# Description
desc = fld.desc.replace('\n', ' ') if fld.desc is not None else ""
# Mask
mask = hex(fld.mask) if fld.mask is not None else ""
# Enumerations
enums = '\n'.join("%s: %s" % (k, fld.enum[k])
for k in fld.enum) if fld.enum is not None else ""
# Set row
row = [fld.name, fld.slice().start, fld.slice().stop,
mask, fld.type.endian, fld.type.name, desc, enums]
csvwriter.writerow(row) | python | def writeToCSV(self, output_path=None):
'''writeToCSV - write the telemetry dictionary to csv
'''
header = ['Name', 'First Byte', 'Last Byte', 'Bit Mask', 'Endian',
'Type', 'Description', 'Values']
if output_path is None:
output_path = ait.config._directory
for pkt_name in self.tlmdict:
filename = os.path.join(output_path, pkt_name + '.csv')
with open(filename, 'wb') as output:
csvwriter = csv.writer(output, quoting=csv.QUOTE_ALL)
csvwriter.writerow(header)
for fld in self.tlmdict[pkt_name].fields:
# Pre-process some fields
# Description
desc = fld.desc.replace('\n', ' ') if fld.desc is not None else ""
# Mask
mask = hex(fld.mask) if fld.mask is not None else ""
# Enumerations
enums = '\n'.join("%s: %s" % (k, fld.enum[k])
for k in fld.enum) if fld.enum is not None else ""
# Set row
row = [fld.name, fld.slice().start, fld.slice().stop,
mask, fld.type.endian, fld.type.name, desc, enums]
csvwriter.writerow(row) | [
"def",
"writeToCSV",
"(",
"self",
",",
"output_path",
"=",
"None",
")",
":",
"header",
"=",
"[",
"'Name'",
",",
"'First Byte'",
",",
"'Last Byte'",
",",
"'Bit Mask'",
",",
"'Endian'",
",",
"'Type'",
",",
"'Description'",
",",
"'Values'",
"]",
"if",
"output... | writeToCSV - write the telemetry dictionary to csv | [
"writeToCSV",
"-",
"write",
"the",
"telemetry",
"dictionary",
"to",
"csv"
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/tlm.py#L1076-L1109 | train | 42,739 |
NASA-AMMOS/AIT-Core | ait/core/cmd.py | ArgDefn.decode | def decode(self, bytes):
"""Decodes the given bytes according to this AIT Argument
Definition.
"""
value = self.type.decode(bytes)
if self._enum is not None:
for name, val in self._enum.items():
if value == val:
value = name
break
return value | python | def decode(self, bytes):
"""Decodes the given bytes according to this AIT Argument
Definition.
"""
value = self.type.decode(bytes)
if self._enum is not None:
for name, val in self._enum.items():
if value == val:
value = name
break
return value | [
"def",
"decode",
"(",
"self",
",",
"bytes",
")",
":",
"value",
"=",
"self",
".",
"type",
".",
"decode",
"(",
"bytes",
")",
"if",
"self",
".",
"_enum",
"is",
"not",
"None",
":",
"for",
"name",
",",
"val",
"in",
"self",
".",
"_enum",
".",
"items",
... | Decodes the given bytes according to this AIT Argument
Definition. | [
"Decodes",
"the",
"given",
"bytes",
"according",
"to",
"this",
"AIT",
"Argument",
"Definition",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/cmd.py#L97-L107 | train | 42,740 |
NASA-AMMOS/AIT-Core | ait/core/cmd.py | ArgDefn.encode | def encode(self, value):
"""Encodes the given value according to this AIT Argument
Definition.
"""
if type(value) == str and self.enum and value in self.enum:
value = self.enum[value]
return self.type.encode(value) if self.type else bytearray() | python | def encode(self, value):
"""Encodes the given value according to this AIT Argument
Definition.
"""
if type(value) == str and self.enum and value in self.enum:
value = self.enum[value]
return self.type.encode(value) if self.type else bytearray() | [
"def",
"encode",
"(",
"self",
",",
"value",
")",
":",
"if",
"type",
"(",
"value",
")",
"==",
"str",
"and",
"self",
".",
"enum",
"and",
"value",
"in",
"self",
".",
"enum",
":",
"value",
"=",
"self",
".",
"enum",
"[",
"value",
"]",
"return",
"self"... | Encodes the given value according to this AIT Argument
Definition. | [
"Encodes",
"the",
"given",
"value",
"according",
"to",
"this",
"AIT",
"Argument",
"Definition",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/cmd.py#L109-L115 | train | 42,741 |
NASA-AMMOS/AIT-Core | ait/core/cmd.py | ArgDefn.validate | def validate(self, value, messages=None):
"""Returns True if the given Argument value is valid, False otherwise.
Validation error messages are appended to an optional messages
array.
"""
valid = True
primitive = value
def log(msg):
if messages is not None:
messages.append(msg)
if self.enum:
if value not in self.enum.keys():
valid = False
args = (self.name, str(value))
log("%s value '%s' not in allowed enumerated values." % args)
else:
primitive = int(self.enum[value])
if self.type:
if self.type.validate(primitive, messages, self.name) is False:
valid = False
if self.range:
if primitive < self.range[0] or primitive > self.range[1]:
valid = False
args = (self.name, str(primitive), self.range[0], self.range[1])
log("%s value '%s' out of range [%d, %d]." % args)
return valid | python | def validate(self, value, messages=None):
"""Returns True if the given Argument value is valid, False otherwise.
Validation error messages are appended to an optional messages
array.
"""
valid = True
primitive = value
def log(msg):
if messages is not None:
messages.append(msg)
if self.enum:
if value not in self.enum.keys():
valid = False
args = (self.name, str(value))
log("%s value '%s' not in allowed enumerated values." % args)
else:
primitive = int(self.enum[value])
if self.type:
if self.type.validate(primitive, messages, self.name) is False:
valid = False
if self.range:
if primitive < self.range[0] or primitive > self.range[1]:
valid = False
args = (self.name, str(primitive), self.range[0], self.range[1])
log("%s value '%s' out of range [%d, %d]." % args)
return valid | [
"def",
"validate",
"(",
"self",
",",
"value",
",",
"messages",
"=",
"None",
")",
":",
"valid",
"=",
"True",
"primitive",
"=",
"value",
"def",
"log",
"(",
"msg",
")",
":",
"if",
"messages",
"is",
"not",
"None",
":",
"messages",
".",
"append",
"(",
"... | Returns True if the given Argument value is valid, False otherwise.
Validation error messages are appended to an optional messages
array. | [
"Returns",
"True",
"if",
"the",
"given",
"Argument",
"value",
"is",
"valid",
"False",
"otherwise",
".",
"Validation",
"error",
"messages",
"are",
"appended",
"to",
"an",
"optional",
"messages",
"array",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/cmd.py#L132-L162 | train | 42,742 |
NASA-AMMOS/AIT-Core | ait/core/cmd.py | Cmd.encode | def encode(self, pad=106):
"""Encodes this AIT command to binary.
If pad is specified, it indicates the maximum size of the encoded
command in bytes. If the encoded command is less than pad, the
remaining bytes are set to zero.
Commands sent to ISS payloads over 1553 are limited to 64 words
(128 bytes) with 11 words (22 bytes) of CCSDS overhead (SSP
52050J, Section 3.2.3.4). This leaves 53 words (106 bytes) for
the command itself.
"""
opcode = struct.pack('>H', self.defn.opcode)
offset = len(opcode)
size = max(offset + self.defn.argsize, pad)
encoded = bytearray(size)
encoded[0:offset] = opcode
encoded[offset] = self.defn.argsize
offset += 1
index = 0
for defn in self.defn.argdefns:
if defn.fixed:
value = defn.value
else:
value = self.args[index]
index += 1
encoded[defn.slice(offset)] = defn.encode(value)
return encoded | python | def encode(self, pad=106):
"""Encodes this AIT command to binary.
If pad is specified, it indicates the maximum size of the encoded
command in bytes. If the encoded command is less than pad, the
remaining bytes are set to zero.
Commands sent to ISS payloads over 1553 are limited to 64 words
(128 bytes) with 11 words (22 bytes) of CCSDS overhead (SSP
52050J, Section 3.2.3.4). This leaves 53 words (106 bytes) for
the command itself.
"""
opcode = struct.pack('>H', self.defn.opcode)
offset = len(opcode)
size = max(offset + self.defn.argsize, pad)
encoded = bytearray(size)
encoded[0:offset] = opcode
encoded[offset] = self.defn.argsize
offset += 1
index = 0
for defn in self.defn.argdefns:
if defn.fixed:
value = defn.value
else:
value = self.args[index]
index += 1
encoded[defn.slice(offset)] = defn.encode(value)
return encoded | [
"def",
"encode",
"(",
"self",
",",
"pad",
"=",
"106",
")",
":",
"opcode",
"=",
"struct",
".",
"pack",
"(",
"'>H'",
",",
"self",
".",
"defn",
".",
"opcode",
")",
"offset",
"=",
"len",
"(",
"opcode",
")",
"size",
"=",
"max",
"(",
"offset",
"+",
"... | Encodes this AIT command to binary.
If pad is specified, it indicates the maximum size of the encoded
command in bytes. If the encoded command is less than pad, the
remaining bytes are set to zero.
Commands sent to ISS payloads over 1553 are limited to 64 words
(128 bytes) with 11 words (22 bytes) of CCSDS overhead (SSP
52050J, Section 3.2.3.4). This leaves 53 words (106 bytes) for
the command itself. | [
"Encodes",
"this",
"AIT",
"command",
"to",
"binary",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/cmd.py#L224-L254 | train | 42,743 |
NASA-AMMOS/AIT-Core | ait/core/cmd.py | CmdDefn.nbytes | def nbytes(self):
"""The number of bytes required to encode this command.
Encoded commands are comprised of a two byte opcode, followed by a
one byte size, and then the command argument bytes. The size
indicates the number of bytes required to represent command
arguments.
"""
return len(self.opcode) + 1 + sum(arg.nbytes for arg in self.argdefns) | python | def nbytes(self):
"""The number of bytes required to encode this command.
Encoded commands are comprised of a two byte opcode, followed by a
one byte size, and then the command argument bytes. The size
indicates the number of bytes required to represent command
arguments.
"""
return len(self.opcode) + 1 + sum(arg.nbytes for arg in self.argdefns) | [
"def",
"nbytes",
"(",
"self",
")",
":",
"return",
"len",
"(",
"self",
".",
"opcode",
")",
"+",
"1",
"+",
"sum",
"(",
"arg",
".",
"nbytes",
"for",
"arg",
"in",
"self",
".",
"argdefns",
")"
] | The number of bytes required to encode this command.
Encoded commands are comprised of a two byte opcode, followed by a
one byte size, and then the command argument bytes. The size
indicates the number of bytes required to represent command
arguments. | [
"The",
"number",
"of",
"bytes",
"required",
"to",
"encode",
"this",
"command",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/cmd.py#L308-L316 | train | 42,744 |
NASA-AMMOS/AIT-Core | ait/core/cmd.py | CmdDefn.argsize | def argsize(self):
"""The total size in bytes of all the command arguments."""
argsize = sum(arg.nbytes for arg in self.argdefns)
return argsize if len(self.argdefns) > 0 else 0 | python | def argsize(self):
"""The total size in bytes of all the command arguments."""
argsize = sum(arg.nbytes for arg in self.argdefns)
return argsize if len(self.argdefns) > 0 else 0 | [
"def",
"argsize",
"(",
"self",
")",
":",
"argsize",
"=",
"sum",
"(",
"arg",
".",
"nbytes",
"for",
"arg",
"in",
"self",
".",
"argdefns",
")",
"return",
"argsize",
"if",
"len",
"(",
"self",
".",
"argdefns",
")",
">",
"0",
"else",
"0"
] | The total size in bytes of all the command arguments. | [
"The",
"total",
"size",
"in",
"bytes",
"of",
"all",
"the",
"command",
"arguments",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/cmd.py#L324-L327 | train | 42,745 |
NASA-AMMOS/AIT-Core | ait/core/cmd.py | CmdDefn.validate | def validate(self, cmd, messages=None):
"""Returns True if the given Command is valid, False otherwise.
Validation error messages are appended to an optional messages
array.
"""
valid = True
args = [ arg for arg in cmd.args if arg is not None ]
if self.nargs != len(args):
valid = False
if messages is not None:
msg = 'Expected %d arguments, but received %d.'
messages.append(msg % (self.nargs, len(args)))
for defn, value in zip(self.args, cmd.args):
if value is None:
valid = False
if messages is not None:
messages.append('Argument "%s" is missing.' % defn.name)
elif defn.validate(value, messages) is False:
valid = False
if len(cmd._unrecognized) > 0:
valid = False
if messages is not None:
for name in cmd.unrecognized:
messages.append('Argument "%s" is unrecognized.' % name)
return valid | python | def validate(self, cmd, messages=None):
"""Returns True if the given Command is valid, False otherwise.
Validation error messages are appended to an optional messages
array.
"""
valid = True
args = [ arg for arg in cmd.args if arg is not None ]
if self.nargs != len(args):
valid = False
if messages is not None:
msg = 'Expected %d arguments, but received %d.'
messages.append(msg % (self.nargs, len(args)))
for defn, value in zip(self.args, cmd.args):
if value is None:
valid = False
if messages is not None:
messages.append('Argument "%s" is missing.' % defn.name)
elif defn.validate(value, messages) is False:
valid = False
if len(cmd._unrecognized) > 0:
valid = False
if messages is not None:
for name in cmd.unrecognized:
messages.append('Argument "%s" is unrecognized.' % name)
return valid | [
"def",
"validate",
"(",
"self",
",",
"cmd",
",",
"messages",
"=",
"None",
")",
":",
"valid",
"=",
"True",
"args",
"=",
"[",
"arg",
"for",
"arg",
"in",
"cmd",
".",
"args",
"if",
"arg",
"is",
"not",
"None",
"]",
"if",
"self",
".",
"nargs",
"!=",
... | Returns True if the given Command is valid, False otherwise.
Validation error messages are appended to an optional messages
array. | [
"Returns",
"True",
"if",
"the",
"given",
"Command",
"is",
"valid",
"False",
"otherwise",
".",
"Validation",
"error",
"messages",
"are",
"appended",
"to",
"an",
"optional",
"messages",
"array",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/cmd.py#L347-L375 | train | 42,746 |
NASA-AMMOS/AIT-Core | ait/core/cmd.py | CmdDict.create | def create(self, name, *args, **kwargs):
"""Creates a new AIT command with the given arguments."""
tokens = name.split()
if len(tokens) > 1 and (len(args) > 0 or len(kwargs) > 0):
msg = 'A Cmd may be created with either positional arguments '
msg += '(passed as a string or a Python list) or keyword '
msg += 'arguments, but not both.'
raise TypeError(msg)
if len(tokens) > 1:
name = tokens[0]
args = [ util.toNumber(t, t) for t in tokens[1:] ]
defn = self.get(name, None)
if defn is None:
raise TypeError('Unrecognized command: %s' % name)
return createCmd(defn, *args, **kwargs) | python | def create(self, name, *args, **kwargs):
"""Creates a new AIT command with the given arguments."""
tokens = name.split()
if len(tokens) > 1 and (len(args) > 0 or len(kwargs) > 0):
msg = 'A Cmd may be created with either positional arguments '
msg += '(passed as a string or a Python list) or keyword '
msg += 'arguments, but not both.'
raise TypeError(msg)
if len(tokens) > 1:
name = tokens[0]
args = [ util.toNumber(t, t) for t in tokens[1:] ]
defn = self.get(name, None)
if defn is None:
raise TypeError('Unrecognized command: %s' % name)
return createCmd(defn, *args, **kwargs) | [
"def",
"create",
"(",
"self",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"tokens",
"=",
"name",
".",
"split",
"(",
")",
"if",
"len",
"(",
"tokens",
")",
">",
"1",
"and",
"(",
"len",
"(",
"args",
")",
">",
"0",
"or",
"... | Creates a new AIT command with the given arguments. | [
"Creates",
"a",
"new",
"AIT",
"command",
"with",
"the",
"given",
"arguments",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/cmd.py#L404-L423 | train | 42,747 |
NASA-AMMOS/AIT-Core | ait/core/cmd.py | CmdDict.decode | def decode(self, bytes):
"""Decodes the given bytes according to this AIT Command
Definition.
"""
opcode = struct.unpack(">H", bytes[0:2])[0]
nbytes = struct.unpack("B", bytes[2:3])[0]
name = None
args = []
if opcode in self.opcodes:
defn = self.opcodes[opcode]
name = defn.name
stop = 3
for arg in defn.argdefns:
start = stop
stop = start + arg.nbytes
if arg.fixed:
pass # FIXME: Confirm fixed bytes are as expected?
else:
args.append(arg.decode(bytes[start:stop]))
return self.create(name, *args) | python | def decode(self, bytes):
"""Decodes the given bytes according to this AIT Command
Definition.
"""
opcode = struct.unpack(">H", bytes[0:2])[0]
nbytes = struct.unpack("B", bytes[2:3])[0]
name = None
args = []
if opcode in self.opcodes:
defn = self.opcodes[opcode]
name = defn.name
stop = 3
for arg in defn.argdefns:
start = stop
stop = start + arg.nbytes
if arg.fixed:
pass # FIXME: Confirm fixed bytes are as expected?
else:
args.append(arg.decode(bytes[start:stop]))
return self.create(name, *args) | [
"def",
"decode",
"(",
"self",
",",
"bytes",
")",
":",
"opcode",
"=",
"struct",
".",
"unpack",
"(",
"\">H\"",
",",
"bytes",
"[",
"0",
":",
"2",
"]",
")",
"[",
"0",
"]",
"nbytes",
"=",
"struct",
".",
"unpack",
"(",
"\"B\"",
",",
"bytes",
"[",
"2"... | Decodes the given bytes according to this AIT Command
Definition. | [
"Decodes",
"the",
"given",
"bytes",
"according",
"to",
"this",
"AIT",
"Command",
"Definition",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/cmd.py#L426-L448 | train | 42,748 |
NASA-AMMOS/AIT-Core | ait/core/cmd.py | CmdDict.load | def load(self, content):
"""Loads Command Definitions from the given YAML content into
into this Command Dictionary. Content may be either a
filename containing YAML content or a YAML string.
Load has no effect if this Command Dictionary was already
instantiated with a filename or YAML content.
"""
if self.filename is None:
if os.path.isfile(content):
self.filename = content
stream = open(self.filename, 'rb')
else:
stream = content
for cmd in yaml.load(stream):
self.add(cmd)
if type(stream) is file:
stream.close() | python | def load(self, content):
"""Loads Command Definitions from the given YAML content into
into this Command Dictionary. Content may be either a
filename containing YAML content or a YAML string.
Load has no effect if this Command Dictionary was already
instantiated with a filename or YAML content.
"""
if self.filename is None:
if os.path.isfile(content):
self.filename = content
stream = open(self.filename, 'rb')
else:
stream = content
for cmd in yaml.load(stream):
self.add(cmd)
if type(stream) is file:
stream.close() | [
"def",
"load",
"(",
"self",
",",
"content",
")",
":",
"if",
"self",
".",
"filename",
"is",
"None",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"content",
")",
":",
"self",
".",
"filename",
"=",
"content",
"stream",
"=",
"open",
"(",
"self",
... | Loads Command Definitions from the given YAML content into
into this Command Dictionary. Content may be either a
filename containing YAML content or a YAML string.
Load has no effect if this Command Dictionary was already
instantiated with a filename or YAML content. | [
"Loads",
"Command",
"Definitions",
"from",
"the",
"given",
"YAML",
"content",
"into",
"into",
"this",
"Command",
"Dictionary",
".",
"Content",
"may",
"be",
"either",
"a",
"filename",
"containing",
"YAML",
"content",
"or",
"a",
"YAML",
"string",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/cmd.py#L450-L469 | train | 42,749 |
NASA-AMMOS/AIT-Core | ait/core/coord.py | cbrt | def cbrt (x):
"""Returns the cube root of x."""
if x >= 0:
return math.pow(x , 1.0 / 3.0)
else:
return - math.pow(abs(x), 1.0 / 3.0) | python | def cbrt (x):
"""Returns the cube root of x."""
if x >= 0:
return math.pow(x , 1.0 / 3.0)
else:
return - math.pow(abs(x), 1.0 / 3.0) | [
"def",
"cbrt",
"(",
"x",
")",
":",
"if",
"x",
">=",
"0",
":",
"return",
"math",
".",
"pow",
"(",
"x",
",",
"1.0",
"/",
"3.0",
")",
"else",
":",
"return",
"-",
"math",
".",
"pow",
"(",
"abs",
"(",
"x",
")",
",",
"1.0",
"/",
"3.0",
")"
] | Returns the cube root of x. | [
"Returns",
"the",
"cube",
"root",
"of",
"x",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/coord.py#L49-L54 | train | 42,750 |
NASA-AMMOS/AIT-Core | ait/core/server/stream.py | Stream.process | def process(self, input_data, topic=None):
"""
Invokes each handler in sequence.
Publishes final output data.
Params:
input_data: message received by stream
topic: name of plugin or stream message received from,
if applicable
"""
for handler in self.handlers:
output = handler.handle(input_data)
input_data = output
self.publish(input_data) | python | def process(self, input_data, topic=None):
"""
Invokes each handler in sequence.
Publishes final output data.
Params:
input_data: message received by stream
topic: name of plugin or stream message received from,
if applicable
"""
for handler in self.handlers:
output = handler.handle(input_data)
input_data = output
self.publish(input_data) | [
"def",
"process",
"(",
"self",
",",
"input_data",
",",
"topic",
"=",
"None",
")",
":",
"for",
"handler",
"in",
"self",
".",
"handlers",
":",
"output",
"=",
"handler",
".",
"handle",
"(",
"input_data",
")",
"input_data",
"=",
"output",
"self",
".",
"pub... | Invokes each handler in sequence.
Publishes final output data.
Params:
input_data: message received by stream
topic: name of plugin or stream message received from,
if applicable | [
"Invokes",
"each",
"handler",
"in",
"sequence",
".",
"Publishes",
"final",
"output",
"data",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/server/stream.py#L54-L68 | train | 42,751 |
NASA-AMMOS/AIT-Core | ait/core/server/stream.py | Stream.valid_workflow | def valid_workflow(self):
"""
Return true if each handler's output type is the same as
the next handler's input type. Return False if not.
Returns: boolean - True if workflow is valid, False if not
"""
for ix, handler in enumerate(self.handlers[:-1]):
next_input_type = self.handlers[ix + 1].input_type
if (handler.output_type is not None and
next_input_type is not None):
if handler.output_type != next_input_type:
return False
return True | python | def valid_workflow(self):
"""
Return true if each handler's output type is the same as
the next handler's input type. Return False if not.
Returns: boolean - True if workflow is valid, False if not
"""
for ix, handler in enumerate(self.handlers[:-1]):
next_input_type = self.handlers[ix + 1].input_type
if (handler.output_type is not None and
next_input_type is not None):
if handler.output_type != next_input_type:
return False
return True | [
"def",
"valid_workflow",
"(",
"self",
")",
":",
"for",
"ix",
",",
"handler",
"in",
"enumerate",
"(",
"self",
".",
"handlers",
"[",
":",
"-",
"1",
"]",
")",
":",
"next_input_type",
"=",
"self",
".",
"handlers",
"[",
"ix",
"+",
"1",
"]",
".",
"input_... | Return true if each handler's output type is the same as
the next handler's input type. Return False if not.
Returns: boolean - True if workflow is valid, False if not | [
"Return",
"true",
"if",
"each",
"handler",
"s",
"output",
"type",
"is",
"the",
"same",
"as",
"the",
"next",
"handler",
"s",
"input",
"type",
".",
"Return",
"False",
"if",
"not",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/server/stream.py#L70-L85 | train | 42,752 |
NASA-AMMOS/AIT-Core | ait/core/geom.py | Polygon.contains | def contains (self, p):
"""Returns True if point is contained inside this Polygon, False
otherwise.
This method uses the Ray Casting algorithm.
Examples:
>>> p = Polygon()
>>> p.vertices = [Point(1, 1), Point(1, -1), Point(-1, -1), Point(-1, 1)]
>>> p.contains( Point(0, 0) )
True
>>> p.contains( Point(2, 3) )
False
"""
inside = False
if p in self.bounds():
for s in self.segments():
if ((s.p.y > p.y) != (s.q.y > p.y) and
(p.x < (s.q.x - s.p.x) * (p.y - s.p.y) / (s.q.y - s.p.y) + s.p.x)):
inside = not inside
return inside | python | def contains (self, p):
"""Returns True if point is contained inside this Polygon, False
otherwise.
This method uses the Ray Casting algorithm.
Examples:
>>> p = Polygon()
>>> p.vertices = [Point(1, 1), Point(1, -1), Point(-1, -1), Point(-1, 1)]
>>> p.contains( Point(0, 0) )
True
>>> p.contains( Point(2, 3) )
False
"""
inside = False
if p in self.bounds():
for s in self.segments():
if ((s.p.y > p.y) != (s.q.y > p.y) and
(p.x < (s.q.x - s.p.x) * (p.y - s.p.y) / (s.q.y - s.p.y) + s.p.x)):
inside = not inside
return inside | [
"def",
"contains",
"(",
"self",
",",
"p",
")",
":",
"inside",
"=",
"False",
"if",
"p",
"in",
"self",
".",
"bounds",
"(",
")",
":",
"for",
"s",
"in",
"self",
".",
"segments",
"(",
")",
":",
"if",
"(",
"(",
"s",
".",
"p",
".",
"y",
">",
"p",
... | Returns True if point is contained inside this Polygon, False
otherwise.
This method uses the Ray Casting algorithm.
Examples:
>>> p = Polygon()
>>> p.vertices = [Point(1, 1), Point(1, -1), Point(-1, -1), Point(-1, 1)]
>>> p.contains( Point(0, 0) )
True
>>> p.contains( Point(2, 3) )
False | [
"Returns",
"True",
"if",
"point",
"is",
"contained",
"inside",
"this",
"Polygon",
"False",
"otherwise",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/geom.py#L671-L697 | train | 42,753 |
NASA-AMMOS/AIT-Core | ait/core/geom.py | Polygon.segments | def segments (self):
"""Return the Line segments that comprise this Polygon."""
for n in xrange(len(self.vertices) - 1):
yield Line(self.vertices[n], self.vertices[n + 1])
yield Line(self.vertices[-1], self.vertices[0]) | python | def segments (self):
"""Return the Line segments that comprise this Polygon."""
for n in xrange(len(self.vertices) - 1):
yield Line(self.vertices[n], self.vertices[n + 1])
yield Line(self.vertices[-1], self.vertices[0]) | [
"def",
"segments",
"(",
"self",
")",
":",
"for",
"n",
"in",
"xrange",
"(",
"len",
"(",
"self",
".",
"vertices",
")",
"-",
"1",
")",
":",
"yield",
"Line",
"(",
"self",
".",
"vertices",
"[",
"n",
"]",
",",
"self",
".",
"vertices",
"[",
"n",
"+",
... | Return the Line segments that comprise this Polygon. | [
"Return",
"the",
"Line",
"segments",
"that",
"comprise",
"this",
"Polygon",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/geom.py#L700-L705 | train | 42,754 |
NASA-AMMOS/AIT-Core | ait/core/evr.py | EVRDefn.format_message | def format_message(self, evr_hist_data):
''' Format EVR message with EVR data
Given a byte array of EVR data, format the EVR's message attribute
printf format strings and split the byte array into appropriately
sized chunks. Supports most format strings containing length and type
fields.
Args:
evr_hist_data: A bytearray of EVR data. Bytes are expected to be in
MSB ordering.
Example formatting::
# This is the character '!', string 'Foo', and int '4279317316'
bytearray([0x21, 0x46, 0x6f, 0x6f, 0x00, 0xff, 0x11, 0x33, 0x44])
Returns:
The EVR's message string formatted with the EVR data or the
unformatted EVR message string if there are no valid format
strings present in it.
Raises:
ValueError: When the bytearray cannot be fully processed with the
specified format strings. This is usually a result of the
expected data length and the byte array length not matching.
'''
size_formatter_info = {
's' : -1,
'c' : 1,
'i' : 4,
'd' : 4,
'u' : 4,
'x' : 4,
'hh': 1,
'h' : 2,
'l' : 4,
'll': 8,
'f' : 8,
'g' : 8,
'e' : 8,
}
type_formatter_info = {
'c' : 'U{}',
'i' : 'MSB_I{}',
'd' : 'MSB_I{}',
'u' : 'MSB_U{}',
'f' : 'MSB_D{}',
'e' : 'MSB_D{}',
'g' : 'MSB_D{}',
'x' : 'MSB_U{}',
}
formatters = re.findall("%(?:\d+\$)?([cdieEfgGosuxXhlL]+)", self._message)
cur_byte_index = 0
data_chunks = []
for f in formatters:
# If the format string we found is > 1 character we know that a length
# field is included and we need to adjust our sizing accordingly.
f_size_char = f_type = f[-1]
if len(f) > 1:
f_size_char = f[:-1]
fsize = size_formatter_info[f_size_char.lower()]
try:
if f_type != 's':
end_index = cur_byte_index + fsize
fstr = type_formatter_info[f_type.lower()].format(fsize*8)
# Type formatting can give us incorrect format strings when
# a size formatter promotes a smaller data type. For instnace,
# 'hhu' says we'll promote a char (1 byte) to an unsigned
# int for display. Here, the type format string would be
# incorrectly set to 'MSB_U8' if we didn't correct.
if fsize == 1 and 'MSB_' in fstr:
fstr = fstr[4:]
d = dtype.PrimitiveType(fstr).decode(
evr_hist_data[cur_byte_index:end_index]
)
# Some formatters have an undefined data size (such as strings)
# and require additional processing to determine the length of
# the data and decode data.
else:
end_index = str(evr_hist_data).index('\x00', cur_byte_index)
d = str(evr_hist_data[cur_byte_index:end_index])
data_chunks.append(d)
except:
msg = "Unable to format EVR Message with data {}".format(evr_hist_data)
log.error(msg)
raise ValueError(msg)
cur_byte_index = end_index
# If we were formatting a string we need to add another index offset
# to exclude the null terminator.
if f == 's':
cur_byte_index += 1
# Format and return the EVR message if formatters were present, otherwise
# just return the EVR message as is.
if len(formatters) == 0:
return self._message
else:
# Python format strings cannot handle size formatter information. So something
# such as %llu needs to be adjusted to be a valid identifier in python by
# removing the size formatter.
msg = self._message
for f in formatters:
if len(f) > 1:
msg = msg.replace('%{}'.format(f), '%{}'.format(f[-1]))
return msg % tuple(data_chunks) | python | def format_message(self, evr_hist_data):
''' Format EVR message with EVR data
Given a byte array of EVR data, format the EVR's message attribute
printf format strings and split the byte array into appropriately
sized chunks. Supports most format strings containing length and type
fields.
Args:
evr_hist_data: A bytearray of EVR data. Bytes are expected to be in
MSB ordering.
Example formatting::
# This is the character '!', string 'Foo', and int '4279317316'
bytearray([0x21, 0x46, 0x6f, 0x6f, 0x00, 0xff, 0x11, 0x33, 0x44])
Returns:
The EVR's message string formatted with the EVR data or the
unformatted EVR message string if there are no valid format
strings present in it.
Raises:
ValueError: When the bytearray cannot be fully processed with the
specified format strings. This is usually a result of the
expected data length and the byte array length not matching.
'''
size_formatter_info = {
's' : -1,
'c' : 1,
'i' : 4,
'd' : 4,
'u' : 4,
'x' : 4,
'hh': 1,
'h' : 2,
'l' : 4,
'll': 8,
'f' : 8,
'g' : 8,
'e' : 8,
}
type_formatter_info = {
'c' : 'U{}',
'i' : 'MSB_I{}',
'd' : 'MSB_I{}',
'u' : 'MSB_U{}',
'f' : 'MSB_D{}',
'e' : 'MSB_D{}',
'g' : 'MSB_D{}',
'x' : 'MSB_U{}',
}
formatters = re.findall("%(?:\d+\$)?([cdieEfgGosuxXhlL]+)", self._message)
cur_byte_index = 0
data_chunks = []
for f in formatters:
# If the format string we found is > 1 character we know that a length
# field is included and we need to adjust our sizing accordingly.
f_size_char = f_type = f[-1]
if len(f) > 1:
f_size_char = f[:-1]
fsize = size_formatter_info[f_size_char.lower()]
try:
if f_type != 's':
end_index = cur_byte_index + fsize
fstr = type_formatter_info[f_type.lower()].format(fsize*8)
# Type formatting can give us incorrect format strings when
# a size formatter promotes a smaller data type. For instnace,
# 'hhu' says we'll promote a char (1 byte) to an unsigned
# int for display. Here, the type format string would be
# incorrectly set to 'MSB_U8' if we didn't correct.
if fsize == 1 and 'MSB_' in fstr:
fstr = fstr[4:]
d = dtype.PrimitiveType(fstr).decode(
evr_hist_data[cur_byte_index:end_index]
)
# Some formatters have an undefined data size (such as strings)
# and require additional processing to determine the length of
# the data and decode data.
else:
end_index = str(evr_hist_data).index('\x00', cur_byte_index)
d = str(evr_hist_data[cur_byte_index:end_index])
data_chunks.append(d)
except:
msg = "Unable to format EVR Message with data {}".format(evr_hist_data)
log.error(msg)
raise ValueError(msg)
cur_byte_index = end_index
# If we were formatting a string we need to add another index offset
# to exclude the null terminator.
if f == 's':
cur_byte_index += 1
# Format and return the EVR message if formatters were present, otherwise
# just return the EVR message as is.
if len(formatters) == 0:
return self._message
else:
# Python format strings cannot handle size formatter information. So something
# such as %llu needs to be adjusted to be a valid identifier in python by
# removing the size formatter.
msg = self._message
for f in formatters:
if len(f) > 1:
msg = msg.replace('%{}'.format(f), '%{}'.format(f[-1]))
return msg % tuple(data_chunks) | [
"def",
"format_message",
"(",
"self",
",",
"evr_hist_data",
")",
":",
"size_formatter_info",
"=",
"{",
"'s'",
":",
"-",
"1",
",",
"'c'",
":",
"1",
",",
"'i'",
":",
"4",
",",
"'d'",
":",
"4",
",",
"'u'",
":",
"4",
",",
"'x'",
":",
"4",
",",
"'hh... | Format EVR message with EVR data
Given a byte array of EVR data, format the EVR's message attribute
printf format strings and split the byte array into appropriately
sized chunks. Supports most format strings containing length and type
fields.
Args:
evr_hist_data: A bytearray of EVR data. Bytes are expected to be in
MSB ordering.
Example formatting::
# This is the character '!', string 'Foo', and int '4279317316'
bytearray([0x21, 0x46, 0x6f, 0x6f, 0x00, 0xff, 0x11, 0x33, 0x44])
Returns:
The EVR's message string formatted with the EVR data or the
unformatted EVR message string if there are no valid format
strings present in it.
Raises:
ValueError: When the bytearray cannot be fully processed with the
specified format strings. This is usually a result of the
expected data length and the byte array length not matching. | [
"Format",
"EVR",
"message",
"with",
"EVR",
"data"
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/evr.py#L104-L221 | train | 42,755 |
NASA-AMMOS/AIT-Core | ait/core/seq.py | Seq.append | def append (self, cmd, delay=0.000, attrs=None):
"""Adds a new command with a relative time delay to this sequence."""
self.lines.append( SeqCmd(cmd, delay, attrs) ) | python | def append (self, cmd, delay=0.000, attrs=None):
"""Adds a new command with a relative time delay to this sequence."""
self.lines.append( SeqCmd(cmd, delay, attrs) ) | [
"def",
"append",
"(",
"self",
",",
"cmd",
",",
"delay",
"=",
"0.000",
",",
"attrs",
"=",
"None",
")",
":",
"self",
".",
"lines",
".",
"append",
"(",
"SeqCmd",
"(",
"cmd",
",",
"delay",
",",
"attrs",
")",
")"
] | Adds a new command with a relative time delay to this sequence. | [
"Adds",
"a",
"new",
"command",
"with",
"a",
"relative",
"time",
"delay",
"to",
"this",
"sequence",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/seq.py#L145-L147 | train | 42,756 |
NASA-AMMOS/AIT-Core | ait/core/seq.py | Seq.printText | def printText (self, stream=None):
"""Prints a text representation of this sequence to the given stream or
standard output.
"""
if stream is None:
stream = sys.stdout
stream.write('# seqid : %u\n' % self.seqid )
stream.write('# version : %u\n' % self.version )
stream.write('# crc32 : 0x%04x\n' % self.crc32 )
stream.write('# ncmds : %u\n' % len(self.commands) )
stream.write('# duration: %.3fs\n' % self.duration )
stream.write('\n')
for line in self.lines:
stream.write( str(line) )
stream.write('\n') | python | def printText (self, stream=None):
"""Prints a text representation of this sequence to the given stream or
standard output.
"""
if stream is None:
stream = sys.stdout
stream.write('# seqid : %u\n' % self.seqid )
stream.write('# version : %u\n' % self.version )
stream.write('# crc32 : 0x%04x\n' % self.crc32 )
stream.write('# ncmds : %u\n' % len(self.commands) )
stream.write('# duration: %.3fs\n' % self.duration )
stream.write('\n')
for line in self.lines:
stream.write( str(line) )
stream.write('\n') | [
"def",
"printText",
"(",
"self",
",",
"stream",
"=",
"None",
")",
":",
"if",
"stream",
"is",
"None",
":",
"stream",
"=",
"sys",
".",
"stdout",
"stream",
".",
"write",
"(",
"'# seqid : %u\\n'",
"%",
"self",
".",
"seqid",
")",
"stream",
".",
"write",
... | Prints a text representation of this sequence to the given stream or
standard output. | [
"Prints",
"a",
"text",
"representation",
"of",
"this",
"sequence",
"to",
"the",
"given",
"stream",
"or",
"standard",
"output",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/seq.py#L150-L166 | train | 42,757 |
NASA-AMMOS/AIT-Core | ait/core/seq.py | Seq.validate | def validate (self):
"""Returns True if this Sequence is valid, False otherwise.
Validation error messages are stored in self.messages.
"""
if not os.path.isfile(self.pathname):
self.message.append('Filename "%s" does not exist.')
else:
try:
with open(self.pathname, 'r') as stream:
pass
except IOError:
self.messages.append('Could not open "%s" for reading.' % self.pathname)
for line in self.commands:
messages = [ ]
if line.cmd and not line.cmd.validate(messages):
msg = 'error: %s: %s' % (line.cmd.name, " ".join(messages))
self.log.messages.append(msg)
return len(self.log.messages) == 0 | python | def validate (self):
"""Returns True if this Sequence is valid, False otherwise.
Validation error messages are stored in self.messages.
"""
if not os.path.isfile(self.pathname):
self.message.append('Filename "%s" does not exist.')
else:
try:
with open(self.pathname, 'r') as stream:
pass
except IOError:
self.messages.append('Could not open "%s" for reading.' % self.pathname)
for line in self.commands:
messages = [ ]
if line.cmd and not line.cmd.validate(messages):
msg = 'error: %s: %s' % (line.cmd.name, " ".join(messages))
self.log.messages.append(msg)
return len(self.log.messages) == 0 | [
"def",
"validate",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"pathname",
")",
":",
"self",
".",
"message",
".",
"append",
"(",
"'Filename \"%s\" does not exist.'",
")",
"else",
":",
"try",
":",
"with",
"ope... | Returns True if this Sequence is valid, False otherwise.
Validation error messages are stored in self.messages. | [
"Returns",
"True",
"if",
"this",
"Sequence",
"is",
"valid",
"False",
"otherwise",
".",
"Validation",
"error",
"messages",
"are",
"stored",
"in",
"self",
".",
"messages",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/seq.py#L240-L259 | train | 42,758 |
NASA-AMMOS/AIT-Core | ait/core/seq.py | SeqCmd.decode | def decode (cls, bytes, cmddict):
"""Decodes a sequence command from an array of bytes, according to the
given command dictionary, and returns a new SeqCmd.
"""
attrs = SeqCmdAttrs.decode(bytes[0:1])
delay = SeqDelay .decode(bytes[1:4])
cmd = cmddict .decode(bytes[4:] )
return cls(cmd, delay, attrs) | python | def decode (cls, bytes, cmddict):
"""Decodes a sequence command from an array of bytes, according to the
given command dictionary, and returns a new SeqCmd.
"""
attrs = SeqCmdAttrs.decode(bytes[0:1])
delay = SeqDelay .decode(bytes[1:4])
cmd = cmddict .decode(bytes[4:] )
return cls(cmd, delay, attrs) | [
"def",
"decode",
"(",
"cls",
",",
"bytes",
",",
"cmddict",
")",
":",
"attrs",
"=",
"SeqCmdAttrs",
".",
"decode",
"(",
"bytes",
"[",
"0",
":",
"1",
"]",
")",
"delay",
"=",
"SeqDelay",
".",
"decode",
"(",
"bytes",
"[",
"1",
":",
"4",
"]",
")",
"c... | Decodes a sequence command from an array of bytes, according to the
given command dictionary, and returns a new SeqCmd. | [
"Decodes",
"a",
"sequence",
"command",
"from",
"an",
"array",
"of",
"bytes",
"according",
"to",
"the",
"given",
"command",
"dictionary",
"and",
"returns",
"a",
"new",
"SeqCmd",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/seq.py#L418-L425 | train | 42,759 |
NASA-AMMOS/AIT-Core | ait/core/seq.py | SeqCmd.encode | def encode (self):
"""Encodes this SeqCmd to binary and returns a bytearray."""
return self.attrs.encode() + self.delay.encode() + self.cmd.encode() | python | def encode (self):
"""Encodes this SeqCmd to binary and returns a bytearray."""
return self.attrs.encode() + self.delay.encode() + self.cmd.encode() | [
"def",
"encode",
"(",
"self",
")",
":",
"return",
"self",
".",
"attrs",
".",
"encode",
"(",
")",
"+",
"self",
".",
"delay",
".",
"encode",
"(",
")",
"+",
"self",
".",
"cmd",
".",
"encode",
"(",
")"
] | Encodes this SeqCmd to binary and returns a bytearray. | [
"Encodes",
"this",
"SeqCmd",
"to",
"binary",
"and",
"returns",
"a",
"bytearray",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/seq.py#L428-L430 | train | 42,760 |
NASA-AMMOS/AIT-Core | ait/core/seq.py | SeqCmd.parse | def parse (cls, line, lineno, log, cmddict):
"""Parses the sequence command from a line of text, according to the
given command dictionary, and returns a new SeqCmd.
"""
delay = SeqDelay .parse(line, lineno, log, cmddict)
attrs = SeqCmdAttrs.parse(line, lineno, log, cmddict)
comment = SeqComment .parse(line, lineno, log, cmddict)
stop = len(line)
if comment:
stop = comment.pos.col.start - 1
if attrs and attrs.pos.col.stop != -1:
stop = attrs.pos.col.start - 1
tokens = line[:stop].split()
name = tokens[1]
args = tokens[2:]
start = line.find(name)
pos = SeqPos(line, lineno, start + 1, stop)
if name not in cmddict:
log.error('Unrecognized command "%s".' % name, pos)
elif cmddict[name].nargs != len(args):
msg = 'Command argument size mismatch: expected %d, but encountered %d.'
log.error(msg % (cmddict[name].nargs, len(args)), pos)
args = [ util.toNumber(a, a) for a in args ]
cmd = cmddict.create(name, *args)
return cls(cmd, delay, attrs, comment, pos) | python | def parse (cls, line, lineno, log, cmddict):
"""Parses the sequence command from a line of text, according to the
given command dictionary, and returns a new SeqCmd.
"""
delay = SeqDelay .parse(line, lineno, log, cmddict)
attrs = SeqCmdAttrs.parse(line, lineno, log, cmddict)
comment = SeqComment .parse(line, lineno, log, cmddict)
stop = len(line)
if comment:
stop = comment.pos.col.start - 1
if attrs and attrs.pos.col.stop != -1:
stop = attrs.pos.col.start - 1
tokens = line[:stop].split()
name = tokens[1]
args = tokens[2:]
start = line.find(name)
pos = SeqPos(line, lineno, start + 1, stop)
if name not in cmddict:
log.error('Unrecognized command "%s".' % name, pos)
elif cmddict[name].nargs != len(args):
msg = 'Command argument size mismatch: expected %d, but encountered %d.'
log.error(msg % (cmddict[name].nargs, len(args)), pos)
args = [ util.toNumber(a, a) for a in args ]
cmd = cmddict.create(name, *args)
return cls(cmd, delay, attrs, comment, pos) | [
"def",
"parse",
"(",
"cls",
",",
"line",
",",
"lineno",
",",
"log",
",",
"cmddict",
")",
":",
"delay",
"=",
"SeqDelay",
".",
"parse",
"(",
"line",
",",
"lineno",
",",
"log",
",",
"cmddict",
")",
"attrs",
"=",
"SeqCmdAttrs",
".",
"parse",
"(",
"line... | Parses the sequence command from a line of text, according to the
given command dictionary, and returns a new SeqCmd. | [
"Parses",
"the",
"sequence",
"command",
"from",
"a",
"line",
"of",
"text",
"according",
"to",
"the",
"given",
"command",
"dictionary",
"and",
"returns",
"a",
"new",
"SeqCmd",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/seq.py#L434-L464 | train | 42,761 |
NASA-AMMOS/AIT-Core | ait/core/seq.py | SeqCmdAttrs.decode | def decode (cls, bytes, cmddict=None):
"""Decodes sequence command attributes from an array of bytes and
returns a new SeqCmdAttrs.
"""
byte = struct.unpack('B', bytes)[0]
self = cls()
defval = self.default
for bit, name, value0, value1, default in SeqCmdAttrs.Table:
mask = 1 << bit
bitset = mask & byte
defset = mask & defval
if bitset != defset:
if bitset:
self.attrs[name] = value1
else:
self.attrs[name] = value0
return self | python | def decode (cls, bytes, cmddict=None):
"""Decodes sequence command attributes from an array of bytes and
returns a new SeqCmdAttrs.
"""
byte = struct.unpack('B', bytes)[0]
self = cls()
defval = self.default
for bit, name, value0, value1, default in SeqCmdAttrs.Table:
mask = 1 << bit
bitset = mask & byte
defset = mask & defval
if bitset != defset:
if bitset:
self.attrs[name] = value1
else:
self.attrs[name] = value0
return self | [
"def",
"decode",
"(",
"cls",
",",
"bytes",
",",
"cmddict",
"=",
"None",
")",
":",
"byte",
"=",
"struct",
".",
"unpack",
"(",
"'B'",
",",
"bytes",
")",
"[",
"0",
"]",
"self",
"=",
"cls",
"(",
")",
"defval",
"=",
"self",
".",
"default",
"for",
"b... | Decodes sequence command attributes from an array of bytes and
returns a new SeqCmdAttrs. | [
"Decodes",
"sequence",
"command",
"attributes",
"from",
"an",
"array",
"of",
"bytes",
"and",
"returns",
"a",
"new",
"SeqCmdAttrs",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/seq.py#L517-L535 | train | 42,762 |
NASA-AMMOS/AIT-Core | ait/core/seq.py | SeqCmdAttrs.encode | def encode (self):
"""Encodes this SeqCmdAttrs to binary and returns a bytearray."""
byte = self.default
for bit, name, value0, value1, default in SeqCmdAttrs.Table:
if name in self.attrs:
value = self.attrs[name]
byte = setBit(byte, bit, value == value1)
return struct.pack('B', byte) | python | def encode (self):
"""Encodes this SeqCmdAttrs to binary and returns a bytearray."""
byte = self.default
for bit, name, value0, value1, default in SeqCmdAttrs.Table:
if name in self.attrs:
value = self.attrs[name]
byte = setBit(byte, bit, value == value1)
return struct.pack('B', byte) | [
"def",
"encode",
"(",
"self",
")",
":",
"byte",
"=",
"self",
".",
"default",
"for",
"bit",
",",
"name",
",",
"value0",
",",
"value1",
",",
"default",
"in",
"SeqCmdAttrs",
".",
"Table",
":",
"if",
"name",
"in",
"self",
".",
"attrs",
":",
"value",
"=... | Encodes this SeqCmdAttrs to binary and returns a bytearray. | [
"Encodes",
"this",
"SeqCmdAttrs",
"to",
"binary",
"and",
"returns",
"a",
"bytearray",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/seq.py#L538-L547 | train | 42,763 |
NASA-AMMOS/AIT-Core | ait/core/seq.py | SeqCmdAttrs.parse | def parse (cls, line, lineno, log, cmddict=None):
"""Parses a SeqCmdAttrs from a line of text and returns it or None.
Warning and error messages are logged via the SeqMsgLog log.
"""
start = line.find('{')
stop = line.find('}')
pos = SeqPos(line, lineno, start + 1, stop)
result = cls(None, pos)
if start >= 0 and stop >= start:
attrs = { }
pairs = line[start + 1:stop].split(',')
for item in pairs:
ncolons = item.count(':')
if ncolons == 0:
log.error('Missing colon in command attribute "%s".' % item, pos)
elif ncolons > 1:
log.error('Too many colons in command attribute "%s".' % item, pos)
else:
name, value = (s.strip() for s in item.split(':'))
attrs[name] = value
result = cls(attrs, pos)
elif start != -1 or stop != -1:
log.error('Incorrect command attribute curly brace placement.', pos)
return result | python | def parse (cls, line, lineno, log, cmddict=None):
"""Parses a SeqCmdAttrs from a line of text and returns it or None.
Warning and error messages are logged via the SeqMsgLog log.
"""
start = line.find('{')
stop = line.find('}')
pos = SeqPos(line, lineno, start + 1, stop)
result = cls(None, pos)
if start >= 0 and stop >= start:
attrs = { }
pairs = line[start + 1:stop].split(',')
for item in pairs:
ncolons = item.count(':')
if ncolons == 0:
log.error('Missing colon in command attribute "%s".' % item, pos)
elif ncolons > 1:
log.error('Too many colons in command attribute "%s".' % item, pos)
else:
name, value = (s.strip() for s in item.split(':'))
attrs[name] = value
result = cls(attrs, pos)
elif start != -1 or stop != -1:
log.error('Incorrect command attribute curly brace placement.', pos)
return result | [
"def",
"parse",
"(",
"cls",
",",
"line",
",",
"lineno",
",",
"log",
",",
"cmddict",
"=",
"None",
")",
":",
"start",
"=",
"line",
".",
"find",
"(",
"'{'",
")",
"stop",
"=",
"line",
".",
"find",
"(",
"'}'",
")",
"pos",
"=",
"SeqPos",
"(",
"line",... | Parses a SeqCmdAttrs from a line of text and returns it or None.
Warning and error messages are logged via the SeqMsgLog log. | [
"Parses",
"a",
"SeqCmdAttrs",
"from",
"a",
"line",
"of",
"text",
"and",
"returns",
"it",
"or",
"None",
".",
"Warning",
"and",
"error",
"messages",
"are",
"logged",
"via",
"the",
"SeqMsgLog",
"log",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/seq.py#L551-L579 | train | 42,764 |
NASA-AMMOS/AIT-Core | ait/core/seq.py | SeqDelay.decode | def decode (cls, bytes, cmddict=None):
"""Decodes a sequence delay from an array of bytes, according to the
given command dictionary, and returns a new SeqDelay.
"""
delay_s = struct.unpack('>H', bytes[0:2])[0]
delay_ms = struct.unpack('B' , bytes[2:3])[0]
return cls(delay_s + (delay_ms / 255.0)) | python | def decode (cls, bytes, cmddict=None):
"""Decodes a sequence delay from an array of bytes, according to the
given command dictionary, and returns a new SeqDelay.
"""
delay_s = struct.unpack('>H', bytes[0:2])[0]
delay_ms = struct.unpack('B' , bytes[2:3])[0]
return cls(delay_s + (delay_ms / 255.0)) | [
"def",
"decode",
"(",
"cls",
",",
"bytes",
",",
"cmddict",
"=",
"None",
")",
":",
"delay_s",
"=",
"struct",
".",
"unpack",
"(",
"'>H'",
",",
"bytes",
"[",
"0",
":",
"2",
"]",
")",
"[",
"0",
"]",
"delay_ms",
"=",
"struct",
".",
"unpack",
"(",
"'... | Decodes a sequence delay from an array of bytes, according to the
given command dictionary, and returns a new SeqDelay. | [
"Decodes",
"a",
"sequence",
"delay",
"from",
"an",
"array",
"of",
"bytes",
"according",
"to",
"the",
"given",
"command",
"dictionary",
"and",
"returns",
"a",
"new",
"SeqDelay",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/seq.py#L630-L636 | train | 42,765 |
NASA-AMMOS/AIT-Core | ait/core/seq.py | SeqDelay.encode | def encode (self):
"""Encodes this SeqDelay to a binary bytearray."""
delay_s = int( math.floor(self.delay) )
delay_ms = int( (self.delay - delay_s) * 255.0 )
return struct.pack('>H', delay_s) + struct.pack('B', delay_ms) | python | def encode (self):
"""Encodes this SeqDelay to a binary bytearray."""
delay_s = int( math.floor(self.delay) )
delay_ms = int( (self.delay - delay_s) * 255.0 )
return struct.pack('>H', delay_s) + struct.pack('B', delay_ms) | [
"def",
"encode",
"(",
"self",
")",
":",
"delay_s",
"=",
"int",
"(",
"math",
".",
"floor",
"(",
"self",
".",
"delay",
")",
")",
"delay_ms",
"=",
"int",
"(",
"(",
"self",
".",
"delay",
"-",
"delay_s",
")",
"*",
"255.0",
")",
"return",
"struct",
"."... | Encodes this SeqDelay to a binary bytearray. | [
"Encodes",
"this",
"SeqDelay",
"to",
"a",
"binary",
"bytearray",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/seq.py#L639-L643 | train | 42,766 |
NASA-AMMOS/AIT-Core | ait/core/seq.py | SeqDelay.parse | def parse (cls, line, lineno, log, cmddict=None):
"""Parses the SeqDelay from a line of text. Warning and error
messages are logged via the SeqMsgLog log.
"""
delay = -1
token = line.split()[0]
start = line.find(token)
pos = SeqPos(line, lineno, start + 1, start + len(token))
try:
delay = float(token)
except ValueError:
msg = 'String "%s" could not be interpreted as a numeric time delay.'
log.error(msg % token, pos)
return cls(delay, pos) | python | def parse (cls, line, lineno, log, cmddict=None):
"""Parses the SeqDelay from a line of text. Warning and error
messages are logged via the SeqMsgLog log.
"""
delay = -1
token = line.split()[0]
start = line.find(token)
pos = SeqPos(line, lineno, start + 1, start + len(token))
try:
delay = float(token)
except ValueError:
msg = 'String "%s" could not be interpreted as a numeric time delay.'
log.error(msg % token, pos)
return cls(delay, pos) | [
"def",
"parse",
"(",
"cls",
",",
"line",
",",
"lineno",
",",
"log",
",",
"cmddict",
"=",
"None",
")",
":",
"delay",
"=",
"-",
"1",
"token",
"=",
"line",
".",
"split",
"(",
")",
"[",
"0",
"]",
"start",
"=",
"line",
".",
"find",
"(",
"token",
"... | Parses the SeqDelay from a line of text. Warning and error
messages are logged via the SeqMsgLog log. | [
"Parses",
"the",
"SeqDelay",
"from",
"a",
"line",
"of",
"text",
".",
"Warning",
"and",
"error",
"messages",
"are",
"logged",
"via",
"the",
"SeqMsgLog",
"log",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/seq.py#L647-L662 | train | 42,767 |
NASA-AMMOS/AIT-Core | ait/core/seq.py | SeqMetaCmd.parse | def parse (cls, line, lineno, log, cmddict=None):
"""Parses the SeqMetaCmd from a line of text. Warning and error
messages are logged via the SeqMsgLog log.
"""
start = line.find('%')
pos = SeqPos(line, lineno, start + 1, len(line))
result = None
if start >= 0:
result = cls(line[start:], pos)
return result | python | def parse (cls, line, lineno, log, cmddict=None):
"""Parses the SeqMetaCmd from a line of text. Warning and error
messages are logged via the SeqMsgLog log.
"""
start = line.find('%')
pos = SeqPos(line, lineno, start + 1, len(line))
result = None
if start >= 0:
result = cls(line[start:], pos)
return result | [
"def",
"parse",
"(",
"cls",
",",
"line",
",",
"lineno",
",",
"log",
",",
"cmddict",
"=",
"None",
")",
":",
"start",
"=",
"line",
".",
"find",
"(",
"'%'",
")",
"pos",
"=",
"SeqPos",
"(",
"line",
",",
"lineno",
",",
"start",
"+",
"1",
",",
"len",... | Parses the SeqMetaCmd from a line of text. Warning and error
messages are logged via the SeqMsgLog log. | [
"Parses",
"the",
"SeqMetaCmd",
"from",
"a",
"line",
"of",
"text",
".",
"Warning",
"and",
"error",
"messages",
"are",
"logged",
"via",
"the",
"SeqMsgLog",
"log",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/seq.py#L687-L698 | train | 42,768 |
NASA-AMMOS/AIT-Core | ait/core/seq.py | SeqMsgLog.error | def error (self, msg, pos=None):
"""Logs an error message pertaining to the given SeqPos."""
self.log(msg, 'error: ' + self.location(pos)) | python | def error (self, msg, pos=None):
"""Logs an error message pertaining to the given SeqPos."""
self.log(msg, 'error: ' + self.location(pos)) | [
"def",
"error",
"(",
"self",
",",
"msg",
",",
"pos",
"=",
"None",
")",
":",
"self",
".",
"log",
"(",
"msg",
",",
"'error: '",
"+",
"self",
".",
"location",
"(",
"pos",
")",
")"
] | Logs an error message pertaining to the given SeqPos. | [
"Logs",
"an",
"error",
"message",
"pertaining",
"to",
"the",
"given",
"SeqPos",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/seq.py#L715-L717 | train | 42,769 |
NASA-AMMOS/AIT-Core | ait/core/seq.py | SeqMsgLog.log | def log (self, msg, prefix=None):
"""Logs a message with an optional prefix."""
if prefix:
if not prefix.strip().endswith(':'):
prefix += ': '
msg = prefix + msg
self.messages.append(msg) | python | def log (self, msg, prefix=None):
"""Logs a message with an optional prefix."""
if prefix:
if not prefix.strip().endswith(':'):
prefix += ': '
msg = prefix + msg
self.messages.append(msg) | [
"def",
"log",
"(",
"self",
",",
"msg",
",",
"prefix",
"=",
"None",
")",
":",
"if",
"prefix",
":",
"if",
"not",
"prefix",
".",
"strip",
"(",
")",
".",
"endswith",
"(",
"':'",
")",
":",
"prefix",
"+=",
"': '",
"msg",
"=",
"prefix",
"+",
"msg",
"s... | Logs a message with an optional prefix. | [
"Logs",
"a",
"message",
"with",
"an",
"optional",
"prefix",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/seq.py#L733-L739 | train | 42,770 |
NASA-AMMOS/AIT-Core | ait/core/seq.py | SeqMsgLog.warning | def warning (self, msg, pos=None):
"""Logs a warning message pertaining to the given SeqAtom."""
self.log(msg, 'warning: ' + self.location(pos)) | python | def warning (self, msg, pos=None):
"""Logs a warning message pertaining to the given SeqAtom."""
self.log(msg, 'warning: ' + self.location(pos)) | [
"def",
"warning",
"(",
"self",
",",
"msg",
",",
"pos",
"=",
"None",
")",
":",
"self",
".",
"log",
"(",
"msg",
",",
"'warning: '",
"+",
"self",
".",
"location",
"(",
"pos",
")",
")"
] | Logs a warning message pertaining to the given SeqAtom. | [
"Logs",
"a",
"warning",
"message",
"pertaining",
"to",
"the",
"given",
"SeqAtom",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/seq.py#L742-L744 | train | 42,771 |
NASA-AMMOS/AIT-Core | ait/core/cfg.py | expandConfigPaths | def expandConfigPaths (config, prefix=None, datetime=None, pathvars=None, parameter_key='', *keys):
"""Updates all relative configuration paths in dictionary config,
which contain a key in keys, by prepending prefix.
If keys is omitted, it defaults to 'directory', 'file',
'filename', 'path', 'pathname'.
See util.expandPath().
"""
if len(keys) == 0:
keys = PATH_KEYS
for name, value in config.items():
if name in keys and type(name) is str:
expanded = util.expandPath(value, prefix)
cleaned = replaceVariables(expanded, datetime=datetime, pathvars=pathvars)
for p in cleaned:
if not os.path.exists(p):
msg = "Config parameter {}.{} specifies nonexistent path {}".format(parameter_key, name, p)
log.warn(msg)
config[name] = cleaned[0] if len(cleaned) == 1 else cleaned
elif type(value) is dict:
param_key = name if parameter_key == '' else parameter_key + '.' + name
expandConfigPaths(value, prefix, datetime, pathvars, param_key, *keys) | python | def expandConfigPaths (config, prefix=None, datetime=None, pathvars=None, parameter_key='', *keys):
"""Updates all relative configuration paths in dictionary config,
which contain a key in keys, by prepending prefix.
If keys is omitted, it defaults to 'directory', 'file',
'filename', 'path', 'pathname'.
See util.expandPath().
"""
if len(keys) == 0:
keys = PATH_KEYS
for name, value in config.items():
if name in keys and type(name) is str:
expanded = util.expandPath(value, prefix)
cleaned = replaceVariables(expanded, datetime=datetime, pathvars=pathvars)
for p in cleaned:
if not os.path.exists(p):
msg = "Config parameter {}.{} specifies nonexistent path {}".format(parameter_key, name, p)
log.warn(msg)
config[name] = cleaned[0] if len(cleaned) == 1 else cleaned
elif type(value) is dict:
param_key = name if parameter_key == '' else parameter_key + '.' + name
expandConfigPaths(value, prefix, datetime, pathvars, param_key, *keys) | [
"def",
"expandConfigPaths",
"(",
"config",
",",
"prefix",
"=",
"None",
",",
"datetime",
"=",
"None",
",",
"pathvars",
"=",
"None",
",",
"parameter_key",
"=",
"''",
",",
"*",
"keys",
")",
":",
"if",
"len",
"(",
"keys",
")",
"==",
"0",
":",
"keys",
"... | Updates all relative configuration paths in dictionary config,
which contain a key in keys, by prepending prefix.
If keys is omitted, it defaults to 'directory', 'file',
'filename', 'path', 'pathname'.
See util.expandPath(). | [
"Updates",
"all",
"relative",
"configuration",
"paths",
"in",
"dictionary",
"config",
"which",
"contain",
"a",
"key",
"in",
"keys",
"by",
"prepending",
"prefix",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/cfg.py#L42-L68 | train | 42,772 |
NASA-AMMOS/AIT-Core | ait/core/cfg.py | replaceVariables | def replaceVariables(path, datetime=None, pathvars=None):
"""Return absolute path with path variables replaced as applicable"""
if datetime is None:
datetime = time.gmtime()
# if path variables are not given, set as empty list
if pathvars is None:
pathvars = [ ]
# create an init path list to loop through
if isinstance(path, list):
path_list = path
else:
path_list = [ path ]
# Set up the regex to search for variables
regex = re.compile('\$\{(.*?)\}')
# create a newpath list that will hold the 'cleaned' paths
# with variables and strftime format directives replaced
newpath_list = [ ]
for p in path_list:
# create temppath_list to be used a we work through the
newpath_list.append(p)
# Variable replacement
# Find all the variables in path using the regex
for k in regex.findall(p):
# Check if the key is in path variables map
if k in pathvars:
# get the str or list of values
v = pathvars[k]
# Check value of variable must be in (string, integer, list)
if type(v) is dict:
msg = "Path variable must refer to string, integer, or list"
raise TypeError(msg)
# get the list of possible variable values
value_list = v if type(v) is list else [ v ]
# create temp_list for now
temp_list = []
# loop through the most recent newpath list
# need to do this every time in order to account for all possible
# combinations
# replace the variables
# loop through the list of values and replace the variables
for v in value_list:
for newpath in newpath_list:
# remove the path from newpath_list
temp_list.append(newpath.replace('${%s}' % k, str(v)))
# replace newpath_list
newpath_list = temp_list
# strftime translation
# Loop through newpath_list to do strftime translation
for index, newpath in enumerate(newpath_list):
# Apply strftime translation
newpath_list[index] = time.strftime(newpath, datetime)
return newpath_list | python | def replaceVariables(path, datetime=None, pathvars=None):
"""Return absolute path with path variables replaced as applicable"""
if datetime is None:
datetime = time.gmtime()
# if path variables are not given, set as empty list
if pathvars is None:
pathvars = [ ]
# create an init path list to loop through
if isinstance(path, list):
path_list = path
else:
path_list = [ path ]
# Set up the regex to search for variables
regex = re.compile('\$\{(.*?)\}')
# create a newpath list that will hold the 'cleaned' paths
# with variables and strftime format directives replaced
newpath_list = [ ]
for p in path_list:
# create temppath_list to be used a we work through the
newpath_list.append(p)
# Variable replacement
# Find all the variables in path using the regex
for k in regex.findall(p):
# Check if the key is in path variables map
if k in pathvars:
# get the str or list of values
v = pathvars[k]
# Check value of variable must be in (string, integer, list)
if type(v) is dict:
msg = "Path variable must refer to string, integer, or list"
raise TypeError(msg)
# get the list of possible variable values
value_list = v if type(v) is list else [ v ]
# create temp_list for now
temp_list = []
# loop through the most recent newpath list
# need to do this every time in order to account for all possible
# combinations
# replace the variables
# loop through the list of values and replace the variables
for v in value_list:
for newpath in newpath_list:
# remove the path from newpath_list
temp_list.append(newpath.replace('${%s}' % k, str(v)))
# replace newpath_list
newpath_list = temp_list
# strftime translation
# Loop through newpath_list to do strftime translation
for index, newpath in enumerate(newpath_list):
# Apply strftime translation
newpath_list[index] = time.strftime(newpath, datetime)
return newpath_list | [
"def",
"replaceVariables",
"(",
"path",
",",
"datetime",
"=",
"None",
",",
"pathvars",
"=",
"None",
")",
":",
"if",
"datetime",
"is",
"None",
":",
"datetime",
"=",
"time",
".",
"gmtime",
"(",
")",
"# if path variables are not given, set as empty list",
"if",
"... | Return absolute path with path variables replaced as applicable | [
"Return",
"absolute",
"path",
"with",
"path",
"variables",
"replaced",
"as",
"applicable"
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/cfg.py#L71-L137 | train | 42,773 |
NASA-AMMOS/AIT-Core | ait/core/cfg.py | flatten | def flatten (d, *keys):
"""Flattens the dictionary d by merging keys in order such that later
keys take precedence over earlier keys.
"""
flat = { }
for k in keys:
flat = merge(flat, d.pop(k, { }))
return flat | python | def flatten (d, *keys):
"""Flattens the dictionary d by merging keys in order such that later
keys take precedence over earlier keys.
"""
flat = { }
for k in keys:
flat = merge(flat, d.pop(k, { }))
return flat | [
"def",
"flatten",
"(",
"d",
",",
"*",
"keys",
")",
":",
"flat",
"=",
"{",
"}",
"for",
"k",
"in",
"keys",
":",
"flat",
"=",
"merge",
"(",
"flat",
",",
"d",
".",
"pop",
"(",
"k",
",",
"{",
"}",
")",
")",
"return",
"flat"
] | Flattens the dictionary d by merging keys in order such that later
keys take precedence over earlier keys. | [
"Flattens",
"the",
"dictionary",
"d",
"by",
"merging",
"keys",
"in",
"order",
"such",
"that",
"later",
"keys",
"take",
"precedence",
"over",
"earlier",
"keys",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/cfg.py#L140-L150 | train | 42,774 |
NASA-AMMOS/AIT-Core | ait/core/cfg.py | loadYAML | def loadYAML (filename=None, data=None):
"""Loads either the given YAML configuration file or YAML data.
Returns None if there was an error reading from the configuration
file and logs an error message via ait.core.log.error().
"""
config = None
try:
if filename:
data = open(filename, 'rt')
config = yaml.load(data)
if type(data) is file:
data.close()
except IOError, e:
msg = 'Could not read AIT configuration file "%s": %s'
log.error(msg, filename, str(e))
return config | python | def loadYAML (filename=None, data=None):
"""Loads either the given YAML configuration file or YAML data.
Returns None if there was an error reading from the configuration
file and logs an error message via ait.core.log.error().
"""
config = None
try:
if filename:
data = open(filename, 'rt')
config = yaml.load(data)
if type(data) is file:
data.close()
except IOError, e:
msg = 'Could not read AIT configuration file "%s": %s'
log.error(msg, filename, str(e))
return config | [
"def",
"loadYAML",
"(",
"filename",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"config",
"=",
"None",
"try",
":",
"if",
"filename",
":",
"data",
"=",
"open",
"(",
"filename",
",",
"'rt'",
")",
"config",
"=",
"yaml",
".",
"load",
"(",
"data",
... | Loads either the given YAML configuration file or YAML data.
Returns None if there was an error reading from the configuration
file and logs an error message via ait.core.log.error(). | [
"Loads",
"either",
"the",
"given",
"YAML",
"configuration",
"file",
"or",
"YAML",
"data",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/cfg.py#L153-L173 | train | 42,775 |
NASA-AMMOS/AIT-Core | ait/core/cfg.py | merge | def merge (d, o):
"""Recursively merges keys from o into d and returns d."""
for k in o.keys():
if type(o[k]) is dict and k in d:
merge(d[k], o[k])
else:
d[k] = o[k]
return d | python | def merge (d, o):
"""Recursively merges keys from o into d and returns d."""
for k in o.keys():
if type(o[k]) is dict and k in d:
merge(d[k], o[k])
else:
d[k] = o[k]
return d | [
"def",
"merge",
"(",
"d",
",",
"o",
")",
":",
"for",
"k",
"in",
"o",
".",
"keys",
"(",
")",
":",
"if",
"type",
"(",
"o",
"[",
"k",
"]",
")",
"is",
"dict",
"and",
"k",
"in",
"d",
":",
"merge",
"(",
"d",
"[",
"k",
"]",
",",
"o",
"[",
"k... | Recursively merges keys from o into d and returns d. | [
"Recursively",
"merges",
"keys",
"from",
"o",
"into",
"d",
"and",
"returns",
"d",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/cfg.py#L176-L183 | train | 42,776 |
NASA-AMMOS/AIT-Core | ait/core/cfg.py | AitConfig._directory | def _directory (self):
"""The directory for this AitConfig."""
if self._filename is None:
return os.path.join(self._ROOT_DIR, 'config')
else:
return os.path.dirname(self._filename) | python | def _directory (self):
"""The directory for this AitConfig."""
if self._filename is None:
return os.path.join(self._ROOT_DIR, 'config')
else:
return os.path.dirname(self._filename) | [
"def",
"_directory",
"(",
"self",
")",
":",
"if",
"self",
".",
"_filename",
"is",
"None",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_ROOT_DIR",
",",
"'config'",
")",
"else",
":",
"return",
"os",
".",
"path",
".",
"dirname",
... | The directory for this AitConfig. | [
"The",
"directory",
"for",
"this",
"AitConfig",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/cfg.py#L297-L302 | train | 42,777 |
NASA-AMMOS/AIT-Core | ait/core/cfg.py | AitConfig._datapaths | def _datapaths(self):
"""Returns a simple key-value map for easy access to data paths"""
paths = { }
try:
data = self._config['data']
for k in data:
paths[k] = data[k]['path']
except KeyError as e:
raise AitConfigMissing(e.message)
except Exception as e:
raise AitConfigError('Error reading data paths: %s' % e)
return paths | python | def _datapaths(self):
"""Returns a simple key-value map for easy access to data paths"""
paths = { }
try:
data = self._config['data']
for k in data:
paths[k] = data[k]['path']
except KeyError as e:
raise AitConfigMissing(e.message)
except Exception as e:
raise AitConfigError('Error reading data paths: %s' % e)
return paths | [
"def",
"_datapaths",
"(",
"self",
")",
":",
"paths",
"=",
"{",
"}",
"try",
":",
"data",
"=",
"self",
".",
"_config",
"[",
"'data'",
"]",
"for",
"k",
"in",
"data",
":",
"paths",
"[",
"k",
"]",
"=",
"data",
"[",
"k",
"]",
"[",
"'path'",
"]",
"e... | Returns a simple key-value map for easy access to data paths | [
"Returns",
"a",
"simple",
"key",
"-",
"value",
"map",
"for",
"easy",
"access",
"to",
"data",
"paths"
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/cfg.py#L315-L327 | train | 42,778 |
NASA-AMMOS/AIT-Core | ait/core/cfg.py | AitConfig.reload | def reload (self, filename=None, data=None):
"""Reloads the a AIT configuration.
The AIT configuration is automatically loaded when the AIT
package is first imported. To replace the configuration, call
reload() (defaults to the current config.filename) or
reload(new_filename).
"""
if data is None and filename is None:
filename = self._filename
self._config = loadYAML(filename, data)
self._filename = filename
if self._config is not None:
keys = 'default', self._platform, self._hostname
self._config = flatten(self._config, *keys)
# on reload, if pathvars have not been set, we want to start
# with the defaults, add the platform and hostname, and
# merge in all of the information provided in the config
if self._pathvars is None:
self._pathvars = self.getDefaultPathVariables()
expandConfigPaths(self._config,
self._directory,
self._datetime,
merge(self._config, self._pathvars))
else:
self._config = { } | python | def reload (self, filename=None, data=None):
"""Reloads the a AIT configuration.
The AIT configuration is automatically loaded when the AIT
package is first imported. To replace the configuration, call
reload() (defaults to the current config.filename) or
reload(new_filename).
"""
if data is None and filename is None:
filename = self._filename
self._config = loadYAML(filename, data)
self._filename = filename
if self._config is not None:
keys = 'default', self._platform, self._hostname
self._config = flatten(self._config, *keys)
# on reload, if pathvars have not been set, we want to start
# with the defaults, add the platform and hostname, and
# merge in all of the information provided in the config
if self._pathvars is None:
self._pathvars = self.getDefaultPathVariables()
expandConfigPaths(self._config,
self._directory,
self._datetime,
merge(self._config, self._pathvars))
else:
self._config = { } | [
"def",
"reload",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"if",
"data",
"is",
"None",
"and",
"filename",
"is",
"None",
":",
"filename",
"=",
"self",
".",
"_filename",
"self",
".",
"_config",
"=",
"loadYAML",
"(",... | Reloads the a AIT configuration.
The AIT configuration is automatically loaded when the AIT
package is first imported. To replace the configuration, call
reload() (defaults to the current config.filename) or
reload(new_filename). | [
"Reloads",
"the",
"a",
"AIT",
"configuration",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/cfg.py#L329-L359 | train | 42,779 |
NASA-AMMOS/AIT-Core | ait/core/cfg.py | AitConfig.addPathVariables | def addPathVariables(self, pathvars):
""" Adds path variables to the pathvars map property"""
if type(pathvars) is dict:
self._pathvars = merge(self._pathvars, pathvars) | python | def addPathVariables(self, pathvars):
""" Adds path variables to the pathvars map property"""
if type(pathvars) is dict:
self._pathvars = merge(self._pathvars, pathvars) | [
"def",
"addPathVariables",
"(",
"self",
",",
"pathvars",
")",
":",
"if",
"type",
"(",
"pathvars",
")",
"is",
"dict",
":",
"self",
".",
"_pathvars",
"=",
"merge",
"(",
"self",
".",
"_pathvars",
",",
"pathvars",
")"
] | Adds path variables to the pathvars map property | [
"Adds",
"path",
"variables",
"to",
"the",
"pathvars",
"map",
"property"
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/cfg.py#L407-L410 | train | 42,780 |
NASA-AMMOS/AIT-Core | ait/core/dtype.py | ArrayType._assertIndex | def _assertIndex(self, index):
"""Raise TypeError or IndexError if index is not an integer or out of
range for the number of elements in this array, respectively.
"""
if type(index) is not int:
raise TypeError('list indices must be integers')
if index < 0 or index >= self.nelems:
raise IndexError('list index out of range') | python | def _assertIndex(self, index):
"""Raise TypeError or IndexError if index is not an integer or out of
range for the number of elements in this array, respectively.
"""
if type(index) is not int:
raise TypeError('list indices must be integers')
if index < 0 or index >= self.nelems:
raise IndexError('list index out of range') | [
"def",
"_assertIndex",
"(",
"self",
",",
"index",
")",
":",
"if",
"type",
"(",
"index",
")",
"is",
"not",
"int",
":",
"raise",
"TypeError",
"(",
"'list indices must be integers'",
")",
"if",
"index",
"<",
"0",
"or",
"index",
">=",
"self",
".",
"nelems",
... | Raise TypeError or IndexError if index is not an integer or out of
range for the number of elements in this array, respectively. | [
"Raise",
"TypeError",
"or",
"IndexError",
"if",
"index",
"is",
"not",
"an",
"integer",
"or",
"out",
"of",
"range",
"for",
"the",
"number",
"of",
"elements",
"in",
"this",
"array",
"respectively",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/dtype.py#L326-L333 | train | 42,781 |
NASA-AMMOS/AIT-Core | ait/core/dtype.py | CmdType.cmddict | def cmddict(self):
"""PrimitiveType base for the ComplexType"""
if self._cmddict is None:
self._cmddict = cmd.getDefaultDict()
return self._cmddict | python | def cmddict(self):
"""PrimitiveType base for the ComplexType"""
if self._cmddict is None:
self._cmddict = cmd.getDefaultDict()
return self._cmddict | [
"def",
"cmddict",
"(",
"self",
")",
":",
"if",
"self",
".",
"_cmddict",
"is",
"None",
":",
"self",
".",
"_cmddict",
"=",
"cmd",
".",
"getDefaultDict",
"(",
")",
"return",
"self",
".",
"_cmddict"
] | PrimitiveType base for the ComplexType | [
"PrimitiveType",
"base",
"for",
"the",
"ComplexType"
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/dtype.py#L468-L473 | train | 42,782 |
NASA-AMMOS/AIT-Core | ait/core/dtype.py | EVRType.evrs | def evrs(self):
"""Getter EVRs dictionary"""
if self._evrs is None:
import ait.core.evr as evr
self._evrs = evr.getDefaultDict()
return self._evrs | python | def evrs(self):
"""Getter EVRs dictionary"""
if self._evrs is None:
import ait.core.evr as evr
self._evrs = evr.getDefaultDict()
return self._evrs | [
"def",
"evrs",
"(",
"self",
")",
":",
"if",
"self",
".",
"_evrs",
"is",
"None",
":",
"import",
"ait",
".",
"core",
".",
"evr",
"as",
"evr",
"self",
".",
"_evrs",
"=",
"evr",
".",
"getDefaultDict",
"(",
")",
"return",
"self",
".",
"_evrs"
] | Getter EVRs dictionary | [
"Getter",
"EVRs",
"dictionary"
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/dtype.py#L535-L541 | train | 42,783 |
NASA-AMMOS/AIT-Core | ait/core/val.py | YAMLProcessor.load | def load(self, ymlfile=None):
"""Load and process the YAML file"""
if ymlfile is not None:
self.ymlfile = ymlfile
try:
# If yaml should be 'cleaned' of document references
if self._clean:
self.data = self.process(self.ymlfile)
else:
with open(self.ymlfile, 'rb') as stream:
for data in yaml.load_all(stream):
self.data.append(data)
self.loaded = True
except ScannerError, e:
msg = "YAML formattting error - '" + self.ymlfile + ": '" + str(e) + "'"
raise util.YAMLError(msg) | python | def load(self, ymlfile=None):
"""Load and process the YAML file"""
if ymlfile is not None:
self.ymlfile = ymlfile
try:
# If yaml should be 'cleaned' of document references
if self._clean:
self.data = self.process(self.ymlfile)
else:
with open(self.ymlfile, 'rb') as stream:
for data in yaml.load_all(stream):
self.data.append(data)
self.loaded = True
except ScannerError, e:
msg = "YAML formattting error - '" + self.ymlfile + ": '" + str(e) + "'"
raise util.YAMLError(msg) | [
"def",
"load",
"(",
"self",
",",
"ymlfile",
"=",
"None",
")",
":",
"if",
"ymlfile",
"is",
"not",
"None",
":",
"self",
".",
"ymlfile",
"=",
"ymlfile",
"try",
":",
"# If yaml should be 'cleaned' of document references",
"if",
"self",
".",
"_clean",
":",
"self"... | Load and process the YAML file | [
"Load",
"and",
"process",
"the",
"YAML",
"file"
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/val.py#L60-L77 | train | 42,784 |
NASA-AMMOS/AIT-Core | ait/core/val.py | YAMLProcessor.process | def process(self, ymlfile):
"""Cleans out all document tags from the YAML file to make it
JSON-friendly to work with the JSON Schema.
"""
output = ""
try:
# Need a list of line numbers where the documents resides
# Used for finding/displaying errors
self.doclines = []
linenum = None
with open(ymlfile, 'r') as txt:
for linenum, line in enumerate(txt):
# Pattern to match document start lines
doc_pattern = re.compile('(---) (![a-z]+)(.*$)', flags=re.I)
# Pattern to match sequence start lines
seq_pattern = re.compile('(\s*)(-+) !([a-z]+)(.*$)', flags=re.I)
# If we find a document, remove the tag
if doc_pattern.match(line):
line = doc_pattern.sub(r"---", line).lower()
self.doclines.append(linenum)
elif seq_pattern.match(line):
# Replace the sequence start with key string
line = seq_pattern.sub(r"\1\2 \3: line " + str(linenum), line).lower()
output = output + line
if linenum is None:
msg = "Empty YAML file: " + ymlfile
raise util.YAMLError(msg)
else:
# Append one more document to docline for the end
self.doclines.append(linenum+1)
return output
except IOError, e:
msg = "Could not process YAML file '" + ymlfile + "': '" + str(e) + "'"
raise IOError(msg) | python | def process(self, ymlfile):
"""Cleans out all document tags from the YAML file to make it
JSON-friendly to work with the JSON Schema.
"""
output = ""
try:
# Need a list of line numbers where the documents resides
# Used for finding/displaying errors
self.doclines = []
linenum = None
with open(ymlfile, 'r') as txt:
for linenum, line in enumerate(txt):
# Pattern to match document start lines
doc_pattern = re.compile('(---) (![a-z]+)(.*$)', flags=re.I)
# Pattern to match sequence start lines
seq_pattern = re.compile('(\s*)(-+) !([a-z]+)(.*$)', flags=re.I)
# If we find a document, remove the tag
if doc_pattern.match(line):
line = doc_pattern.sub(r"---", line).lower()
self.doclines.append(linenum)
elif seq_pattern.match(line):
# Replace the sequence start with key string
line = seq_pattern.sub(r"\1\2 \3: line " + str(linenum), line).lower()
output = output + line
if linenum is None:
msg = "Empty YAML file: " + ymlfile
raise util.YAMLError(msg)
else:
# Append one more document to docline for the end
self.doclines.append(linenum+1)
return output
except IOError, e:
msg = "Could not process YAML file '" + ymlfile + "': '" + str(e) + "'"
raise IOError(msg) | [
"def",
"process",
"(",
"self",
",",
"ymlfile",
")",
":",
"output",
"=",
"\"\"",
"try",
":",
"# Need a list of line numbers where the documents resides",
"# Used for finding/displaying errors",
"self",
".",
"doclines",
"=",
"[",
"]",
"linenum",
"=",
"None",
"with",
"... | Cleans out all document tags from the YAML file to make it
JSON-friendly to work with the JSON Schema. | [
"Cleans",
"out",
"all",
"document",
"tags",
"from",
"the",
"YAML",
"file",
"to",
"make",
"it",
"JSON",
"-",
"friendly",
"to",
"work",
"with",
"the",
"JSON",
"Schema",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/val.py#L79-L119 | train | 42,785 |
NASA-AMMOS/AIT-Core | ait/core/val.py | SchemaProcessor.load | def load(self, schemafile=None):
"""Load and process the schema file"""
if schemafile is not None:
self._schemafile = schemafile
try:
self.data = json.load(open(self._schemafile))
except (IOError, ValueError), e:
msg = "Could not load schema file '" + self._schemafile + "': '" + str(e) + "'"
raise jsonschema.SchemaError(msg)
self.loaded = True | python | def load(self, schemafile=None):
"""Load and process the schema file"""
if schemafile is not None:
self._schemafile = schemafile
try:
self.data = json.load(open(self._schemafile))
except (IOError, ValueError), e:
msg = "Could not load schema file '" + self._schemafile + "': '" + str(e) + "'"
raise jsonschema.SchemaError(msg)
self.loaded = True | [
"def",
"load",
"(",
"self",
",",
"schemafile",
"=",
"None",
")",
":",
"if",
"schemafile",
"is",
"not",
"None",
":",
"self",
".",
"_schemafile",
"=",
"schemafile",
"try",
":",
"self",
".",
"data",
"=",
"json",
".",
"load",
"(",
"open",
"(",
"self",
... | Load and process the schema file | [
"Load",
"and",
"process",
"the",
"schema",
"file"
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/val.py#L150-L161 | train | 42,786 |
NASA-AMMOS/AIT-Core | ait/core/val.py | Validator.schema_val | def schema_val(self, messages=None):
"Perform validation with processed YAML and Schema"
self._ymlproc = YAMLProcessor(self._ymlfile)
self._schemaproc = SchemaProcessor(self._schemafile)
valid = True
log.debug("BEGIN: Schema-based validation for YAML '%s' with schema '%s'", self._ymlfile, self._schemafile)
# Make sure the yml and schema have been loaded
if self._ymlproc.loaded and self._schemaproc.loaded:
# Load all of the yaml documents. Could be more than one in the same YAML file.
for docnum, data in enumerate(yaml.load_all(self._ymlproc.data)):
# Since YAML allows integer keys but JSON does not, we need to first
# dump the data as a JSON string to encode all of the potential integers
# as strings, and then read it back out into the YAML format. Kind of
# a clunky workaround but it works as expected.
data = yaml.load(json.dumps(data))
# Now we want to get a validator ready
v = jsonschema.Draft4Validator(self._schemaproc.data)
# Loop through the errors (if any) and set valid = False if any are found
# Display the error message
for error in sorted(v.iter_errors(data)):
msg = "Schema-based validation failed for YAML file '" + self._ymlfile + "'"
self.ehandler.process(docnum, self._ymlproc.doclines, error, messages)
valid = False
if not valid:
log.error(msg)
elif not self._ymlproc.loaded:
raise util.YAMLError("YAML must be loaded in order to validate.")
elif not self._schemaproc.loaded:
raise jsonschema.SchemaError("Schema must be loaded in order to validate.")
log.debug("END: Schema-based validation complete for '%s'", self._ymlfile)
return valid | python | def schema_val(self, messages=None):
"Perform validation with processed YAML and Schema"
self._ymlproc = YAMLProcessor(self._ymlfile)
self._schemaproc = SchemaProcessor(self._schemafile)
valid = True
log.debug("BEGIN: Schema-based validation for YAML '%s' with schema '%s'", self._ymlfile, self._schemafile)
# Make sure the yml and schema have been loaded
if self._ymlproc.loaded and self._schemaproc.loaded:
# Load all of the yaml documents. Could be more than one in the same YAML file.
for docnum, data in enumerate(yaml.load_all(self._ymlproc.data)):
# Since YAML allows integer keys but JSON does not, we need to first
# dump the data as a JSON string to encode all of the potential integers
# as strings, and then read it back out into the YAML format. Kind of
# a clunky workaround but it works as expected.
data = yaml.load(json.dumps(data))
# Now we want to get a validator ready
v = jsonschema.Draft4Validator(self._schemaproc.data)
# Loop through the errors (if any) and set valid = False if any are found
# Display the error message
for error in sorted(v.iter_errors(data)):
msg = "Schema-based validation failed for YAML file '" + self._ymlfile + "'"
self.ehandler.process(docnum, self._ymlproc.doclines, error, messages)
valid = False
if not valid:
log.error(msg)
elif not self._ymlproc.loaded:
raise util.YAMLError("YAML must be loaded in order to validate.")
elif not self._schemaproc.loaded:
raise jsonschema.SchemaError("Schema must be loaded in order to validate.")
log.debug("END: Schema-based validation complete for '%s'", self._ymlfile)
return valid | [
"def",
"schema_val",
"(",
"self",
",",
"messages",
"=",
"None",
")",
":",
"self",
".",
"_ymlproc",
"=",
"YAMLProcessor",
"(",
"self",
".",
"_ymlfile",
")",
"self",
".",
"_schemaproc",
"=",
"SchemaProcessor",
"(",
"self",
".",
"_schemafile",
")",
"valid",
... | Perform validation with processed YAML and Schema | [
"Perform",
"validation",
"with",
"processed",
"YAML",
"and",
"Schema"
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/val.py#L367-L405 | train | 42,787 |
NASA-AMMOS/AIT-Core | ait/core/val.py | CmdValidator.content_val | def content_val(self, ymldata=None, messages=None):
"""Validates the Command Dictionary to ensure the contents for each of the fields
meets specific criteria regarding the expected types, byte ranges, etc."""
self._ymlproc = YAMLProcessor(self._ymlfile, False)
# Turn off the YAML Processor
log.debug("BEGIN: Content-based validation of Command dictionary")
if ymldata is not None:
cmddict = ymldata
elif ymldata is None and self._ymlproc.loaded:
cmddict = self._ymlproc.data
elif not self._ymlproc.loaded:
raise util.YAMLError("YAML failed to load.")
try:
# instantiate the document number. this will increment in order to
# track the line numbers and section where validation fails
docnum = 0
# boolean to hold argument validity
argsvalid = True
# list of rules to validate against
rules = []
### set the command rules
#
# set uniqueness rule for command names
rules.append(UniquenessRule('name', "Duplicate command name: %s", messages))
# set uniqueness rule for opcodes
rules.append(UniquenessRule('opcode', "Duplicate opcode: %s", messages))
#
###
for cmdcnt, cmddefn in enumerate(cmddict[0]):
# check the command rules
for rule in rules:
rule.check(cmddefn)
# list of argument rules to validate against
argrules = []
### set rules for command arguments
#
# set uniqueness rule for opcodes
argrules.append(UniquenessRule('name', "Duplicate argument name: " + cmddefn.name + ".%s", messages))
# set type rule for arg.type
argrules.append(TypeRule('type', "Invalid argument type for argument: " + cmddefn.name + ".%s", messages))
# set argument size rule for arg.type.nbytes
argrules.append(TypeSizeRule('nbytes', "Invalid argument size for argument: " + cmddefn.name + ".%s", messages))
# set argument enumerations rule to check no enumerations contain un-quoted YAML special variables
argrules.append(EnumRule('enum', "Invalid enum value for argument: " + cmddefn.name + ".%s", messages))
# set byte order rule to ensure proper ordering of aruguments
argrules.append(ByteOrderRule('bytes', "Invalid byte order for argument: " + cmddefn.name + ".%s", messages))
#
###
argdefns = cmddefn.argdefns
for arg in argdefns:
# check argument rules
for rule in argrules:
rule.check(arg)
# check if argument rule failed, if so set the validity to False
if not all(r.valid is True for r in argrules):
argsvalid = False
log.debug("END: Content-based validation complete for '%s'", self._ymlfile)
# check validity of all command rules and argument validity
return all(rule.valid is True for rule in rules) and argsvalid
except util.YAMLValidationError, e:
# Display the error message
if messages is not None:
if len(e.message) < 128:
msg = "Validation Failed for YAML file '" + self._ymlfile + "': '" + str(e.message) + "'"
else:
msg = "Validation Failed for YAML file '" + self._ymlfile + "'"
log.error(msg)
self.ehandler.process(docnum, self.ehandler.doclines, e, messages)
return False | python | def content_val(self, ymldata=None, messages=None):
"""Validates the Command Dictionary to ensure the contents for each of the fields
meets specific criteria regarding the expected types, byte ranges, etc."""
self._ymlproc = YAMLProcessor(self._ymlfile, False)
# Turn off the YAML Processor
log.debug("BEGIN: Content-based validation of Command dictionary")
if ymldata is not None:
cmddict = ymldata
elif ymldata is None and self._ymlproc.loaded:
cmddict = self._ymlproc.data
elif not self._ymlproc.loaded:
raise util.YAMLError("YAML failed to load.")
try:
# instantiate the document number. this will increment in order to
# track the line numbers and section where validation fails
docnum = 0
# boolean to hold argument validity
argsvalid = True
# list of rules to validate against
rules = []
### set the command rules
#
# set uniqueness rule for command names
rules.append(UniquenessRule('name', "Duplicate command name: %s", messages))
# set uniqueness rule for opcodes
rules.append(UniquenessRule('opcode', "Duplicate opcode: %s", messages))
#
###
for cmdcnt, cmddefn in enumerate(cmddict[0]):
# check the command rules
for rule in rules:
rule.check(cmddefn)
# list of argument rules to validate against
argrules = []
### set rules for command arguments
#
# set uniqueness rule for opcodes
argrules.append(UniquenessRule('name', "Duplicate argument name: " + cmddefn.name + ".%s", messages))
# set type rule for arg.type
argrules.append(TypeRule('type', "Invalid argument type for argument: " + cmddefn.name + ".%s", messages))
# set argument size rule for arg.type.nbytes
argrules.append(TypeSizeRule('nbytes', "Invalid argument size for argument: " + cmddefn.name + ".%s", messages))
# set argument enumerations rule to check no enumerations contain un-quoted YAML special variables
argrules.append(EnumRule('enum', "Invalid enum value for argument: " + cmddefn.name + ".%s", messages))
# set byte order rule to ensure proper ordering of aruguments
argrules.append(ByteOrderRule('bytes', "Invalid byte order for argument: " + cmddefn.name + ".%s", messages))
#
###
argdefns = cmddefn.argdefns
for arg in argdefns:
# check argument rules
for rule in argrules:
rule.check(arg)
# check if argument rule failed, if so set the validity to False
if not all(r.valid is True for r in argrules):
argsvalid = False
log.debug("END: Content-based validation complete for '%s'", self._ymlfile)
# check validity of all command rules and argument validity
return all(rule.valid is True for rule in rules) and argsvalid
except util.YAMLValidationError, e:
# Display the error message
if messages is not None:
if len(e.message) < 128:
msg = "Validation Failed for YAML file '" + self._ymlfile + "': '" + str(e.message) + "'"
else:
msg = "Validation Failed for YAML file '" + self._ymlfile + "'"
log.error(msg)
self.ehandler.process(docnum, self.ehandler.doclines, e, messages)
return False | [
"def",
"content_val",
"(",
"self",
",",
"ymldata",
"=",
"None",
",",
"messages",
"=",
"None",
")",
":",
"self",
".",
"_ymlproc",
"=",
"YAMLProcessor",
"(",
"self",
".",
"_ymlfile",
",",
"False",
")",
"# Turn off the YAML Processor",
"log",
".",
"debug",
"(... | Validates the Command Dictionary to ensure the contents for each of the fields
meets specific criteria regarding the expected types, byte ranges, etc. | [
"Validates",
"the",
"Command",
"Dictionary",
"to",
"ensure",
"the",
"contents",
"for",
"each",
"of",
"the",
"fields",
"meets",
"specific",
"criteria",
"regarding",
"the",
"expected",
"types",
"byte",
"ranges",
"etc",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/val.py#L420-L507 | train | 42,788 |
NASA-AMMOS/AIT-Core | ait/core/val.py | TlmValidator.validate | def validate(self, ymldata=None, messages=None):
"""Validates the Telemetry Dictionary definitions"""
schema_val = self.schema_val(messages)
if len(messages) == 0:
content_val = self.content_val(ymldata, messages)
return schema_val and content_val | python | def validate(self, ymldata=None, messages=None):
"""Validates the Telemetry Dictionary definitions"""
schema_val = self.schema_val(messages)
if len(messages) == 0:
content_val = self.content_val(ymldata, messages)
return schema_val and content_val | [
"def",
"validate",
"(",
"self",
",",
"ymldata",
"=",
"None",
",",
"messages",
"=",
"None",
")",
":",
"schema_val",
"=",
"self",
".",
"schema_val",
"(",
"messages",
")",
"if",
"len",
"(",
"messages",
")",
"==",
"0",
":",
"content_val",
"=",
"self",
".... | Validates the Telemetry Dictionary definitions | [
"Validates",
"the",
"Telemetry",
"Dictionary",
"definitions"
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/val.py#L514-L520 | train | 42,789 |
NASA-AMMOS/AIT-Core | ait/core/val.py | TlmValidator.content_val | def content_val(self, ymldata=None, messages=None):
"""Validates the Telemetry Dictionary to ensure the contents for each of the fields
meets specific criteria regarding the expected types, byte ranges, etc."""
# Turn off the YAML Processor
log.debug("BEGIN: Content-based validation of Telemetry dictionary")
if ymldata is not None:
tlmdict = ymldata
else:
tlmdict = tlm.TlmDict(self._ymlfile)
try:
# instantiate the document number. this will increment in order to
# track the line numbers and section where validation fails
docnum = 0
# boolean to hold argument validity
fldsvalid = True
# list of rules to validate against
rules = []
### set the packet rules
#
# set uniqueness rule for packet names
rules.append(UniquenessRule('name', "Duplicate packet name: %s", messages))
###
# Loop through the keys and check each PacketDefinition
for key in tlmdict.keys():
pktdefn = tlmdict[key]
# check the telemetry packet rules
for rule in rules:
rule.check(pktdefn)
# list of field rules to validate against
fldrules = []
### set rules for telemetry fields
#
# set uniqueness rule for field name
fldrules.append(UniquenessRule('name', "Duplicate field name: " + pktdefn.name + ".%s", messages))
# set type rule for field.type
fldrules.append(TypeRule('type', "Invalid field type for field: " + pktdefn.name + ".%s", messages))
# set field size rule for field.type.nbytes
fldrules.append(TypeSizeRule('nbytes', "Invalid field size for field: " + pktdefn.name + ".%s", messages))
# set field enumerations rule to check no enumerations contain un-quoted YAML special variables
fldrules.append(EnumRule('enum', "Invalid enum value for field: " + pktdefn.name + ".%s", messages))
#
###
flddefns = pktdefn.fields
for fld in flddefns:
# check field rules
for rule in fldrules:
rule.check(fld)
# check if field rule failed, if so set the validity to False
if not all(r.valid is True for r in fldrules):
fldsvalid = False
log.debug("END: Content-based validation complete for '%s'", self._ymlfile)
# check validity of all packet rules and field validity
return all(rule.valid is True for rule in rules) and fldsvalid
except util.YAMLValidationError, e:
# Display the error message
if messages is not None:
if len(e.message) < 128:
msg = "Validation Failed for YAML file '" + self._ymlfile + "': '" + str(e.message) + "'"
else:
msg = "Validation Failed for YAML file '" + self._ymlfile + "'"
log.error(msg)
self.ehandler.process(self.ehandler.doclines, e, messages)
return False | python | def content_val(self, ymldata=None, messages=None):
"""Validates the Telemetry Dictionary to ensure the contents for each of the fields
meets specific criteria regarding the expected types, byte ranges, etc."""
# Turn off the YAML Processor
log.debug("BEGIN: Content-based validation of Telemetry dictionary")
if ymldata is not None:
tlmdict = ymldata
else:
tlmdict = tlm.TlmDict(self._ymlfile)
try:
# instantiate the document number. this will increment in order to
# track the line numbers and section where validation fails
docnum = 0
# boolean to hold argument validity
fldsvalid = True
# list of rules to validate against
rules = []
### set the packet rules
#
# set uniqueness rule for packet names
rules.append(UniquenessRule('name', "Duplicate packet name: %s", messages))
###
# Loop through the keys and check each PacketDefinition
for key in tlmdict.keys():
pktdefn = tlmdict[key]
# check the telemetry packet rules
for rule in rules:
rule.check(pktdefn)
# list of field rules to validate against
fldrules = []
### set rules for telemetry fields
#
# set uniqueness rule for field name
fldrules.append(UniquenessRule('name', "Duplicate field name: " + pktdefn.name + ".%s", messages))
# set type rule for field.type
fldrules.append(TypeRule('type', "Invalid field type for field: " + pktdefn.name + ".%s", messages))
# set field size rule for field.type.nbytes
fldrules.append(TypeSizeRule('nbytes', "Invalid field size for field: " + pktdefn.name + ".%s", messages))
# set field enumerations rule to check no enumerations contain un-quoted YAML special variables
fldrules.append(EnumRule('enum', "Invalid enum value for field: " + pktdefn.name + ".%s", messages))
#
###
flddefns = pktdefn.fields
for fld in flddefns:
# check field rules
for rule in fldrules:
rule.check(fld)
# check if field rule failed, if so set the validity to False
if not all(r.valid is True for r in fldrules):
fldsvalid = False
log.debug("END: Content-based validation complete for '%s'", self._ymlfile)
# check validity of all packet rules and field validity
return all(rule.valid is True for rule in rules) and fldsvalid
except util.YAMLValidationError, e:
# Display the error message
if messages is not None:
if len(e.message) < 128:
msg = "Validation Failed for YAML file '" + self._ymlfile + "': '" + str(e.message) + "'"
else:
msg = "Validation Failed for YAML file '" + self._ymlfile + "'"
log.error(msg)
self.ehandler.process(self.ehandler.doclines, e, messages)
return False | [
"def",
"content_val",
"(",
"self",
",",
"ymldata",
"=",
"None",
",",
"messages",
"=",
"None",
")",
":",
"# Turn off the YAML Processor",
"log",
".",
"debug",
"(",
"\"BEGIN: Content-based validation of Telemetry dictionary\"",
")",
"if",
"ymldata",
"is",
"not",
"None... | Validates the Telemetry Dictionary to ensure the contents for each of the fields
meets specific criteria regarding the expected types, byte ranges, etc. | [
"Validates",
"the",
"Telemetry",
"Dictionary",
"to",
"ensure",
"the",
"contents",
"for",
"each",
"of",
"the",
"fields",
"meets",
"specific",
"criteria",
"regarding",
"the",
"expected",
"types",
"byte",
"ranges",
"etc",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/val.py#L522-L601 | train | 42,790 |
NASA-AMMOS/AIT-Core | ait/core/val.py | UniquenessRule.check | def check(self, defn):
"""Performs the uniqueness check against the value list
maintained in this rule objects
"""
val = getattr(defn, self.attr)
if val is not None and val in self.val_list:
self.messages.append(self.msg % str(val))
# TODO self.messages.append("TBD location message")
self.valid = False
elif val is not None:
self.val_list.append(val)
log.debug(self.val_list) | python | def check(self, defn):
"""Performs the uniqueness check against the value list
maintained in this rule objects
"""
val = getattr(defn, self.attr)
if val is not None and val in self.val_list:
self.messages.append(self.msg % str(val))
# TODO self.messages.append("TBD location message")
self.valid = False
elif val is not None:
self.val_list.append(val)
log.debug(self.val_list) | [
"def",
"check",
"(",
"self",
",",
"defn",
")",
":",
"val",
"=",
"getattr",
"(",
"defn",
",",
"self",
".",
"attr",
")",
"if",
"val",
"is",
"not",
"None",
"and",
"val",
"in",
"self",
".",
"val_list",
":",
"self",
".",
"messages",
".",
"append",
"("... | Performs the uniqueness check against the value list
maintained in this rule objects | [
"Performs",
"the",
"uniqueness",
"check",
"against",
"the",
"value",
"list",
"maintained",
"in",
"this",
"rule",
"objects"
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/val.py#L622-L633 | train | 42,791 |
NASA-AMMOS/AIT-Core | ait/core/val.py | TypeRule.check | def check(self, defn):
"""Performs isinstance check for the definitions data type.
Assumes the defn has 'type' and 'name' attributes
"""
allowedTypes = dtype.PrimitiveType, dtype.ArrayType
if not isinstance(defn.type, allowedTypes):
self.messages.append(self.msg % str(defn.name))
# self.messages.append("TBD location message")
self.valid = False | python | def check(self, defn):
"""Performs isinstance check for the definitions data type.
Assumes the defn has 'type' and 'name' attributes
"""
allowedTypes = dtype.PrimitiveType, dtype.ArrayType
if not isinstance(defn.type, allowedTypes):
self.messages.append(self.msg % str(defn.name))
# self.messages.append("TBD location message")
self.valid = False | [
"def",
"check",
"(",
"self",
",",
"defn",
")",
":",
"allowedTypes",
"=",
"dtype",
".",
"PrimitiveType",
",",
"dtype",
".",
"ArrayType",
"if",
"not",
"isinstance",
"(",
"defn",
".",
"type",
",",
"allowedTypes",
")",
":",
"self",
".",
"messages",
".",
"a... | Performs isinstance check for the definitions data type.
Assumes the defn has 'type' and 'name' attributes | [
"Performs",
"isinstance",
"check",
"for",
"the",
"definitions",
"data",
"type",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/val.py#L645-L654 | train | 42,792 |
NASA-AMMOS/AIT-Core | ait/core/val.py | TypeSizeRule.check | def check(self, defn, msg=None):
"""Uses the byte range in the object definition to determine
the number of bytes and compares to the size defined in the type.
Assumes the defn has 'type' and 'name' attributes, and a slice() method
"""
if isinstance(defn.type, dtype.PrimitiveType):
# Check the nbytes designated in the YAML match the PDT
nbytes = defn.type.nbytes
defnbytes = defn.slice().stop - defn.slice().start
if nbytes != defnbytes:
self.messages.append(self.msg % defn.name)
self.messages.append("Definition size of (" + str(defnbytes) +
" bytes) does not match size of data" +
" type " +str(defn.type.name) + " (" +
str(nbytes) + " byte(s))")
# TODO self.messages.append("TBD location message")
self.valid = False | python | def check(self, defn, msg=None):
"""Uses the byte range in the object definition to determine
the number of bytes and compares to the size defined in the type.
Assumes the defn has 'type' and 'name' attributes, and a slice() method
"""
if isinstance(defn.type, dtype.PrimitiveType):
# Check the nbytes designated in the YAML match the PDT
nbytes = defn.type.nbytes
defnbytes = defn.slice().stop - defn.slice().start
if nbytes != defnbytes:
self.messages.append(self.msg % defn.name)
self.messages.append("Definition size of (" + str(defnbytes) +
" bytes) does not match size of data" +
" type " +str(defn.type.name) + " (" +
str(nbytes) + " byte(s))")
# TODO self.messages.append("TBD location message")
self.valid = False | [
"def",
"check",
"(",
"self",
",",
"defn",
",",
"msg",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"defn",
".",
"type",
",",
"dtype",
".",
"PrimitiveType",
")",
":",
"# Check the nbytes designated in the YAML match the PDT",
"nbytes",
"=",
"defn",
".",
"t... | Uses the byte range in the object definition to determine
the number of bytes and compares to the size defined in the type.
Assumes the defn has 'type' and 'name' attributes, and a slice() method | [
"Uses",
"the",
"byte",
"range",
"in",
"the",
"object",
"definition",
"to",
"determine",
"the",
"number",
"of",
"bytes",
"and",
"compares",
"to",
"the",
"size",
"defined",
"in",
"the",
"type",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/val.py#L666-L683 | train | 42,793 |
NASA-AMMOS/AIT-Core | ait/core/api.py | GeventDeque._pop | def _pop(self, block=True, timeout=None, left=False):
"""Removes and returns the an item from this GeventDeque.
This is an internal method, called by the public methods
pop() and popleft().
"""
item = None
timer = None
deque = self._deque
empty = IndexError('pop from an empty deque')
if block is False:
if len(self._deque) > 0:
item = deque.popleft() if left else deque.pop()
else:
raise empty
else:
try:
if timeout is not None:
timer = gevent.Timeout(timeout, empty)
timer.start()
while True:
self.notEmpty.wait()
if len(deque) > 0:
item = deque.popleft() if left else deque.pop()
break
finally:
if timer is not None:
timer.cancel()
if len(deque) == 0:
self.notEmpty.clear()
return item | python | def _pop(self, block=True, timeout=None, left=False):
"""Removes and returns the an item from this GeventDeque.
This is an internal method, called by the public methods
pop() and popleft().
"""
item = None
timer = None
deque = self._deque
empty = IndexError('pop from an empty deque')
if block is False:
if len(self._deque) > 0:
item = deque.popleft() if left else deque.pop()
else:
raise empty
else:
try:
if timeout is not None:
timer = gevent.Timeout(timeout, empty)
timer.start()
while True:
self.notEmpty.wait()
if len(deque) > 0:
item = deque.popleft() if left else deque.pop()
break
finally:
if timer is not None:
timer.cancel()
if len(deque) == 0:
self.notEmpty.clear()
return item | [
"def",
"_pop",
"(",
"self",
",",
"block",
"=",
"True",
",",
"timeout",
"=",
"None",
",",
"left",
"=",
"False",
")",
":",
"item",
"=",
"None",
"timer",
"=",
"None",
"deque",
"=",
"self",
".",
"_deque",
"empty",
"=",
"IndexError",
"(",
"'pop from an em... | Removes and returns the an item from this GeventDeque.
This is an internal method, called by the public methods
pop() and popleft(). | [
"Removes",
"and",
"returns",
"the",
"an",
"item",
"from",
"this",
"GeventDeque",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/api.py#L207-L241 | train | 42,794 |
NASA-AMMOS/AIT-Core | ait/core/api.py | GeventDeque.append | def append(self, item):
"""Add item to the right side of the GeventDeque.
This method does not block. Either the GeventDeque grows to
consume available memory, or if this GeventDeque has and is at
maxlen, the leftmost item is removed.
"""
self._deque.append(item)
self.notEmpty.set() | python | def append(self, item):
"""Add item to the right side of the GeventDeque.
This method does not block. Either the GeventDeque grows to
consume available memory, or if this GeventDeque has and is at
maxlen, the leftmost item is removed.
"""
self._deque.append(item)
self.notEmpty.set() | [
"def",
"append",
"(",
"self",
",",
"item",
")",
":",
"self",
".",
"_deque",
".",
"append",
"(",
"item",
")",
"self",
".",
"notEmpty",
".",
"set",
"(",
")"
] | Add item to the right side of the GeventDeque.
This method does not block. Either the GeventDeque grows to
consume available memory, or if this GeventDeque has and is at
maxlen, the leftmost item is removed. | [
"Add",
"item",
"to",
"the",
"right",
"side",
"of",
"the",
"GeventDeque",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/api.py#L268-L276 | train | 42,795 |
NASA-AMMOS/AIT-Core | ait/core/api.py | GeventDeque.appendleft | def appendleft(self, item):
"""Add item to the left side of the GeventDeque.
This method does not block. Either the GeventDeque grows to
consume available memory, or if this GeventDeque has and is at
maxlen, the rightmost item is removed.
"""
self._deque.appendleft(item)
self.notEmpty.set() | python | def appendleft(self, item):
"""Add item to the left side of the GeventDeque.
This method does not block. Either the GeventDeque grows to
consume available memory, or if this GeventDeque has and is at
maxlen, the rightmost item is removed.
"""
self._deque.appendleft(item)
self.notEmpty.set() | [
"def",
"appendleft",
"(",
"self",
",",
"item",
")",
":",
"self",
".",
"_deque",
".",
"appendleft",
"(",
"item",
")",
"self",
".",
"notEmpty",
".",
"set",
"(",
")"
] | Add item to the left side of the GeventDeque.
This method does not block. Either the GeventDeque grows to
consume available memory, or if this GeventDeque has and is at
maxlen, the rightmost item is removed. | [
"Add",
"item",
"to",
"the",
"left",
"side",
"of",
"the",
"GeventDeque",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/api.py#L278-L286 | train | 42,796 |
NASA-AMMOS/AIT-Core | ait/core/api.py | GeventDeque.extend | def extend(self, iterable):
"""Extend the right side of this GeventDeque by appending
elements from the iterable argument.
"""
self._deque.extend(iterable)
if len(self._deque) > 0:
self.notEmpty.set() | python | def extend(self, iterable):
"""Extend the right side of this GeventDeque by appending
elements from the iterable argument.
"""
self._deque.extend(iterable)
if len(self._deque) > 0:
self.notEmpty.set() | [
"def",
"extend",
"(",
"self",
",",
"iterable",
")",
":",
"self",
".",
"_deque",
".",
"extend",
"(",
"iterable",
")",
"if",
"len",
"(",
"self",
".",
"_deque",
")",
">",
"0",
":",
"self",
".",
"notEmpty",
".",
"set",
"(",
")"
] | Extend the right side of this GeventDeque by appending
elements from the iterable argument. | [
"Extend",
"the",
"right",
"side",
"of",
"this",
"GeventDeque",
"by",
"appending",
"elements",
"from",
"the",
"iterable",
"argument",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/api.py#L299-L305 | train | 42,797 |
NASA-AMMOS/AIT-Core | ait/core/api.py | GeventDeque.extendleft | def extendleft(self, iterable):
"""Extend the left side of this GeventDeque by appending
elements from the iterable argument. Note, the series of left
appends results in reversing the order of elements in the
iterable argument.
"""
self._deque.extendleft(iterable)
if len(self._deque) > 0:
self.notEmpty.set() | python | def extendleft(self, iterable):
"""Extend the left side of this GeventDeque by appending
elements from the iterable argument. Note, the series of left
appends results in reversing the order of elements in the
iterable argument.
"""
self._deque.extendleft(iterable)
if len(self._deque) > 0:
self.notEmpty.set() | [
"def",
"extendleft",
"(",
"self",
",",
"iterable",
")",
":",
"self",
".",
"_deque",
".",
"extendleft",
"(",
"iterable",
")",
"if",
"len",
"(",
"self",
".",
"_deque",
")",
">",
"0",
":",
"self",
".",
"notEmpty",
".",
"set",
"(",
")"
] | Extend the left side of this GeventDeque by appending
elements from the iterable argument. Note, the series of left
appends results in reversing the order of elements in the
iterable argument. | [
"Extend",
"the",
"left",
"side",
"of",
"this",
"GeventDeque",
"by",
"appending",
"elements",
"from",
"the",
"iterable",
"argument",
".",
"Note",
"the",
"series",
"of",
"left",
"appends",
"results",
"in",
"reversing",
"the",
"order",
"of",
"elements",
"in",
"... | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/api.py#L307-L315 | train | 42,798 |
NASA-AMMOS/AIT-Core | ait/core/api.py | GeventDeque.popleft | def popleft(self, block=True, timeout=None):
"""Remove and return an item from the right side of the
GeventDeque. If no elements are present, raises an IndexError.
If optional args *block* is True and *timeout* is ``None``
(the default), block if necessary until an item is
available. If *timeout* is a positive number, it blocks at
most *timeout* seconds and raises the :class:`IndexError`
exception if no item was available within that time. Otherwise
(*block* is False), return an item if one is immediately
available, else raise the :class:`IndexError` exception
(*timeout* is ignored in that case).
"""
return self._pop(block, timeout, left=True) | python | def popleft(self, block=True, timeout=None):
"""Remove and return an item from the right side of the
GeventDeque. If no elements are present, raises an IndexError.
If optional args *block* is True and *timeout* is ``None``
(the default), block if necessary until an item is
available. If *timeout* is a positive number, it blocks at
most *timeout* seconds and raises the :class:`IndexError`
exception if no item was available within that time. Otherwise
(*block* is False), return an item if one is immediately
available, else raise the :class:`IndexError` exception
(*timeout* is ignored in that case).
"""
return self._pop(block, timeout, left=True) | [
"def",
"popleft",
"(",
"self",
",",
"block",
"=",
"True",
",",
"timeout",
"=",
"None",
")",
":",
"return",
"self",
".",
"_pop",
"(",
"block",
",",
"timeout",
",",
"left",
"=",
"True",
")"
] | Remove and return an item from the right side of the
GeventDeque. If no elements are present, raises an IndexError.
If optional args *block* is True and *timeout* is ``None``
(the default), block if necessary until an item is
available. If *timeout* is a positive number, it blocks at
most *timeout* seconds and raises the :class:`IndexError`
exception if no item was available within that time. Otherwise
(*block* is False), return an item if one is immediately
available, else raise the :class:`IndexError` exception
(*timeout* is ignored in that case). | [
"Remove",
"and",
"return",
"an",
"item",
"from",
"the",
"right",
"side",
"of",
"the",
"GeventDeque",
".",
"If",
"no",
"elements",
"are",
"present",
"raises",
"an",
"IndexError",
"."
] | 9d85bd9c738e7a6a6fbdff672bea708238b02a3a | https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/api.py#L332-L345 | train | 42,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.