INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Adds the unlock command arguments to the parser.
Args:
self (UnlockCommand): the ``UnlockCommand`` instance
parser (argparse.ArgumentParser): the parser to add the arguments to
Returns:
``None`` | def add_arguments(self, parser):
"""Adds the unlock command arguments to the parser.
Args:
self (UnlockCommand): the ``UnlockCommand`` instance
parser (argparse.ArgumentParser): the parser to add the arguments to
Returns:
``None``
"""
parser.add_ar... |
Unlocks the target device.
Args:
self (UnlockCommand): the ``UnlockCommand`` instance
args (Namespace): the arguments passed on the command-line
Returns:
``None`` | def run(self, args):
"""Unlocks the target device.
Args:
self (UnlockCommand): the ``UnlockCommand`` instance
args (Namespace): the arguments passed on the command-line
Returns:
``None``
"""
jlink = self.create_jlink(args)
mcu = args.name[0... |
Runs the license command.
Args:
self (LicenseCommand): the ``LicenseCommand`` instance
args (Namespace): the arguments passed on the command-line
Returns:
``None`` | def run(self, args):
"""Runs the license command.
Args:
self (LicenseCommand): the ``LicenseCommand`` instance
args (Namespace): the arguments passed on the command-line
Returns:
``None``
"""
jlink = self.create_jlink(args)
if args.list:
... |
Adds the information commands to the parser.
Args:
self (InfoCommand): the ``InfoCommand`` instance
parser (argparse.ArgumentParser): the parser to add the arguments to
Returns:
``None`` | def add_arguments(self, parser):
"""Adds the information commands to the parser.
Args:
self (InfoCommand): the ``InfoCommand`` instance
parser (argparse.ArgumentParser): the parser to add the arguments to
Returns:
``None``
"""
parser.add_argument('... |
Runs the information command.
Args:
self (InfoCommand): the ``InfoCommand`` instance
args (Namespace): the arguments passed on the command-line
Returns:
``None`` | def run(self, args):
"""Runs the information command.
Args:
self (InfoCommand): the ``InfoCommand`` instance
args (Namespace): the arguments passed on the command-line
Returns:
``None``
"""
jlink = self.create_jlink(args)
if args.product:
... |
Adds the arguments for the emulator command.
Args:
self (EmulatorCommand): the ``EmulatorCommand`` instance
parser (argparse.ArgumentParser): parser to add the commands to
Returns:
``None`` | def add_arguments(self, parser):
"""Adds the arguments for the emulator command.
Args:
self (EmulatorCommand): the ``EmulatorCommand`` instance
parser (argparse.ArgumentParser): parser to add the commands to
Returns:
``None``
"""
group = parser.add... |
Runs the emulator command.
Args:
self (EmulatorCommand): the ``EmulatorCommand`` instance
args (Namespace): arguments to parse
Returns:
``None`` | def run(self, args):
"""Runs the emulator command.
Args:
self (EmulatorCommand): the ``EmulatorCommand`` instance
args (Namespace): arguments to parse
Returns:
``None``
"""
jlink = pylink.JLink()
if args.test:
if jlink.test():
... |
Adds the arguments for the firmware command.
Args:
self (FirmwareCommand): the ``FirmwareCommand`` instance
parser (argparse.ArgumentParser): parser to add the commands to
Returns:
``None`` | def add_arguments(self, parser):
"""Adds the arguments for the firmware command.
Args:
self (FirmwareCommand): the ``FirmwareCommand`` instance
parser (argparse.ArgumentParser): parser to add the commands to
Returns:
``None``
"""
group = parser.add... |
Runs the firmware command.
Args:
self (FirmwareCommand): the ``FirmwareCommand`` instance
args (Namespace): arguments to parse
Returns:
``None`` | def run(self, args):
"""Runs the firmware command.
Args:
self (FirmwareCommand): the ``FirmwareCommand`` instance
args (Namespace): arguments to parse
Returns:
``None``
"""
jlink = self.create_jlink(args)
if args.downgrade:
if n... |
Returns the name of the device.
Args:
self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance
Returns:
Device name. | def name(self):
"""Returns the name of the device.
Args:
self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance
Returns:
Device name.
"""
return ctypes.cast(self.sName, ctypes.c_char_p).value.decode() |
Returns the name of the manufacturer of the device.
Args:
self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance
Returns:
Manufacturer name. | def manufacturer(self):
"""Returns the name of the manufacturer of the device.
Args:
self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance
Returns:
Manufacturer name.
"""
buf = ctypes.cast(self.sManu, ctypes.c_char_p).value
return buf.decode() if ... |
Returns whether this is a software breakpoint.
Args:
self (JLinkBreakpointInfo): the ``JLinkBreakpointInfo`` instance
Returns:
``True`` if the breakpoint is a software breakpoint, otherwise
``False``. | def software_breakpoint(self):
"""Returns whether this is a software breakpoint.
Args:
self (JLinkBreakpointInfo): the ``JLinkBreakpointInfo`` instance
Returns:
``True`` if the breakpoint is a software breakpoint, otherwise
``False``.
"""
software_... |
Loads the SEGGER DLL from the windows installation directory.
On Windows, these are found either under:
- ``C:\\Program Files\\SEGGER\\JLink``
- ``C:\\Program Files (x86)\\SEGGER\\JLink``.
Args:
cls (Library): the ``Library`` class
Returns:
The paths to... | def find_library_windows(cls):
"""Loads the SEGGER DLL from the windows installation directory.
On Windows, these are found either under:
- ``C:\\Program Files\\SEGGER\\JLink``
- ``C:\\Program Files (x86)\\SEGGER\\JLink``.
Args:
cls (Library): the ``Library`` clas... |
Loads the SEGGER DLL from the root directory.
On Linux, the SEGGER tools are installed under the ``/opt/SEGGER``
directory with versioned directories having the suffix ``_VERSION``.
Args:
cls (Library): the ``Library`` class
Returns:
The paths to the J-Link library... | def find_library_linux(cls):
"""Loads the SEGGER DLL from the root directory.
On Linux, the SEGGER tools are installed under the ``/opt/SEGGER``
directory with versioned directories having the suffix ``_VERSION``.
Args:
cls (Library): the ``Library`` class
Returns:
... |
Loads the SEGGER DLL from the installed applications.
This method accounts for the all the different ways in which the DLL
may be installed depending on the version of the DLL. Always uses
the first directory found.
SEGGER's DLL is installed in one of three ways dependent on which
... | def find_library_darwin(cls):
"""Loads the SEGGER DLL from the installed applications.
This method accounts for the all the different ways in which the DLL
may be installed depending on the version of the DLL. Always uses
the first directory found.
SEGGER's DLL is installed in... |
Loads the default J-Link SDK DLL.
The default J-Link SDK is determined by first checking if ``ctypes``
can find the DLL, then by searching the platform-specific paths.
Args:
self (Library): the ``Library`` instance
Returns:
``True`` if the DLL was loaded, otherwise... | def load_default(self):
"""Loads the default J-Link SDK DLL.
The default J-Link SDK is determined by first checking if ``ctypes``
can find the DLL, then by searching the platform-specific paths.
Args:
self (Library): the ``Library`` instance
Returns:
``True... |
Loads the specified DLL, if any, otherwise re-loads the current DLL.
If ``path`` is specified, loads the DLL at the given ``path``,
otherwise re-loads the DLL currently specified by this library.
Note:
This creates a temporary DLL file to use for the instance. This is
nece... | def load(self, path=None):
"""Loads the specified DLL, if any, otherwise re-loads the current DLL.
If ``path`` is specified, loads the DLL at the given ``path``,
otherwise re-loads the DLL currently specified by this library.
Note:
This creates a temporary DLL file to use for... |
Unloads the library's DLL if it has been loaded.
This additionally cleans up the temporary DLL file that was created
when the library was loaded.
Args:
self (Library): the ``Library`` instance
Returns:
``True`` if the DLL was unloaded, otherwise ``False``. | def unload(self):
"""Unloads the library's DLL if it has been loaded.
This additionally cleans up the temporary DLL file that was created
when the library was loaded.
Args:
self (Library): the ``Library`` instance
Returns:
``True`` if the DLL was unloaded, ... |
Open a file or ``sys.stdout`` depending on the provided filename.
Args:
filename (str): The path to the file that should be opened. If
``None`` or ``'-'``, ``sys.stdout`` or ``sys.stdin`` is
returned depending on the desired mode. Defaults to ``None``.
mode (str): The mode t... | def _open(filename=None, mode='r'):
"""Open a file or ``sys.stdout`` depending on the provided filename.
Args:
filename (str): The path to the file that should be opened. If
``None`` or ``'-'``, ``sys.stdout`` or ``sys.stdin`` is
returned depending on the desired mode. Defaults ... |
Get PyPI package names from a list of imports.
Args:
pkgs (List[str]): List of import names.
Returns:
List[str]: The corresponding PyPI package names. | def get_pkg_names(pkgs):
"""Get PyPI package names from a list of imports.
Args:
pkgs (List[str]): List of import names.
Returns:
List[str]: The corresponding PyPI package names.
"""
result = set()
with open(join("mapping"), "r") as f:
data = dict(x.strip().split(":") ... |
Loads a font file and the associated charmap.
If ``directory`` is None, the files will be looked for in ``./fonts/``.
Parameters
----------
prefix: str
Prefix string to be used when accessing a given font set
ttf_filename: str
Ttf font filename
charmap_filename: str
Cha... | def load_font(prefix, ttf_filename, charmap_filename, directory=None):
"""
Loads a font file and the associated charmap.
If ``directory`` is None, the files will be looked for in ``./fonts/``.
Parameters
----------
prefix: str
Prefix string to be used when accessing a given font set
... |
Return the character map used for a given font.
Returns
-------
return_value: dict
The dictionary mapping the icon names to the corresponding unicode character. | def charmap(prefixed_name):
"""
Return the character map used for a given font.
Returns
-------
return_value: dict
The dictionary mapping the icon names to the corresponding unicode character.
"""
prefix, name = prefixed_name.split('.')
return _instance().charmap[prefix][name] |
Set global defaults for the options passed to the icon painter. | def set_global_defaults(**kwargs):
"""Set global defaults for the options passed to the icon painter."""
valid_options = [
'active', 'selected', 'disabled', 'on', 'off',
'on_active', 'on_selected', 'on_disabled',
'off_active', 'off_selected', 'off_disabled',
'color', 'color_on',... |
Main paint method. | def paint(self, iconic, painter, rect, mode, state, options):
"""Main paint method."""
for opt in options:
self._paint_icon(iconic, painter, rect, mode, state, opt) |
Paint a single icon. | def _paint_icon(self, iconic, painter, rect, mode, state, options):
"""Paint a single icon."""
painter.save()
color = options['color']
char = options['char']
color_options = {
QIcon.On: {
QIcon.Normal: (options['color_on'], options['on']),
... |
Loads a font file and the associated charmap.
If ``directory`` is None, the files will be looked for in ``./fonts/``.
Parameters
----------
prefix: str
Prefix string to be used when accessing a given font set
ttf_filename: str
Ttf font filename
c... | def load_font(self, prefix, ttf_filename, charmap_filename, directory=None):
"""Loads a font file and the associated charmap.
If ``directory`` is None, the files will be looked for in ``./fonts/``.
Parameters
----------
prefix: str
Prefix string to be used when acce... |
Return a QIcon object corresponding to the provided icon name. | def icon(self, *names, **kwargs):
"""Return a QIcon object corresponding to the provided icon name."""
cache_key = '{}{}'.format(names,kwargs)
if cache_key not in self.icon_cache:
options_list = kwargs.pop('options', [{}] * len(names))
general_options = kwargs
... |
Return a QFont corresponding to the given prefix and size. | def font(self, prefix, size):
"""Return a QFont corresponding to the given prefix and size."""
font = QFont(self.fontname[prefix])
font.setPixelSize(size)
if prefix[-1] == 's': # solid style
font.setStyleName('Solid')
return font |
Return the custom icon corresponding to the given name. | def _custom_icon(self, name, **kwargs):
"""Return the custom icon corresponding to the given name."""
options = dict(_default_options, **kwargs)
if name in self.painters:
painter = self.painters[name]
return self._icon_by_painter(painter, options)
else:
... |
Return the icon corresponding to the given painter. | def _icon_by_painter(self, painter, options):
"""Return the icon corresponding to the given painter."""
engine = CharIconEngine(self, painter, options)
return QIcon(engine) |
Font renaming code originally from:
https://github.com/chrissimpkins/fontname.py/blob/master/fontname.py | def rename_font(font_path, font_name):
"""
Font renaming code originally from:
https://github.com/chrissimpkins/fontname.py/blob/master/fontname.py
"""
tt = ttLib.TTFont(font_path)
namerecord_list = tt["name"].names
variant = ""
# determine font variant for this file path from name reco... |
Validate the command options. | def finalize_options(self):
"""Validate the command options."""
assert bool(self.fa_version), 'FA version is mandatory for this command.'
if self.zip_path:
assert os.path.exists(self.zip_path), (
'Local zipfile does not exist: %s' % self.zip_path) |
Shortcut for printing with the distutils logger. | def __print(self, msg):
"""Shortcut for printing with the distutils logger."""
self.announce(msg, level=distutils.log.INFO) |
Get a file object of the FA zip file. | def __zip_file(self):
"""Get a file object of the FA zip file."""
if self.zip_path:
# If using a local file, just open it:
self.__print('Opening local zipfile: %s' % self.zip_path)
return open(self.zip_path, 'rb')
# Otherwise, download it and make a file obje... |
Get a dict of all files of interest from the FA release zipfile. | def __zipped_files_data(self):
"""Get a dict of all files of interest from the FA release zipfile."""
files = {}
with zipfile.ZipFile(self.__zip_file) as thezip:
for zipinfo in thezip.infolist():
if zipinfo.filename.endswith('metadata/icons.json'):
... |
Run command. | def run(self):
"""Run command."""
files = self.__zipped_files_data
hashes = {}
icons = {}
# Read icons.json (from the webfont zip download)
data = json.loads(files['icons.json'])
# Group icons by style, since not all icons exist for all styles:
for icon,... |
Traverse a path ($PATH by default) to find the protoc compiler | def find_protoc(path=os.environ['PATH']):
'''
Traverse a path ($PATH by default) to find the protoc compiler
'''
protoc_filename = 'protoc'
bin_search_paths = path.split(':') or []
for search_path in bin_search_paths:
bin_path = os.path.join(search_path, protoc_filename)
... |
Produce a Protobuf module from a string description.
Return the module if successfully compiled, otherwise raise a BadProtobuf
exception. | def from_string(proto_str):
'''
Produce a Protobuf module from a string description.
Return the module if successfully compiled, otherwise raise a BadProtobuf
exception.
'''
_, proto_file = tempfile.mkstemp(suffix='.proto')
with open(proto_file, 'w+') as proto_f:
proto_f.... |
Helper to load a Python file at path and return as a module | def _load_module(path):
'Helper to load a Python file at path and return as a module'
module_name = os.path.splitext(os.path.basename(path))[0]
module = None
if sys.version_info.minor < 5:
loader = importlib.machinery.SourceFileLoader(module_name, path)
module = loader.load_mod... |
Helper to compile protobuf files | def _compile_proto(full_path, dest):
'Helper to compile protobuf files'
proto_path = os.path.dirname(full_path)
protoc_args = [find_protoc(),
'--python_out={}'.format(dest),
'--proto_path={}'.format(proto_path),
full_path]
proc = subprocess... |
Take a filename |protoc_file|, compile it via the Protobuf
compiler, and import the module.
Return the module if successfully compiled, otherwise raise either
a ProtocNotFound or BadProtobuf exception. | def from_file(proto_file):
'''
Take a filename |protoc_file|, compile it via the Protobuf
compiler, and import the module.
Return the module if successfully compiled, otherwise raise either
a ProtocNotFound or BadProtobuf exception.
'''
if not proto_file.endswith('.proto'):
... |
Return protobuf class types from an imported generated module. | def types_from_module(pb_module):
'''
Return protobuf class types from an imported generated module.
'''
types = pb_module.DESCRIPTOR.message_types_by_name
return [getattr(pb_module, name) for name in types] |
Commit an arbitrary (picklable) object to the log | def log(self, obj):
'''
Commit an arbitrary (picklable) object to the log
'''
entries = self.get()
entries.append(obj)
# Only log the last |n| entries if set
if self._size > 0:
entries = entries[-self._size:]
self._write_entries(entries) |
Return a member generator by a dot-delimited path | def _resolve_child(self, path):
'Return a member generator by a dot-delimited path'
obj = self
for component in path.split('.'):
ptr = obj
if not isinstance(ptr, Permuter):
raise self.MessageNotFound("Bad element path [wrong type]")
# pylint:... |
Create a dependency between path 'source' and path 'target' via the
callable 'action'.
>>> permuter._generators
[IterValueGenerator(one), IterValueGenerator(two)]
>>> permuter.make_dependent('one', 'two', lambda x: x + 1)
Going forward, 'two' will only contain values that are (... | def make_dependent(self, source, target, action):
'''
Create a dependency between path 'source' and path 'target' via the
callable 'action'.
>>> permuter._generators
[IterValueGenerator(one), IterValueGenerator(two)]
>>> permuter.make_dependent('one', 'two', lambda x: x ... |
Retrieve the most recent value generated | def get(self):
'Retrieve the most recent value generated'
# If you attempt to use a generator comprehension below, it will
# consume the StopIteration exception and just return an empty tuple,
# instead of stopping iteration normally
return tuple([(x.name(), x.get()) for x in sel... |
Helper to grab some integers from fuzzdb | def _fuzzdb_integers(limit=0):
'Helper to grab some integers from fuzzdb'
path = os.path.join(BASE_PATH, 'integer-overflow/integer-overflows.txt')
stream = _open_fuzzdb_file(path)
for line in _limit_helper(stream, limit):
yield int(line.decode('utf-8'), 0) |
Helper to get all the strings from fuzzdb | def _fuzzdb_get_strings(max_len=0):
'Helper to get all the strings from fuzzdb'
ignored = ['integer-overflow']
for subdir in pkg_resources.resource_listdir('protofuzz', BASE_PATH):
if subdir in ignored:
continue
path = '{}/{}'.format(BASE_PATH, subdir)
listing = pkg_re... |
Get integers from fuzzdb database
bitwidth - The bitwidth that has to contain the integer
unsigned - Whether the type is unsigned
limit - Limit to |limit| results | def get_integers(bitwidth, unsigned, limit=0):
'''
Get integers from fuzzdb database
bitwidth - The bitwidth that has to contain the integer
unsigned - Whether the type is unsigned
limit - Limit to |limit| results
'''
if unsigned:
start, stop = 0, ((1 << bitwidth) - 1)
els... |
Return a number of interesting floating point values | def get_floats(bitwidth, limit=0):
'''
Return a number of interesting floating point values
'''
assert bitwidth in (32, 64, 80)
values = [0.0, -1.0, 1.0, -1231231231231.0123, 123123123123123.123]
for val in _limit_helper(values, limit):
yield val |
Helper to create a basic integer value generator | def _int_generator(descriptor, bitwidth, unsigned):
'Helper to create a basic integer value generator'
vals = list(values.get_integers(bitwidth, unsigned))
return gen.IterValueGenerator(descriptor.name, vals) |
Helper to create a string generator | def _string_generator(descriptor, max_length=0, limit=0):
'Helper to create a string generator'
vals = list(values.get_strings(max_length, limit))
return gen.IterValueGenerator(descriptor.name, vals) |
Helper to create bytes values. (Derived from string generator) | def _bytes_generator(descriptor, max_length=0, limit=0):
'Helper to create bytes values. (Derived from string generator)'
strs = values.get_strings(max_length, limit)
vals = [bytes(_, 'utf-8') for _ in strs]
return gen.IterValueGenerator(descriptor.name, vals) |
Helper to create floating point values | def _float_generator(descriptor, bitwidth):
'Helper to create floating point values'
return gen.IterValueGenerator(descriptor.name, values.get_floats(bitwidth)) |
Helper to create protobuf enums | def _enum_generator(descriptor):
'Helper to create protobuf enums'
vals = descriptor.enum_type.values_by_number.keys()
return gen.IterValueGenerator(descriptor.name, vals) |
Helper to map a descriptor to a protofuzz generator | def _prototype_to_generator(descriptor, cls):
'Helper to map a descriptor to a protofuzz generator'
_fd = D.FieldDescriptor
generator = None
ints32 = [_fd.TYPE_INT32, _fd.TYPE_UINT32, _fd.TYPE_FIXED32,
_fd.TYPE_SFIXED32, _fd.TYPE_SINT32]
ints64 = [_fd.TYPE_INT64, _fd.TYPE_UINT64, _fd.... |
Convert a protobuf descriptor to a protofuzz generator for same type | def descriptor_to_generator(cls_descriptor, cls, limit=0):
'Convert a protobuf descriptor to a protofuzz generator for same type'
generators = []
for descriptor in cls_descriptor.fields_by_name.values():
generator = _prototype_to_generator(descriptor, cls)
if limit != 0:
genera... |
Helper to assign an arbitrary value to a protobuf field | def _assign_to_field(obj, name, val):
'Helper to assign an arbitrary value to a protobuf field'
target = getattr(obj, name)
if isinstance(target, containers.RepeatedScalarFieldContainer):
target.append(val)
elif isinstance(target, containers.RepeatedCompositeFieldContainer):
target = ta... |
Helper to convert a descriptor and a set of fields to a Protobuf instance | def _fields_to_object(descriptor, fields):
'Helper to convert a descriptor and a set of fields to a Protobuf instance'
# pylint: disable=protected-access
obj = descriptor._concrete_class()
for name, value in fields:
if isinstance(value, tuple):
subtype = descriptor.fields_by_name[na... |
Convert a protobuf module to a dict of generators.
This is typically used with modules that contain multiple type definitions. | def _module_to_generators(pb_module):
'''
Convert a protobuf module to a dict of generators.
This is typically used with modules that contain multiple type definitions.
'''
if not pb_module:
return None
message_types = pb_module.DESCRIPTOR.message_types_by_name
return {k: ProtobufGe... |
Create a dependency between fields source and target via callable
action.
>>> permuter = protofuzz.from_description_string("""
... message Address {
... required uint32 one = 1;
... required uint32 two = 2;
... }""")['Address']
>>> permuter.add_de... | def add_dependency(self, source, target, action):
'''
Create a dependency between fields source and target via callable
action.
>>> permuter = protofuzz.from_description_string("""
... message Address {
... required uint32 one = 1;
... required uint... |
Print Compare report.
:return: None | def print_report(self):
"""
Print Compare report.
:return: None
"""
report = compare_report_print(
self.sorted, self.scores, self.best_name)
print(report) |
Save Compare report in .comp (flat file format).
:param name: filename
:type name : str
:param address: flag for address return
:type address : bool
:return: saving Status as dict {"Status":bool , "Message":str} | def save_report(
self,
name,
address=True):
"""
Save Compare report in .comp (flat file format).
:param name: filename
:type name : str
:param address: flag for address return
:type address : bool
:return: saving Status as dict... |
Calculate accuracy.
:param TP: true positive
:type TP : int
:param TN: true negative
:type TN : int
:param FP: false positive
:type FP : int
:param FN: false negative
:type FN : int
:return: accuracy as float | def ACC_calc(TP, TN, FP, FN):
"""
Calculate accuracy.
:param TP: true positive
:type TP : int
:param TN: true negative
:type TN : int
:param FP: false positive
:type FP : int
:param FN: false negative
:type FN : int
:return: accuracy as float
"""
try:
result ... |
Calculate F-score.
:param TP: true positive
:type TP : int
:param FP: false positive
:type FP : int
:param FN: false negative
:type FN : int
:param beta : beta coefficient
:type beta : float
:return: F score as float | def F_calc(TP, FP, FN, beta):
"""
Calculate F-score.
:param TP: true positive
:type TP : int
:param FP: false positive
:type FP : int
:param FN: false negative
:type FN : int
:param beta : beta coefficient
:type beta : float
:return: F score as float
"""
try:
... |
Calculate MCC (Matthews correlation coefficient).
:param TP: true positive
:type TP : int
:param TN: true negative
:type TN : int
:param FP: false positive
:type FP : int
:param FN: false negative
:type FN : int
:return: MCC as float | def MCC_calc(TP, TN, FP, FN):
"""
Calculate MCC (Matthews correlation coefficient).
:param TP: true positive
:type TP : int
:param TN: true negative
:type TN : int
:param FP: false positive
:type FP : int
:param FN: false negative
:type FN : int
:return: MCC as float
"""... |
Calculate G-measure & G-mean.
:param item1: PPV or TPR or TNR
:type item1 : float
:param item2: PPV or TPR or TNR
:type item2 : float
:return: G-measure or G-mean as float | def G_calc(item1, item2):
"""
Calculate G-measure & G-mean.
:param item1: PPV or TPR or TNR
:type item1 : float
:param item2: PPV or TPR or TNR
:type item2 : float
:return: G-measure or G-mean as float
"""
try:
result = math.sqrt(item1 * item2)
return result
exce... |
Calculate random accuracy.
:param TOP: test outcome positive
:type TOP : int
:param P: condition positive
:type P : int
:param POP: population
:type POP:int
:return: RACC as float | def RACC_calc(TOP, P, POP):
"""
Calculate random accuracy.
:param TOP: test outcome positive
:type TOP : int
:param P: condition positive
:type P : int
:param POP: population
:type POP:int
:return: RACC as float
"""
try:
result = (TOP * P) / ((POP) ** 2)
ret... |
Calculate RACCU (Random accuracy unbiased).
:param TOP: test outcome positive
:type TOP : int
:param P: condition positive
:type P : int
:param POP: population
:type POP : int
:return: RACCU as float | def RACCU_calc(TOP, P, POP):
"""
Calculate RACCU (Random accuracy unbiased).
:param TOP: test outcome positive
:type TOP : int
:param P: condition positive
:type P : int
:param POP: population
:type POP : int
:return: RACCU as float
"""
try:
result = ((TOP + P) / (2 ... |
Calculate IS (Information score).
:param TP: true positive
:type TP : int
:param FP: false positive
:type FP : int
:param FN: false negative
:type FN : int
:param POP: population
:type POP : int
:return: IS as float | def IS_calc(TP, FP, FN, POP):
"""
Calculate IS (Information score).
:param TP: true positive
:type TP : int
:param FP: false positive
:type FP : int
:param FN: false negative
:type FN : int
:param POP: population
:type POP : int
:return: IS as float
"""
try:
... |
Calculate misclassification probability of classifying.
:param table: input matrix
:type table : dict
:param TOP: test outcome positive
:type TOP : int
:param P: condition positive
:type P : int
:param i: table row index (class name)
:type i : any valid type
:param j: table col inde... | def CEN_misclassification_calc(
table,
TOP,
P,
i,
j,
subject_class,
modified=False):
"""
Calculate misclassification probability of classifying.
:param table: input matrix
:type table : dict
:param TOP: test outcome positive
:type TOP : in... |
Calculate CEN (Confusion Entropy)/ MCEN(Modified Confusion Entropy).
:param classes: classes
:type classes : list
:param table: input matrix
:type table : dict
:param TOP: test outcome positive
:type TOP : int
:param P: condition positive
:type P : int
:param class_name: reviewed cl... | def CEN_calc(classes, table, TOP, P, class_name, modified=False):
"""
Calculate CEN (Confusion Entropy)/ MCEN(Modified Confusion Entropy).
:param classes: classes
:type classes : list
:param table: input matrix
:type table : dict
:param TOP: test outcome positive
:type TOP : int
:pa... |
Calculate dInd (Distance index).
:param TNR: specificity or true negative rate
:type TNR : float
:param TPR: sensitivity, recall, hit rate, or true positive rate
:type TPR : float
:return: dInd as float | def dInd_calc(TNR, TPR):
"""
Calculate dInd (Distance index).
:param TNR: specificity or true negative rate
:type TNR : float
:param TPR: sensitivity, recall, hit rate, or true positive rate
:type TPR : float
:return: dInd as float
"""
try:
result = math.sqrt(((1 - TNR)**2) ... |
Calculate DP (Discriminant power).
:param TNR: specificity or true negative rate
:type TNR : float
:param TPR: sensitivity, recall, hit rate, or true positive rate
:type TPR : float
:return: DP as float | def DP_calc(TPR, TNR):
"""
Calculate DP (Discriminant power).
:param TNR: specificity or true negative rate
:type TNR : float
:param TPR: sensitivity, recall, hit rate, or true positive rate
:type TPR : float
:return: DP as float
"""
try:
X = TPR / (1 - TPR)
Y = TNR ... |
Calculate OP (Optimized precision).
:param ACC: accuracy
:type ACC : float
:param TNR: specificity or true negative rate
:type TNR : float
:param TPR: sensitivity, recall, hit rate, or true positive rate
:type TPR : float
:return: OP as float | def OP_calc(ACC, TPR, TNR):
"""
Calculate OP (Optimized precision).
:param ACC: accuracy
:type ACC : float
:param TNR: specificity or true negative rate
:type TNR : float
:param TPR: sensitivity, recall, hit rate, or true positive rate
:type TPR : float
:return: OP as float
"""
... |
Calculate IBA (Index of balanced accuracy).
:param TNR: specificity or true negative rate
:type TNR : float
:param TPR: sensitivity, recall, hit rate, or true positive rate
:type TPR : float
:param alpha : alpha coefficient
:type alpha : float
:return: IBA as float | def IBA_calc(TPR, TNR, alpha=1):
"""
Calculate IBA (Index of balanced accuracy).
:param TNR: specificity or true negative rate
:type TNR : float
:param TPR: sensitivity, recall, hit rate, or true positive rate
:type TPR : float
:param alpha : alpha coefficient
:type alpha : float
:r... |
Calculate BCD (Bray-Curtis dissimilarity).
:param TOP: test outcome positive
:type TOP : dict
:param P: condition positive
:type P : dict
:param AM: Automatic/Manual
:type AM : int
:return: BCD as float | def BCD_calc(TOP, P, AM):
"""
Calculate BCD (Bray-Curtis dissimilarity).
:param TOP: test outcome positive
:type TOP : dict
:param P: condition positive
:type P : dict
:param AM: Automatic/Manual
:type AM : int
:return: BCD as float
"""
try:
TOP_sum = sum(TOP.values(... |
Return all class statistics.
:param TP: true positive dict for all classes
:type TP : dict
:param TN: true negative dict for all classes
:type TN : dict
:param FP: false positive dict for all classes
:type FP : dict
:param FN: false negative dict for all classes
:type FN : dict
:par... | def class_statistics(TP, TN, FP, FN, classes, table):
"""
Return all class statistics.
:param TP: true positive dict for all classes
:type TP : dict
:param TN: true negative dict for all classes
:type TN : dict
:param FP: false positive dict for all classes
:type FP : dict
:param FN... |
Return HTML report file first lines.
:param name: name of file
:type name : str
:return: html_init as str | def html_init(name):
"""
Return HTML report file first lines.
:param name: name of file
:type name : str
:return: html_init as str
"""
result = ""
result += "<html>\n"
result += "<head>\n"
result += "<title>" + str(name) + "</title>\n"
result += "</head>\n"
result += "<b... |
Return HTML report file dataset type.
:param is_binary: is_binary flag (binary : True , multi-class : False)
:type is_binary: bool
:param is_imbalanced: is_imbalanced flag (imbalance : True , balance : False)
:type is_imbalanced: bool
:return: dataset_type as str | def html_dataset_type(is_binary, is_imbalanced):
"""
Return HTML report file dataset type.
:param is_binary: is_binary flag (binary : True , multi-class : False)
:type is_binary: bool
:param is_imbalanced: is_imbalanced flag (imbalance : True , balance : False)
:type is_imbalanced: bool
:re... |
Check input color format.
:param color: input color
:type color : tuple
:return: color as list | def color_check(color):
"""
Check input color format.
:param color: input color
:type color : tuple
:return: color as list
"""
if isinstance(color, (tuple, list)):
if all(map(lambda x: isinstance(x, int), color)):
if all(map(lambda x: x < 256, color)):
re... |
Return background color of each cell of table.
:param row: row dictionary
:type row : dict
:param item: cell number
:type item : int
:param color : input color
:type color : tuple
:return: background color as list [R,G,B] | def html_table_color(row, item, color=(0, 0, 0)):
"""
Return background color of each cell of table.
:param row: row dictionary
:type row : dict
:param item: cell number
:type item : int
:param color : input color
:type color : tuple
:return: background color as list [R,G,B]
"""... |
Return HTML report file confusion matrix.
:param classes: matrix classes
:type classes: list
:param table: matrix
:type table : dict
:param rgb_color : input color
:type rgb_color : tuple
:param normalize : save normalize matrix flag
:type normalize : bool
:return: html_table as str | def html_table(classes, table, rgb_color, normalize=False):
"""
Return HTML report file confusion matrix.
:param classes: matrix classes
:type classes: list
:param table: matrix
:type table : dict
:param rgb_color : input color
:type rgb_color : tuple
:param normalize : save normali... |
Return HTML report file class_stat.
:param classes: matrix classes
:type classes: list
:param class_stat: class stat
:type class_stat:dict
:param digit: scale (the number of digits to the right of the decimal point in a number.)
:type digit : int
:param class_param : Class parameters list f... | def html_class_stat(
classes,
class_stat,
digit=5,
class_param=None,
recommended_list=()):
"""
Return HTML report file class_stat.
:param classes: matrix classes
:type classes: list
:param class_stat: class stat
:type class_stat:dict
:param digit: sca... |
Return matrix as csv data.
:param classes: classes list
:type classes:list
:param table: table
:type table:dict
:return: | def csv_matrix_print(classes, table):
"""
Return matrix as csv data.
:param classes: classes list
:type classes:list
:param table: table
:type table:dict
:return:
"""
result = ""
classes.sort()
for i in classes:
for j in classes:
result += str(table[i][j]... |
Return printable confusion matrix.
:param classes: classes list
:type classes:list
:param table: table
:type table:dict
:return: printable table as str | def table_print(classes, table):
"""
Return printable confusion matrix.
:param classes: classes list
:type classes:list
:param table: table
:type table:dict
:return: printable table as str
"""
classes_len = len(classes)
table_list = []
for key in classes:
table_list.... |
Return csv file data.
:param classes: classes list
:type classes:list
:param class_stat: statistic result for each class
:type class_stat:dict
:param digit: scale (the number of digits to the right of the decimal point in a number.)
:type digit : int
:param class_param : class parameters li... | def csv_print(classes, class_stat, digit=5, class_param=None):
"""
Return csv file data.
:param classes: classes list
:type classes:list
:param class_stat: statistic result for each class
:type class_stat:dict
:param digit: scale (the number of digits to the right of the decimal point in a ... |
Return printable statistics table.
:param classes: classes list
:type classes:list
:param class_stat: statistic result for each class
:type class_stat:dict
:param overall_stat : overall statistic result
:type overall_stat:dict
:param digit: scale (the number of digits to the right of the de... | def stat_print(
classes,
class_stat,
overall_stat,
digit=5,
overall_param=None,
class_param=None):
"""
Return printable statistics table.
:param classes: classes list
:type classes:list
:param class_stat: statistic result for each class
:type clas... |
Return compare report.
:param sorted_list: sorted list of cm's
:type sorted_list: list
:param scores: scores of cm's
:type scores: dict
:param best_name: best cm name
:type best_name: str
:return: printable result as str | def compare_report_print(sorted_list, scores, best_name):
"""
Return compare report.
:param sorted_list: sorted list of cm's
:type sorted_list: list
:param scores: scores of cm's
:type scores: dict
:param best_name: best cm name
:type best_name: str
:return: printable result as str
... |
Open online document in web browser.
:param param: input parameter
:type param : int or str
:return: None | def online_help(param=None):
"""
Open online document in web browser.
:param param: input parameter
:type param : int or str
:return: None
"""
try:
PARAMS_LINK_KEYS = sorted(PARAMS_LINK.keys())
if param in PARAMS_LINK_KEYS:
webbrowser.open_new_tab(DOCUMENT_ADR + ... |
Round input number and convert to str.
:param input_number: input number
:type input_number : anything
:param digit: scale (the number of digits to the right of the decimal point in a number.)
:type digit : int
:return: round number as str | def rounder(input_number, digit=5):
"""
Round input number and convert to str.
:param input_number: input number
:type input_number : anything
:param digit: scale (the number of digits to the right of the decimal point in a number.)
:type digit : int
:return: round number as str
"""
... |
Filter classes by comparing two lists.
:param classes: matrix classes
:type classes: list
:param class_name: sub set of classes
:type class_name : list
:return: filtered classes as list | def class_filter(classes, class_name):
"""
Filter classes by comparing two lists.
:param classes: matrix classes
:type classes: list
:param class_name: sub set of classes
:type class_name : list
:return: filtered classes as list
"""
result_classes = classes
if isinstance(class_n... |
Check input vector items type.
:param vector: input vector
:type vector : list
:return: bool | def vector_check(vector):
"""
Check input vector items type.
:param vector: input vector
:type vector : list
:return: bool
"""
for i in vector:
if isinstance(i, int) is False:
return False
if i < 0:
return False
return True |
Check input matrix format.
:param table: input matrix
:type table : dict
:return: bool | def matrix_check(table):
"""
Check input matrix format.
:param table: input matrix
:type table : dict
:return: bool
"""
try:
if len(table.keys()) == 0:
return False
for i in table.keys():
if table.keys() != table[i].keys() or vector_check(
... |
Convert different type of items in vectors to str.
:param actual_vector: actual values
:type actual_vector : list
:param predict_vector: predict value
:type predict_vector : list
:return: new actual and predict vector | def vector_filter(actual_vector, predict_vector):
"""
Convert different type of items in vectors to str.
:param actual_vector: actual values
:type actual_vector : list
:param predict_vector: predict value
:type predict_vector : list
:return: new actual and predict vector
"""
temp = ... |
Check different items in matrix classes.
:param vector: input vector
:type vector : list
:return: bool | def class_check(vector):
"""
Check different items in matrix classes.
:param vector: input vector
:type vector : list
:return: bool
"""
for i in vector:
if not isinstance(i, type(vector[0])):
return False
return True |
One-Vs-All mode handler.
:param classes: classes
:type classes : list
:param table: input matrix
:type table : dict
:param TP: true positive dict for all classes
:type TP : dict
:param TN: true negative dict for all classes
:type TN : dict
:param FP: false positive dict for all clas... | def one_vs_all_func(classes, table, TP, TN, FP, FN, class_name):
"""
One-Vs-All mode handler.
:param classes: classes
:type classes : list
:param table: input matrix
:type table : dict
:param TP: true positive dict for all classes
:type TP : dict
:param TN: true negative dict for al... |
Return normalized confusion matrix.
:param classes: classes list
:type classes:list
:param table: table
:type table:dict
:return: normalized table as dict | def normalized_table_calc(classes, table):
"""
Return normalized confusion matrix.
:param classes: classes list
:type classes:list
:param table: table
:type table:dict
:return: normalized table as dict
"""
map_dict = {k: 0 for k in classes}
new_table = {k: map_dict.copy() for k ... |
Transpose table.
:param classes: classes
:type classes : list
:param table: input matrix
:type table : dict
:return: transposed table as dict | def transpose_func(classes, table):
"""
Transpose table.
:param classes: classes
:type classes : list
:param table: input matrix
:type table : dict
:return: transposed table as dict
"""
transposed_table = table
for i, item1 in enumerate(classes):
for j, item2 in enumerat... |
Calculate TP,TN,FP,FN from confusion matrix.
:param table: input matrix
:type table : dict
:param transpose : transpose flag
:type transpose : bool
:return: [classes_list,table,TP,TN,FP,FN] | def matrix_params_from_table(table, transpose=False):
"""
Calculate TP,TN,FP,FN from confusion matrix.
:param table: input matrix
:type table : dict
:param transpose : transpose flag
:type transpose : bool
:return: [classes_list,table,TP,TN,FP,FN]
"""
classes = sorted(table.keys())
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.