body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
3e736577b913b53ec5201a82caf177a30b760629d4d95904f533b258b3f64586
def recursive_glob(rootdir='.', suffix=''): 'Performs recursive glob with given suffix and rootdir \n :param rootdir is the root directory\n :param suffix is the suffix to be searched\n ' return [os.path.join(looproot, filename) for (looproot, _, filenames) in os.walk(rootdir) for filename in filenames if filename.endswith(suffix)]
Performs recursive glob with given suffix and rootdir :param rootdir is the root directory :param suffix is the suffix to be searched
models/utils.py
recursive_glob
usama13o/codeServerEPI
0
python
def recursive_glob(rootdir='.', suffix=): 'Performs recursive glob with given suffix and rootdir \n :param rootdir is the root directory\n :param suffix is the suffix to be searched\n ' return [os.path.join(looproot, filename) for (looproot, _, filenames) in os.walk(rootdir) for filename in filenames if filename.endswith(suffix)]
def recursive_glob(rootdir='.', suffix=): 'Performs recursive glob with given suffix and rootdir \n :param rootdir is the root directory\n :param suffix is the suffix to be searched\n ' return [os.path.join(looproot, filename) for (looproot, _, filenames) in os.walk(rootdir) for filename in filenames if filename.endswith(suffix)]<|docstring|>Performs recursive glob with given suffix and rootdir :param rootdir is the root directory :param suffix is the suffix to be searched<|endoftext|>
185816d69287dc7267f7099b3455f1f4315b125c4f4ed0ffae0417ae3b57c7d1
def poly_lr_scheduler(optimizer, init_lr, iter, lr_decay_iter=1, max_iter=30000, power=0.9): 'Polynomial decay of learning rate\n :param init_lr is base learning rate\n :param iter is a current iteration\n :param lr_decay_iter how frequently decay occurs, default is 1\n :param max_iter is number of maximum iterations\n :param power is a polymomial power\n\n ' if ((iter % lr_decay_iter) or (iter > max_iter)): return optimizer for param_group in optimizer.param_groups: param_group['lr'] = (init_lr * ((1 - (iter / max_iter)) ** power))
Polynomial decay of learning rate :param init_lr is base learning rate :param iter is a current iteration :param lr_decay_iter how frequently decay occurs, default is 1 :param max_iter is number of maximum iterations :param power is a polymomial power
models/utils.py
poly_lr_scheduler
usama13o/codeServerEPI
0
python
def poly_lr_scheduler(optimizer, init_lr, iter, lr_decay_iter=1, max_iter=30000, power=0.9): 'Polynomial decay of learning rate\n :param init_lr is base learning rate\n :param iter is a current iteration\n :param lr_decay_iter how frequently decay occurs, default is 1\n :param max_iter is number of maximum iterations\n :param power is a polymomial power\n\n ' if ((iter % lr_decay_iter) or (iter > max_iter)): return optimizer for param_group in optimizer.param_groups: param_group['lr'] = (init_lr * ((1 - (iter / max_iter)) ** power))
def poly_lr_scheduler(optimizer, init_lr, iter, lr_decay_iter=1, max_iter=30000, power=0.9): 'Polynomial decay of learning rate\n :param init_lr is base learning rate\n :param iter is a current iteration\n :param lr_decay_iter how frequently decay occurs, default is 1\n :param max_iter is number of maximum iterations\n :param power is a polymomial power\n\n ' if ((iter % lr_decay_iter) or (iter > max_iter)): return optimizer for param_group in optimizer.param_groups: param_group['lr'] = (init_lr * ((1 - (iter / max_iter)) ** power))<|docstring|>Polynomial decay of learning rate :param init_lr is base learning rate :param iter is a current iteration :param lr_decay_iter how frequently decay occurs, default is 1 :param max_iter is number of maximum iterations :param power is a polymomial power<|endoftext|>
06772256623a7832b8d01e4607928bfdc742c8b4605e2ba65b8f551a26c76c45
def adjust_learning_rate(optimizer, init_lr, epoch): 'Sets the learning rate to the initial LR decayed by 10 every 30 epochs' lr = (init_lr * (0.1 ** (epoch // 30))) for param_group in optimizer.param_groups: param_group['lr'] = lr
Sets the learning rate to the initial LR decayed by 10 every 30 epochs
models/utils.py
adjust_learning_rate
usama13o/codeServerEPI
0
python
def adjust_learning_rate(optimizer, init_lr, epoch): lr = (init_lr * (0.1 ** (epoch // 30))) for param_group in optimizer.param_groups: param_group['lr'] = lr
def adjust_learning_rate(optimizer, init_lr, epoch): lr = (init_lr * (0.1 ** (epoch // 30))) for param_group in optimizer.param_groups: param_group['lr'] = lr<|docstring|>Sets the learning rate to the initial LR decayed by 10 every 30 epochs<|endoftext|>
10fd54a872e7ed2e92faaaebedf9922c653a1d731e7aa0744b5b1de28e8566d1
def load_state_dict(module, state_dict, strict=False, logger=None): "Load state_dict to a module.\n\n This method is modified from :meth:`torch.nn.Module.load_state_dict`.\n Default value for ``strict`` is set to ``False`` and the message for\n param mismatch will be shown even if strict is False.\n\n Args:\n module (Module): Module that receives the state_dict.\n state_dict (OrderedDict): Weights.\n strict (bool): whether to strictly enforce that the keys\n in :attr:`state_dict` match the keys returned by this module's\n :meth:`~torch.nn.Module.state_dict` function. Default: ``False``.\n logger (:obj:`logging.Logger`, optional): Logger to log the error\n message. If not specified, print function will be used.\n " unexpected_keys = [] all_missing_keys = [] err_msg = [] metadata = getattr(state_dict, '_metadata', None) state_dict = state_dict.copy() if (metadata is not None): state_dict._metadata = metadata def load(module, prefix=''): if is_module_wrapper(module): module = module.module local_metadata = ({} if (metadata is None) else metadata.get(prefix[:(- 1)], {})) module._load_from_state_dict(state_dict, prefix, local_metadata, True, all_missing_keys, unexpected_keys, err_msg) for (name, child) in module._modules.items(): if (child is not None): load(child, ((prefix + name) + '.')) load(module) load = None missing_keys = [key for key in all_missing_keys if ('num_batches_tracked' not in key)] if unexpected_keys: err_msg.append(f'''unexpected key in source state_dict: {', '.join(unexpected_keys)} ''') if missing_keys: err_msg.append(f'''missing keys in source state_dict: {', '.join(missing_keys)} ''') (rank, _) = get_dist_info() if ((len(err_msg) > 0) and (rank == 0)): err_msg.insert(0, 'The model and loaded state dict do not match exactly\n') err_msg = '\n'.join(err_msg) if strict: raise RuntimeError(err_msg) elif (logger is not None): logger.warning(err_msg) else: print(err_msg)
Load state_dict to a module. This method is modified from :meth:`torch.nn.Module.load_state_dict`. Default value for ``strict`` is set to ``False`` and the message for param mismatch will be shown even if strict is False. Args: module (Module): Module that receives the state_dict. state_dict (OrderedDict): Weights. strict (bool): whether to strictly enforce that the keys in :attr:`state_dict` match the keys returned by this module's :meth:`~torch.nn.Module.state_dict` function. Default: ``False``. logger (:obj:`logging.Logger`, optional): Logger to log the error message. If not specified, print function will be used.
models/utils.py
load_state_dict
usama13o/codeServerEPI
0
python
def load_state_dict(module, state_dict, strict=False, logger=None): "Load state_dict to a module.\n\n This method is modified from :meth:`torch.nn.Module.load_state_dict`.\n Default value for ``strict`` is set to ``False`` and the message for\n param mismatch will be shown even if strict is False.\n\n Args:\n module (Module): Module that receives the state_dict.\n state_dict (OrderedDict): Weights.\n strict (bool): whether to strictly enforce that the keys\n in :attr:`state_dict` match the keys returned by this module's\n :meth:`~torch.nn.Module.state_dict` function. Default: ``False``.\n logger (:obj:`logging.Logger`, optional): Logger to log the error\n message. If not specified, print function will be used.\n " unexpected_keys = [] all_missing_keys = [] err_msg = [] metadata = getattr(state_dict, '_metadata', None) state_dict = state_dict.copy() if (metadata is not None): state_dict._metadata = metadata def load(module, prefix=): if is_module_wrapper(module): module = module.module local_metadata = ({} if (metadata is None) else metadata.get(prefix[:(- 1)], {})) module._load_from_state_dict(state_dict, prefix, local_metadata, True, all_missing_keys, unexpected_keys, err_msg) for (name, child) in module._modules.items(): if (child is not None): load(child, ((prefix + name) + '.')) load(module) load = None missing_keys = [key for key in all_missing_keys if ('num_batches_tracked' not in key)] if unexpected_keys: err_msg.append(f'unexpected key in source state_dict: {', '.join(unexpected_keys)} ') if missing_keys: err_msg.append(f'missing keys in source state_dict: {', '.join(missing_keys)} ') (rank, _) = get_dist_info() if ((len(err_msg) > 0) and (rank == 0)): err_msg.insert(0, 'The model and loaded state dict do not match exactly\n') err_msg = '\n'.join(err_msg) if strict: raise RuntimeError(err_msg) elif (logger is not None): logger.warning(err_msg) else: print(err_msg)
def load_state_dict(module, state_dict, strict=False, logger=None): "Load state_dict to a module.\n\n This method is modified from :meth:`torch.nn.Module.load_state_dict`.\n Default value for ``strict`` is set to ``False`` and the message for\n param mismatch will be shown even if strict is False.\n\n Args:\n module (Module): Module that receives the state_dict.\n state_dict (OrderedDict): Weights.\n strict (bool): whether to strictly enforce that the keys\n in :attr:`state_dict` match the keys returned by this module's\n :meth:`~torch.nn.Module.state_dict` function. Default: ``False``.\n logger (:obj:`logging.Logger`, optional): Logger to log the error\n message. If not specified, print function will be used.\n " unexpected_keys = [] all_missing_keys = [] err_msg = [] metadata = getattr(state_dict, '_metadata', None) state_dict = state_dict.copy() if (metadata is not None): state_dict._metadata = metadata def load(module, prefix=): if is_module_wrapper(module): module = module.module local_metadata = ({} if (metadata is None) else metadata.get(prefix[:(- 1)], {})) module._load_from_state_dict(state_dict, prefix, local_metadata, True, all_missing_keys, unexpected_keys, err_msg) for (name, child) in module._modules.items(): if (child is not None): load(child, ((prefix + name) + '.')) load(module) load = None missing_keys = [key for key in all_missing_keys if ('num_batches_tracked' not in key)] if unexpected_keys: err_msg.append(f'unexpected key in source state_dict: {', '.join(unexpected_keys)} ') if missing_keys: err_msg.append(f'missing keys in source state_dict: {', '.join(missing_keys)} ') (rank, _) = get_dist_info() if ((len(err_msg) > 0) and (rank == 0)): err_msg.insert(0, 'The model and loaded state dict do not match exactly\n') err_msg = '\n'.join(err_msg) if strict: raise RuntimeError(err_msg) elif (logger is not None): logger.warning(err_msg) else: print(err_msg)<|docstring|>Load state_dict to a module. This method is modified from :meth:`torch.nn.Module.load_state_dict`. Default value for ``strict`` is set to ``False`` and the message for param mismatch will be shown even if strict is False. Args: module (Module): Module that receives the state_dict. state_dict (OrderedDict): Weights. strict (bool): whether to strictly enforce that the keys in :attr:`state_dict` match the keys returned by this module's :meth:`~torch.nn.Module.state_dict` function. Default: ``False``. logger (:obj:`logging.Logger`, optional): Logger to log the error message. If not specified, print function will be used.<|endoftext|>
43d18cc560813f6de8d8a5b1bcf154c3d01542750b3475f3af83bc145cf2ca4d
def load_url_dist(url, model_dir=None): 'In distributed setting, this function only download checkpoint at local\n rank 0.' (rank, world_size) = get_dist_info() rank = int(os.environ.get('LOCAL_RANK', rank)) if (rank == 0): checkpoint = model_zoo.load_url(url, model_dir=model_dir) if (world_size > 1): torch.distributed.barrier() if (rank > 0): checkpoint = model_zoo.load_url(url, model_dir=model_dir) return checkpoint
In distributed setting, this function only download checkpoint at local rank 0.
models/utils.py
load_url_dist
usama13o/codeServerEPI
0
python
def load_url_dist(url, model_dir=None): 'In distributed setting, this function only download checkpoint at local\n rank 0.' (rank, world_size) = get_dist_info() rank = int(os.environ.get('LOCAL_RANK', rank)) if (rank == 0): checkpoint = model_zoo.load_url(url, model_dir=model_dir) if (world_size > 1): torch.distributed.barrier() if (rank > 0): checkpoint = model_zoo.load_url(url, model_dir=model_dir) return checkpoint
def load_url_dist(url, model_dir=None): 'In distributed setting, this function only download checkpoint at local\n rank 0.' (rank, world_size) = get_dist_info() rank = int(os.environ.get('LOCAL_RANK', rank)) if (rank == 0): checkpoint = model_zoo.load_url(url, model_dir=model_dir) if (world_size > 1): torch.distributed.barrier() if (rank > 0): checkpoint = model_zoo.load_url(url, model_dir=model_dir) return checkpoint<|docstring|>In distributed setting, this function only download checkpoint at local rank 0.<|endoftext|>
99d9951478d7bc01a55be45bd97b0bc6d95136728623573157d27a8c219b934b
def load_pavimodel_dist(model_path, map_location=None): 'In distributed setting, this function only download checkpoint at local\n rank 0.' try: from pavi import modelcloud except ImportError: raise ImportError('Please install pavi to load checkpoint from modelcloud.') (rank, world_size) = get_dist_info() rank = int(os.environ.get('LOCAL_RANK', rank)) if (rank == 0): model = modelcloud.get(model_path) with TemporaryDirectory() as tmp_dir: downloaded_file = osp.join(tmp_dir, model.name) model.download(downloaded_file) checkpoint = torch.load(downloaded_file, map_location=map_location) if (world_size > 1): torch.distributed.barrier() if (rank > 0): model = modelcloud.get(model_path) with TemporaryDirectory() as tmp_dir: downloaded_file = osp.join(tmp_dir, model.name) model.download(downloaded_file) checkpoint = torch.load(downloaded_file, map_location=map_location) return checkpoint
In distributed setting, this function only download checkpoint at local rank 0.
models/utils.py
load_pavimodel_dist
usama13o/codeServerEPI
0
python
def load_pavimodel_dist(model_path, map_location=None): 'In distributed setting, this function only download checkpoint at local\n rank 0.' try: from pavi import modelcloud except ImportError: raise ImportError('Please install pavi to load checkpoint from modelcloud.') (rank, world_size) = get_dist_info() rank = int(os.environ.get('LOCAL_RANK', rank)) if (rank == 0): model = modelcloud.get(model_path) with TemporaryDirectory() as tmp_dir: downloaded_file = osp.join(tmp_dir, model.name) model.download(downloaded_file) checkpoint = torch.load(downloaded_file, map_location=map_location) if (world_size > 1): torch.distributed.barrier() if (rank > 0): model = modelcloud.get(model_path) with TemporaryDirectory() as tmp_dir: downloaded_file = osp.join(tmp_dir, model.name) model.download(downloaded_file) checkpoint = torch.load(downloaded_file, map_location=map_location) return checkpoint
def load_pavimodel_dist(model_path, map_location=None): 'In distributed setting, this function only download checkpoint at local\n rank 0.' try: from pavi import modelcloud except ImportError: raise ImportError('Please install pavi to load checkpoint from modelcloud.') (rank, world_size) = get_dist_info() rank = int(os.environ.get('LOCAL_RANK', rank)) if (rank == 0): model = modelcloud.get(model_path) with TemporaryDirectory() as tmp_dir: downloaded_file = osp.join(tmp_dir, model.name) model.download(downloaded_file) checkpoint = torch.load(downloaded_file, map_location=map_location) if (world_size > 1): torch.distributed.barrier() if (rank > 0): model = modelcloud.get(model_path) with TemporaryDirectory() as tmp_dir: downloaded_file = osp.join(tmp_dir, model.name) model.download(downloaded_file) checkpoint = torch.load(downloaded_file, map_location=map_location) return checkpoint<|docstring|>In distributed setting, this function only download checkpoint at local rank 0.<|endoftext|>
365bc3e3dae4ba1fcfebec2b12b423acae43bc97eac4ec17e4c544be3705ba0d
def load_fileclient_dist(filename, backend, map_location): 'In distributed setting, this function only download checkpoint at local\n rank 0.' (rank, world_size) = get_dist_info() rank = int(os.environ.get('LOCAL_RANK', rank)) allowed_backends = ['ceph'] if (backend not in allowed_backends): raise ValueError(f'Load from Backend {backend} is not supported.') if (rank == 0): fileclient = FileClient(backend=backend) buffer = io.BytesIO(fileclient.get(filename)) checkpoint = torch.load(buffer, map_location=map_location) if (world_size > 1): torch.distributed.barrier() if (rank > 0): fileclient = FileClient(backend=backend) buffer = io.BytesIO(fileclient.get(filename)) checkpoint = torch.load(buffer, map_location=map_location) return checkpoint
In distributed setting, this function only download checkpoint at local rank 0.
models/utils.py
load_fileclient_dist
usama13o/codeServerEPI
0
python
def load_fileclient_dist(filename, backend, map_location): 'In distributed setting, this function only download checkpoint at local\n rank 0.' (rank, world_size) = get_dist_info() rank = int(os.environ.get('LOCAL_RANK', rank)) allowed_backends = ['ceph'] if (backend not in allowed_backends): raise ValueError(f'Load from Backend {backend} is not supported.') if (rank == 0): fileclient = FileClient(backend=backend) buffer = io.BytesIO(fileclient.get(filename)) checkpoint = torch.load(buffer, map_location=map_location) if (world_size > 1): torch.distributed.barrier() if (rank > 0): fileclient = FileClient(backend=backend) buffer = io.BytesIO(fileclient.get(filename)) checkpoint = torch.load(buffer, map_location=map_location) return checkpoint
def load_fileclient_dist(filename, backend, map_location): 'In distributed setting, this function only download checkpoint at local\n rank 0.' (rank, world_size) = get_dist_info() rank = int(os.environ.get('LOCAL_RANK', rank)) allowed_backends = ['ceph'] if (backend not in allowed_backends): raise ValueError(f'Load from Backend {backend} is not supported.') if (rank == 0): fileclient = FileClient(backend=backend) buffer = io.BytesIO(fileclient.get(filename)) checkpoint = torch.load(buffer, map_location=map_location) if (world_size > 1): torch.distributed.barrier() if (rank > 0): fileclient = FileClient(backend=backend) buffer = io.BytesIO(fileclient.get(filename)) checkpoint = torch.load(buffer, map_location=map_location) return checkpoint<|docstring|>In distributed setting, this function only download checkpoint at local rank 0.<|endoftext|>
8dd7876a7a198a8b3fd1f7ec3791a34066e7b06a3d273d1eb6274e2479c46043
def _load_checkpoint(filename, map_location=None): 'Load checkpoint from somewhere (modelzoo, file, url).\n\n Args:\n filename (str): Accept local filepath, URL, ``torchvision://xxx``,\n ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for\n details.\n map_location (str | None): Same as :func:`torch.load`. Default: None.\n\n Returns:\n dict | OrderedDict: The loaded checkpoint. It can be either an\n OrderedDict storing model weights or a dict containing other\n information, which depends on the checkpoint.\n ' if filename.startswith('modelzoo://'): warnings.warn('The URL scheme of "modelzoo://" is deprecated, please use "torchvision://" instead') model_urls = get_torchvision_models() model_name = filename[11:] checkpoint = load_url_dist(model_urls[model_name]) elif filename.startswith('torchvision://'): model_urls = get_torchvision_models() model_name = filename[14:] checkpoint = load_url_dist(model_urls[model_name]) elif filename.startswith('open-mmlab://'): model_urls = get_external_models() model_name = filename[13:] deprecated_urls = get_deprecated_model_names() if (model_name in deprecated_urls): warnings.warn(f'open-mmlab://{model_name} is deprecated in favor of open-mmlab://{deprecated_urls[model_name]}') model_name = deprecated_urls[model_name] model_url = model_urls[model_name] if model_url.startswith(('http://', 'https://')): checkpoint = load_url_dist(model_url) else: filename = osp.join(_get_mmcv_home(), model_url) if (not osp.isfile(filename)): raise IOError(f'{filename} is not a checkpoint file') checkpoint = torch.load(filename, map_location=map_location) elif filename.startswith('mmcls://'): model_urls = get_mmcls_models() model_name = filename[8:] checkpoint = load_url_dist(model_urls[model_name]) checkpoint = _process_mmcls_checkpoint(checkpoint) elif filename.startswith(('http://', 'https://')): checkpoint = load_url_dist(filename) elif filename.startswith('pavi://'): model_path = filename[7:] checkpoint = load_pavimodel_dist(model_path, map_location=map_location) elif filename.startswith('s3://'): checkpoint = load_fileclient_dist(filename, backend='ceph', map_location=map_location) else: if (not osp.isfile(filename)): raise IOError(f'{filename} is not a checkpoint file') checkpoint = torch.load(filename, map_location=map_location) return checkpoint
Load checkpoint from somewhere (modelzoo, file, url). Args: filename (str): Accept local filepath, URL, ``torchvision://xxx``, ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for details. map_location (str | None): Same as :func:`torch.load`. Default: None. Returns: dict | OrderedDict: The loaded checkpoint. It can be either an OrderedDict storing model weights or a dict containing other information, which depends on the checkpoint.
models/utils.py
_load_checkpoint
usama13o/codeServerEPI
0
python
def _load_checkpoint(filename, map_location=None): 'Load checkpoint from somewhere (modelzoo, file, url).\n\n Args:\n filename (str): Accept local filepath, URL, ``torchvision://xxx``,\n ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for\n details.\n map_location (str | None): Same as :func:`torch.load`. Default: None.\n\n Returns:\n dict | OrderedDict: The loaded checkpoint. It can be either an\n OrderedDict storing model weights or a dict containing other\n information, which depends on the checkpoint.\n ' if filename.startswith('modelzoo://'): warnings.warn('The URL scheme of "modelzoo://" is deprecated, please use "torchvision://" instead') model_urls = get_torchvision_models() model_name = filename[11:] checkpoint = load_url_dist(model_urls[model_name]) elif filename.startswith('torchvision://'): model_urls = get_torchvision_models() model_name = filename[14:] checkpoint = load_url_dist(model_urls[model_name]) elif filename.startswith('open-mmlab://'): model_urls = get_external_models() model_name = filename[13:] deprecated_urls = get_deprecated_model_names() if (model_name in deprecated_urls): warnings.warn(f'open-mmlab://{model_name} is deprecated in favor of open-mmlab://{deprecated_urls[model_name]}') model_name = deprecated_urls[model_name] model_url = model_urls[model_name] if model_url.startswith(('http://', 'https://')): checkpoint = load_url_dist(model_url) else: filename = osp.join(_get_mmcv_home(), model_url) if (not osp.isfile(filename)): raise IOError(f'{filename} is not a checkpoint file') checkpoint = torch.load(filename, map_location=map_location) elif filename.startswith('mmcls://'): model_urls = get_mmcls_models() model_name = filename[8:] checkpoint = load_url_dist(model_urls[model_name]) checkpoint = _process_mmcls_checkpoint(checkpoint) elif filename.startswith(('http://', 'https://')): checkpoint = load_url_dist(filename) elif filename.startswith('pavi://'): model_path = filename[7:] checkpoint = load_pavimodel_dist(model_path, map_location=map_location) elif filename.startswith('s3://'): checkpoint = load_fileclient_dist(filename, backend='ceph', map_location=map_location) else: if (not osp.isfile(filename)): raise IOError(f'{filename} is not a checkpoint file') checkpoint = torch.load(filename, map_location=map_location) return checkpoint
def _load_checkpoint(filename, map_location=None): 'Load checkpoint from somewhere (modelzoo, file, url).\n\n Args:\n filename (str): Accept local filepath, URL, ``torchvision://xxx``,\n ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for\n details.\n map_location (str | None): Same as :func:`torch.load`. Default: None.\n\n Returns:\n dict | OrderedDict: The loaded checkpoint. It can be either an\n OrderedDict storing model weights or a dict containing other\n information, which depends on the checkpoint.\n ' if filename.startswith('modelzoo://'): warnings.warn('The URL scheme of "modelzoo://" is deprecated, please use "torchvision://" instead') model_urls = get_torchvision_models() model_name = filename[11:] checkpoint = load_url_dist(model_urls[model_name]) elif filename.startswith('torchvision://'): model_urls = get_torchvision_models() model_name = filename[14:] checkpoint = load_url_dist(model_urls[model_name]) elif filename.startswith('open-mmlab://'): model_urls = get_external_models() model_name = filename[13:] deprecated_urls = get_deprecated_model_names() if (model_name in deprecated_urls): warnings.warn(f'open-mmlab://{model_name} is deprecated in favor of open-mmlab://{deprecated_urls[model_name]}') model_name = deprecated_urls[model_name] model_url = model_urls[model_name] if model_url.startswith(('http://', 'https://')): checkpoint = load_url_dist(model_url) else: filename = osp.join(_get_mmcv_home(), model_url) if (not osp.isfile(filename)): raise IOError(f'{filename} is not a checkpoint file') checkpoint = torch.load(filename, map_location=map_location) elif filename.startswith('mmcls://'): model_urls = get_mmcls_models() model_name = filename[8:] checkpoint = load_url_dist(model_urls[model_name]) checkpoint = _process_mmcls_checkpoint(checkpoint) elif filename.startswith(('http://', 'https://')): checkpoint = load_url_dist(filename) elif filename.startswith('pavi://'): model_path = filename[7:] checkpoint = load_pavimodel_dist(model_path, map_location=map_location) elif filename.startswith('s3://'): checkpoint = load_fileclient_dist(filename, backend='ceph', map_location=map_location) else: if (not osp.isfile(filename)): raise IOError(f'{filename} is not a checkpoint file') checkpoint = torch.load(filename, map_location=map_location) return checkpoint<|docstring|>Load checkpoint from somewhere (modelzoo, file, url). Args: filename (str): Accept local filepath, URL, ``torchvision://xxx``, ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for details. map_location (str | None): Same as :func:`torch.load`. Default: None. Returns: dict | OrderedDict: The loaded checkpoint. It can be either an OrderedDict storing model weights or a dict containing other information, which depends on the checkpoint.<|endoftext|>
06cc6536b78aa0df804311b0189651755a3ac1aa2dc7efa6283c09eab968d447
def load_checkpoint(model, filename, map_location='cpu', strict=False, logger=None): 'Load checkpoint from a file or URI.\n\n Args:\n model (Module): Module to load checkpoint.\n filename (str): Accept local filepath, URL, ``torchvision://xxx``,\n ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for\n details.\n map_location (str): Same as :func:`torch.load`.\n strict (bool): Whether to allow different params for the model and\n checkpoint.\n logger (:mod:`logging.Logger` or None): The logger for error message.\n\n Returns:\n dict or OrderedDict: The loaded checkpoint.\n ' checkpoint = _load_checkpoint(filename, map_location) if (not isinstance(checkpoint, dict)): raise RuntimeError(f'No state_dict found in checkpoint file {filename}') if ('state_dict' in checkpoint): state_dict = checkpoint['state_dict'] elif ('model' in checkpoint): state_dict = checkpoint['model'] else: state_dict = checkpoint if list(state_dict.keys())[0].startswith('module.'): state_dict = {k[7:]: v for (k, v) in state_dict.items()} if sorted(list(state_dict.keys()))[0].startswith('encoder'): state_dict = {k.replace('encoder.', ''): v for (k, v) in state_dict.items() if k.startswith('encoder.')} if list(state_dict.keys())[0].startswith('backbone.'): state_dict = {k[9:]: v for (k, v) in state_dict.items()} if (state_dict.get('absolute_pos_embed') is not None): absolute_pos_embed = state_dict['absolute_pos_embed'] (N1, L, C1) = absolute_pos_embed.size() (N2, C2, H, W) = model.absolute_pos_embed.size() if ((N1 != N2) or (C1 != C2) or (L != (H * W))): logger.warning('Error in loading absolute_pos_embed, pass') else: state_dict['absolute_pos_embed'] = absolute_pos_embed.view(N2, H, W, C2).permute(0, 3, 1, 2) relative_position_bias_table_keys = [k for k in state_dict.keys() if ('relative_position_bias_table' in k)] for table_key in relative_position_bias_table_keys: table_pretrained = state_dict[table_key] table_current = model.state_dict()[table_key] (L1, nH1) = table_pretrained.size() (L2, nH2) = table_current.size() if (nH1 != nH2): logger.warning(f'Error in loading {table_key}, pass') elif (L1 != L2): S1 = int((L1 ** 0.5)) S2 = int((L2 ** 0.5)) table_pretrained_resized = F.interpolate(table_pretrained.permute(1, 0).view(1, nH1, S1, S1), size=(S2, S2), mode='bicubic') state_dict[table_key] = table_pretrained_resized.view(nH2, L2).permute(1, 0) load_state_dict(model, state_dict, strict, logger) return checkpoint
Load checkpoint from a file or URI. Args: model (Module): Module to load checkpoint. filename (str): Accept local filepath, URL, ``torchvision://xxx``, ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for details. map_location (str): Same as :func:`torch.load`. strict (bool): Whether to allow different params for the model and checkpoint. logger (:mod:`logging.Logger` or None): The logger for error message. Returns: dict or OrderedDict: The loaded checkpoint.
models/utils.py
load_checkpoint
usama13o/codeServerEPI
0
python
def load_checkpoint(model, filename, map_location='cpu', strict=False, logger=None): 'Load checkpoint from a file or URI.\n\n Args:\n model (Module): Module to load checkpoint.\n filename (str): Accept local filepath, URL, ``torchvision://xxx``,\n ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for\n details.\n map_location (str): Same as :func:`torch.load`.\n strict (bool): Whether to allow different params for the model and\n checkpoint.\n logger (:mod:`logging.Logger` or None): The logger for error message.\n\n Returns:\n dict or OrderedDict: The loaded checkpoint.\n ' checkpoint = _load_checkpoint(filename, map_location) if (not isinstance(checkpoint, dict)): raise RuntimeError(f'No state_dict found in checkpoint file {filename}') if ('state_dict' in checkpoint): state_dict = checkpoint['state_dict'] elif ('model' in checkpoint): state_dict = checkpoint['model'] else: state_dict = checkpoint if list(state_dict.keys())[0].startswith('module.'): state_dict = {k[7:]: v for (k, v) in state_dict.items()} if sorted(list(state_dict.keys()))[0].startswith('encoder'): state_dict = {k.replace('encoder.', ): v for (k, v) in state_dict.items() if k.startswith('encoder.')} if list(state_dict.keys())[0].startswith('backbone.'): state_dict = {k[9:]: v for (k, v) in state_dict.items()} if (state_dict.get('absolute_pos_embed') is not None): absolute_pos_embed = state_dict['absolute_pos_embed'] (N1, L, C1) = absolute_pos_embed.size() (N2, C2, H, W) = model.absolute_pos_embed.size() if ((N1 != N2) or (C1 != C2) or (L != (H * W))): logger.warning('Error in loading absolute_pos_embed, pass') else: state_dict['absolute_pos_embed'] = absolute_pos_embed.view(N2, H, W, C2).permute(0, 3, 1, 2) relative_position_bias_table_keys = [k for k in state_dict.keys() if ('relative_position_bias_table' in k)] for table_key in relative_position_bias_table_keys: table_pretrained = state_dict[table_key] table_current = model.state_dict()[table_key] (L1, nH1) = table_pretrained.size() (L2, nH2) = table_current.size() if (nH1 != nH2): logger.warning(f'Error in loading {table_key}, pass') elif (L1 != L2): S1 = int((L1 ** 0.5)) S2 = int((L2 ** 0.5)) table_pretrained_resized = F.interpolate(table_pretrained.permute(1, 0).view(1, nH1, S1, S1), size=(S2, S2), mode='bicubic') state_dict[table_key] = table_pretrained_resized.view(nH2, L2).permute(1, 0) load_state_dict(model, state_dict, strict, logger) return checkpoint
def load_checkpoint(model, filename, map_location='cpu', strict=False, logger=None): 'Load checkpoint from a file or URI.\n\n Args:\n model (Module): Module to load checkpoint.\n filename (str): Accept local filepath, URL, ``torchvision://xxx``,\n ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for\n details.\n map_location (str): Same as :func:`torch.load`.\n strict (bool): Whether to allow different params for the model and\n checkpoint.\n logger (:mod:`logging.Logger` or None): The logger for error message.\n\n Returns:\n dict or OrderedDict: The loaded checkpoint.\n ' checkpoint = _load_checkpoint(filename, map_location) if (not isinstance(checkpoint, dict)): raise RuntimeError(f'No state_dict found in checkpoint file {filename}') if ('state_dict' in checkpoint): state_dict = checkpoint['state_dict'] elif ('model' in checkpoint): state_dict = checkpoint['model'] else: state_dict = checkpoint if list(state_dict.keys())[0].startswith('module.'): state_dict = {k[7:]: v for (k, v) in state_dict.items()} if sorted(list(state_dict.keys()))[0].startswith('encoder'): state_dict = {k.replace('encoder.', ): v for (k, v) in state_dict.items() if k.startswith('encoder.')} if list(state_dict.keys())[0].startswith('backbone.'): state_dict = {k[9:]: v for (k, v) in state_dict.items()} if (state_dict.get('absolute_pos_embed') is not None): absolute_pos_embed = state_dict['absolute_pos_embed'] (N1, L, C1) = absolute_pos_embed.size() (N2, C2, H, W) = model.absolute_pos_embed.size() if ((N1 != N2) or (C1 != C2) or (L != (H * W))): logger.warning('Error in loading absolute_pos_embed, pass') else: state_dict['absolute_pos_embed'] = absolute_pos_embed.view(N2, H, W, C2).permute(0, 3, 1, 2) relative_position_bias_table_keys = [k for k in state_dict.keys() if ('relative_position_bias_table' in k)] for table_key in relative_position_bias_table_keys: table_pretrained = state_dict[table_key] table_current = model.state_dict()[table_key] (L1, nH1) = table_pretrained.size() (L2, nH2) = table_current.size() if (nH1 != nH2): logger.warning(f'Error in loading {table_key}, pass') elif (L1 != L2): S1 = int((L1 ** 0.5)) S2 = int((L2 ** 0.5)) table_pretrained_resized = F.interpolate(table_pretrained.permute(1, 0).view(1, nH1, S1, S1), size=(S2, S2), mode='bicubic') state_dict[table_key] = table_pretrained_resized.view(nH2, L2).permute(1, 0) load_state_dict(model, state_dict, strict, logger) return checkpoint<|docstring|>Load checkpoint from a file or URI. Args: model (Module): Module to load checkpoint. filename (str): Accept local filepath, URL, ``torchvision://xxx``, ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for details. map_location (str): Same as :func:`torch.load`. strict (bool): Whether to allow different params for the model and checkpoint. logger (:mod:`logging.Logger` or None): The logger for error message. Returns: dict or OrderedDict: The loaded checkpoint.<|endoftext|>
cfc1e86220859a9d379a4c434282f39c24d88a192e7f7d27d4fa17f741238906
def weights_to_cpu(state_dict): 'Copy a model state_dict to cpu.\n\n Args:\n state_dict (OrderedDict): Model weights on GPU.\n\n Returns:\n OrderedDict: Model weights on GPU.\n ' state_dict_cpu = OrderedDict() for (key, val) in state_dict.items(): state_dict_cpu[key] = val.cpu() return state_dict_cpu
Copy a model state_dict to cpu. Args: state_dict (OrderedDict): Model weights on GPU. Returns: OrderedDict: Model weights on GPU.
models/utils.py
weights_to_cpu
usama13o/codeServerEPI
0
python
def weights_to_cpu(state_dict): 'Copy a model state_dict to cpu.\n\n Args:\n state_dict (OrderedDict): Model weights on GPU.\n\n Returns:\n OrderedDict: Model weights on GPU.\n ' state_dict_cpu = OrderedDict() for (key, val) in state_dict.items(): state_dict_cpu[key] = val.cpu() return state_dict_cpu
def weights_to_cpu(state_dict): 'Copy a model state_dict to cpu.\n\n Args:\n state_dict (OrderedDict): Model weights on GPU.\n\n Returns:\n OrderedDict: Model weights on GPU.\n ' state_dict_cpu = OrderedDict() for (key, val) in state_dict.items(): state_dict_cpu[key] = val.cpu() return state_dict_cpu<|docstring|>Copy a model state_dict to cpu. Args: state_dict (OrderedDict): Model weights on GPU. Returns: OrderedDict: Model weights on GPU.<|endoftext|>
10c4c30e205454983941698550a53fdeb5e491338db4355f93e22913bfb4df65
def _save_to_state_dict(module, destination, prefix, keep_vars): 'Saves module state to `destination` dictionary.\n\n This method is modified from :meth:`torch.nn.Module._save_to_state_dict`.\n\n Args:\n module (nn.Module): The module to generate state_dict.\n destination (dict): A dict where state will be stored.\n prefix (str): The prefix for parameters and buffers used in this\n module.\n ' for (name, param) in module._parameters.items(): if (param is not None): destination[(prefix + name)] = (param if keep_vars else param.detach()) for (name, buf) in module._buffers.items(): if (buf is not None): destination[(prefix + name)] = (buf if keep_vars else buf.detach())
Saves module state to `destination` dictionary. This method is modified from :meth:`torch.nn.Module._save_to_state_dict`. Args: module (nn.Module): The module to generate state_dict. destination (dict): A dict where state will be stored. prefix (str): The prefix for parameters and buffers used in this module.
models/utils.py
_save_to_state_dict
usama13o/codeServerEPI
0
python
def _save_to_state_dict(module, destination, prefix, keep_vars): 'Saves module state to `destination` dictionary.\n\n This method is modified from :meth:`torch.nn.Module._save_to_state_dict`.\n\n Args:\n module (nn.Module): The module to generate state_dict.\n destination (dict): A dict where state will be stored.\n prefix (str): The prefix for parameters and buffers used in this\n module.\n ' for (name, param) in module._parameters.items(): if (param is not None): destination[(prefix + name)] = (param if keep_vars else param.detach()) for (name, buf) in module._buffers.items(): if (buf is not None): destination[(prefix + name)] = (buf if keep_vars else buf.detach())
def _save_to_state_dict(module, destination, prefix, keep_vars): 'Saves module state to `destination` dictionary.\n\n This method is modified from :meth:`torch.nn.Module._save_to_state_dict`.\n\n Args:\n module (nn.Module): The module to generate state_dict.\n destination (dict): A dict where state will be stored.\n prefix (str): The prefix for parameters and buffers used in this\n module.\n ' for (name, param) in module._parameters.items(): if (param is not None): destination[(prefix + name)] = (param if keep_vars else param.detach()) for (name, buf) in module._buffers.items(): if (buf is not None): destination[(prefix + name)] = (buf if keep_vars else buf.detach())<|docstring|>Saves module state to `destination` dictionary. This method is modified from :meth:`torch.nn.Module._save_to_state_dict`. Args: module (nn.Module): The module to generate state_dict. destination (dict): A dict where state will be stored. prefix (str): The prefix for parameters and buffers used in this module.<|endoftext|>
b3904322dde7e35298c2be3cc0cc574400cd9d967ebaeb6c7b7d10aa2ff066ca
def get_state_dict(module, destination=None, prefix='', keep_vars=False): 'Returns a dictionary containing a whole state of the module.\n\n Both parameters and persistent buffers (e.g. running averages) are\n included. Keys are corresponding parameter and buffer names.\n\n This method is modified from :meth:`torch.nn.Module.state_dict` to\n recursively check parallel module in case that the model has a complicated\n structure, e.g., nn.Module(nn.Module(DDP)).\n\n Args:\n module (nn.Module): The module to generate state_dict.\n destination (OrderedDict): Returned dict for the state of the\n module.\n prefix (str): Prefix of the key.\n keep_vars (bool): Whether to keep the variable property of the\n parameters. Default: False.\n\n Returns:\n dict: A dictionary containing a whole state of the module.\n ' if is_module_wrapper(module): module = module.module if (destination is None): destination = OrderedDict() destination._metadata = OrderedDict() destination._metadata[prefix[:(- 1)]] = local_metadata = dict(version=module._version) _save_to_state_dict(module, destination, prefix, keep_vars) for (name, child) in module._modules.items(): if (child is not None): get_state_dict(child, destination, ((prefix + name) + '.'), keep_vars=keep_vars) for hook in module._state_dict_hooks.values(): hook_result = hook(module, destination, prefix, local_metadata) if (hook_result is not None): destination = hook_result return destination
Returns a dictionary containing a whole state of the module. Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. This method is modified from :meth:`torch.nn.Module.state_dict` to recursively check parallel module in case that the model has a complicated structure, e.g., nn.Module(nn.Module(DDP)). Args: module (nn.Module): The module to generate state_dict. destination (OrderedDict): Returned dict for the state of the module. prefix (str): Prefix of the key. keep_vars (bool): Whether to keep the variable property of the parameters. Default: False. Returns: dict: A dictionary containing a whole state of the module.
models/utils.py
get_state_dict
usama13o/codeServerEPI
0
python
def get_state_dict(module, destination=None, prefix=, keep_vars=False): 'Returns a dictionary containing a whole state of the module.\n\n Both parameters and persistent buffers (e.g. running averages) are\n included. Keys are corresponding parameter and buffer names.\n\n This method is modified from :meth:`torch.nn.Module.state_dict` to\n recursively check parallel module in case that the model has a complicated\n structure, e.g., nn.Module(nn.Module(DDP)).\n\n Args:\n module (nn.Module): The module to generate state_dict.\n destination (OrderedDict): Returned dict for the state of the\n module.\n prefix (str): Prefix of the key.\n keep_vars (bool): Whether to keep the variable property of the\n parameters. Default: False.\n\n Returns:\n dict: A dictionary containing a whole state of the module.\n ' if is_module_wrapper(module): module = module.module if (destination is None): destination = OrderedDict() destination._metadata = OrderedDict() destination._metadata[prefix[:(- 1)]] = local_metadata = dict(version=module._version) _save_to_state_dict(module, destination, prefix, keep_vars) for (name, child) in module._modules.items(): if (child is not None): get_state_dict(child, destination, ((prefix + name) + '.'), keep_vars=keep_vars) for hook in module._state_dict_hooks.values(): hook_result = hook(module, destination, prefix, local_metadata) if (hook_result is not None): destination = hook_result return destination
def get_state_dict(module, destination=None, prefix=, keep_vars=False): 'Returns a dictionary containing a whole state of the module.\n\n Both parameters and persistent buffers (e.g. running averages) are\n included. Keys are corresponding parameter and buffer names.\n\n This method is modified from :meth:`torch.nn.Module.state_dict` to\n recursively check parallel module in case that the model has a complicated\n structure, e.g., nn.Module(nn.Module(DDP)).\n\n Args:\n module (nn.Module): The module to generate state_dict.\n destination (OrderedDict): Returned dict for the state of the\n module.\n prefix (str): Prefix of the key.\n keep_vars (bool): Whether to keep the variable property of the\n parameters. Default: False.\n\n Returns:\n dict: A dictionary containing a whole state of the module.\n ' if is_module_wrapper(module): module = module.module if (destination is None): destination = OrderedDict() destination._metadata = OrderedDict() destination._metadata[prefix[:(- 1)]] = local_metadata = dict(version=module._version) _save_to_state_dict(module, destination, prefix, keep_vars) for (name, child) in module._modules.items(): if (child is not None): get_state_dict(child, destination, ((prefix + name) + '.'), keep_vars=keep_vars) for hook in module._state_dict_hooks.values(): hook_result = hook(module, destination, prefix, local_metadata) if (hook_result is not None): destination = hook_result return destination<|docstring|>Returns a dictionary containing a whole state of the module. Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. This method is modified from :meth:`torch.nn.Module.state_dict` to recursively check parallel module in case that the model has a complicated structure, e.g., nn.Module(nn.Module(DDP)). Args: module (nn.Module): The module to generate state_dict. destination (OrderedDict): Returned dict for the state of the module. prefix (str): Prefix of the key. keep_vars (bool): Whether to keep the variable property of the parameters. Default: False. Returns: dict: A dictionary containing a whole state of the module.<|endoftext|>
e1ac9cb9524b9fa647b9aa7e38dd743a642e15c7a3ada9430d11dba355f0226e
def save_checkpoint(model, filename, optimizer=None, meta=None): 'Save checkpoint to file.\n\n The checkpoint will have 3 fields: ``meta``, ``state_dict`` and\n ``optimizer``. By default ``meta`` will contain version and time info.\n\n Args:\n model (Module): Module whose params are to be saved.\n filename (str): Checkpoint filename.\n optimizer (:obj:`Optimizer`, optional): Optimizer to be saved.\n meta (dict, optional): Metadata to be saved in checkpoint.\n ' if (meta is None): meta = {} elif (not isinstance(meta, dict)): raise TypeError(f'meta must be a dict or None, but got {type(meta)}') meta.update(mmcv_version=mmcv.__version__, time=time.asctime()) if is_module_wrapper(model): model = model.module if (hasattr(model, 'CLASSES') and (model.CLASSES is not None)): meta.update(CLASSES=model.CLASSES) checkpoint = {'meta': meta, 'state_dict': weights_to_cpu(get_state_dict(model))} if isinstance(optimizer, Optimizer): checkpoint['optimizer'] = optimizer.state_dict() elif isinstance(optimizer, dict): checkpoint['optimizer'] = {} for (name, optim) in optimizer.items(): checkpoint['optimizer'][name] = optim.state_dict() if filename.startswith('pavi://'): try: from pavi import modelcloud from pavi.exception import NodeNotFoundError except ImportError: raise ImportError('Please install pavi to load checkpoint from modelcloud.') model_path = filename[7:] root = modelcloud.Folder() (model_dir, model_name) = osp.split(model_path) try: model = modelcloud.get(model_dir) except NodeNotFoundError: model = root.create_training_model(model_dir) with TemporaryDirectory() as tmp_dir: checkpoint_file = osp.join(tmp_dir, model_name) with open(checkpoint_file, 'wb') as f: torch.save(checkpoint, f) f.flush() model.create_file(checkpoint_file, name=model_name) else: mmcv.mkdir_or_exist(osp.dirname(filename)) with open(filename, 'wb') as f: torch.save(checkpoint, f) f.flush()
Save checkpoint to file. The checkpoint will have 3 fields: ``meta``, ``state_dict`` and ``optimizer``. By default ``meta`` will contain version and time info. Args: model (Module): Module whose params are to be saved. filename (str): Checkpoint filename. optimizer (:obj:`Optimizer`, optional): Optimizer to be saved. meta (dict, optional): Metadata to be saved in checkpoint.
models/utils.py
save_checkpoint
usama13o/codeServerEPI
0
python
def save_checkpoint(model, filename, optimizer=None, meta=None): 'Save checkpoint to file.\n\n The checkpoint will have 3 fields: ``meta``, ``state_dict`` and\n ``optimizer``. By default ``meta`` will contain version and time info.\n\n Args:\n model (Module): Module whose params are to be saved.\n filename (str): Checkpoint filename.\n optimizer (:obj:`Optimizer`, optional): Optimizer to be saved.\n meta (dict, optional): Metadata to be saved in checkpoint.\n ' if (meta is None): meta = {} elif (not isinstance(meta, dict)): raise TypeError(f'meta must be a dict or None, but got {type(meta)}') meta.update(mmcv_version=mmcv.__version__, time=time.asctime()) if is_module_wrapper(model): model = model.module if (hasattr(model, 'CLASSES') and (model.CLASSES is not None)): meta.update(CLASSES=model.CLASSES) checkpoint = {'meta': meta, 'state_dict': weights_to_cpu(get_state_dict(model))} if isinstance(optimizer, Optimizer): checkpoint['optimizer'] = optimizer.state_dict() elif isinstance(optimizer, dict): checkpoint['optimizer'] = {} for (name, optim) in optimizer.items(): checkpoint['optimizer'][name] = optim.state_dict() if filename.startswith('pavi://'): try: from pavi import modelcloud from pavi.exception import NodeNotFoundError except ImportError: raise ImportError('Please install pavi to load checkpoint from modelcloud.') model_path = filename[7:] root = modelcloud.Folder() (model_dir, model_name) = osp.split(model_path) try: model = modelcloud.get(model_dir) except NodeNotFoundError: model = root.create_training_model(model_dir) with TemporaryDirectory() as tmp_dir: checkpoint_file = osp.join(tmp_dir, model_name) with open(checkpoint_file, 'wb') as f: torch.save(checkpoint, f) f.flush() model.create_file(checkpoint_file, name=model_name) else: mmcv.mkdir_or_exist(osp.dirname(filename)) with open(filename, 'wb') as f: torch.save(checkpoint, f) f.flush()
def save_checkpoint(model, filename, optimizer=None, meta=None): 'Save checkpoint to file.\n\n The checkpoint will have 3 fields: ``meta``, ``state_dict`` and\n ``optimizer``. By default ``meta`` will contain version and time info.\n\n Args:\n model (Module): Module whose params are to be saved.\n filename (str): Checkpoint filename.\n optimizer (:obj:`Optimizer`, optional): Optimizer to be saved.\n meta (dict, optional): Metadata to be saved in checkpoint.\n ' if (meta is None): meta = {} elif (not isinstance(meta, dict)): raise TypeError(f'meta must be a dict or None, but got {type(meta)}') meta.update(mmcv_version=mmcv.__version__, time=time.asctime()) if is_module_wrapper(model): model = model.module if (hasattr(model, 'CLASSES') and (model.CLASSES is not None)): meta.update(CLASSES=model.CLASSES) checkpoint = {'meta': meta, 'state_dict': weights_to_cpu(get_state_dict(model))} if isinstance(optimizer, Optimizer): checkpoint['optimizer'] = optimizer.state_dict() elif isinstance(optimizer, dict): checkpoint['optimizer'] = {} for (name, optim) in optimizer.items(): checkpoint['optimizer'][name] = optim.state_dict() if filename.startswith('pavi://'): try: from pavi import modelcloud from pavi.exception import NodeNotFoundError except ImportError: raise ImportError('Please install pavi to load checkpoint from modelcloud.') model_path = filename[7:] root = modelcloud.Folder() (model_dir, model_name) = osp.split(model_path) try: model = modelcloud.get(model_dir) except NodeNotFoundError: model = root.create_training_model(model_dir) with TemporaryDirectory() as tmp_dir: checkpoint_file = osp.join(tmp_dir, model_name) with open(checkpoint_file, 'wb') as f: torch.save(checkpoint, f) f.flush() model.create_file(checkpoint_file, name=model_name) else: mmcv.mkdir_or_exist(osp.dirname(filename)) with open(filename, 'wb') as f: torch.save(checkpoint, f) f.flush()<|docstring|>Save checkpoint to file. The checkpoint will have 3 fields: ``meta``, ``state_dict`` and ``optimizer``. By default ``meta`` will contain version and time info. Args: model (Module): Module whose params are to be saved. filename (str): Checkpoint filename. optimizer (:obj:`Optimizer`, optional): Optimizer to be saved. meta (dict, optional): Metadata to be saved in checkpoint.<|endoftext|>
3df2cf27cbc8b1c92068b4aa9fbe60e56061808003e456bb11ec294ddbcdc945
def setUp(self): '\n Perturb the normal import behavior subtly by installing an import\n hook. No custom behavior is provided, but this adds some extra\n frames to the call stack, which L{namedAny} must be able to account\n for.\n ' self.importer = ModuleImporter() self.importer.install()
Perturb the normal import behavior subtly by installing an import hook. No custom behavior is provided, but this adds some extra frames to the call stack, which L{namedAny} must be able to account for.
libraries/twisted/test/test_reflect.py
setUp
Heufneutje/DideRobot
0
python
def setUp(self): '\n Perturb the normal import behavior subtly by installing an import\n hook. No custom behavior is provided, but this adds some extra\n frames to the call stack, which L{namedAny} must be able to account\n for.\n ' self.importer = ModuleImporter() self.importer.install()
def setUp(self): '\n Perturb the normal import behavior subtly by installing an import\n hook. No custom behavior is provided, but this adds some extra\n frames to the call stack, which L{namedAny} must be able to account\n for.\n ' self.importer = ModuleImporter() self.importer.install()<|docstring|>Perturb the normal import behavior subtly by installing an import hook. No custom behavior is provided, but this adds some extra frames to the call stack, which L{namedAny} must be able to account for.<|endoftext|>
66fb96ee2fef46d43a56ab648b82f2b27755ef1642981b70c9567e60aeddcba8
def tearDown(self): '\n Uninstall the custom import hook.\n ' self.importer.uninstall()
Uninstall the custom import hook.
libraries/twisted/test/test_reflect.py
tearDown
Heufneutje/DideRobot
0
python
def tearDown(self): '\n \n ' self.importer.uninstall()
def tearDown(self): '\n \n ' self.importer.uninstall()<|docstring|>Uninstall the custom import hook.<|endoftext|>
9e0f8110eb8f2aa9bf074bb892c1fd5a23f0180a78a5e08e37762a85bcdafed8
def test_dictionary(self): '\n Test references search through a dictionnary, as a key or as a value.\n ' o = object() d1 = {None: o} d2 = {o: None} self.assertIn('[None]', reflect.objgrep(d1, o, reflect.isSame)) self.assertIn('{None}', reflect.objgrep(d2, o, reflect.isSame))
Test references search through a dictionnary, as a key or as a value.
libraries/twisted/test/test_reflect.py
test_dictionary
Heufneutje/DideRobot
0
python
def test_dictionary(self): '\n \n ' o = object() d1 = {None: o} d2 = {o: None} self.assertIn('[None]', reflect.objgrep(d1, o, reflect.isSame)) self.assertIn('{None}', reflect.objgrep(d2, o, reflect.isSame))
def test_dictionary(self): '\n \n ' o = object() d1 = {None: o} d2 = {o: None} self.assertIn('[None]', reflect.objgrep(d1, o, reflect.isSame)) self.assertIn('{None}', reflect.objgrep(d2, o, reflect.isSame))<|docstring|>Test references search through a dictionnary, as a key or as a value.<|endoftext|>
bc0549368d97a180619ede69382761a8884b85aba54cc6233a7a8b08fba624e8
def test_list(self): '\n Test references search through a list.\n ' o = object() L = [None, o] self.assertIn('[1]', reflect.objgrep(L, o, reflect.isSame))
Test references search through a list.
libraries/twisted/test/test_reflect.py
test_list
Heufneutje/DideRobot
0
python
def test_list(self): '\n \n ' o = object() L = [None, o] self.assertIn('[1]', reflect.objgrep(L, o, reflect.isSame))
def test_list(self): '\n \n ' o = object() L = [None, o] self.assertIn('[1]', reflect.objgrep(L, o, reflect.isSame))<|docstring|>Test references search through a list.<|endoftext|>
d40bb2574f4ba0d9e644dbc8fbe10676bfd416622b1400e73c609bb0fc790aa8
def test_tuple(self): '\n Test references search through a tuple.\n ' o = object() T = (o, None) self.assertIn('[0]', reflect.objgrep(T, o, reflect.isSame))
Test references search through a tuple.
libraries/twisted/test/test_reflect.py
test_tuple
Heufneutje/DideRobot
0
python
def test_tuple(self): '\n \n ' o = object() T = (o, None) self.assertIn('[0]', reflect.objgrep(T, o, reflect.isSame))
def test_tuple(self): '\n \n ' o = object() T = (o, None) self.assertIn('[0]', reflect.objgrep(T, o, reflect.isSame))<|docstring|>Test references search through a tuple.<|endoftext|>
1bb36a7a9dd81316ee8caab88cefe1f62bad31773acea34249eab4ddb1a9e1a1
def test_instance(self): '\n Test references search through an object attribute.\n ' class Dummy(): pass o = object() d = Dummy() d.o = o self.assertIn('.o', reflect.objgrep(d, o, reflect.isSame))
Test references search through an object attribute.
libraries/twisted/test/test_reflect.py
test_instance
Heufneutje/DideRobot
0
python
def test_instance(self): '\n \n ' class Dummy(): pass o = object() d = Dummy() d.o = o self.assertIn('.o', reflect.objgrep(d, o, reflect.isSame))
def test_instance(self): '\n \n ' class Dummy(): pass o = object() d = Dummy() d.o = o self.assertIn('.o', reflect.objgrep(d, o, reflect.isSame))<|docstring|>Test references search through an object attribute.<|endoftext|>
f1b59ee40d2379927ddd63715c78b635b237e19b7ed8a063d5a9820c3fe8f240
def test_weakref(self): '\n Test references search through a weakref object.\n ' class Dummy(): pass o = Dummy() w1 = weakref.ref(o) self.assertIn('()', reflect.objgrep(w1, o, reflect.isSame))
Test references search through a weakref object.
libraries/twisted/test/test_reflect.py
test_weakref
Heufneutje/DideRobot
0
python
def test_weakref(self): '\n \n ' class Dummy(): pass o = Dummy() w1 = weakref.ref(o) self.assertIn('()', reflect.objgrep(w1, o, reflect.isSame))
def test_weakref(self): '\n \n ' class Dummy(): pass o = Dummy() w1 = weakref.ref(o) self.assertIn('()', reflect.objgrep(w1, o, reflect.isSame))<|docstring|>Test references search through a weakref object.<|endoftext|>
53f555fc1d13445813ebe3e0fa289a201d85ebbd370f6e2ad51a90c1c6be82fd
def test_boundMethod(self): '\n Test references search through method special attributes.\n ' class Dummy(): def dummy(self): pass o = Dummy() m = o.dummy self.assertIn('.im_self', reflect.objgrep(m, m.im_self, reflect.isSame)) self.assertIn('.im_class', reflect.objgrep(m, m.im_class, reflect.isSame)) self.assertIn('.im_func', reflect.objgrep(m, m.im_func, reflect.isSame))
Test references search through method special attributes.
libraries/twisted/test/test_reflect.py
test_boundMethod
Heufneutje/DideRobot
0
python
def test_boundMethod(self): '\n \n ' class Dummy(): def dummy(self): pass o = Dummy() m = o.dummy self.assertIn('.im_self', reflect.objgrep(m, m.im_self, reflect.isSame)) self.assertIn('.im_class', reflect.objgrep(m, m.im_class, reflect.isSame)) self.assertIn('.im_func', reflect.objgrep(m, m.im_func, reflect.isSame))
def test_boundMethod(self): '\n \n ' class Dummy(): def dummy(self): pass o = Dummy() m = o.dummy self.assertIn('.im_self', reflect.objgrep(m, m.im_self, reflect.isSame)) self.assertIn('.im_class', reflect.objgrep(m, m.im_class, reflect.isSame)) self.assertIn('.im_func', reflect.objgrep(m, m.im_func, reflect.isSame))<|docstring|>Test references search through method special attributes.<|endoftext|>
826a872163a6884cbc353ea49c7a6909dd2d6e568daaeaba4936d3823ea872bf
def test_everything(self): '\n Test references search using complex set of objects.\n ' class Dummy(): def method(self): pass o = Dummy() D1 = {(): 'baz', None: 'Quux', o: 'Foosh'} L = [None, (), D1, 3] T = (L, {}, Dummy()) D2 = {0: 'foo', 1: 'bar', 2: T} i = Dummy() i.attr = D2 m = i.method w = weakref.ref(m) self.assertIn("().im_self.attr[2][0][2]{'Foosh'}", reflect.objgrep(w, o, reflect.isSame))
Test references search using complex set of objects.
libraries/twisted/test/test_reflect.py
test_everything
Heufneutje/DideRobot
0
python
def test_everything(self): '\n \n ' class Dummy(): def method(self): pass o = Dummy() D1 = {(): 'baz', None: 'Quux', o: 'Foosh'} L = [None, (), D1, 3] T = (L, {}, Dummy()) D2 = {0: 'foo', 1: 'bar', 2: T} i = Dummy() i.attr = D2 m = i.method w = weakref.ref(m) self.assertIn("().im_self.attr[2][0][2]{'Foosh'}", reflect.objgrep(w, o, reflect.isSame))
def test_everything(self): '\n \n ' class Dummy(): def method(self): pass o = Dummy() D1 = {(): 'baz', None: 'Quux', o: 'Foosh'} L = [None, (), D1, 3] T = (L, {}, Dummy()) D2 = {0: 'foo', 1: 'bar', 2: T} i = Dummy() i.attr = D2 m = i.method w = weakref.ref(m) self.assertIn("().im_self.attr[2][0][2]{'Foosh'}", reflect.objgrep(w, o, reflect.isSame))<|docstring|>Test references search using complex set of objects.<|endoftext|>
7a9a0d59e98a2c60a113a6018fb736948945a2a9e931754f5be67031306461ac
def test_depthLimit(self): '\n Test the depth of references search.\n ' a = [] b = [a] c = [a, b] d = [a, c] self.assertEqual(['[0]'], reflect.objgrep(d, a, reflect.isSame, maxDepth=1)) self.assertEqual(['[0]', '[1][0]'], reflect.objgrep(d, a, reflect.isSame, maxDepth=2)) self.assertEqual(['[0]', '[1][0]', '[1][1][0]'], reflect.objgrep(d, a, reflect.isSame, maxDepth=3))
Test the depth of references search.
libraries/twisted/test/test_reflect.py
test_depthLimit
Heufneutje/DideRobot
0
python
def test_depthLimit(self): '\n \n ' a = [] b = [a] c = [a, b] d = [a, c] self.assertEqual(['[0]'], reflect.objgrep(d, a, reflect.isSame, maxDepth=1)) self.assertEqual(['[0]', '[1][0]'], reflect.objgrep(d, a, reflect.isSame, maxDepth=2)) self.assertEqual(['[0]', '[1][0]', '[1][1][0]'], reflect.objgrep(d, a, reflect.isSame, maxDepth=3))
def test_depthLimit(self): '\n \n ' a = [] b = [a] c = [a, b] d = [a, c] self.assertEqual(['[0]'], reflect.objgrep(d, a, reflect.isSame, maxDepth=1)) self.assertEqual(['[0]', '[1][0]'], reflect.objgrep(d, a, reflect.isSame, maxDepth=2)) self.assertEqual(['[0]', '[1][0]', '[1][1][0]'], reflect.objgrep(d, a, reflect.isSame, maxDepth=3))<|docstring|>Test the depth of references search.<|endoftext|>
66b5acacec71ebd346d3f7a2f4a8ac6219c6abcccc9de3695ee7594940764ba8
def test_deque(self): '\n Test references search through a deque object.\n ' o = object() D = deque() D.append(None) D.append(o) self.assertIn('[1]', reflect.objgrep(D, o, reflect.isSame))
Test references search through a deque object.
libraries/twisted/test/test_reflect.py
test_deque
Heufneutje/DideRobot
0
python
def test_deque(self): '\n \n ' o = object() D = deque() D.append(None) D.append(o) self.assertIn('[1]', reflect.objgrep(D, o, reflect.isSame))
def test_deque(self): '\n \n ' o = object() D = deque() D.append(None) D.append(o) self.assertIn('[1]', reflect.objgrep(D, o, reflect.isSame))<|docstring|>Test references search through a deque object.<|endoftext|>
653f53719c7d477ee2aeb3100c449e8581504e1733376eece08c2c9d817a80b7
def test_allYourBase(self): '\n Test deprecation of L{reflect.allYourBase}. See #5481 for removal.\n ' self.callDeprecated((Version('Twisted', 11, 0, 0), 'inspect.getmro'), reflect.allYourBase, DeprecationTestCase)
Test deprecation of L{reflect.allYourBase}. See #5481 for removal.
libraries/twisted/test/test_reflect.py
test_allYourBase
Heufneutje/DideRobot
0
python
def test_allYourBase(self): '\n \n ' self.callDeprecated((Version('Twisted', 11, 0, 0), 'inspect.getmro'), reflect.allYourBase, DeprecationTestCase)
def test_allYourBase(self): '\n \n ' self.callDeprecated((Version('Twisted', 11, 0, 0), 'inspect.getmro'), reflect.allYourBase, DeprecationTestCase)<|docstring|>Test deprecation of L{reflect.allYourBase}. See #5481 for removal.<|endoftext|>
ccc930f732b43c062cf4de9ba6e1d746003753a2655aa33dd81139bfa2077c01
def test_accumulateBases(self): '\n Test deprecation of L{reflect.accumulateBases}. See #5481 for removal.\n ' l = [] self.callDeprecated((Version('Twisted', 11, 0, 0), 'inspect.getmro'), reflect.accumulateBases, DeprecationTestCase, l, None)
Test deprecation of L{reflect.accumulateBases}. See #5481 for removal.
libraries/twisted/test/test_reflect.py
test_accumulateBases
Heufneutje/DideRobot
0
python
def test_accumulateBases(self): '\n \n ' l = [] self.callDeprecated((Version('Twisted', 11, 0, 0), 'inspect.getmro'), reflect.accumulateBases, DeprecationTestCase, l, None)
def test_accumulateBases(self): '\n \n ' l = [] self.callDeprecated((Version('Twisted', 11, 0, 0), 'inspect.getmro'), reflect.accumulateBases, DeprecationTestCase, l, None)<|docstring|>Test deprecation of L{reflect.accumulateBases}. See #5481 for removal.<|endoftext|>
3117fa5fc7fbc3d9b605fc742796864d6f552bd9ddca8ca99b04c373e98b9ee8
def _hash_artifact(filepath, hash_algorithms=None, normalize_line_endings=False): "Internal helper that takes a filename and hashes the respective file's\n contents using the passed hash_algorithms and returns a hashdict conformant\n with securesystemslib.formats.HASHDICT_SCHEMA. " if (not hash_algorithms): hash_algorithms = ['sha256'] securesystemslib.formats.HASHALGORITHMS_SCHEMA.check_match(hash_algorithms) hash_dict = {} for algorithm in hash_algorithms: digest_object = securesystemslib.hash.digest_filename(filepath, algorithm, normalize_line_endings=normalize_line_endings) hash_dict.update({algorithm: digest_object.hexdigest()}) securesystemslib.formats.HASHDICT_SCHEMA.check_match(hash_dict) return hash_dict
Internal helper that takes a filename and hashes the respective file's contents using the passed hash_algorithms and returns a hashdict conformant with securesystemslib.formats.HASHDICT_SCHEMA.
in_toto/runlib.py
_hash_artifact
reeeeeeem/in-toto
507
python
def _hash_artifact(filepath, hash_algorithms=None, normalize_line_endings=False): "Internal helper that takes a filename and hashes the respective file's\n contents using the passed hash_algorithms and returns a hashdict conformant\n with securesystemslib.formats.HASHDICT_SCHEMA. " if (not hash_algorithms): hash_algorithms = ['sha256'] securesystemslib.formats.HASHALGORITHMS_SCHEMA.check_match(hash_algorithms) hash_dict = {} for algorithm in hash_algorithms: digest_object = securesystemslib.hash.digest_filename(filepath, algorithm, normalize_line_endings=normalize_line_endings) hash_dict.update({algorithm: digest_object.hexdigest()}) securesystemslib.formats.HASHDICT_SCHEMA.check_match(hash_dict) return hash_dict
def _hash_artifact(filepath, hash_algorithms=None, normalize_line_endings=False): "Internal helper that takes a filename and hashes the respective file's\n contents using the passed hash_algorithms and returns a hashdict conformant\n with securesystemslib.formats.HASHDICT_SCHEMA. " if (not hash_algorithms): hash_algorithms = ['sha256'] securesystemslib.formats.HASHALGORITHMS_SCHEMA.check_match(hash_algorithms) hash_dict = {} for algorithm in hash_algorithms: digest_object = securesystemslib.hash.digest_filename(filepath, algorithm, normalize_line_endings=normalize_line_endings) hash_dict.update({algorithm: digest_object.hexdigest()}) securesystemslib.formats.HASHDICT_SCHEMA.check_match(hash_dict) return hash_dict<|docstring|>Internal helper that takes a filename and hashes the respective file's contents using the passed hash_algorithms and returns a hashdict conformant with securesystemslib.formats.HASHDICT_SCHEMA.<|endoftext|>
c290a79c62ac0889d44bbe8cbffe0c2c75e46d8c9ab37a486aa37cf0ab6beafe
def _apply_exclude_patterns(names, exclude_filter): 'Exclude matched patterns from passed names.' included = set(names) if hasattr(exclude_filter, '__iter__'): exclude_filter = PathSpec.from_lines('gitwildmatch', exclude_filter) for excluded in exclude_filter.match_files(names): included.discard(excluded) return sorted(included)
Exclude matched patterns from passed names.
in_toto/runlib.py
_apply_exclude_patterns
reeeeeeem/in-toto
507
python
def _apply_exclude_patterns(names, exclude_filter): included = set(names) if hasattr(exclude_filter, '__iter__'): exclude_filter = PathSpec.from_lines('gitwildmatch', exclude_filter) for excluded in exclude_filter.match_files(names): included.discard(excluded) return sorted(included)
def _apply_exclude_patterns(names, exclude_filter): included = set(names) if hasattr(exclude_filter, '__iter__'): exclude_filter = PathSpec.from_lines('gitwildmatch', exclude_filter) for excluded in exclude_filter.match_files(names): included.discard(excluded) return sorted(included)<|docstring|>Exclude matched patterns from passed names.<|endoftext|>
06e1f730b14a9e790039ae5a3a1b41cea669c3c4623ce1d407843387e8f663ff
def _apply_left_strip(artifact_filepath, artifacts_dict, lstrip_paths=None): ' Internal helper function to left strip dictionary keys based on\n prefixes passed by the user. ' if lstrip_paths: for prefix in lstrip_paths: if artifact_filepath.startswith(prefix): artifact_filepath = artifact_filepath[len(prefix):] break if (artifact_filepath in artifacts_dict): raise in_toto.exceptions.PrefixError("Prefix selection has resulted in non unique dictionary key '{}'".format(artifact_filepath)) return artifact_filepath
Internal helper function to left strip dictionary keys based on prefixes passed by the user.
in_toto/runlib.py
_apply_left_strip
reeeeeeem/in-toto
507
python
def _apply_left_strip(artifact_filepath, artifacts_dict, lstrip_paths=None): ' Internal helper function to left strip dictionary keys based on\n prefixes passed by the user. ' if lstrip_paths: for prefix in lstrip_paths: if artifact_filepath.startswith(prefix): artifact_filepath = artifact_filepath[len(prefix):] break if (artifact_filepath in artifacts_dict): raise in_toto.exceptions.PrefixError("Prefix selection has resulted in non unique dictionary key '{}'".format(artifact_filepath)) return artifact_filepath
def _apply_left_strip(artifact_filepath, artifacts_dict, lstrip_paths=None): ' Internal helper function to left strip dictionary keys based on\n prefixes passed by the user. ' if lstrip_paths: for prefix in lstrip_paths: if artifact_filepath.startswith(prefix): artifact_filepath = artifact_filepath[len(prefix):] break if (artifact_filepath in artifacts_dict): raise in_toto.exceptions.PrefixError("Prefix selection has resulted in non unique dictionary key '{}'".format(artifact_filepath)) return artifact_filepath<|docstring|>Internal helper function to left strip dictionary keys based on prefixes passed by the user.<|endoftext|>
31b19156ab43bcfe60788355f39b0bb09d7f64feae29742fec1b329811f942c1
def record_artifacts_as_dict(artifacts, exclude_patterns=None, base_path=None, follow_symlink_dirs=False, normalize_line_endings=False, lstrip_paths=None): '\n <Purpose>\n Hashes each file in the passed path list. If the path list contains\n paths to directories the directory tree(s) are traversed.\n\n The files a link command is executed on are called materials.\n The files that result form a link command execution are called\n products.\n\n Paths are normalized for matching and storing by left stripping "./"\n\n NOTE on exclude patterns:\n - Uses PathSpec to compile gitignore-style patterns, making use of the\n GitWildMatchPattern class (registered as \'gitwildmatch\')\n\n - Patterns are checked for match against the full path relative to each\n path passed in the artifacts list\n\n - If a directory is excluded, all its files and subdirectories are also\n excluded\n\n - How it differs from .gitignore\n - No need to escape #\n - No ignoring of trailing spaces\n - No general negation with exclamation mark !\n - No special treatment of slash /\n - No special treatment of consecutive asterisks **\n\n - Exclude patterns are likely to become command line arguments or part of\n a config file.\n\n <Arguments>\n artifacts:\n A list of file or directory paths used as materials or products for\n the link command.\n\n exclude_patterns: (optional)\n Artifacts matched by the pattern are excluded from the result.\n Exclude patterns can be passed as argument or specified via\n ARTIFACT_EXCLUDE_PATTERNS setting (see `in_toto.settings`) or\n via envvars or rcfiles (see `in_toto.user_settings`).\n If passed, patterns specified via settings are overriden.\n\n base_path: (optional)\n Change to base_path and record artifacts relative from there.\n If not passed, current working directory is used as base_path.\n NOTE: The base_path part of the recorded artifact is not included\n in the returned paths.\n\n follow_symlink_dirs: (optional)\n Follow symlinked dirs if the linked dir exists (default is False).\n The recorded path contains the symlink name, not the resolved name.\n NOTE: This parameter toggles following linked directories only,\n linked files are always recorded, independently of this parameter.\n NOTE: Beware of infinite recursions that can occur if a symlink\n points to a parent directory or itself.\n\n normalize_line_endings: (optional)\n If True, replaces windows and mac line endings with unix line\n endings before hashing the content of the passed files, for\n cross-platform support.\n\n lstrip_paths: (optional)\n If a prefix path is passed, the prefix is left stripped from\n the path of every artifact that contains the prefix.\n\n <Exceptions>\n in_toto.exceptions.ValueError,\n if we cannot change to base path directory\n\n in_toto.exceptions.FormatError,\n if the list of exlcude patterns does not match format\n securesystemslib.formats.NAMES_SCHEMA\n\n <Side Effects>\n Calls functions to generate cryptographic hashes.\n\n <Returns>\n A dictionary with file paths as keys and the files\' hashes as values.\n ' artifacts_dict = {} if (not artifacts): return artifacts_dict if base_path: LOG.info('Overriding setting ARTIFACT_BASE_PATH with passed base path.') else: base_path = in_toto.settings.ARTIFACT_BASE_PATH if base_path: original_cwd = os.getcwd() try: os.chdir(base_path) except Exception as e: raise ValueError("Could not use '{}' as base path: '{}'".format(base_path, e)) from e norm_artifacts = [] for path in artifacts: norm_artifacts.append(os.path.normpath(path)) if exclude_patterns: LOG.info('Overriding setting ARTIFACT_EXCLUDE_PATTERNS with passed exclude patterns.') else: exclude_patterns = in_toto.settings.ARTIFACT_EXCLUDE_PATTERNS if exclude_patterns: securesystemslib.formats.NAMES_SCHEMA.check_match(exclude_patterns) norm_artifacts = _apply_exclude_patterns(norm_artifacts, exclude_patterns) if lstrip_paths: for (prefix_one, prefix_two) in itertools.combinations(lstrip_paths, 2): if (prefix_one.startswith(prefix_two) or prefix_two.startswith(prefix_one)): raise in_toto.exceptions.PrefixError("'{}' and '{}' triggered a left substring error".format(prefix_one, prefix_two)) exclude_filter = PathSpec.from_lines('gitwildmatch', (exclude_patterns or [])) for artifact in norm_artifacts: if os.path.isfile(artifact): artifact = artifact.replace('\\', '/') key = _apply_left_strip(artifact, artifacts_dict, lstrip_paths) artifacts_dict[key] = _hash_artifact(artifact, normalize_line_endings=normalize_line_endings) elif os.path.isdir(artifact): for (root, dirs, files) in os.walk(artifact, followlinks=follow_symlink_dirs): dirpaths = [] for dirname in dirs: norm_dirpath = os.path.normpath(os.path.join(root, dirname)) dirpaths.append(norm_dirpath) if exclude_patterns: dirpaths = _apply_exclude_patterns(dirpaths, exclude_filter) dirs[:] = [] for dirpath in dirpaths: name = os.path.basename(dirpath) dirs.append(name) filepaths = [] for filename in files: norm_filepath = os.path.normpath(os.path.join(root, filename)) if os.path.isfile(norm_filepath): filepaths.append(norm_filepath) else: LOG.info("File '{}' appears to be a broken symlink. Skipping...".format(norm_filepath)) if exclude_patterns: filepaths = _apply_exclude_patterns(filepaths, exclude_filter) for filepath in filepaths: normalized_filepath = filepath.replace('\\', '/') key = _apply_left_strip(normalized_filepath, artifacts_dict, lstrip_paths) artifacts_dict[key] = _hash_artifact(filepath, normalize_line_endings=normalize_line_endings) else: LOG.info('path: {} does not exist, skipping..'.format(artifact)) if base_path: os.chdir(original_cwd) return artifacts_dict
<Purpose> Hashes each file in the passed path list. If the path list contains paths to directories the directory tree(s) are traversed. The files a link command is executed on are called materials. The files that result form a link command execution are called products. Paths are normalized for matching and storing by left stripping "./" NOTE on exclude patterns: - Uses PathSpec to compile gitignore-style patterns, making use of the GitWildMatchPattern class (registered as 'gitwildmatch') - Patterns are checked for match against the full path relative to each path passed in the artifacts list - If a directory is excluded, all its files and subdirectories are also excluded - How it differs from .gitignore - No need to escape # - No ignoring of trailing spaces - No general negation with exclamation mark ! - No special treatment of slash / - No special treatment of consecutive asterisks ** - Exclude patterns are likely to become command line arguments or part of a config file. <Arguments> artifacts: A list of file or directory paths used as materials or products for the link command. exclude_patterns: (optional) Artifacts matched by the pattern are excluded from the result. Exclude patterns can be passed as argument or specified via ARTIFACT_EXCLUDE_PATTERNS setting (see `in_toto.settings`) or via envvars or rcfiles (see `in_toto.user_settings`). If passed, patterns specified via settings are overriden. base_path: (optional) Change to base_path and record artifacts relative from there. If not passed, current working directory is used as base_path. NOTE: The base_path part of the recorded artifact is not included in the returned paths. follow_symlink_dirs: (optional) Follow symlinked dirs if the linked dir exists (default is False). The recorded path contains the symlink name, not the resolved name. NOTE: This parameter toggles following linked directories only, linked files are always recorded, independently of this parameter. NOTE: Beware of infinite recursions that can occur if a symlink points to a parent directory or itself. normalize_line_endings: (optional) If True, replaces windows and mac line endings with unix line endings before hashing the content of the passed files, for cross-platform support. lstrip_paths: (optional) If a prefix path is passed, the prefix is left stripped from the path of every artifact that contains the prefix. <Exceptions> in_toto.exceptions.ValueError, if we cannot change to base path directory in_toto.exceptions.FormatError, if the list of exlcude patterns does not match format securesystemslib.formats.NAMES_SCHEMA <Side Effects> Calls functions to generate cryptographic hashes. <Returns> A dictionary with file paths as keys and the files' hashes as values.
in_toto/runlib.py
record_artifacts_as_dict
reeeeeeem/in-toto
507
python
def record_artifacts_as_dict(artifacts, exclude_patterns=None, base_path=None, follow_symlink_dirs=False, normalize_line_endings=False, lstrip_paths=None): '\n <Purpose>\n Hashes each file in the passed path list. If the path list contains\n paths to directories the directory tree(s) are traversed.\n\n The files a link command is executed on are called materials.\n The files that result form a link command execution are called\n products.\n\n Paths are normalized for matching and storing by left stripping "./"\n\n NOTE on exclude patterns:\n - Uses PathSpec to compile gitignore-style patterns, making use of the\n GitWildMatchPattern class (registered as \'gitwildmatch\')\n\n - Patterns are checked for match against the full path relative to each\n path passed in the artifacts list\n\n - If a directory is excluded, all its files and subdirectories are also\n excluded\n\n - How it differs from .gitignore\n - No need to escape #\n - No ignoring of trailing spaces\n - No general negation with exclamation mark !\n - No special treatment of slash /\n - No special treatment of consecutive asterisks **\n\n - Exclude patterns are likely to become command line arguments or part of\n a config file.\n\n <Arguments>\n artifacts:\n A list of file or directory paths used as materials or products for\n the link command.\n\n exclude_patterns: (optional)\n Artifacts matched by the pattern are excluded from the result.\n Exclude patterns can be passed as argument or specified via\n ARTIFACT_EXCLUDE_PATTERNS setting (see `in_toto.settings`) or\n via envvars or rcfiles (see `in_toto.user_settings`).\n If passed, patterns specified via settings are overriden.\n\n base_path: (optional)\n Change to base_path and record artifacts relative from there.\n If not passed, current working directory is used as base_path.\n NOTE: The base_path part of the recorded artifact is not included\n in the returned paths.\n\n follow_symlink_dirs: (optional)\n Follow symlinked dirs if the linked dir exists (default is False).\n The recorded path contains the symlink name, not the resolved name.\n NOTE: This parameter toggles following linked directories only,\n linked files are always recorded, independently of this parameter.\n NOTE: Beware of infinite recursions that can occur if a symlink\n points to a parent directory or itself.\n\n normalize_line_endings: (optional)\n If True, replaces windows and mac line endings with unix line\n endings before hashing the content of the passed files, for\n cross-platform support.\n\n lstrip_paths: (optional)\n If a prefix path is passed, the prefix is left stripped from\n the path of every artifact that contains the prefix.\n\n <Exceptions>\n in_toto.exceptions.ValueError,\n if we cannot change to base path directory\n\n in_toto.exceptions.FormatError,\n if the list of exlcude patterns does not match format\n securesystemslib.formats.NAMES_SCHEMA\n\n <Side Effects>\n Calls functions to generate cryptographic hashes.\n\n <Returns>\n A dictionary with file paths as keys and the files\' hashes as values.\n ' artifacts_dict = {} if (not artifacts): return artifacts_dict if base_path: LOG.info('Overriding setting ARTIFACT_BASE_PATH with passed base path.') else: base_path = in_toto.settings.ARTIFACT_BASE_PATH if base_path: original_cwd = os.getcwd() try: os.chdir(base_path) except Exception as e: raise ValueError("Could not use '{}' as base path: '{}'".format(base_path, e)) from e norm_artifacts = [] for path in artifacts: norm_artifacts.append(os.path.normpath(path)) if exclude_patterns: LOG.info('Overriding setting ARTIFACT_EXCLUDE_PATTERNS with passed exclude patterns.') else: exclude_patterns = in_toto.settings.ARTIFACT_EXCLUDE_PATTERNS if exclude_patterns: securesystemslib.formats.NAMES_SCHEMA.check_match(exclude_patterns) norm_artifacts = _apply_exclude_patterns(norm_artifacts, exclude_patterns) if lstrip_paths: for (prefix_one, prefix_two) in itertools.combinations(lstrip_paths, 2): if (prefix_one.startswith(prefix_two) or prefix_two.startswith(prefix_one)): raise in_toto.exceptions.PrefixError("'{}' and '{}' triggered a left substring error".format(prefix_one, prefix_two)) exclude_filter = PathSpec.from_lines('gitwildmatch', (exclude_patterns or [])) for artifact in norm_artifacts: if os.path.isfile(artifact): artifact = artifact.replace('\\', '/') key = _apply_left_strip(artifact, artifacts_dict, lstrip_paths) artifacts_dict[key] = _hash_artifact(artifact, normalize_line_endings=normalize_line_endings) elif os.path.isdir(artifact): for (root, dirs, files) in os.walk(artifact, followlinks=follow_symlink_dirs): dirpaths = [] for dirname in dirs: norm_dirpath = os.path.normpath(os.path.join(root, dirname)) dirpaths.append(norm_dirpath) if exclude_patterns: dirpaths = _apply_exclude_patterns(dirpaths, exclude_filter) dirs[:] = [] for dirpath in dirpaths: name = os.path.basename(dirpath) dirs.append(name) filepaths = [] for filename in files: norm_filepath = os.path.normpath(os.path.join(root, filename)) if os.path.isfile(norm_filepath): filepaths.append(norm_filepath) else: LOG.info("File '{}' appears to be a broken symlink. Skipping...".format(norm_filepath)) if exclude_patterns: filepaths = _apply_exclude_patterns(filepaths, exclude_filter) for filepath in filepaths: normalized_filepath = filepath.replace('\\', '/') key = _apply_left_strip(normalized_filepath, artifacts_dict, lstrip_paths) artifacts_dict[key] = _hash_artifact(filepath, normalize_line_endings=normalize_line_endings) else: LOG.info('path: {} does not exist, skipping..'.format(artifact)) if base_path: os.chdir(original_cwd) return artifacts_dict
def record_artifacts_as_dict(artifacts, exclude_patterns=None, base_path=None, follow_symlink_dirs=False, normalize_line_endings=False, lstrip_paths=None): '\n <Purpose>\n Hashes each file in the passed path list. If the path list contains\n paths to directories the directory tree(s) are traversed.\n\n The files a link command is executed on are called materials.\n The files that result form a link command execution are called\n products.\n\n Paths are normalized for matching and storing by left stripping "./"\n\n NOTE on exclude patterns:\n - Uses PathSpec to compile gitignore-style patterns, making use of the\n GitWildMatchPattern class (registered as \'gitwildmatch\')\n\n - Patterns are checked for match against the full path relative to each\n path passed in the artifacts list\n\n - If a directory is excluded, all its files and subdirectories are also\n excluded\n\n - How it differs from .gitignore\n - No need to escape #\n - No ignoring of trailing spaces\n - No general negation with exclamation mark !\n - No special treatment of slash /\n - No special treatment of consecutive asterisks **\n\n - Exclude patterns are likely to become command line arguments or part of\n a config file.\n\n <Arguments>\n artifacts:\n A list of file or directory paths used as materials or products for\n the link command.\n\n exclude_patterns: (optional)\n Artifacts matched by the pattern are excluded from the result.\n Exclude patterns can be passed as argument or specified via\n ARTIFACT_EXCLUDE_PATTERNS setting (see `in_toto.settings`) or\n via envvars or rcfiles (see `in_toto.user_settings`).\n If passed, patterns specified via settings are overriden.\n\n base_path: (optional)\n Change to base_path and record artifacts relative from there.\n If not passed, current working directory is used as base_path.\n NOTE: The base_path part of the recorded artifact is not included\n in the returned paths.\n\n follow_symlink_dirs: (optional)\n Follow symlinked dirs if the linked dir exists (default is False).\n The recorded path contains the symlink name, not the resolved name.\n NOTE: This parameter toggles following linked directories only,\n linked files are always recorded, independently of this parameter.\n NOTE: Beware of infinite recursions that can occur if a symlink\n points to a parent directory or itself.\n\n normalize_line_endings: (optional)\n If True, replaces windows and mac line endings with unix line\n endings before hashing the content of the passed files, for\n cross-platform support.\n\n lstrip_paths: (optional)\n If a prefix path is passed, the prefix is left stripped from\n the path of every artifact that contains the prefix.\n\n <Exceptions>\n in_toto.exceptions.ValueError,\n if we cannot change to base path directory\n\n in_toto.exceptions.FormatError,\n if the list of exlcude patterns does not match format\n securesystemslib.formats.NAMES_SCHEMA\n\n <Side Effects>\n Calls functions to generate cryptographic hashes.\n\n <Returns>\n A dictionary with file paths as keys and the files\' hashes as values.\n ' artifacts_dict = {} if (not artifacts): return artifacts_dict if base_path: LOG.info('Overriding setting ARTIFACT_BASE_PATH with passed base path.') else: base_path = in_toto.settings.ARTIFACT_BASE_PATH if base_path: original_cwd = os.getcwd() try: os.chdir(base_path) except Exception as e: raise ValueError("Could not use '{}' as base path: '{}'".format(base_path, e)) from e norm_artifacts = [] for path in artifacts: norm_artifacts.append(os.path.normpath(path)) if exclude_patterns: LOG.info('Overriding setting ARTIFACT_EXCLUDE_PATTERNS with passed exclude patterns.') else: exclude_patterns = in_toto.settings.ARTIFACT_EXCLUDE_PATTERNS if exclude_patterns: securesystemslib.formats.NAMES_SCHEMA.check_match(exclude_patterns) norm_artifacts = _apply_exclude_patterns(norm_artifacts, exclude_patterns) if lstrip_paths: for (prefix_one, prefix_two) in itertools.combinations(lstrip_paths, 2): if (prefix_one.startswith(prefix_two) or prefix_two.startswith(prefix_one)): raise in_toto.exceptions.PrefixError("'{}' and '{}' triggered a left substring error".format(prefix_one, prefix_two)) exclude_filter = PathSpec.from_lines('gitwildmatch', (exclude_patterns or [])) for artifact in norm_artifacts: if os.path.isfile(artifact): artifact = artifact.replace('\\', '/') key = _apply_left_strip(artifact, artifacts_dict, lstrip_paths) artifacts_dict[key] = _hash_artifact(artifact, normalize_line_endings=normalize_line_endings) elif os.path.isdir(artifact): for (root, dirs, files) in os.walk(artifact, followlinks=follow_symlink_dirs): dirpaths = [] for dirname in dirs: norm_dirpath = os.path.normpath(os.path.join(root, dirname)) dirpaths.append(norm_dirpath) if exclude_patterns: dirpaths = _apply_exclude_patterns(dirpaths, exclude_filter) dirs[:] = [] for dirpath in dirpaths: name = os.path.basename(dirpath) dirs.append(name) filepaths = [] for filename in files: norm_filepath = os.path.normpath(os.path.join(root, filename)) if os.path.isfile(norm_filepath): filepaths.append(norm_filepath) else: LOG.info("File '{}' appears to be a broken symlink. Skipping...".format(norm_filepath)) if exclude_patterns: filepaths = _apply_exclude_patterns(filepaths, exclude_filter) for filepath in filepaths: normalized_filepath = filepath.replace('\\', '/') key = _apply_left_strip(normalized_filepath, artifacts_dict, lstrip_paths) artifacts_dict[key] = _hash_artifact(filepath, normalize_line_endings=normalize_line_endings) else: LOG.info('path: {} does not exist, skipping..'.format(artifact)) if base_path: os.chdir(original_cwd) return artifacts_dict<|docstring|><Purpose> Hashes each file in the passed path list. If the path list contains paths to directories the directory tree(s) are traversed. The files a link command is executed on are called materials. The files that result form a link command execution are called products. Paths are normalized for matching and storing by left stripping "./" NOTE on exclude patterns: - Uses PathSpec to compile gitignore-style patterns, making use of the GitWildMatchPattern class (registered as 'gitwildmatch') - Patterns are checked for match against the full path relative to each path passed in the artifacts list - If a directory is excluded, all its files and subdirectories are also excluded - How it differs from .gitignore - No need to escape # - No ignoring of trailing spaces - No general negation with exclamation mark ! - No special treatment of slash / - No special treatment of consecutive asterisks ** - Exclude patterns are likely to become command line arguments or part of a config file. <Arguments> artifacts: A list of file or directory paths used as materials or products for the link command. exclude_patterns: (optional) Artifacts matched by the pattern are excluded from the result. Exclude patterns can be passed as argument or specified via ARTIFACT_EXCLUDE_PATTERNS setting (see `in_toto.settings`) or via envvars or rcfiles (see `in_toto.user_settings`). If passed, patterns specified via settings are overriden. base_path: (optional) Change to base_path and record artifacts relative from there. If not passed, current working directory is used as base_path. NOTE: The base_path part of the recorded artifact is not included in the returned paths. follow_symlink_dirs: (optional) Follow symlinked dirs if the linked dir exists (default is False). The recorded path contains the symlink name, not the resolved name. NOTE: This parameter toggles following linked directories only, linked files are always recorded, independently of this parameter. NOTE: Beware of infinite recursions that can occur if a symlink points to a parent directory or itself. normalize_line_endings: (optional) If True, replaces windows and mac line endings with unix line endings before hashing the content of the passed files, for cross-platform support. lstrip_paths: (optional) If a prefix path is passed, the prefix is left stripped from the path of every artifact that contains the prefix. <Exceptions> in_toto.exceptions.ValueError, if we cannot change to base path directory in_toto.exceptions.FormatError, if the list of exlcude patterns does not match format securesystemslib.formats.NAMES_SCHEMA <Side Effects> Calls functions to generate cryptographic hashes. <Returns> A dictionary with file paths as keys and the files' hashes as values.<|endoftext|>
6a24753a4968c6f2d3e9320521acf6e3ae2f1bfc44a3b91492a5a93123b62e0a
def execute_link(link_cmd_args, record_streams): '\n <Purpose>\n Executes the passed command plus arguments in a subprocess and returns\n the return value of the executed command. If the specified standard output\n and standard error of the command are recorded and also returned to the\n caller.\n\n <Arguments>\n link_cmd_args:\n A list where the first element is a command and the remaining\n elements are arguments passed to that command.\n record_streams:\n A bool that specifies whether to redirect standard output and\n and standard error to a temporary file which is returned to the\n caller (True) or not (False).\n\n <Exceptions>\n OSError:\n The given command is not present or non-executable\n\n securesystemslib.process.subprocess.TimeoutExpired:\n The execution of the given command times out. The default timeout\n is securesystemslib.settings.SUBPROCESS_TIMEOUT.\n\n\n <Side Effects>\n Executes passed command in a subprocess and redirects stdout and stderr\n if specified.\n\n <Returns>\n - A dictionary containing standard output and standard error of the\n executed command, called by-products.\n Note: If record_streams is False, the dict values are empty strings.\n - The return value of the executed command.\n ' if record_streams: (return_code, stdout_str, stderr_str) = securesystemslib.process.run_duplicate_streams(link_cmd_args, timeout=float(in_toto.settings.LINK_CMD_EXEC_TIMEOUT)) else: process = securesystemslib.process.run(link_cmd_args, check=False, timeout=float(in_toto.settings.LINK_CMD_EXEC_TIMEOUT), stdout=securesystemslib.process.DEVNULL, stderr=securesystemslib.process.DEVNULL) stdout_str = stderr_str = '' return_code = process.returncode return {'stdout': stdout_str, 'stderr': stderr_str, 'return-value': return_code}
<Purpose> Executes the passed command plus arguments in a subprocess and returns the return value of the executed command. If the specified standard output and standard error of the command are recorded and also returned to the caller. <Arguments> link_cmd_args: A list where the first element is a command and the remaining elements are arguments passed to that command. record_streams: A bool that specifies whether to redirect standard output and and standard error to a temporary file which is returned to the caller (True) or not (False). <Exceptions> OSError: The given command is not present or non-executable securesystemslib.process.subprocess.TimeoutExpired: The execution of the given command times out. The default timeout is securesystemslib.settings.SUBPROCESS_TIMEOUT. <Side Effects> Executes passed command in a subprocess and redirects stdout and stderr if specified. <Returns> - A dictionary containing standard output and standard error of the executed command, called by-products. Note: If record_streams is False, the dict values are empty strings. - The return value of the executed command.
in_toto/runlib.py
execute_link
reeeeeeem/in-toto
507
python
def execute_link(link_cmd_args, record_streams): '\n <Purpose>\n Executes the passed command plus arguments in a subprocess and returns\n the return value of the executed command. If the specified standard output\n and standard error of the command are recorded and also returned to the\n caller.\n\n <Arguments>\n link_cmd_args:\n A list where the first element is a command and the remaining\n elements are arguments passed to that command.\n record_streams:\n A bool that specifies whether to redirect standard output and\n and standard error to a temporary file which is returned to the\n caller (True) or not (False).\n\n <Exceptions>\n OSError:\n The given command is not present or non-executable\n\n securesystemslib.process.subprocess.TimeoutExpired:\n The execution of the given command times out. The default timeout\n is securesystemslib.settings.SUBPROCESS_TIMEOUT.\n\n\n <Side Effects>\n Executes passed command in a subprocess and redirects stdout and stderr\n if specified.\n\n <Returns>\n - A dictionary containing standard output and standard error of the\n executed command, called by-products.\n Note: If record_streams is False, the dict values are empty strings.\n - The return value of the executed command.\n ' if record_streams: (return_code, stdout_str, stderr_str) = securesystemslib.process.run_duplicate_streams(link_cmd_args, timeout=float(in_toto.settings.LINK_CMD_EXEC_TIMEOUT)) else: process = securesystemslib.process.run(link_cmd_args, check=False, timeout=float(in_toto.settings.LINK_CMD_EXEC_TIMEOUT), stdout=securesystemslib.process.DEVNULL, stderr=securesystemslib.process.DEVNULL) stdout_str = stderr_str = return_code = process.returncode return {'stdout': stdout_str, 'stderr': stderr_str, 'return-value': return_code}
def execute_link(link_cmd_args, record_streams): '\n <Purpose>\n Executes the passed command plus arguments in a subprocess and returns\n the return value of the executed command. If the specified standard output\n and standard error of the command are recorded and also returned to the\n caller.\n\n <Arguments>\n link_cmd_args:\n A list where the first element is a command and the remaining\n elements are arguments passed to that command.\n record_streams:\n A bool that specifies whether to redirect standard output and\n and standard error to a temporary file which is returned to the\n caller (True) or not (False).\n\n <Exceptions>\n OSError:\n The given command is not present or non-executable\n\n securesystemslib.process.subprocess.TimeoutExpired:\n The execution of the given command times out. The default timeout\n is securesystemslib.settings.SUBPROCESS_TIMEOUT.\n\n\n <Side Effects>\n Executes passed command in a subprocess and redirects stdout and stderr\n if specified.\n\n <Returns>\n - A dictionary containing standard output and standard error of the\n executed command, called by-products.\n Note: If record_streams is False, the dict values are empty strings.\n - The return value of the executed command.\n ' if record_streams: (return_code, stdout_str, stderr_str) = securesystemslib.process.run_duplicate_streams(link_cmd_args, timeout=float(in_toto.settings.LINK_CMD_EXEC_TIMEOUT)) else: process = securesystemslib.process.run(link_cmd_args, check=False, timeout=float(in_toto.settings.LINK_CMD_EXEC_TIMEOUT), stdout=securesystemslib.process.DEVNULL, stderr=securesystemslib.process.DEVNULL) stdout_str = stderr_str = return_code = process.returncode return {'stdout': stdout_str, 'stderr': stderr_str, 'return-value': return_code}<|docstring|><Purpose> Executes the passed command plus arguments in a subprocess and returns the return value of the executed command. If the specified standard output and standard error of the command are recorded and also returned to the caller. <Arguments> link_cmd_args: A list where the first element is a command and the remaining elements are arguments passed to that command. record_streams: A bool that specifies whether to redirect standard output and and standard error to a temporary file which is returned to the caller (True) or not (False). <Exceptions> OSError: The given command is not present or non-executable securesystemslib.process.subprocess.TimeoutExpired: The execution of the given command times out. The default timeout is securesystemslib.settings.SUBPROCESS_TIMEOUT. <Side Effects> Executes passed command in a subprocess and redirects stdout and stderr if specified. <Returns> - A dictionary containing standard output and standard error of the executed command, called by-products. Note: If record_streams is False, the dict values are empty strings. - The return value of the executed command.<|endoftext|>
2576852086da7ef4b2499ccb2a81c2d3e08f51f85f550486de19ba3b84f40c3c
def in_toto_mock(name, link_cmd_args): '\n <Purpose>\n in_toto_run with defaults\n - Records materials and products in current directory\n - Does not sign resulting link file\n - Stores resulting link file under "<name>.link"\n\n <Arguments>\n name:\n A unique name to relate mock link metadata with a step or\n inspection defined in the layout.\n link_cmd_args:\n A list where the first element is a command and the remaining\n elements are arguments passed to that command.\n\n <Exceptions>\n None.\n\n <Side Effects>\n Writes newly created link metadata file to disk using the filename scheme\n from link.FILENAME_FORMAT_SHORT\n\n <Returns>\n Newly created Metablock object containing a Link object\n\n ' link_metadata = in_toto_run(name, ['.'], ['.'], link_cmd_args, record_streams=True) filename = FILENAME_FORMAT_SHORT.format(step_name=name) LOG.info("Storing unsigned link metadata to '{}'...".format(filename)) link_metadata.dump(filename) return link_metadata
<Purpose> in_toto_run with defaults - Records materials and products in current directory - Does not sign resulting link file - Stores resulting link file under "<name>.link" <Arguments> name: A unique name to relate mock link metadata with a step or inspection defined in the layout. link_cmd_args: A list where the first element is a command and the remaining elements are arguments passed to that command. <Exceptions> None. <Side Effects> Writes newly created link metadata file to disk using the filename scheme from link.FILENAME_FORMAT_SHORT <Returns> Newly created Metablock object containing a Link object
in_toto/runlib.py
in_toto_mock
reeeeeeem/in-toto
507
python
def in_toto_mock(name, link_cmd_args): '\n <Purpose>\n in_toto_run with defaults\n - Records materials and products in current directory\n - Does not sign resulting link file\n - Stores resulting link file under "<name>.link"\n\n <Arguments>\n name:\n A unique name to relate mock link metadata with a step or\n inspection defined in the layout.\n link_cmd_args:\n A list where the first element is a command and the remaining\n elements are arguments passed to that command.\n\n <Exceptions>\n None.\n\n <Side Effects>\n Writes newly created link metadata file to disk using the filename scheme\n from link.FILENAME_FORMAT_SHORT\n\n <Returns>\n Newly created Metablock object containing a Link object\n\n ' link_metadata = in_toto_run(name, ['.'], ['.'], link_cmd_args, record_streams=True) filename = FILENAME_FORMAT_SHORT.format(step_name=name) LOG.info("Storing unsigned link metadata to '{}'...".format(filename)) link_metadata.dump(filename) return link_metadata
def in_toto_mock(name, link_cmd_args): '\n <Purpose>\n in_toto_run with defaults\n - Records materials and products in current directory\n - Does not sign resulting link file\n - Stores resulting link file under "<name>.link"\n\n <Arguments>\n name:\n A unique name to relate mock link metadata with a step or\n inspection defined in the layout.\n link_cmd_args:\n A list where the first element is a command and the remaining\n elements are arguments passed to that command.\n\n <Exceptions>\n None.\n\n <Side Effects>\n Writes newly created link metadata file to disk using the filename scheme\n from link.FILENAME_FORMAT_SHORT\n\n <Returns>\n Newly created Metablock object containing a Link object\n\n ' link_metadata = in_toto_run(name, ['.'], ['.'], link_cmd_args, record_streams=True) filename = FILENAME_FORMAT_SHORT.format(step_name=name) LOG.info("Storing unsigned link metadata to '{}'...".format(filename)) link_metadata.dump(filename) return link_metadata<|docstring|><Purpose> in_toto_run with defaults - Records materials and products in current directory - Does not sign resulting link file - Stores resulting link file under "<name>.link" <Arguments> name: A unique name to relate mock link metadata with a step or inspection defined in the layout. link_cmd_args: A list where the first element is a command and the remaining elements are arguments passed to that command. <Exceptions> None. <Side Effects> Writes newly created link metadata file to disk using the filename scheme from link.FILENAME_FORMAT_SHORT <Returns> Newly created Metablock object containing a Link object<|endoftext|>
c962dd0dc7c09f84701e32d9a2379ba6a11180b901b2806cab6ffa51c89f60da
def _check_match_signing_key(signing_key): " Helper method to check if the signing_key has securesystemslib's\n KEY_SCHEMA and the private part is not empty.\n # FIXME: Add private key format check to formats\n " securesystemslib.formats.KEY_SCHEMA.check_match(signing_key) if (not signing_key['keyval'].get('private')): raise securesystemslib.exceptions.FormatError('Signing key needs to be a private key.')
Helper method to check if the signing_key has securesystemslib's KEY_SCHEMA and the private part is not empty. # FIXME: Add private key format check to formats
in_toto/runlib.py
_check_match_signing_key
reeeeeeem/in-toto
507
python
def _check_match_signing_key(signing_key): " Helper method to check if the signing_key has securesystemslib's\n KEY_SCHEMA and the private part is not empty.\n # FIXME: Add private key format check to formats\n " securesystemslib.formats.KEY_SCHEMA.check_match(signing_key) if (not signing_key['keyval'].get('private')): raise securesystemslib.exceptions.FormatError('Signing key needs to be a private key.')
def _check_match_signing_key(signing_key): " Helper method to check if the signing_key has securesystemslib's\n KEY_SCHEMA and the private part is not empty.\n # FIXME: Add private key format check to formats\n " securesystemslib.formats.KEY_SCHEMA.check_match(signing_key) if (not signing_key['keyval'].get('private')): raise securesystemslib.exceptions.FormatError('Signing key needs to be a private key.')<|docstring|>Helper method to check if the signing_key has securesystemslib's KEY_SCHEMA and the private part is not empty. # FIXME: Add private key format check to formats<|endoftext|>
88c8f7f5c1deb5a17e9cbc57f76f2ddff584702b8823a35509d28bd2d0accc1b
def in_toto_run(name, material_list, product_list, link_cmd_args, record_streams=False, signing_key=None, gpg_keyid=None, gpg_use_default=False, gpg_home=None, exclude_patterns=None, base_path=None, compact_json=False, record_environment=False, normalize_line_endings=False, lstrip_paths=None, metadata_directory=None): 'Performs a supply chain step or inspection generating link metadata.\n\n Executes link_cmd_args, recording paths and hashes of files before and after\n command execution (aka. artifacts) in a link metadata file. The metadata is\n signed with the passed signing_key, a gpg key identified by its ID, or the\n default gpg key. If multiple key arguments are passed, only one key is used\n in above order of precedence. The resulting link file is written to\n ``STEP-NAME.KEYID-PREFIX.link``. If no key argument is passed the link\n metadata is neither signed nor written to disk.\n\n Arguments:\n name: A unique name to associate link metadata with a step or inspection.\n\n material_list: A list of artifact paths to be recorded before command\n execution. Directories are traversed recursively.\n\n product_list: A list of artifact paths to be recorded after command\n execution. Directories are traversed recursively.\n\n link_cmd_args: A list where the first element is a command and the\n remaining elements are arguments passed to that command.\n\n record_streams (optional): A boolean indicating if standard output and\n standard error of the link command should be recorded in the link\n metadata in addition to being displayed while the command is executed.\n\n signing_key (optional): A key used to sign the resulting link metadata. The\n format is securesystemslib.formats.KEY_SCHEMA.\n\n gpg_keyid (optional): A keyid used to identify a local gpg key used to sign\n the resulting link metadata.\n\n gpg_use_default (optional): A boolean indicating if the default gpg key\n should be used to sign the resulting link metadata.\n\n gpg_home (optional): A path to the gpg home directory. If not set the\n default gpg home directory is used.\n\n exclude_patterns (optional): A list of filename patterns to exclude certain\n files from being recorded as artifacts. See Config docs for details.\n\n base_path (optional): A path relative to which artifacts are recorded.\n Default is the current working directory.\n\n compact_json (optional): A boolean indicating if the resulting link\n metadata should be written in the most compact JSON representation.\n\n record_environment (optional): A boolean indicating if information about\n the environment should be added in the resulting link metadata.\n\n normalize_line_endings (optional): A boolean indicating if line endings of\n artifacts should be normalized before hashing for cross-platform\n support.\n\n lstrip_paths (optional): A list of path prefixes used to left-strip\n artifact paths before storing them in the resulting link metadata.\n\n metadata_directory (optional): A directory path to write the resulting link\n metadata file to. Default destination is the current working directory.\n\n Raises:\n securesystemslib.exceptions.FormatError: Passed arguments are malformed.\n\n ValueError: Cannot change to base path directory.\n\n securesystemslib.exceptions.StorageError: Cannot hash artifacts.\n\n PrefixError: Left-stripping artifact paths results in non-unique dict keys.\n\n securesystemslib.process.subprocess.TimeoutExpired: Link command times out.\n\n IOError, FileNotFoundError, NotADirectoryError, PermissionError:\n Cannot write link metadata.\n\n securesystemslib.exceptions.CryptoError, securesystemslib.exceptions.UnsupportedAlgorithmError:\n Signing errors.\n\n ValueError, OSError, securesystemslib.gpg.exceptions.CommandError, securesystemslib.gpg.exceptions.KeyNotFoundError:\n gpg signing errors.\n\n Side Effects:\n Reads artifact files from disk.\n Runs link command in subprocess.\n Calls system gpg in a subprocess, if a gpg key argument is passed.\n Writes link metadata file to disk, if any key argument is passed.\n\n Returns:\n A Metablock object that contains the resulting link object.\n\n ' LOG.info("Running '{}'...".format(name)) if signing_key: _check_match_signing_key(signing_key) if gpg_keyid: securesystemslib.formats.KEYID_SCHEMA.check_match(gpg_keyid) if exclude_patterns: securesystemslib.formats.NAMES_SCHEMA.check_match(exclude_patterns) if base_path: securesystemslib.formats.PATH_SCHEMA.check_match(base_path) if metadata_directory: securesystemslib.formats.PATH_SCHEMA.check_match(metadata_directory) if material_list: LOG.info("Recording materials '{}'...".format(', '.join(material_list))) materials_dict = record_artifacts_as_dict(material_list, exclude_patterns=exclude_patterns, base_path=base_path, follow_symlink_dirs=True, normalize_line_endings=normalize_line_endings, lstrip_paths=lstrip_paths) if link_cmd_args: LOG.info("Running command '{}'...".format(' '.join(link_cmd_args))) byproducts = execute_link(link_cmd_args, record_streams) else: byproducts = {} if product_list: securesystemslib.formats.PATHS_SCHEMA.check_match(product_list) LOG.info("Recording products '{}'...".format(', '.join(product_list))) products_dict = record_artifacts_as_dict(product_list, exclude_patterns=exclude_patterns, base_path=base_path, follow_symlink_dirs=True, normalize_line_endings=normalize_line_endings, lstrip_paths=lstrip_paths) LOG.info('Creating link metadata...') environment = {} if record_environment: environment['workdir'] = os.getcwd().replace('\\', '/') link = in_toto.models.link.Link(name=name, materials=materials_dict, products=products_dict, command=link_cmd_args, byproducts=byproducts, environment=environment) link_metadata = Metablock(signed=link, compact_json=compact_json) signature = None if signing_key: LOG.info('Signing link metadata using passed key...') signature = link_metadata.sign(signing_key) elif gpg_keyid: LOG.info('Signing link metadata using passed GPG keyid...') signature = link_metadata.sign_gpg(gpg_keyid, gpg_home=gpg_home) elif gpg_use_default: LOG.info('Signing link metadata using default GPG key ...') signature = link_metadata.sign_gpg(gpg_keyid=None, gpg_home=gpg_home) if signature: signing_keyid = signature['keyid'] filename = FILENAME_FORMAT.format(step_name=name, keyid=signing_keyid) if (metadata_directory is not None): filename = os.path.join(metadata_directory, filename) LOG.info("Storing link metadata to '{}'...".format(filename)) link_metadata.dump(filename) return link_metadata
Performs a supply chain step or inspection generating link metadata. Executes link_cmd_args, recording paths and hashes of files before and after command execution (aka. artifacts) in a link metadata file. The metadata is signed with the passed signing_key, a gpg key identified by its ID, or the default gpg key. If multiple key arguments are passed, only one key is used in above order of precedence. The resulting link file is written to ``STEP-NAME.KEYID-PREFIX.link``. If no key argument is passed the link metadata is neither signed nor written to disk. Arguments: name: A unique name to associate link metadata with a step or inspection. material_list: A list of artifact paths to be recorded before command execution. Directories are traversed recursively. product_list: A list of artifact paths to be recorded after command execution. Directories are traversed recursively. link_cmd_args: A list where the first element is a command and the remaining elements are arguments passed to that command. record_streams (optional): A boolean indicating if standard output and standard error of the link command should be recorded in the link metadata in addition to being displayed while the command is executed. signing_key (optional): A key used to sign the resulting link metadata. The format is securesystemslib.formats.KEY_SCHEMA. gpg_keyid (optional): A keyid used to identify a local gpg key used to sign the resulting link metadata. gpg_use_default (optional): A boolean indicating if the default gpg key should be used to sign the resulting link metadata. gpg_home (optional): A path to the gpg home directory. If not set the default gpg home directory is used. exclude_patterns (optional): A list of filename patterns to exclude certain files from being recorded as artifacts. See Config docs for details. base_path (optional): A path relative to which artifacts are recorded. Default is the current working directory. compact_json (optional): A boolean indicating if the resulting link metadata should be written in the most compact JSON representation. record_environment (optional): A boolean indicating if information about the environment should be added in the resulting link metadata. normalize_line_endings (optional): A boolean indicating if line endings of artifacts should be normalized before hashing for cross-platform support. lstrip_paths (optional): A list of path prefixes used to left-strip artifact paths before storing them in the resulting link metadata. metadata_directory (optional): A directory path to write the resulting link metadata file to. Default destination is the current working directory. Raises: securesystemslib.exceptions.FormatError: Passed arguments are malformed. ValueError: Cannot change to base path directory. securesystemslib.exceptions.StorageError: Cannot hash artifacts. PrefixError: Left-stripping artifact paths results in non-unique dict keys. securesystemslib.process.subprocess.TimeoutExpired: Link command times out. IOError, FileNotFoundError, NotADirectoryError, PermissionError: Cannot write link metadata. securesystemslib.exceptions.CryptoError, securesystemslib.exceptions.UnsupportedAlgorithmError: Signing errors. ValueError, OSError, securesystemslib.gpg.exceptions.CommandError, securesystemslib.gpg.exceptions.KeyNotFoundError: gpg signing errors. Side Effects: Reads artifact files from disk. Runs link command in subprocess. Calls system gpg in a subprocess, if a gpg key argument is passed. Writes link metadata file to disk, if any key argument is passed. Returns: A Metablock object that contains the resulting link object.
in_toto/runlib.py
in_toto_run
reeeeeeem/in-toto
507
python
def in_toto_run(name, material_list, product_list, link_cmd_args, record_streams=False, signing_key=None, gpg_keyid=None, gpg_use_default=False, gpg_home=None, exclude_patterns=None, base_path=None, compact_json=False, record_environment=False, normalize_line_endings=False, lstrip_paths=None, metadata_directory=None): 'Performs a supply chain step or inspection generating link metadata.\n\n Executes link_cmd_args, recording paths and hashes of files before and after\n command execution (aka. artifacts) in a link metadata file. The metadata is\n signed with the passed signing_key, a gpg key identified by its ID, or the\n default gpg key. If multiple key arguments are passed, only one key is used\n in above order of precedence. The resulting link file is written to\n ``STEP-NAME.KEYID-PREFIX.link``. If no key argument is passed the link\n metadata is neither signed nor written to disk.\n\n Arguments:\n name: A unique name to associate link metadata with a step or inspection.\n\n material_list: A list of artifact paths to be recorded before command\n execution. Directories are traversed recursively.\n\n product_list: A list of artifact paths to be recorded after command\n execution. Directories are traversed recursively.\n\n link_cmd_args: A list where the first element is a command and the\n remaining elements are arguments passed to that command.\n\n record_streams (optional): A boolean indicating if standard output and\n standard error of the link command should be recorded in the link\n metadata in addition to being displayed while the command is executed.\n\n signing_key (optional): A key used to sign the resulting link metadata. The\n format is securesystemslib.formats.KEY_SCHEMA.\n\n gpg_keyid (optional): A keyid used to identify a local gpg key used to sign\n the resulting link metadata.\n\n gpg_use_default (optional): A boolean indicating if the default gpg key\n should be used to sign the resulting link metadata.\n\n gpg_home (optional): A path to the gpg home directory. If not set the\n default gpg home directory is used.\n\n exclude_patterns (optional): A list of filename patterns to exclude certain\n files from being recorded as artifacts. See Config docs for details.\n\n base_path (optional): A path relative to which artifacts are recorded.\n Default is the current working directory.\n\n compact_json (optional): A boolean indicating if the resulting link\n metadata should be written in the most compact JSON representation.\n\n record_environment (optional): A boolean indicating if information about\n the environment should be added in the resulting link metadata.\n\n normalize_line_endings (optional): A boolean indicating if line endings of\n artifacts should be normalized before hashing for cross-platform\n support.\n\n lstrip_paths (optional): A list of path prefixes used to left-strip\n artifact paths before storing them in the resulting link metadata.\n\n metadata_directory (optional): A directory path to write the resulting link\n metadata file to. Default destination is the current working directory.\n\n Raises:\n securesystemslib.exceptions.FormatError: Passed arguments are malformed.\n\n ValueError: Cannot change to base path directory.\n\n securesystemslib.exceptions.StorageError: Cannot hash artifacts.\n\n PrefixError: Left-stripping artifact paths results in non-unique dict keys.\n\n securesystemslib.process.subprocess.TimeoutExpired: Link command times out.\n\n IOError, FileNotFoundError, NotADirectoryError, PermissionError:\n Cannot write link metadata.\n\n securesystemslib.exceptions.CryptoError, securesystemslib.exceptions.UnsupportedAlgorithmError:\n Signing errors.\n\n ValueError, OSError, securesystemslib.gpg.exceptions.CommandError, securesystemslib.gpg.exceptions.KeyNotFoundError:\n gpg signing errors.\n\n Side Effects:\n Reads artifact files from disk.\n Runs link command in subprocess.\n Calls system gpg in a subprocess, if a gpg key argument is passed.\n Writes link metadata file to disk, if any key argument is passed.\n\n Returns:\n A Metablock object that contains the resulting link object.\n\n ' LOG.info("Running '{}'...".format(name)) if signing_key: _check_match_signing_key(signing_key) if gpg_keyid: securesystemslib.formats.KEYID_SCHEMA.check_match(gpg_keyid) if exclude_patterns: securesystemslib.formats.NAMES_SCHEMA.check_match(exclude_patterns) if base_path: securesystemslib.formats.PATH_SCHEMA.check_match(base_path) if metadata_directory: securesystemslib.formats.PATH_SCHEMA.check_match(metadata_directory) if material_list: LOG.info("Recording materials '{}'...".format(', '.join(material_list))) materials_dict = record_artifacts_as_dict(material_list, exclude_patterns=exclude_patterns, base_path=base_path, follow_symlink_dirs=True, normalize_line_endings=normalize_line_endings, lstrip_paths=lstrip_paths) if link_cmd_args: LOG.info("Running command '{}'...".format(' '.join(link_cmd_args))) byproducts = execute_link(link_cmd_args, record_streams) else: byproducts = {} if product_list: securesystemslib.formats.PATHS_SCHEMA.check_match(product_list) LOG.info("Recording products '{}'...".format(', '.join(product_list))) products_dict = record_artifacts_as_dict(product_list, exclude_patterns=exclude_patterns, base_path=base_path, follow_symlink_dirs=True, normalize_line_endings=normalize_line_endings, lstrip_paths=lstrip_paths) LOG.info('Creating link metadata...') environment = {} if record_environment: environment['workdir'] = os.getcwd().replace('\\', '/') link = in_toto.models.link.Link(name=name, materials=materials_dict, products=products_dict, command=link_cmd_args, byproducts=byproducts, environment=environment) link_metadata = Metablock(signed=link, compact_json=compact_json) signature = None if signing_key: LOG.info('Signing link metadata using passed key...') signature = link_metadata.sign(signing_key) elif gpg_keyid: LOG.info('Signing link metadata using passed GPG keyid...') signature = link_metadata.sign_gpg(gpg_keyid, gpg_home=gpg_home) elif gpg_use_default: LOG.info('Signing link metadata using default GPG key ...') signature = link_metadata.sign_gpg(gpg_keyid=None, gpg_home=gpg_home) if signature: signing_keyid = signature['keyid'] filename = FILENAME_FORMAT.format(step_name=name, keyid=signing_keyid) if (metadata_directory is not None): filename = os.path.join(metadata_directory, filename) LOG.info("Storing link metadata to '{}'...".format(filename)) link_metadata.dump(filename) return link_metadata
def in_toto_run(name, material_list, product_list, link_cmd_args, record_streams=False, signing_key=None, gpg_keyid=None, gpg_use_default=False, gpg_home=None, exclude_patterns=None, base_path=None, compact_json=False, record_environment=False, normalize_line_endings=False, lstrip_paths=None, metadata_directory=None): 'Performs a supply chain step or inspection generating link metadata.\n\n Executes link_cmd_args, recording paths and hashes of files before and after\n command execution (aka. artifacts) in a link metadata file. The metadata is\n signed with the passed signing_key, a gpg key identified by its ID, or the\n default gpg key. If multiple key arguments are passed, only one key is used\n in above order of precedence. The resulting link file is written to\n ``STEP-NAME.KEYID-PREFIX.link``. If no key argument is passed the link\n metadata is neither signed nor written to disk.\n\n Arguments:\n name: A unique name to associate link metadata with a step or inspection.\n\n material_list: A list of artifact paths to be recorded before command\n execution. Directories are traversed recursively.\n\n product_list: A list of artifact paths to be recorded after command\n execution. Directories are traversed recursively.\n\n link_cmd_args: A list where the first element is a command and the\n remaining elements are arguments passed to that command.\n\n record_streams (optional): A boolean indicating if standard output and\n standard error of the link command should be recorded in the link\n metadata in addition to being displayed while the command is executed.\n\n signing_key (optional): A key used to sign the resulting link metadata. The\n format is securesystemslib.formats.KEY_SCHEMA.\n\n gpg_keyid (optional): A keyid used to identify a local gpg key used to sign\n the resulting link metadata.\n\n gpg_use_default (optional): A boolean indicating if the default gpg key\n should be used to sign the resulting link metadata.\n\n gpg_home (optional): A path to the gpg home directory. If not set the\n default gpg home directory is used.\n\n exclude_patterns (optional): A list of filename patterns to exclude certain\n files from being recorded as artifacts. See Config docs for details.\n\n base_path (optional): A path relative to which artifacts are recorded.\n Default is the current working directory.\n\n compact_json (optional): A boolean indicating if the resulting link\n metadata should be written in the most compact JSON representation.\n\n record_environment (optional): A boolean indicating if information about\n the environment should be added in the resulting link metadata.\n\n normalize_line_endings (optional): A boolean indicating if line endings of\n artifacts should be normalized before hashing for cross-platform\n support.\n\n lstrip_paths (optional): A list of path prefixes used to left-strip\n artifact paths before storing them in the resulting link metadata.\n\n metadata_directory (optional): A directory path to write the resulting link\n metadata file to. Default destination is the current working directory.\n\n Raises:\n securesystemslib.exceptions.FormatError: Passed arguments are malformed.\n\n ValueError: Cannot change to base path directory.\n\n securesystemslib.exceptions.StorageError: Cannot hash artifacts.\n\n PrefixError: Left-stripping artifact paths results in non-unique dict keys.\n\n securesystemslib.process.subprocess.TimeoutExpired: Link command times out.\n\n IOError, FileNotFoundError, NotADirectoryError, PermissionError:\n Cannot write link metadata.\n\n securesystemslib.exceptions.CryptoError, securesystemslib.exceptions.UnsupportedAlgorithmError:\n Signing errors.\n\n ValueError, OSError, securesystemslib.gpg.exceptions.CommandError, securesystemslib.gpg.exceptions.KeyNotFoundError:\n gpg signing errors.\n\n Side Effects:\n Reads artifact files from disk.\n Runs link command in subprocess.\n Calls system gpg in a subprocess, if a gpg key argument is passed.\n Writes link metadata file to disk, if any key argument is passed.\n\n Returns:\n A Metablock object that contains the resulting link object.\n\n ' LOG.info("Running '{}'...".format(name)) if signing_key: _check_match_signing_key(signing_key) if gpg_keyid: securesystemslib.formats.KEYID_SCHEMA.check_match(gpg_keyid) if exclude_patterns: securesystemslib.formats.NAMES_SCHEMA.check_match(exclude_patterns) if base_path: securesystemslib.formats.PATH_SCHEMA.check_match(base_path) if metadata_directory: securesystemslib.formats.PATH_SCHEMA.check_match(metadata_directory) if material_list: LOG.info("Recording materials '{}'...".format(', '.join(material_list))) materials_dict = record_artifacts_as_dict(material_list, exclude_patterns=exclude_patterns, base_path=base_path, follow_symlink_dirs=True, normalize_line_endings=normalize_line_endings, lstrip_paths=lstrip_paths) if link_cmd_args: LOG.info("Running command '{}'...".format(' '.join(link_cmd_args))) byproducts = execute_link(link_cmd_args, record_streams) else: byproducts = {} if product_list: securesystemslib.formats.PATHS_SCHEMA.check_match(product_list) LOG.info("Recording products '{}'...".format(', '.join(product_list))) products_dict = record_artifacts_as_dict(product_list, exclude_patterns=exclude_patterns, base_path=base_path, follow_symlink_dirs=True, normalize_line_endings=normalize_line_endings, lstrip_paths=lstrip_paths) LOG.info('Creating link metadata...') environment = {} if record_environment: environment['workdir'] = os.getcwd().replace('\\', '/') link = in_toto.models.link.Link(name=name, materials=materials_dict, products=products_dict, command=link_cmd_args, byproducts=byproducts, environment=environment) link_metadata = Metablock(signed=link, compact_json=compact_json) signature = None if signing_key: LOG.info('Signing link metadata using passed key...') signature = link_metadata.sign(signing_key) elif gpg_keyid: LOG.info('Signing link metadata using passed GPG keyid...') signature = link_metadata.sign_gpg(gpg_keyid, gpg_home=gpg_home) elif gpg_use_default: LOG.info('Signing link metadata using default GPG key ...') signature = link_metadata.sign_gpg(gpg_keyid=None, gpg_home=gpg_home) if signature: signing_keyid = signature['keyid'] filename = FILENAME_FORMAT.format(step_name=name, keyid=signing_keyid) if (metadata_directory is not None): filename = os.path.join(metadata_directory, filename) LOG.info("Storing link metadata to '{}'...".format(filename)) link_metadata.dump(filename) return link_metadata<|docstring|>Performs a supply chain step or inspection generating link metadata. Executes link_cmd_args, recording paths and hashes of files before and after command execution (aka. artifacts) in a link metadata file. The metadata is signed with the passed signing_key, a gpg key identified by its ID, or the default gpg key. If multiple key arguments are passed, only one key is used in above order of precedence. The resulting link file is written to ``STEP-NAME.KEYID-PREFIX.link``. If no key argument is passed the link metadata is neither signed nor written to disk. Arguments: name: A unique name to associate link metadata with a step or inspection. material_list: A list of artifact paths to be recorded before command execution. Directories are traversed recursively. product_list: A list of artifact paths to be recorded after command execution. Directories are traversed recursively. link_cmd_args: A list where the first element is a command and the remaining elements are arguments passed to that command. record_streams (optional): A boolean indicating if standard output and standard error of the link command should be recorded in the link metadata in addition to being displayed while the command is executed. signing_key (optional): A key used to sign the resulting link metadata. The format is securesystemslib.formats.KEY_SCHEMA. gpg_keyid (optional): A keyid used to identify a local gpg key used to sign the resulting link metadata. gpg_use_default (optional): A boolean indicating if the default gpg key should be used to sign the resulting link metadata. gpg_home (optional): A path to the gpg home directory. If not set the default gpg home directory is used. exclude_patterns (optional): A list of filename patterns to exclude certain files from being recorded as artifacts. See Config docs for details. base_path (optional): A path relative to which artifacts are recorded. Default is the current working directory. compact_json (optional): A boolean indicating if the resulting link metadata should be written in the most compact JSON representation. record_environment (optional): A boolean indicating if information about the environment should be added in the resulting link metadata. normalize_line_endings (optional): A boolean indicating if line endings of artifacts should be normalized before hashing for cross-platform support. lstrip_paths (optional): A list of path prefixes used to left-strip artifact paths before storing them in the resulting link metadata. metadata_directory (optional): A directory path to write the resulting link metadata file to. Default destination is the current working directory. Raises: securesystemslib.exceptions.FormatError: Passed arguments are malformed. ValueError: Cannot change to base path directory. securesystemslib.exceptions.StorageError: Cannot hash artifacts. PrefixError: Left-stripping artifact paths results in non-unique dict keys. securesystemslib.process.subprocess.TimeoutExpired: Link command times out. IOError, FileNotFoundError, NotADirectoryError, PermissionError: Cannot write link metadata. securesystemslib.exceptions.CryptoError, securesystemslib.exceptions.UnsupportedAlgorithmError: Signing errors. ValueError, OSError, securesystemslib.gpg.exceptions.CommandError, securesystemslib.gpg.exceptions.KeyNotFoundError: gpg signing errors. Side Effects: Reads artifact files from disk. Runs link command in subprocess. Calls system gpg in a subprocess, if a gpg key argument is passed. Writes link metadata file to disk, if any key argument is passed. Returns: A Metablock object that contains the resulting link object.<|endoftext|>
4d69a919706bf2d4e580ecff31a9442772f8c7685bdc2efaf041566034627979
def in_toto_record_start(step_name, material_list, signing_key=None, gpg_keyid=None, gpg_use_default=False, gpg_home=None, exclude_patterns=None, base_path=None, record_environment=False, normalize_line_endings=False, lstrip_paths=None): 'Generates preliminary link metadata.\n\n Records paths and hashes of materials in a preliminary link metadata file.\n The metadata is signed with the passed signing_key, a gpg key identified by\n its ID, or the default gpg key. If multiple key arguments are passed, only\n one key is used in above order of precedence. At least one key argument must\n be passed. The resulting link file is written to\n ``.STEP-NAME.KEYID-PREFIX.link-unfinished``.\n\n Use this function together with in_toto_record_stop as an alternative to\n in_toto_run, in order to provide evidence for supply chain steps that cannot\n be carried out by a single command.\n\n Arguments:\n step_name: A unique name to associate link metadata with a step.\n\n material_list: A list of artifact paths to be recorded as materials.\n Directories are traversed recursively.\n\n signing_key (optional): A key used to sign the resulting link metadata. The\n format is securesystemslib.formats.KEY_SCHEMA.\n\n gpg_keyid (optional): A keyid used to identify a local gpg key used to sign\n the resulting link metadata.\n\n gpg_use_default (optional): A boolean indicating if the default gpg key\n should be used to sign the resulting link metadata.\n\n gpg_home (optional): A path to the gpg home directory. If not set the\n default gpg home directory is used.\n\n exclude_patterns (optional): A list of filename patterns to exclude certain\n files from being recorded as artifacts. See Config docs for details.\n\n base_path (optional): A path relative to which artifacts are recorded.\n Default is the current working directory.\n\n record_environment (optional): A boolean indicating if information about\n the environment should be added in the resulting link metadata.\n\n normalize_line_endings (optional): A boolean indicating if line endings of\n artifacts should be normalized before hashing for cross-platform\n support.\n\n lstrip_paths (optional): A list of path prefixes used to left-strip\n artifact paths before storing them in the resulting link metadata.\n\n Raises:\n securesystemslib.exceptions.FormatError: Passed arguments are malformed.\n\n ValueError: None of signing_key, gpg_keyid or gpg_use_default=True is\n passed.\n\n securesystemslib.exceptions.StorageError: Cannot hash artifacts.\n\n PrefixError: Left-stripping artifact paths results in non-unique dict keys.\n\n securesystemslib.process.subprocess.TimeoutExpired: Link command times out.\n\n IOError, PermissionError:\n Cannot write link metadata.\n\n securesystemslib.exceptions.CryptoError, securesystemslib.exceptions.UnsupportedAlgorithmError:\n Signing errors.\n\n ValueError, OSError, securesystemslib.gpg.exceptions.CommandError, securesystemslib.gpg.exceptions.KeyNotFoundError:\n gpg signing errors.\n\n Side Effects:\n Reads artifact files from disk.\n Calls system gpg in a subprocess, if a gpg key argument is passed.\n Writes preliminary link metadata file to disk.\n\n ' LOG.info("Start recording '{}'...".format(step_name)) if ((not signing_key) and (not gpg_keyid) and (not gpg_use_default)): raise ValueError('Pass either a signing key, a gpg keyid or set gpg_use_default to True!') if signing_key: _check_match_signing_key(signing_key) if gpg_keyid: securesystemslib.formats.KEYID_SCHEMA.check_match(gpg_keyid) if exclude_patterns: securesystemslib.formats.NAMES_SCHEMA.check_match(exclude_patterns) if base_path: securesystemslib.formats.PATH_SCHEMA.check_match(base_path) if material_list: LOG.info("Recording materials '{}'...".format(', '.join(material_list))) materials_dict = record_artifacts_as_dict(material_list, exclude_patterns=exclude_patterns, base_path=base_path, follow_symlink_dirs=True, normalize_line_endings=normalize_line_endings, lstrip_paths=lstrip_paths) LOG.info('Creating preliminary link metadata...') environment = {} if record_environment: environment['workdir'] = os.getcwd().replace('\\', '/') link = in_toto.models.link.Link(name=step_name, materials=materials_dict, products={}, command=[], byproducts={}, environment=environment) link_metadata = Metablock(signed=link) if signing_key: LOG.info('Signing link metadata using passed key...') signature = link_metadata.sign(signing_key) elif gpg_keyid: LOG.info('Signing link metadata using passed GPG keyid...') signature = link_metadata.sign_gpg(gpg_keyid, gpg_home=gpg_home) else: LOG.info('Signing link metadata using default GPG key ...') signature = link_metadata.sign_gpg(gpg_keyid=None, gpg_home=gpg_home) signing_keyid = signature['keyid'] unfinished_fn = UNFINISHED_FILENAME_FORMAT.format(step_name=step_name, keyid=signing_keyid) LOG.info("Storing preliminary link metadata to '{}'...".format(unfinished_fn)) link_metadata.dump(unfinished_fn)
Generates preliminary link metadata. Records paths and hashes of materials in a preliminary link metadata file. The metadata is signed with the passed signing_key, a gpg key identified by its ID, or the default gpg key. If multiple key arguments are passed, only one key is used in above order of precedence. At least one key argument must be passed. The resulting link file is written to ``.STEP-NAME.KEYID-PREFIX.link-unfinished``. Use this function together with in_toto_record_stop as an alternative to in_toto_run, in order to provide evidence for supply chain steps that cannot be carried out by a single command. Arguments: step_name: A unique name to associate link metadata with a step. material_list: A list of artifact paths to be recorded as materials. Directories are traversed recursively. signing_key (optional): A key used to sign the resulting link metadata. The format is securesystemslib.formats.KEY_SCHEMA. gpg_keyid (optional): A keyid used to identify a local gpg key used to sign the resulting link metadata. gpg_use_default (optional): A boolean indicating if the default gpg key should be used to sign the resulting link metadata. gpg_home (optional): A path to the gpg home directory. If not set the default gpg home directory is used. exclude_patterns (optional): A list of filename patterns to exclude certain files from being recorded as artifacts. See Config docs for details. base_path (optional): A path relative to which artifacts are recorded. Default is the current working directory. record_environment (optional): A boolean indicating if information about the environment should be added in the resulting link metadata. normalize_line_endings (optional): A boolean indicating if line endings of artifacts should be normalized before hashing for cross-platform support. lstrip_paths (optional): A list of path prefixes used to left-strip artifact paths before storing them in the resulting link metadata. Raises: securesystemslib.exceptions.FormatError: Passed arguments are malformed. ValueError: None of signing_key, gpg_keyid or gpg_use_default=True is passed. securesystemslib.exceptions.StorageError: Cannot hash artifacts. PrefixError: Left-stripping artifact paths results in non-unique dict keys. securesystemslib.process.subprocess.TimeoutExpired: Link command times out. IOError, PermissionError: Cannot write link metadata. securesystemslib.exceptions.CryptoError, securesystemslib.exceptions.UnsupportedAlgorithmError: Signing errors. ValueError, OSError, securesystemslib.gpg.exceptions.CommandError, securesystemslib.gpg.exceptions.KeyNotFoundError: gpg signing errors. Side Effects: Reads artifact files from disk. Calls system gpg in a subprocess, if a gpg key argument is passed. Writes preliminary link metadata file to disk.
in_toto/runlib.py
in_toto_record_start
reeeeeeem/in-toto
507
python
def in_toto_record_start(step_name, material_list, signing_key=None, gpg_keyid=None, gpg_use_default=False, gpg_home=None, exclude_patterns=None, base_path=None, record_environment=False, normalize_line_endings=False, lstrip_paths=None): 'Generates preliminary link metadata.\n\n Records paths and hashes of materials in a preliminary link metadata file.\n The metadata is signed with the passed signing_key, a gpg key identified by\n its ID, or the default gpg key. If multiple key arguments are passed, only\n one key is used in above order of precedence. At least one key argument must\n be passed. The resulting link file is written to\n ``.STEP-NAME.KEYID-PREFIX.link-unfinished``.\n\n Use this function together with in_toto_record_stop as an alternative to\n in_toto_run, in order to provide evidence for supply chain steps that cannot\n be carried out by a single command.\n\n Arguments:\n step_name: A unique name to associate link metadata with a step.\n\n material_list: A list of artifact paths to be recorded as materials.\n Directories are traversed recursively.\n\n signing_key (optional): A key used to sign the resulting link metadata. The\n format is securesystemslib.formats.KEY_SCHEMA.\n\n gpg_keyid (optional): A keyid used to identify a local gpg key used to sign\n the resulting link metadata.\n\n gpg_use_default (optional): A boolean indicating if the default gpg key\n should be used to sign the resulting link metadata.\n\n gpg_home (optional): A path to the gpg home directory. If not set the\n default gpg home directory is used.\n\n exclude_patterns (optional): A list of filename patterns to exclude certain\n files from being recorded as artifacts. See Config docs for details.\n\n base_path (optional): A path relative to which artifacts are recorded.\n Default is the current working directory.\n\n record_environment (optional): A boolean indicating if information about\n the environment should be added in the resulting link metadata.\n\n normalize_line_endings (optional): A boolean indicating if line endings of\n artifacts should be normalized before hashing for cross-platform\n support.\n\n lstrip_paths (optional): A list of path prefixes used to left-strip\n artifact paths before storing them in the resulting link metadata.\n\n Raises:\n securesystemslib.exceptions.FormatError: Passed arguments are malformed.\n\n ValueError: None of signing_key, gpg_keyid or gpg_use_default=True is\n passed.\n\n securesystemslib.exceptions.StorageError: Cannot hash artifacts.\n\n PrefixError: Left-stripping artifact paths results in non-unique dict keys.\n\n securesystemslib.process.subprocess.TimeoutExpired: Link command times out.\n\n IOError, PermissionError:\n Cannot write link metadata.\n\n securesystemslib.exceptions.CryptoError, securesystemslib.exceptions.UnsupportedAlgorithmError:\n Signing errors.\n\n ValueError, OSError, securesystemslib.gpg.exceptions.CommandError, securesystemslib.gpg.exceptions.KeyNotFoundError:\n gpg signing errors.\n\n Side Effects:\n Reads artifact files from disk.\n Calls system gpg in a subprocess, if a gpg key argument is passed.\n Writes preliminary link metadata file to disk.\n\n ' LOG.info("Start recording '{}'...".format(step_name)) if ((not signing_key) and (not gpg_keyid) and (not gpg_use_default)): raise ValueError('Pass either a signing key, a gpg keyid or set gpg_use_default to True!') if signing_key: _check_match_signing_key(signing_key) if gpg_keyid: securesystemslib.formats.KEYID_SCHEMA.check_match(gpg_keyid) if exclude_patterns: securesystemslib.formats.NAMES_SCHEMA.check_match(exclude_patterns) if base_path: securesystemslib.formats.PATH_SCHEMA.check_match(base_path) if material_list: LOG.info("Recording materials '{}'...".format(', '.join(material_list))) materials_dict = record_artifacts_as_dict(material_list, exclude_patterns=exclude_patterns, base_path=base_path, follow_symlink_dirs=True, normalize_line_endings=normalize_line_endings, lstrip_paths=lstrip_paths) LOG.info('Creating preliminary link metadata...') environment = {} if record_environment: environment['workdir'] = os.getcwd().replace('\\', '/') link = in_toto.models.link.Link(name=step_name, materials=materials_dict, products={}, command=[], byproducts={}, environment=environment) link_metadata = Metablock(signed=link) if signing_key: LOG.info('Signing link metadata using passed key...') signature = link_metadata.sign(signing_key) elif gpg_keyid: LOG.info('Signing link metadata using passed GPG keyid...') signature = link_metadata.sign_gpg(gpg_keyid, gpg_home=gpg_home) else: LOG.info('Signing link metadata using default GPG key ...') signature = link_metadata.sign_gpg(gpg_keyid=None, gpg_home=gpg_home) signing_keyid = signature['keyid'] unfinished_fn = UNFINISHED_FILENAME_FORMAT.format(step_name=step_name, keyid=signing_keyid) LOG.info("Storing preliminary link metadata to '{}'...".format(unfinished_fn)) link_metadata.dump(unfinished_fn)
def in_toto_record_start(step_name, material_list, signing_key=None, gpg_keyid=None, gpg_use_default=False, gpg_home=None, exclude_patterns=None, base_path=None, record_environment=False, normalize_line_endings=False, lstrip_paths=None): 'Generates preliminary link metadata.\n\n Records paths and hashes of materials in a preliminary link metadata file.\n The metadata is signed with the passed signing_key, a gpg key identified by\n its ID, or the default gpg key. If multiple key arguments are passed, only\n one key is used in above order of precedence. At least one key argument must\n be passed. The resulting link file is written to\n ``.STEP-NAME.KEYID-PREFIX.link-unfinished``.\n\n Use this function together with in_toto_record_stop as an alternative to\n in_toto_run, in order to provide evidence for supply chain steps that cannot\n be carried out by a single command.\n\n Arguments:\n step_name: A unique name to associate link metadata with a step.\n\n material_list: A list of artifact paths to be recorded as materials.\n Directories are traversed recursively.\n\n signing_key (optional): A key used to sign the resulting link metadata. The\n format is securesystemslib.formats.KEY_SCHEMA.\n\n gpg_keyid (optional): A keyid used to identify a local gpg key used to sign\n the resulting link metadata.\n\n gpg_use_default (optional): A boolean indicating if the default gpg key\n should be used to sign the resulting link metadata.\n\n gpg_home (optional): A path to the gpg home directory. If not set the\n default gpg home directory is used.\n\n exclude_patterns (optional): A list of filename patterns to exclude certain\n files from being recorded as artifacts. See Config docs for details.\n\n base_path (optional): A path relative to which artifacts are recorded.\n Default is the current working directory.\n\n record_environment (optional): A boolean indicating if information about\n the environment should be added in the resulting link metadata.\n\n normalize_line_endings (optional): A boolean indicating if line endings of\n artifacts should be normalized before hashing for cross-platform\n support.\n\n lstrip_paths (optional): A list of path prefixes used to left-strip\n artifact paths before storing them in the resulting link metadata.\n\n Raises:\n securesystemslib.exceptions.FormatError: Passed arguments are malformed.\n\n ValueError: None of signing_key, gpg_keyid or gpg_use_default=True is\n passed.\n\n securesystemslib.exceptions.StorageError: Cannot hash artifacts.\n\n PrefixError: Left-stripping artifact paths results in non-unique dict keys.\n\n securesystemslib.process.subprocess.TimeoutExpired: Link command times out.\n\n IOError, PermissionError:\n Cannot write link metadata.\n\n securesystemslib.exceptions.CryptoError, securesystemslib.exceptions.UnsupportedAlgorithmError:\n Signing errors.\n\n ValueError, OSError, securesystemslib.gpg.exceptions.CommandError, securesystemslib.gpg.exceptions.KeyNotFoundError:\n gpg signing errors.\n\n Side Effects:\n Reads artifact files from disk.\n Calls system gpg in a subprocess, if a gpg key argument is passed.\n Writes preliminary link metadata file to disk.\n\n ' LOG.info("Start recording '{}'...".format(step_name)) if ((not signing_key) and (not gpg_keyid) and (not gpg_use_default)): raise ValueError('Pass either a signing key, a gpg keyid or set gpg_use_default to True!') if signing_key: _check_match_signing_key(signing_key) if gpg_keyid: securesystemslib.formats.KEYID_SCHEMA.check_match(gpg_keyid) if exclude_patterns: securesystemslib.formats.NAMES_SCHEMA.check_match(exclude_patterns) if base_path: securesystemslib.formats.PATH_SCHEMA.check_match(base_path) if material_list: LOG.info("Recording materials '{}'...".format(', '.join(material_list))) materials_dict = record_artifacts_as_dict(material_list, exclude_patterns=exclude_patterns, base_path=base_path, follow_symlink_dirs=True, normalize_line_endings=normalize_line_endings, lstrip_paths=lstrip_paths) LOG.info('Creating preliminary link metadata...') environment = {} if record_environment: environment['workdir'] = os.getcwd().replace('\\', '/') link = in_toto.models.link.Link(name=step_name, materials=materials_dict, products={}, command=[], byproducts={}, environment=environment) link_metadata = Metablock(signed=link) if signing_key: LOG.info('Signing link metadata using passed key...') signature = link_metadata.sign(signing_key) elif gpg_keyid: LOG.info('Signing link metadata using passed GPG keyid...') signature = link_metadata.sign_gpg(gpg_keyid, gpg_home=gpg_home) else: LOG.info('Signing link metadata using default GPG key ...') signature = link_metadata.sign_gpg(gpg_keyid=None, gpg_home=gpg_home) signing_keyid = signature['keyid'] unfinished_fn = UNFINISHED_FILENAME_FORMAT.format(step_name=step_name, keyid=signing_keyid) LOG.info("Storing preliminary link metadata to '{}'...".format(unfinished_fn)) link_metadata.dump(unfinished_fn)<|docstring|>Generates preliminary link metadata. Records paths and hashes of materials in a preliminary link metadata file. The metadata is signed with the passed signing_key, a gpg key identified by its ID, or the default gpg key. If multiple key arguments are passed, only one key is used in above order of precedence. At least one key argument must be passed. The resulting link file is written to ``.STEP-NAME.KEYID-PREFIX.link-unfinished``. Use this function together with in_toto_record_stop as an alternative to in_toto_run, in order to provide evidence for supply chain steps that cannot be carried out by a single command. Arguments: step_name: A unique name to associate link metadata with a step. material_list: A list of artifact paths to be recorded as materials. Directories are traversed recursively. signing_key (optional): A key used to sign the resulting link metadata. The format is securesystemslib.formats.KEY_SCHEMA. gpg_keyid (optional): A keyid used to identify a local gpg key used to sign the resulting link metadata. gpg_use_default (optional): A boolean indicating if the default gpg key should be used to sign the resulting link metadata. gpg_home (optional): A path to the gpg home directory. If not set the default gpg home directory is used. exclude_patterns (optional): A list of filename patterns to exclude certain files from being recorded as artifacts. See Config docs for details. base_path (optional): A path relative to which artifacts are recorded. Default is the current working directory. record_environment (optional): A boolean indicating if information about the environment should be added in the resulting link metadata. normalize_line_endings (optional): A boolean indicating if line endings of artifacts should be normalized before hashing for cross-platform support. lstrip_paths (optional): A list of path prefixes used to left-strip artifact paths before storing them in the resulting link metadata. Raises: securesystemslib.exceptions.FormatError: Passed arguments are malformed. ValueError: None of signing_key, gpg_keyid or gpg_use_default=True is passed. securesystemslib.exceptions.StorageError: Cannot hash artifacts. PrefixError: Left-stripping artifact paths results in non-unique dict keys. securesystemslib.process.subprocess.TimeoutExpired: Link command times out. IOError, PermissionError: Cannot write link metadata. securesystemslib.exceptions.CryptoError, securesystemslib.exceptions.UnsupportedAlgorithmError: Signing errors. ValueError, OSError, securesystemslib.gpg.exceptions.CommandError, securesystemslib.gpg.exceptions.KeyNotFoundError: gpg signing errors. Side Effects: Reads artifact files from disk. Calls system gpg in a subprocess, if a gpg key argument is passed. Writes preliminary link metadata file to disk.<|endoftext|>
716dd3a0f54efe8ea396da9780f67bb3ea3489e282c7733a51328cecd23461f0
def in_toto_record_stop(step_name, product_list, signing_key=None, gpg_keyid=None, gpg_use_default=False, gpg_home=None, exclude_patterns=None, base_path=None, normalize_line_endings=False, lstrip_paths=None, metadata_directory=None): 'Finalizes preliminary link metadata generated with in_toto_record_start.\n\n Loads preliminary link metadata file, verifies its signature, and records\n paths and hashes as products, thus finalizing the link metadata. The metadata\n is signed with the passed signing_key, a gpg key identified by its ID, or the\n default gpg key. If multiple key arguments are passed, only one key is used\n in above order of precedence. At least one key argument must be passed and it\n must be the same as the one used to sign the preliminary link metadata file.\n The resulting link file is written to ``STEP-NAME.KEYID-PREFIX.link``.\n\n Use this function together with in_toto_record_start as an alternative to\n in_toto_run, in order to provide evidence for supply chain steps that cannot\n be carried out by a single command.\n\n Arguments:\n step_name: A unique name to associate link metadata with a step.\n\n product_list: A list of artifact paths to be recorded as products.\n Directories are traversed recursively.\n\n signing_key (optional): A key used to sign the resulting link metadata. The\n format is securesystemslib.formats.KEY_SCHEMA.\n\n gpg_keyid (optional): A keyid used to identify a local gpg key used to sign\n the resulting link metadata.\n\n gpg_use_default (optional): A boolean indicating if the default gpg key\n should be used to sign the resulting link metadata.\n\n gpg_home (optional): A path to the gpg home directory. If not set the\n default gpg home directory is used.\n\n exclude_patterns (optional): A list of filename patterns to exclude certain\n files from being recorded as artifacts.\n\n base_path (optional): A path relative to which artifacts are recorded.\n Default is the current working directory.\n\n normalize_line_endings (optional): A boolean indicating if line endings of\n artifacts should be normalized before hashing for cross-platform\n support.\n\n lstrip_paths (optional): A list of path prefixes used to left-strip\n artifact paths before storing them in the resulting link metadata.\n\n metadata_directory (optional): A directory path to write the resulting link\n metadata file to. Default destination is the current working directory.\n\n Raises:\n securesystemslib.exceptions.FormatError: Passed arguments are malformed.\n\n ValueError: None of signing_key, gpg_keyid or gpg_use_default=True is\n passed.\n\n LinkNotFoundError: No preliminary link metadata file found.\n\n securesystemslib.exceptions.StorageError: Cannot hash artifacts.\n\n PrefixError: Left-stripping artifact paths results in non-unique dict keys.\n\n securesystemslib.process.subprocess.TimeoutExpired: Link command times out.\n\n IOError, FileNotFoundError, NotADirectoryError, PermissionError:\n Cannot write link metadata.\n\n securesystemslib.exceptions.CryptoError, securesystemslib.exceptions.UnsupportedAlgorithmError:\n Signing errors.\n\n ValueError, OSError, securesystemslib.gpg.exceptions.CommandError, securesystemslib.gpg.exceptions.KeyNotFoundError:\n gpg signing errors.\n\n Side Effects:\n Reads preliminary link metadata file from disk.\n Reads artifact files from disk.\n Calls system gpg in a subprocess, if a gpg key argument is passed.\n Writes resulting link metadata file to disk.\n Removes preliminary link metadata file from disk.\n\n ' LOG.info("Stop recording '{}'...".format(step_name)) if ((not signing_key) and (not gpg_keyid) and (not gpg_use_default)): raise ValueError('Pass either a signing key, a gpg keyid or set gpg_use_default to True') if signing_key: _check_match_signing_key(signing_key) if gpg_keyid: securesystemslib.formats.KEYID_SCHEMA.check_match(gpg_keyid) if exclude_patterns: securesystemslib.formats.NAMES_SCHEMA.check_match(exclude_patterns) if base_path: securesystemslib.formats.PATH_SCHEMA.check_match(base_path) if metadata_directory: securesystemslib.formats.PATH_SCHEMA.check_match(metadata_directory) if signing_key: unfinished_fn = UNFINISHED_FILENAME_FORMAT.format(step_name=step_name, keyid=signing_key['keyid']) else: unfinished_fn_glob = UNFINISHED_FILENAME_FORMAT_GLOB.format(step_name=step_name, pattern='*') unfinished_fn_list = glob.glob(unfinished_fn_glob) if (not len(unfinished_fn_list)): raise in_toto.exceptions.LinkNotFoundError("Could not find a preliminary link for step '{}' in the current working directory.".format(step_name)) if (len(unfinished_fn_list) > 1): raise in_toto.exceptions.LinkNotFoundError("Found more than one preliminary links for step '{}' in the current working directory: {}. We need exactly one to stop recording.".format(step_name, ', '.join(unfinished_fn_list))) unfinished_fn = unfinished_fn_list[0] LOG.info("Loading preliminary link metadata '{}'...".format(unfinished_fn)) link_metadata = Metablock.load(unfinished_fn) if signing_key: LOG.info('Verifying preliminary link signature using passed signing key...') keyid = signing_key['keyid'] verification_key = signing_key elif gpg_keyid: LOG.info('Verifying preliminary link signature using passed gpg key...') gpg_pubkey = securesystemslib.gpg.functions.export_pubkey(gpg_keyid, gpg_home) keyid = gpg_pubkey['keyid'] verification_key = gpg_pubkey else: LOG.info('Verifying preliminary link signature using default gpg key...') keyid = link_metadata.signatures[0]['keyid'] gpg_pubkey = securesystemslib.gpg.functions.export_pubkey(keyid, gpg_home) verification_key = gpg_pubkey link_metadata.verify_signature(verification_key) if product_list: LOG.info("Recording products '{}'...".format(', '.join(product_list))) link_metadata.signed.products = record_artifacts_as_dict(product_list, exclude_patterns=exclude_patterns, base_path=base_path, follow_symlink_dirs=True, normalize_line_endings=normalize_line_endings, lstrip_paths=lstrip_paths) link_metadata.signatures = [] if signing_key: LOG.info("Updating signature with key '{:.8}...'...".format(keyid)) link_metadata.sign(signing_key) else: LOG.info("Updating signature with gpg key '{:.8}...'...".format(keyid)) link_metadata.sign_gpg(keyid, gpg_home) fn = FILENAME_FORMAT.format(step_name=step_name, keyid=keyid) if (metadata_directory is not None): fn = os.path.join(metadata_directory, fn) LOG.info("Storing link metadata to '{}'...".format(fn)) link_metadata.dump(fn) LOG.info("Removing unfinished link metadata '{}'...".format(unfinished_fn)) os.remove(unfinished_fn)
Finalizes preliminary link metadata generated with in_toto_record_start. Loads preliminary link metadata file, verifies its signature, and records paths and hashes as products, thus finalizing the link metadata. The metadata is signed with the passed signing_key, a gpg key identified by its ID, or the default gpg key. If multiple key arguments are passed, only one key is used in above order of precedence. At least one key argument must be passed and it must be the same as the one used to sign the preliminary link metadata file. The resulting link file is written to ``STEP-NAME.KEYID-PREFIX.link``. Use this function together with in_toto_record_start as an alternative to in_toto_run, in order to provide evidence for supply chain steps that cannot be carried out by a single command. Arguments: step_name: A unique name to associate link metadata with a step. product_list: A list of artifact paths to be recorded as products. Directories are traversed recursively. signing_key (optional): A key used to sign the resulting link metadata. The format is securesystemslib.formats.KEY_SCHEMA. gpg_keyid (optional): A keyid used to identify a local gpg key used to sign the resulting link metadata. gpg_use_default (optional): A boolean indicating if the default gpg key should be used to sign the resulting link metadata. gpg_home (optional): A path to the gpg home directory. If not set the default gpg home directory is used. exclude_patterns (optional): A list of filename patterns to exclude certain files from being recorded as artifacts. base_path (optional): A path relative to which artifacts are recorded. Default is the current working directory. normalize_line_endings (optional): A boolean indicating if line endings of artifacts should be normalized before hashing for cross-platform support. lstrip_paths (optional): A list of path prefixes used to left-strip artifact paths before storing them in the resulting link metadata. metadata_directory (optional): A directory path to write the resulting link metadata file to. Default destination is the current working directory. Raises: securesystemslib.exceptions.FormatError: Passed arguments are malformed. ValueError: None of signing_key, gpg_keyid or gpg_use_default=True is passed. LinkNotFoundError: No preliminary link metadata file found. securesystemslib.exceptions.StorageError: Cannot hash artifacts. PrefixError: Left-stripping artifact paths results in non-unique dict keys. securesystemslib.process.subprocess.TimeoutExpired: Link command times out. IOError, FileNotFoundError, NotADirectoryError, PermissionError: Cannot write link metadata. securesystemslib.exceptions.CryptoError, securesystemslib.exceptions.UnsupportedAlgorithmError: Signing errors. ValueError, OSError, securesystemslib.gpg.exceptions.CommandError, securesystemslib.gpg.exceptions.KeyNotFoundError: gpg signing errors. Side Effects: Reads preliminary link metadata file from disk. Reads artifact files from disk. Calls system gpg in a subprocess, if a gpg key argument is passed. Writes resulting link metadata file to disk. Removes preliminary link metadata file from disk.
in_toto/runlib.py
in_toto_record_stop
reeeeeeem/in-toto
507
python
def in_toto_record_stop(step_name, product_list, signing_key=None, gpg_keyid=None, gpg_use_default=False, gpg_home=None, exclude_patterns=None, base_path=None, normalize_line_endings=False, lstrip_paths=None, metadata_directory=None): 'Finalizes preliminary link metadata generated with in_toto_record_start.\n\n Loads preliminary link metadata file, verifies its signature, and records\n paths and hashes as products, thus finalizing the link metadata. The metadata\n is signed with the passed signing_key, a gpg key identified by its ID, or the\n default gpg key. If multiple key arguments are passed, only one key is used\n in above order of precedence. At least one key argument must be passed and it\n must be the same as the one used to sign the preliminary link metadata file.\n The resulting link file is written to ``STEP-NAME.KEYID-PREFIX.link``.\n\n Use this function together with in_toto_record_start as an alternative to\n in_toto_run, in order to provide evidence for supply chain steps that cannot\n be carried out by a single command.\n\n Arguments:\n step_name: A unique name to associate link metadata with a step.\n\n product_list: A list of artifact paths to be recorded as products.\n Directories are traversed recursively.\n\n signing_key (optional): A key used to sign the resulting link metadata. The\n format is securesystemslib.formats.KEY_SCHEMA.\n\n gpg_keyid (optional): A keyid used to identify a local gpg key used to sign\n the resulting link metadata.\n\n gpg_use_default (optional): A boolean indicating if the default gpg key\n should be used to sign the resulting link metadata.\n\n gpg_home (optional): A path to the gpg home directory. If not set the\n default gpg home directory is used.\n\n exclude_patterns (optional): A list of filename patterns to exclude certain\n files from being recorded as artifacts.\n\n base_path (optional): A path relative to which artifacts are recorded.\n Default is the current working directory.\n\n normalize_line_endings (optional): A boolean indicating if line endings of\n artifacts should be normalized before hashing for cross-platform\n support.\n\n lstrip_paths (optional): A list of path prefixes used to left-strip\n artifact paths before storing them in the resulting link metadata.\n\n metadata_directory (optional): A directory path to write the resulting link\n metadata file to. Default destination is the current working directory.\n\n Raises:\n securesystemslib.exceptions.FormatError: Passed arguments are malformed.\n\n ValueError: None of signing_key, gpg_keyid or gpg_use_default=True is\n passed.\n\n LinkNotFoundError: No preliminary link metadata file found.\n\n securesystemslib.exceptions.StorageError: Cannot hash artifacts.\n\n PrefixError: Left-stripping artifact paths results in non-unique dict keys.\n\n securesystemslib.process.subprocess.TimeoutExpired: Link command times out.\n\n IOError, FileNotFoundError, NotADirectoryError, PermissionError:\n Cannot write link metadata.\n\n securesystemslib.exceptions.CryptoError, securesystemslib.exceptions.UnsupportedAlgorithmError:\n Signing errors.\n\n ValueError, OSError, securesystemslib.gpg.exceptions.CommandError, securesystemslib.gpg.exceptions.KeyNotFoundError:\n gpg signing errors.\n\n Side Effects:\n Reads preliminary link metadata file from disk.\n Reads artifact files from disk.\n Calls system gpg in a subprocess, if a gpg key argument is passed.\n Writes resulting link metadata file to disk.\n Removes preliminary link metadata file from disk.\n\n ' LOG.info("Stop recording '{}'...".format(step_name)) if ((not signing_key) and (not gpg_keyid) and (not gpg_use_default)): raise ValueError('Pass either a signing key, a gpg keyid or set gpg_use_default to True') if signing_key: _check_match_signing_key(signing_key) if gpg_keyid: securesystemslib.formats.KEYID_SCHEMA.check_match(gpg_keyid) if exclude_patterns: securesystemslib.formats.NAMES_SCHEMA.check_match(exclude_patterns) if base_path: securesystemslib.formats.PATH_SCHEMA.check_match(base_path) if metadata_directory: securesystemslib.formats.PATH_SCHEMA.check_match(metadata_directory) if signing_key: unfinished_fn = UNFINISHED_FILENAME_FORMAT.format(step_name=step_name, keyid=signing_key['keyid']) else: unfinished_fn_glob = UNFINISHED_FILENAME_FORMAT_GLOB.format(step_name=step_name, pattern='*') unfinished_fn_list = glob.glob(unfinished_fn_glob) if (not len(unfinished_fn_list)): raise in_toto.exceptions.LinkNotFoundError("Could not find a preliminary link for step '{}' in the current working directory.".format(step_name)) if (len(unfinished_fn_list) > 1): raise in_toto.exceptions.LinkNotFoundError("Found more than one preliminary links for step '{}' in the current working directory: {}. We need exactly one to stop recording.".format(step_name, ', '.join(unfinished_fn_list))) unfinished_fn = unfinished_fn_list[0] LOG.info("Loading preliminary link metadata '{}'...".format(unfinished_fn)) link_metadata = Metablock.load(unfinished_fn) if signing_key: LOG.info('Verifying preliminary link signature using passed signing key...') keyid = signing_key['keyid'] verification_key = signing_key elif gpg_keyid: LOG.info('Verifying preliminary link signature using passed gpg key...') gpg_pubkey = securesystemslib.gpg.functions.export_pubkey(gpg_keyid, gpg_home) keyid = gpg_pubkey['keyid'] verification_key = gpg_pubkey else: LOG.info('Verifying preliminary link signature using default gpg key...') keyid = link_metadata.signatures[0]['keyid'] gpg_pubkey = securesystemslib.gpg.functions.export_pubkey(keyid, gpg_home) verification_key = gpg_pubkey link_metadata.verify_signature(verification_key) if product_list: LOG.info("Recording products '{}'...".format(', '.join(product_list))) link_metadata.signed.products = record_artifacts_as_dict(product_list, exclude_patterns=exclude_patterns, base_path=base_path, follow_symlink_dirs=True, normalize_line_endings=normalize_line_endings, lstrip_paths=lstrip_paths) link_metadata.signatures = [] if signing_key: LOG.info("Updating signature with key '{:.8}...'...".format(keyid)) link_metadata.sign(signing_key) else: LOG.info("Updating signature with gpg key '{:.8}...'...".format(keyid)) link_metadata.sign_gpg(keyid, gpg_home) fn = FILENAME_FORMAT.format(step_name=step_name, keyid=keyid) if (metadata_directory is not None): fn = os.path.join(metadata_directory, fn) LOG.info("Storing link metadata to '{}'...".format(fn)) link_metadata.dump(fn) LOG.info("Removing unfinished link metadata '{}'...".format(unfinished_fn)) os.remove(unfinished_fn)
def in_toto_record_stop(step_name, product_list, signing_key=None, gpg_keyid=None, gpg_use_default=False, gpg_home=None, exclude_patterns=None, base_path=None, normalize_line_endings=False, lstrip_paths=None, metadata_directory=None): 'Finalizes preliminary link metadata generated with in_toto_record_start.\n\n Loads preliminary link metadata file, verifies its signature, and records\n paths and hashes as products, thus finalizing the link metadata. The metadata\n is signed with the passed signing_key, a gpg key identified by its ID, or the\n default gpg key. If multiple key arguments are passed, only one key is used\n in above order of precedence. At least one key argument must be passed and it\n must be the same as the one used to sign the preliminary link metadata file.\n The resulting link file is written to ``STEP-NAME.KEYID-PREFIX.link``.\n\n Use this function together with in_toto_record_start as an alternative to\n in_toto_run, in order to provide evidence for supply chain steps that cannot\n be carried out by a single command.\n\n Arguments:\n step_name: A unique name to associate link metadata with a step.\n\n product_list: A list of artifact paths to be recorded as products.\n Directories are traversed recursively.\n\n signing_key (optional): A key used to sign the resulting link metadata. The\n format is securesystemslib.formats.KEY_SCHEMA.\n\n gpg_keyid (optional): A keyid used to identify a local gpg key used to sign\n the resulting link metadata.\n\n gpg_use_default (optional): A boolean indicating if the default gpg key\n should be used to sign the resulting link metadata.\n\n gpg_home (optional): A path to the gpg home directory. If not set the\n default gpg home directory is used.\n\n exclude_patterns (optional): A list of filename patterns to exclude certain\n files from being recorded as artifacts.\n\n base_path (optional): A path relative to which artifacts are recorded.\n Default is the current working directory.\n\n normalize_line_endings (optional): A boolean indicating if line endings of\n artifacts should be normalized before hashing for cross-platform\n support.\n\n lstrip_paths (optional): A list of path prefixes used to left-strip\n artifact paths before storing them in the resulting link metadata.\n\n metadata_directory (optional): A directory path to write the resulting link\n metadata file to. Default destination is the current working directory.\n\n Raises:\n securesystemslib.exceptions.FormatError: Passed arguments are malformed.\n\n ValueError: None of signing_key, gpg_keyid or gpg_use_default=True is\n passed.\n\n LinkNotFoundError: No preliminary link metadata file found.\n\n securesystemslib.exceptions.StorageError: Cannot hash artifacts.\n\n PrefixError: Left-stripping artifact paths results in non-unique dict keys.\n\n securesystemslib.process.subprocess.TimeoutExpired: Link command times out.\n\n IOError, FileNotFoundError, NotADirectoryError, PermissionError:\n Cannot write link metadata.\n\n securesystemslib.exceptions.CryptoError, securesystemslib.exceptions.UnsupportedAlgorithmError:\n Signing errors.\n\n ValueError, OSError, securesystemslib.gpg.exceptions.CommandError, securesystemslib.gpg.exceptions.KeyNotFoundError:\n gpg signing errors.\n\n Side Effects:\n Reads preliminary link metadata file from disk.\n Reads artifact files from disk.\n Calls system gpg in a subprocess, if a gpg key argument is passed.\n Writes resulting link metadata file to disk.\n Removes preliminary link metadata file from disk.\n\n ' LOG.info("Stop recording '{}'...".format(step_name)) if ((not signing_key) and (not gpg_keyid) and (not gpg_use_default)): raise ValueError('Pass either a signing key, a gpg keyid or set gpg_use_default to True') if signing_key: _check_match_signing_key(signing_key) if gpg_keyid: securesystemslib.formats.KEYID_SCHEMA.check_match(gpg_keyid) if exclude_patterns: securesystemslib.formats.NAMES_SCHEMA.check_match(exclude_patterns) if base_path: securesystemslib.formats.PATH_SCHEMA.check_match(base_path) if metadata_directory: securesystemslib.formats.PATH_SCHEMA.check_match(metadata_directory) if signing_key: unfinished_fn = UNFINISHED_FILENAME_FORMAT.format(step_name=step_name, keyid=signing_key['keyid']) else: unfinished_fn_glob = UNFINISHED_FILENAME_FORMAT_GLOB.format(step_name=step_name, pattern='*') unfinished_fn_list = glob.glob(unfinished_fn_glob) if (not len(unfinished_fn_list)): raise in_toto.exceptions.LinkNotFoundError("Could not find a preliminary link for step '{}' in the current working directory.".format(step_name)) if (len(unfinished_fn_list) > 1): raise in_toto.exceptions.LinkNotFoundError("Found more than one preliminary links for step '{}' in the current working directory: {}. We need exactly one to stop recording.".format(step_name, ', '.join(unfinished_fn_list))) unfinished_fn = unfinished_fn_list[0] LOG.info("Loading preliminary link metadata '{}'...".format(unfinished_fn)) link_metadata = Metablock.load(unfinished_fn) if signing_key: LOG.info('Verifying preliminary link signature using passed signing key...') keyid = signing_key['keyid'] verification_key = signing_key elif gpg_keyid: LOG.info('Verifying preliminary link signature using passed gpg key...') gpg_pubkey = securesystemslib.gpg.functions.export_pubkey(gpg_keyid, gpg_home) keyid = gpg_pubkey['keyid'] verification_key = gpg_pubkey else: LOG.info('Verifying preliminary link signature using default gpg key...') keyid = link_metadata.signatures[0]['keyid'] gpg_pubkey = securesystemslib.gpg.functions.export_pubkey(keyid, gpg_home) verification_key = gpg_pubkey link_metadata.verify_signature(verification_key) if product_list: LOG.info("Recording products '{}'...".format(', '.join(product_list))) link_metadata.signed.products = record_artifacts_as_dict(product_list, exclude_patterns=exclude_patterns, base_path=base_path, follow_symlink_dirs=True, normalize_line_endings=normalize_line_endings, lstrip_paths=lstrip_paths) link_metadata.signatures = [] if signing_key: LOG.info("Updating signature with key '{:.8}...'...".format(keyid)) link_metadata.sign(signing_key) else: LOG.info("Updating signature with gpg key '{:.8}...'...".format(keyid)) link_metadata.sign_gpg(keyid, gpg_home) fn = FILENAME_FORMAT.format(step_name=step_name, keyid=keyid) if (metadata_directory is not None): fn = os.path.join(metadata_directory, fn) LOG.info("Storing link metadata to '{}'...".format(fn)) link_metadata.dump(fn) LOG.info("Removing unfinished link metadata '{}'...".format(unfinished_fn)) os.remove(unfinished_fn)<|docstring|>Finalizes preliminary link metadata generated with in_toto_record_start. Loads preliminary link metadata file, verifies its signature, and records paths and hashes as products, thus finalizing the link metadata. The metadata is signed with the passed signing_key, a gpg key identified by its ID, or the default gpg key. If multiple key arguments are passed, only one key is used in above order of precedence. At least one key argument must be passed and it must be the same as the one used to sign the preliminary link metadata file. The resulting link file is written to ``STEP-NAME.KEYID-PREFIX.link``. Use this function together with in_toto_record_start as an alternative to in_toto_run, in order to provide evidence for supply chain steps that cannot be carried out by a single command. Arguments: step_name: A unique name to associate link metadata with a step. product_list: A list of artifact paths to be recorded as products. Directories are traversed recursively. signing_key (optional): A key used to sign the resulting link metadata. The format is securesystemslib.formats.KEY_SCHEMA. gpg_keyid (optional): A keyid used to identify a local gpg key used to sign the resulting link metadata. gpg_use_default (optional): A boolean indicating if the default gpg key should be used to sign the resulting link metadata. gpg_home (optional): A path to the gpg home directory. If not set the default gpg home directory is used. exclude_patterns (optional): A list of filename patterns to exclude certain files from being recorded as artifacts. base_path (optional): A path relative to which artifacts are recorded. Default is the current working directory. normalize_line_endings (optional): A boolean indicating if line endings of artifacts should be normalized before hashing for cross-platform support. lstrip_paths (optional): A list of path prefixes used to left-strip artifact paths before storing them in the resulting link metadata. metadata_directory (optional): A directory path to write the resulting link metadata file to. Default destination is the current working directory. Raises: securesystemslib.exceptions.FormatError: Passed arguments are malformed. ValueError: None of signing_key, gpg_keyid or gpg_use_default=True is passed. LinkNotFoundError: No preliminary link metadata file found. securesystemslib.exceptions.StorageError: Cannot hash artifacts. PrefixError: Left-stripping artifact paths results in non-unique dict keys. securesystemslib.process.subprocess.TimeoutExpired: Link command times out. IOError, FileNotFoundError, NotADirectoryError, PermissionError: Cannot write link metadata. securesystemslib.exceptions.CryptoError, securesystemslib.exceptions.UnsupportedAlgorithmError: Signing errors. ValueError, OSError, securesystemslib.gpg.exceptions.CommandError, securesystemslib.gpg.exceptions.KeyNotFoundError: gpg signing errors. Side Effects: Reads preliminary link metadata file from disk. Reads artifact files from disk. Calls system gpg in a subprocess, if a gpg key argument is passed. Writes resulting link metadata file to disk. Removes preliminary link metadata file from disk.<|endoftext|>
af46b1de7d497263550fef07bae567313a87626c1757ffe292bf3ecdb277d59d
def is_good_license(detected_license): '\n Return True if a `detected license` mapping is consider to a high quality\n conclusive match.\n ' score = detected_license['score'] rule = detected_license['matched_rule'] coverage = (rule.get('match_coverage') or 0) relevance = (rule.get('rule_relevance') or 0) match_types = dict([('is_license_text', rule['is_license_text']), ('is_license_notice', rule['is_license_notice']), ('is_license_reference', rule['is_license_reference']), ('is_license_tag', rule['is_license_tag']), ('is_license_intro', rule['is_license_intro'])]) matched = False for (match_type, mval) in match_types.items(): if mval: matched = True break if (not matched): return False thresholds = FILTERS[match_type] if ((not coverage) or (not relevance)): if (score >= thresholds.min_score): return True elif ((score >= thresholds.min_score) and (coverage >= thresholds.min_coverage) and (relevance >= thresholds.min_relevance)): return True return False
Return True if a `detected license` mapping is consider to a high quality conclusive match.
src/summarycode/score.py
is_good_license
alec-z/zhangfei
1,511
python
def is_good_license(detected_license): '\n Return True if a `detected license` mapping is consider to a high quality\n conclusive match.\n ' score = detected_license['score'] rule = detected_license['matched_rule'] coverage = (rule.get('match_coverage') or 0) relevance = (rule.get('rule_relevance') or 0) match_types = dict([('is_license_text', rule['is_license_text']), ('is_license_notice', rule['is_license_notice']), ('is_license_reference', rule['is_license_reference']), ('is_license_tag', rule['is_license_tag']), ('is_license_intro', rule['is_license_intro'])]) matched = False for (match_type, mval) in match_types.items(): if mval: matched = True break if (not matched): return False thresholds = FILTERS[match_type] if ((not coverage) or (not relevance)): if (score >= thresholds.min_score): return True elif ((score >= thresholds.min_score) and (coverage >= thresholds.min_coverage) and (relevance >= thresholds.min_relevance)): return True return False
def is_good_license(detected_license): '\n Return True if a `detected license` mapping is consider to a high quality\n conclusive match.\n ' score = detected_license['score'] rule = detected_license['matched_rule'] coverage = (rule.get('match_coverage') or 0) relevance = (rule.get('rule_relevance') or 0) match_types = dict([('is_license_text', rule['is_license_text']), ('is_license_notice', rule['is_license_notice']), ('is_license_reference', rule['is_license_reference']), ('is_license_tag', rule['is_license_tag']), ('is_license_intro', rule['is_license_intro'])]) matched = False for (match_type, mval) in match_types.items(): if mval: matched = True break if (not matched): return False thresholds = FILTERS[match_type] if ((not coverage) or (not relevance)): if (score >= thresholds.min_score): return True elif ((score >= thresholds.min_score) and (coverage >= thresholds.min_coverage) and (relevance >= thresholds.min_relevance)): return True return False<|docstring|>Return True if a `detected license` mapping is consider to a high quality conclusive match.<|endoftext|>
b0673290ca73811c77e545f0b78c064a441bd9201cae6133b7bb44e2561cf927
def compute_license_score(codebase): '\n Return a mapping of scoring elements and a license clarity score computed at\n the codebase level.\n ' score = 0 scoring_elements = dict(score=score) for element in SCORING_ELEMENTS: element_score = element.scorer(codebase) if element.is_binary: scoring_elements[element.name] = bool(element_score) element_score = (1 if element_score else 0) else: scoring_elements[element.name] = (round(element_score, 2) or 0) score += int((element_score * element.weight)) if TRACE: logger_debug('compute_license_score: element:', element, 'element_score: ', element_score, ' new score:', score) scoring_elements['score'] = (score or 0) return scoring_elements
Return a mapping of scoring elements and a license clarity score computed at the codebase level.
src/summarycode/score.py
compute_license_score
alec-z/zhangfei
1,511
python
def compute_license_score(codebase): '\n Return a mapping of scoring elements and a license clarity score computed at\n the codebase level.\n ' score = 0 scoring_elements = dict(score=score) for element in SCORING_ELEMENTS: element_score = element.scorer(codebase) if element.is_binary: scoring_elements[element.name] = bool(element_score) element_score = (1 if element_score else 0) else: scoring_elements[element.name] = (round(element_score, 2) or 0) score += int((element_score * element.weight)) if TRACE: logger_debug('compute_license_score: element:', element, 'element_score: ', element_score, ' new score:', score) scoring_elements['score'] = (score or 0) return scoring_elements
def compute_license_score(codebase): '\n Return a mapping of scoring elements and a license clarity score computed at\n the codebase level.\n ' score = 0 scoring_elements = dict(score=score) for element in SCORING_ELEMENTS: element_score = element.scorer(codebase) if element.is_binary: scoring_elements[element.name] = bool(element_score) element_score = (1 if element_score else 0) else: scoring_elements[element.name] = (round(element_score, 2) or 0) score += int((element_score * element.weight)) if TRACE: logger_debug('compute_license_score: element:', element, 'element_score: ', element_score, ' new score:', score) scoring_elements['score'] = (score or 0) return scoring_elements<|docstring|>Return a mapping of scoring elements and a license clarity score computed at the codebase level.<|endoftext|>
8fbcc1266910069f1115f0ac1e51e67c15ddbc1f1c775f9d18cf0704ec7c3b50
def get_declared_license_keys(codebase): '\n Return a list of declared license keys found in packages and key files.\n ' return (get_declared_license_keys_in_key_files(codebase) + get_declared_license_keys_in_packages(codebase))
Return a list of declared license keys found in packages and key files.
src/summarycode/score.py
get_declared_license_keys
alec-z/zhangfei
1,511
python
def get_declared_license_keys(codebase): '\n \n ' return (get_declared_license_keys_in_key_files(codebase) + get_declared_license_keys_in_packages(codebase))
def get_declared_license_keys(codebase): '\n \n ' return (get_declared_license_keys_in_key_files(codebase) + get_declared_license_keys_in_packages(codebase))<|docstring|>Return a list of declared license keys found in packages and key files.<|endoftext|>
11d737c81053dbd01b7658dd3757701d197a6cad7b8b5d756c367f7dcfa13586
def get_declared_license_keys_in_packages(codebase): '\n Return a list of declared license keys found in packages.\n\n A package manifest (such as Maven POM file or an npm package.json file)\n contains structured declared license information. This is further normalized\n as a license_expression. We extract the list of licenses from the normalized\n license expressions.\n ' packages = chain.from_iterable(((getattr(res, 'packages', []) or []) for res in codebase.walk(topdown=True))) licensing = Licensing() detected_good_licenses = [] for package in packages: expression = package.get('license_expression') if expression: exp = licensing.parse(expression, validate=False, strict=False, simple=True) keys = licensing.license_keys(exp, unique=True) detected_good_licenses.extend(keys) return detected_good_licenses
Return a list of declared license keys found in packages. A package manifest (such as Maven POM file or an npm package.json file) contains structured declared license information. This is further normalized as a license_expression. We extract the list of licenses from the normalized license expressions.
src/summarycode/score.py
get_declared_license_keys_in_packages
alec-z/zhangfei
1,511
python
def get_declared_license_keys_in_packages(codebase): '\n Return a list of declared license keys found in packages.\n\n A package manifest (such as Maven POM file or an npm package.json file)\n contains structured declared license information. This is further normalized\n as a license_expression. We extract the list of licenses from the normalized\n license expressions.\n ' packages = chain.from_iterable(((getattr(res, 'packages', []) or []) for res in codebase.walk(topdown=True))) licensing = Licensing() detected_good_licenses = [] for package in packages: expression = package.get('license_expression') if expression: exp = licensing.parse(expression, validate=False, strict=False, simple=True) keys = licensing.license_keys(exp, unique=True) detected_good_licenses.extend(keys) return detected_good_licenses
def get_declared_license_keys_in_packages(codebase): '\n Return a list of declared license keys found in packages.\n\n A package manifest (such as Maven POM file or an npm package.json file)\n contains structured declared license information. This is further normalized\n as a license_expression. We extract the list of licenses from the normalized\n license expressions.\n ' packages = chain.from_iterable(((getattr(res, 'packages', []) or []) for res in codebase.walk(topdown=True))) licensing = Licensing() detected_good_licenses = [] for package in packages: expression = package.get('license_expression') if expression: exp = licensing.parse(expression, validate=False, strict=False, simple=True) keys = licensing.license_keys(exp, unique=True) detected_good_licenses.extend(keys) return detected_good_licenses<|docstring|>Return a list of declared license keys found in packages. A package manifest (such as Maven POM file or an npm package.json file) contains structured declared license information. This is further normalized as a license_expression. We extract the list of licenses from the normalized license expressions.<|endoftext|>
f806372b745aa0a836e5b7b0f3a8adc69760cfc96c28abbaa2ae288aea96be5d
def get_declared_license_keys_in_key_files(codebase): '\n Return a list of "declared" license keys from the expressions as detected in\n key files.\n\n A project has specific key file(s) at the top level of its code hierarchy\n such as LICENSE, NOTICE or similar (and/or a package manifest) containing\n structured license information such as an SPDX license expression or SPDX\n license identifier: when such a file contains "clearly defined" declared\n license information, we return this.\n\n Note: this ignores facets.\n ' declared = [] for resource in codebase.walk(topdown=True): if (not resource.is_key_file): continue for detected_license in (getattr(resource, 'licenses', []) or []): if (not is_good_license(detected_license)): declared.append('unknown') else: declared.append(detected_license['key']) return declared
Return a list of "declared" license keys from the expressions as detected in key files. A project has specific key file(s) at the top level of its code hierarchy such as LICENSE, NOTICE or similar (and/or a package manifest) containing structured license information such as an SPDX license expression or SPDX license identifier: when such a file contains "clearly defined" declared license information, we return this. Note: this ignores facets.
src/summarycode/score.py
get_declared_license_keys_in_key_files
alec-z/zhangfei
1,511
python
def get_declared_license_keys_in_key_files(codebase): '\n Return a list of "declared" license keys from the expressions as detected in\n key files.\n\n A project has specific key file(s) at the top level of its code hierarchy\n such as LICENSE, NOTICE or similar (and/or a package manifest) containing\n structured license information such as an SPDX license expression or SPDX\n license identifier: when such a file contains "clearly defined" declared\n license information, we return this.\n\n Note: this ignores facets.\n ' declared = [] for resource in codebase.walk(topdown=True): if (not resource.is_key_file): continue for detected_license in (getattr(resource, 'licenses', []) or []): if (not is_good_license(detected_license)): declared.append('unknown') else: declared.append(detected_license['key']) return declared
def get_declared_license_keys_in_key_files(codebase): '\n Return a list of "declared" license keys from the expressions as detected in\n key files.\n\n A project has specific key file(s) at the top level of its code hierarchy\n such as LICENSE, NOTICE or similar (and/or a package manifest) containing\n structured license information such as an SPDX license expression or SPDX\n license identifier: when such a file contains "clearly defined" declared\n license information, we return this.\n\n Note: this ignores facets.\n ' declared = [] for resource in codebase.walk(topdown=True): if (not resource.is_key_file): continue for detected_license in (getattr(resource, 'licenses', []) or []): if (not is_good_license(detected_license)): declared.append('unknown') else: declared.append(detected_license['key']) return declared<|docstring|>Return a list of "declared" license keys from the expressions as detected in key files. A project has specific key file(s) at the top level of its code hierarchy such as LICENSE, NOTICE or similar (and/or a package manifest) containing structured license information such as an SPDX license expression or SPDX license identifier: when such a file contains "clearly defined" declared license information, we return this. Note: this ignores facets.<|endoftext|>
cd62a2ea6d9d22683e6cb6a7957db496d44e95954a0c21b37be673a43983c0b7
def is_core_facet(resource, core_facet=facet.FACET_CORE): '\n Return True if the resource is in the core facet.\n If we do not have facets, everything is considered as being core by default.\n ' has_facets = hasattr(resource, 'facets') if (not has_facets): return True return ((not resource.facets) or (core_facet in resource.facets))
Return True if the resource is in the core facet. If we do not have facets, everything is considered as being core by default.
src/summarycode/score.py
is_core_facet
alec-z/zhangfei
1,511
python
def is_core_facet(resource, core_facet=facet.FACET_CORE): '\n Return True if the resource is in the core facet.\n If we do not have facets, everything is considered as being core by default.\n ' has_facets = hasattr(resource, 'facets') if (not has_facets): return True return ((not resource.facets) or (core_facet in resource.facets))
def is_core_facet(resource, core_facet=facet.FACET_CORE): '\n Return True if the resource is in the core facet.\n If we do not have facets, everything is considered as being core by default.\n ' has_facets = hasattr(resource, 'facets') if (not has_facets): return True return ((not resource.facets) or (core_facet in resource.facets))<|docstring|>Return True if the resource is in the core facet. If we do not have facets, everything is considered as being core by default.<|endoftext|>
d01d33bc9b8166bd10a9f9dc19bce68e78dd9d2c861f25f1f1d5eb7c6b2be25d
def has_good_licenses(resource): '\n Return True if a Resource licenses are all detected as a "good license"\n detection-wise.\n ' licenses = (getattr(resource, 'licenses', []) or []) if (not licenses): return False for detected_license in licenses: if (not is_good_license(detected_license)): return False if is_unknown_license(detected_license['key']): return False return True
Return True if a Resource licenses are all detected as a "good license" detection-wise.
src/summarycode/score.py
has_good_licenses
alec-z/zhangfei
1,511
python
def has_good_licenses(resource): '\n Return True if a Resource licenses are all detected as a "good license"\n detection-wise.\n ' licenses = (getattr(resource, 'licenses', []) or []) if (not licenses): return False for detected_license in licenses: if (not is_good_license(detected_license)): return False if is_unknown_license(detected_license['key']): return False return True
def has_good_licenses(resource): '\n Return True if a Resource licenses are all detected as a "good license"\n detection-wise.\n ' licenses = (getattr(resource, 'licenses', []) or []) if (not licenses): return False for detected_license in licenses: if (not is_good_license(detected_license)): return False if is_unknown_license(detected_license['key']): return False return True<|docstring|>Return True if a Resource licenses are all detected as a "good license" detection-wise.<|endoftext|>
615e8c95e88e25f77fc3430c183aa565ccd96cf4ab9c383c50f2f8314631658f
def is_unknown_license(lic_key): '\n Return True if a license key is for some lesser known or unknown license.\n ' return (lic_key.startswith(('unknown', 'other-')) or ('unknown' in lic_key))
Return True if a license key is for some lesser known or unknown license.
src/summarycode/score.py
is_unknown_license
alec-z/zhangfei
1,511
python
def is_unknown_license(lic_key): '\n \n ' return (lic_key.startswith(('unknown', 'other-')) or ('unknown' in lic_key))
def is_unknown_license(lic_key): '\n \n ' return (lic_key.startswith(('unknown', 'other-')) or ('unknown' in lic_key))<|docstring|>Return True if a license key is for some lesser known or unknown license.<|endoftext|>
77755f5950ebd70a4e3fcd742db041300c18d0b3943ad5b7a793354b5a203f1f
def has_unkown_licenses(resource): '\n Return True if some Resource licenses are unknown.\n ' return (not any((is_unknown_license(lic['key']) for lic in (getattr(resource, 'licenses', []) or []))))
Return True if some Resource licenses are unknown.
src/summarycode/score.py
has_unkown_licenses
alec-z/zhangfei
1,511
python
def has_unkown_licenses(resource): '\n \n ' return (not any((is_unknown_license(lic['key']) for lic in (getattr(resource, 'licenses', []) or []))))
def has_unkown_licenses(resource): '\n \n ' return (not any((is_unknown_license(lic['key']) for lic in (getattr(resource, 'licenses', []) or []))))<|docstring|>Return True if some Resource licenses are unknown.<|endoftext|>
adfdc1bf3d09ea227fff8ca0e926914978c322d94a2ab0a38a4ab44aa39ebc9f
def get_spdx_keys(): '\n Return a set of ScanCode license keys for licenses that are listed in SPDX.\n ' global _spdx_keys if (not _spdx_keys): _spdx_keys = frozenset(models.get_all_spdx_keys(get_licenses_db())) return _spdx_keys
Return a set of ScanCode license keys for licenses that are listed in SPDX.
src/summarycode/score.py
get_spdx_keys
alec-z/zhangfei
1,511
python
def get_spdx_keys(): '\n \n ' global _spdx_keys if (not _spdx_keys): _spdx_keys = frozenset(models.get_all_spdx_keys(get_licenses_db())) return _spdx_keys
def get_spdx_keys(): '\n \n ' global _spdx_keys if (not _spdx_keys): _spdx_keys = frozenset(models.get_all_spdx_keys(get_licenses_db())) return _spdx_keys<|docstring|>Return a set of ScanCode license keys for licenses that are listed in SPDX.<|endoftext|>
4bb0f39bc4c38dbd369852193f624beb0e287a1f3e920e771d74f65fbd63f701
def is_using_only_spdx_licenses(codebase): '\n Return True if all file-level detected licenses are SPDX licenses.\n ' licenses = chain.from_iterable((res.licenses for res in codebase.walk() if res.is_file)) keys = set((l['key'] for l in licenses)) spdx_keys = get_spdx_keys() return (keys and spdx_keys and all(((k in spdx_keys) for k in keys)))
Return True if all file-level detected licenses are SPDX licenses.
src/summarycode/score.py
is_using_only_spdx_licenses
alec-z/zhangfei
1,511
python
def is_using_only_spdx_licenses(codebase): '\n \n ' licenses = chain.from_iterable((res.licenses for res in codebase.walk() if res.is_file)) keys = set((l['key'] for l in licenses)) spdx_keys = get_spdx_keys() return (keys and spdx_keys and all(((k in spdx_keys) for k in keys)))
def is_using_only_spdx_licenses(codebase): '\n \n ' licenses = chain.from_iterable((res.licenses for res in codebase.walk() if res.is_file)) keys = set((l['key'] for l in licenses)) spdx_keys = get_spdx_keys() return (keys and spdx_keys and all(((k in spdx_keys) for k in keys)))<|docstring|>Return True if all file-level detected licenses are SPDX licenses.<|endoftext|>
f6c62a2345f0f6e24bbf9f2f839d82024e0578425915487e29676781ea2f0990
def has_consistent_key_and_file_level_licenses(codebase): '\n Return True if the file-level licenses are consistent with top level key\n files licenses.\n ' (key_files_licenses, other_files_licenses) = get_unique_licenses(codebase) if (key_files_licenses and (key_files_licenses == other_files_licenses) and (not any((is_unknown_license(l) for l in key_files_licenses)))): return True else: return False
Return True if the file-level licenses are consistent with top level key files licenses.
src/summarycode/score.py
has_consistent_key_and_file_level_licenses
alec-z/zhangfei
1,511
python
def has_consistent_key_and_file_level_licenses(codebase): '\n Return True if the file-level licenses are consistent with top level key\n files licenses.\n ' (key_files_licenses, other_files_licenses) = get_unique_licenses(codebase) if (key_files_licenses and (key_files_licenses == other_files_licenses) and (not any((is_unknown_license(l) for l in key_files_licenses)))): return True else: return False
def has_consistent_key_and_file_level_licenses(codebase): '\n Return True if the file-level licenses are consistent with top level key\n files licenses.\n ' (key_files_licenses, other_files_licenses) = get_unique_licenses(codebase) if (key_files_licenses and (key_files_licenses == other_files_licenses) and (not any((is_unknown_license(l) for l in key_files_licenses)))): return True else: return False<|docstring|>Return True if the file-level licenses are consistent with top level key files licenses.<|endoftext|>
338513f3ab8eb7cdcecc1883bbab4dec2ff2c45bb84c916aebbf5e2a3b075d68
def get_unique_licenses(codebase, good_only=True): '\n Return a tuple of two sets of license keys found in the codebase:\n - the set license found in key files\n - the set license found in non-key files\n\n This is only for files in the core facet.\n ' key_license_keys = set() other_license_keys = set() for resource in codebase.walk(): if (not resource.is_file): continue if (not (resource.is_key_file or is_core_facet(resource))): continue if resource.is_key_file: license_keys = key_license_keys else: license_keys = other_license_keys for detected_license in (getattr(resource, 'licenses', []) or []): if (good_only and (not is_good_license(detected_license))): license_keys.add('unknown') else: license_keys.add(detected_license['key']) return (key_license_keys, other_license_keys)
Return a tuple of two sets of license keys found in the codebase: - the set license found in key files - the set license found in non-key files This is only for files in the core facet.
src/summarycode/score.py
get_unique_licenses
alec-z/zhangfei
1,511
python
def get_unique_licenses(codebase, good_only=True): '\n Return a tuple of two sets of license keys found in the codebase:\n - the set license found in key files\n - the set license found in non-key files\n\n This is only for files in the core facet.\n ' key_license_keys = set() other_license_keys = set() for resource in codebase.walk(): if (not resource.is_file): continue if (not (resource.is_key_file or is_core_facet(resource))): continue if resource.is_key_file: license_keys = key_license_keys else: license_keys = other_license_keys for detected_license in (getattr(resource, 'licenses', []) or []): if (good_only and (not is_good_license(detected_license))): license_keys.add('unknown') else: license_keys.add(detected_license['key']) return (key_license_keys, other_license_keys)
def get_unique_licenses(codebase, good_only=True): '\n Return a tuple of two sets of license keys found in the codebase:\n - the set license found in key files\n - the set license found in non-key files\n\n This is only for files in the core facet.\n ' key_license_keys = set() other_license_keys = set() for resource in codebase.walk(): if (not resource.is_file): continue if (not (resource.is_key_file or is_core_facet(resource))): continue if resource.is_key_file: license_keys = key_license_keys else: license_keys = other_license_keys for detected_license in (getattr(resource, 'licenses', []) or []): if (good_only and (not is_good_license(detected_license))): license_keys.add('unknown') else: license_keys.add(detected_license['key']) return (key_license_keys, other_license_keys)<|docstring|>Return a tuple of two sets of license keys found in the codebase: - the set license found in key files - the set license found in non-key files This is only for files in the core facet.<|endoftext|>
e364ea57f3f7a763a22632276e1146d7da353a7acafad3c2d6a22c6bac181a4b
def get_detected_license_keys_with_full_text(codebase, key_files_only=False, good_only=True): '\n Return a set of license keys for which at least one detection includes the\n full license text.\n\n This is for any files in the core facet or not.\n ' license_keys = set() for resource in codebase.walk(): if (not resource.is_file): continue if (key_files_only and (not resource.is_key_file)): continue for detected_license in (getattr(resource, 'licenses', []) or []): if (good_only and (not is_good_license(detected_license))): continue if detected_license['matched_rule']['is_license_text']: license_keys.add(detected_license['key']) return license_keys
Return a set of license keys for which at least one detection includes the full license text. This is for any files in the core facet or not.
src/summarycode/score.py
get_detected_license_keys_with_full_text
alec-z/zhangfei
1,511
python
def get_detected_license_keys_with_full_text(codebase, key_files_only=False, good_only=True): '\n Return a set of license keys for which at least one detection includes the\n full license text.\n\n This is for any files in the core facet or not.\n ' license_keys = set() for resource in codebase.walk(): if (not resource.is_file): continue if (key_files_only and (not resource.is_key_file)): continue for detected_license in (getattr(resource, 'licenses', []) or []): if (good_only and (not is_good_license(detected_license))): continue if detected_license['matched_rule']['is_license_text']: license_keys.add(detected_license['key']) return license_keys
def get_detected_license_keys_with_full_text(codebase, key_files_only=False, good_only=True): '\n Return a set of license keys for which at least one detection includes the\n full license text.\n\n This is for any files in the core facet or not.\n ' license_keys = set() for resource in codebase.walk(): if (not resource.is_file): continue if (key_files_only and (not resource.is_key_file)): continue for detected_license in (getattr(resource, 'licenses', []) or []): if (good_only and (not is_good_license(detected_license))): continue if detected_license['matched_rule']['is_license_text']: license_keys.add(detected_license['key']) return license_keys<|docstring|>Return a set of license keys for which at least one detection includes the full license text. This is for any files in the core facet or not.<|endoftext|>
398e111ab26af22da8fb6a72532addbb23c0d51c8aabc63a83d54698c95b3394
def has_full_text_in_key_files_for_all_licenses(codebase): '\n Return True if the full text of all licenses is preset in the codebase key,\n top level files.\n ' return _has_full_text(codebase, key_files_only=True)
Return True if the full text of all licenses is preset in the codebase key, top level files.
src/summarycode/score.py
has_full_text_in_key_files_for_all_licenses
alec-z/zhangfei
1,511
python
def has_full_text_in_key_files_for_all_licenses(codebase): '\n Return True if the full text of all licenses is preset in the codebase key,\n top level files.\n ' return _has_full_text(codebase, key_files_only=True)
def has_full_text_in_key_files_for_all_licenses(codebase): '\n Return True if the full text of all licenses is preset in the codebase key,\n top level files.\n ' return _has_full_text(codebase, key_files_only=True)<|docstring|>Return True if the full text of all licenses is preset in the codebase key, top level files.<|endoftext|>
545b30f3ecec088ae89336afa3fa051436c82b72beafd2d9a35a7e1bc348c041
def has_full_text_for_all_licenses(codebase): '\n Return True if the full text of all licenses is preset in the codebase.\n ' return _has_full_text(codebase, key_files_only=False)
Return True if the full text of all licenses is preset in the codebase.
src/summarycode/score.py
has_full_text_for_all_licenses
alec-z/zhangfei
1,511
python
def has_full_text_for_all_licenses(codebase): '\n \n ' return _has_full_text(codebase, key_files_only=False)
def has_full_text_for_all_licenses(codebase): '\n \n ' return _has_full_text(codebase, key_files_only=False)<|docstring|>Return True if the full text of all licenses is preset in the codebase.<|endoftext|>
4f957e6720871ff8d748195edc2a5748aad1e535908cb84fbee921cb05cea8fc
def _has_full_text(codebase, key_files_only=False): '\n Return True if the full text of all licenses is preset in the codebase.\n Consider only key files if key_files_only is True.\n ' (key_files_licenses, other_files_licenses) = get_unique_licenses(codebase, good_only=False) if TRACE: logger_debug('_has_full_text: key_files_licenses:', key_files_licenses, 'other_files_licenses:', other_files_licenses) all_keys = (key_files_licenses | other_files_licenses) if (not all_keys): return False if TRACE: logger_debug('_has_full_text: all_keys:', all_keys) keys_with_license_text = get_detected_license_keys_with_full_text(codebase, key_files_only, good_only=False) if TRACE: logger_debug('_has_full_text: keys_with_license_text:', keys_with_license_text) logger_debug('_has_full_text: all_keys == keys_with_license_text:', (all_keys == keys_with_license_text)) return (all_keys == keys_with_license_text)
Return True if the full text of all licenses is preset in the codebase. Consider only key files if key_files_only is True.
src/summarycode/score.py
_has_full_text
alec-z/zhangfei
1,511
python
def _has_full_text(codebase, key_files_only=False): '\n Return True if the full text of all licenses is preset in the codebase.\n Consider only key files if key_files_only is True.\n ' (key_files_licenses, other_files_licenses) = get_unique_licenses(codebase, good_only=False) if TRACE: logger_debug('_has_full_text: key_files_licenses:', key_files_licenses, 'other_files_licenses:', other_files_licenses) all_keys = (key_files_licenses | other_files_licenses) if (not all_keys): return False if TRACE: logger_debug('_has_full_text: all_keys:', all_keys) keys_with_license_text = get_detected_license_keys_with_full_text(codebase, key_files_only, good_only=False) if TRACE: logger_debug('_has_full_text: keys_with_license_text:', keys_with_license_text) logger_debug('_has_full_text: all_keys == keys_with_license_text:', (all_keys == keys_with_license_text)) return (all_keys == keys_with_license_text)
def _has_full_text(codebase, key_files_only=False): '\n Return True if the full text of all licenses is preset in the codebase.\n Consider only key files if key_files_only is True.\n ' (key_files_licenses, other_files_licenses) = get_unique_licenses(codebase, good_only=False) if TRACE: logger_debug('_has_full_text: key_files_licenses:', key_files_licenses, 'other_files_licenses:', other_files_licenses) all_keys = (key_files_licenses | other_files_licenses) if (not all_keys): return False if TRACE: logger_debug('_has_full_text: all_keys:', all_keys) keys_with_license_text = get_detected_license_keys_with_full_text(codebase, key_files_only, good_only=False) if TRACE: logger_debug('_has_full_text: keys_with_license_text:', keys_with_license_text) logger_debug('_has_full_text: all_keys == keys_with_license_text:', (all_keys == keys_with_license_text)) return (all_keys == keys_with_license_text)<|docstring|>Return True if the full text of all licenses is preset in the codebase. Consider only key files if key_files_only is True.<|endoftext|>
6b3ac6b60797b713c730928f32fd08d36d3c761e1b3c32cb69cbecb2557f27db
def get_file_level_license_and_copyright_coverage(codebase): '\n Return a float between 0 and 1 that represent the proportions of files that\n have a license and a copyright vs. all files.\n ' scoring_element = 0 (covered_files, files_count) = get_other_licenses_and_copyrights_counts(codebase) if TRACE: logger_debug('compute_license_score:covered_files:', covered_files, 'files_count:', files_count) if files_count: scoring_element = ((covered_files / files_count) or 0) if TRACE: logger_debug('compute_license_score:scoring_element:', scoring_element) return scoring_element
Return a float between 0 and 1 that represent the proportions of files that have a license and a copyright vs. all files.
src/summarycode/score.py
get_file_level_license_and_copyright_coverage
alec-z/zhangfei
1,511
python
def get_file_level_license_and_copyright_coverage(codebase): '\n Return a float between 0 and 1 that represent the proportions of files that\n have a license and a copyright vs. all files.\n ' scoring_element = 0 (covered_files, files_count) = get_other_licenses_and_copyrights_counts(codebase) if TRACE: logger_debug('compute_license_score:covered_files:', covered_files, 'files_count:', files_count) if files_count: scoring_element = ((covered_files / files_count) or 0) if TRACE: logger_debug('compute_license_score:scoring_element:', scoring_element) return scoring_element
def get_file_level_license_and_copyright_coverage(codebase): '\n Return a float between 0 and 1 that represent the proportions of files that\n have a license and a copyright vs. all files.\n ' scoring_element = 0 (covered_files, files_count) = get_other_licenses_and_copyrights_counts(codebase) if TRACE: logger_debug('compute_license_score:covered_files:', covered_files, 'files_count:', files_count) if files_count: scoring_element = ((covered_files / files_count) or 0) if TRACE: logger_debug('compute_license_score:scoring_element:', scoring_element) return scoring_element<|docstring|>Return a float between 0 and 1 that represent the proportions of files that have a license and a copyright vs. all files.<|endoftext|>
274e68c2840a1e177110cd99d012536548a416c8dbeb19509af0cb67df77e8f5
def get_other_licenses_and_copyrights_counts(codebase): '\n Return a tuple of (count of files with a license/copyright, total count of\n files).\n\n Do files that can contain licensing and copyright information reliably carry\n such information? This is based on a percentage of files in the core facet\n of the project that have both:\n\n - A license text, notice or an SPDX-License-Identifier and,\n - A copyright statement in standard (e.g. recognized) format.\n\n Here "reliably" means that these are reliably detected by tool(s) with a\n high level of confidence This is a progressive element that is computed\n based on:\n\n - LICCOP: the number of files with a license notice and copyright statement\n - TOT: the total number of files\n\n ' total_files_count = 0 files_with_good_license_and_copyright_count = 0 files_with_a_license_count = 0 files_with_a_good_license_count = 0 files_with_a_copyright_count = 0 for resource in codebase.walk(): if (resource.is_key_file or (not resource.is_file)): continue if (not is_core_facet(resource)): continue total_files_count += 1 licenses = (getattr(resource, 'licenses', []) or []) if licenses: files_with_a_license_count += 1 is_public_domain = ([l['key'] for l in licenses] == 'public-domain') copyrights = (getattr(resource, 'copyrights', []) or []) if (copyrights or ((not copyrights) and is_public_domain)): files_with_a_copyright_count += 1 if has_good_licenses(resource): files_with_a_good_license_count += 1 if copyrights: files_with_good_license_and_copyright_count += 1 return (files_with_good_license_and_copyright_count, total_files_count)
Return a tuple of (count of files with a license/copyright, total count of files). Do files that can contain licensing and copyright information reliably carry such information? This is based on a percentage of files in the core facet of the project that have both: - A license text, notice or an SPDX-License-Identifier and, - A copyright statement in standard (e.g. recognized) format. Here "reliably" means that these are reliably detected by tool(s) with a high level of confidence This is a progressive element that is computed based on: - LICCOP: the number of files with a license notice and copyright statement - TOT: the total number of files
src/summarycode/score.py
get_other_licenses_and_copyrights_counts
alec-z/zhangfei
1,511
python
def get_other_licenses_and_copyrights_counts(codebase): '\n Return a tuple of (count of files with a license/copyright, total count of\n files).\n\n Do files that can contain licensing and copyright information reliably carry\n such information? This is based on a percentage of files in the core facet\n of the project that have both:\n\n - A license text, notice or an SPDX-License-Identifier and,\n - A copyright statement in standard (e.g. recognized) format.\n\n Here "reliably" means that these are reliably detected by tool(s) with a\n high level of confidence This is a progressive element that is computed\n based on:\n\n - LICCOP: the number of files with a license notice and copyright statement\n - TOT: the total number of files\n\n ' total_files_count = 0 files_with_good_license_and_copyright_count = 0 files_with_a_license_count = 0 files_with_a_good_license_count = 0 files_with_a_copyright_count = 0 for resource in codebase.walk(): if (resource.is_key_file or (not resource.is_file)): continue if (not is_core_facet(resource)): continue total_files_count += 1 licenses = (getattr(resource, 'licenses', []) or []) if licenses: files_with_a_license_count += 1 is_public_domain = ([l['key'] for l in licenses] == 'public-domain') copyrights = (getattr(resource, 'copyrights', []) or []) if (copyrights or ((not copyrights) and is_public_domain)): files_with_a_copyright_count += 1 if has_good_licenses(resource): files_with_a_good_license_count += 1 if copyrights: files_with_good_license_and_copyright_count += 1 return (files_with_good_license_and_copyright_count, total_files_count)
def get_other_licenses_and_copyrights_counts(codebase): '\n Return a tuple of (count of files with a license/copyright, total count of\n files).\n\n Do files that can contain licensing and copyright information reliably carry\n such information? This is based on a percentage of files in the core facet\n of the project that have both:\n\n - A license text, notice or an SPDX-License-Identifier and,\n - A copyright statement in standard (e.g. recognized) format.\n\n Here "reliably" means that these are reliably detected by tool(s) with a\n high level of confidence This is a progressive element that is computed\n based on:\n\n - LICCOP: the number of files with a license notice and copyright statement\n - TOT: the total number of files\n\n ' total_files_count = 0 files_with_good_license_and_copyright_count = 0 files_with_a_license_count = 0 files_with_a_good_license_count = 0 files_with_a_copyright_count = 0 for resource in codebase.walk(): if (resource.is_key_file or (not resource.is_file)): continue if (not is_core_facet(resource)): continue total_files_count += 1 licenses = (getattr(resource, 'licenses', []) or []) if licenses: files_with_a_license_count += 1 is_public_domain = ([l['key'] for l in licenses] == 'public-domain') copyrights = (getattr(resource, 'copyrights', []) or []) if (copyrights or ((not copyrights) and is_public_domain)): files_with_a_copyright_count += 1 if has_good_licenses(resource): files_with_a_good_license_count += 1 if copyrights: files_with_good_license_and_copyright_count += 1 return (files_with_good_license_and_copyright_count, total_files_count)<|docstring|>Return a tuple of (count of files with a license/copyright, total count of files). Do files that can contain licensing and copyright information reliably carry such information? This is based on a percentage of files in the core facet of the project that have both: - A license text, notice or an SPDX-License-Identifier and, - A copyright statement in standard (e.g. recognized) format. Here "reliably" means that these are reliably detected by tool(s) with a high level of confidence This is a progressive element that is computed based on: - LICCOP: the number of files with a license notice and copyright statement - TOT: the total number of files<|endoftext|>
3e4aab1cdae4f1163ecaaa5461dd697d4ad73fa521ab288c3e99381fbca5a93f
def get(self, x: int, y: int): 'Coordinate system starts top left.' return self._storage[((y * self._width) + x)]
Coordinate system starts top left.
submitted_algorithms/mentoren/nils.py
get
coderdojoka/algo-battle
1
python
def get(self, x: int, y: int): return self._storage[((y * self._width) + x)]
def get(self, x: int, y: int): return self._storage[((y * self._width) + x)]<|docstring|>Coordinate system starts top left.<|endoftext|>
c0d85087823da77bd2df39cf7115581c159c2c3a05711bca080887d8b2b64ec6
@ComponentGetter(QRTComponentType.ComponentAnalog, RTAnalogComponent) def get_analog(self, component_info=None, data=None, component_position=None): 'Get analog data.' components = [] append_components = components.append for _ in range(component_info.device_count): (component_position, device) = QRTPacket._get_exact(RTAnalogDevice, data, component_position) if (device.sample_count > 0): (component_position, sample_number) = QRTPacket._get_exact(RTSampleNumber, data, component_position) RTAnalogChannel.format = struct.Struct((RTAnalogChannel.format_str % device.sample_count)) for _ in range(device.channel_count): (component_position, channel) = QRTPacket._get_tuple(RTAnalogChannel, data, component_position) append_components((device, sample_number, channel)) return components
Get analog data.
qtm/packet.py
get_analog
qualisys/qualisys_python_sdk
24
python
@ComponentGetter(QRTComponentType.ComponentAnalog, RTAnalogComponent) def get_analog(self, component_info=None, data=None, component_position=None): components = [] append_components = components.append for _ in range(component_info.device_count): (component_position, device) = QRTPacket._get_exact(RTAnalogDevice, data, component_position) if (device.sample_count > 0): (component_position, sample_number) = QRTPacket._get_exact(RTSampleNumber, data, component_position) RTAnalogChannel.format = struct.Struct((RTAnalogChannel.format_str % device.sample_count)) for _ in range(device.channel_count): (component_position, channel) = QRTPacket._get_tuple(RTAnalogChannel, data, component_position) append_components((device, sample_number, channel)) return components
@ComponentGetter(QRTComponentType.ComponentAnalog, RTAnalogComponent) def get_analog(self, component_info=None, data=None, component_position=None): components = [] append_components = components.append for _ in range(component_info.device_count): (component_position, device) = QRTPacket._get_exact(RTAnalogDevice, data, component_position) if (device.sample_count > 0): (component_position, sample_number) = QRTPacket._get_exact(RTSampleNumber, data, component_position) RTAnalogChannel.format = struct.Struct((RTAnalogChannel.format_str % device.sample_count)) for _ in range(device.channel_count): (component_position, channel) = QRTPacket._get_tuple(RTAnalogChannel, data, component_position) append_components((device, sample_number, channel)) return components<|docstring|>Get analog data.<|endoftext|>
d7fb4fd81096f80919ce717f24e1584c79c891494a23651244cc9e11bae5ff63
@ComponentGetter(QRTComponentType.ComponentAnalogSingle, RTAnalogComponent) def get_analog_single(self, component_info=None, data=None, component_position=None): 'Get a single analog data channel.' components = [] append_components = components.append for _ in range(component_info.device_count): (component_position, device) = QRTPacket._get_exact(RTAnalogDeviceSingle, data, component_position) RTAnalogDeviceSamples.format = struct.Struct((RTAnalogDeviceSamples.format_str % device.channel_count)) (component_position, sample) = QRTPacket._get_tuple(RTAnalogDeviceSamples, data, component_position) append_components((device, sample)) return components
Get a single analog data channel.
qtm/packet.py
get_analog_single
qualisys/qualisys_python_sdk
24
python
@ComponentGetter(QRTComponentType.ComponentAnalogSingle, RTAnalogComponent) def get_analog_single(self, component_info=None, data=None, component_position=None): components = [] append_components = components.append for _ in range(component_info.device_count): (component_position, device) = QRTPacket._get_exact(RTAnalogDeviceSingle, data, component_position) RTAnalogDeviceSamples.format = struct.Struct((RTAnalogDeviceSamples.format_str % device.channel_count)) (component_position, sample) = QRTPacket._get_tuple(RTAnalogDeviceSamples, data, component_position) append_components((device, sample)) return components
@ComponentGetter(QRTComponentType.ComponentAnalogSingle, RTAnalogComponent) def get_analog_single(self, component_info=None, data=None, component_position=None): components = [] append_components = components.append for _ in range(component_info.device_count): (component_position, device) = QRTPacket._get_exact(RTAnalogDeviceSingle, data, component_position) RTAnalogDeviceSamples.format = struct.Struct((RTAnalogDeviceSamples.format_str % device.channel_count)) (component_position, sample) = QRTPacket._get_tuple(RTAnalogDeviceSamples, data, component_position) append_components((device, sample)) return components<|docstring|>Get a single analog data channel.<|endoftext|>
2da3f46195f541e9da7c07d1f54f852384851ee1b0e4a89a6ad0e4ecab809ad2
@ComponentGetter(QRTComponentType.ComponentForce, RTForceComponent) def get_force(self, component_info=None, data=None, component_position=None): 'Get force data.' components = [] append_components = components.append for _ in range(component_info.plate_count): (component_position, plate) = QRTPacket._get_exact(RTForcePlate, data, component_position) force_list = [] for _ in range(plate.force_count): (component_position, force) = QRTPacket._get_exact(RTForce, data, component_position) force_list.append(force) append_components((plate, force_list)) return components
Get force data.
qtm/packet.py
get_force
qualisys/qualisys_python_sdk
24
python
@ComponentGetter(QRTComponentType.ComponentForce, RTForceComponent) def get_force(self, component_info=None, data=None, component_position=None): components = [] append_components = components.append for _ in range(component_info.plate_count): (component_position, plate) = QRTPacket._get_exact(RTForcePlate, data, component_position) force_list = [] for _ in range(plate.force_count): (component_position, force) = QRTPacket._get_exact(RTForce, data, component_position) force_list.append(force) append_components((plate, force_list)) return components
@ComponentGetter(QRTComponentType.ComponentForce, RTForceComponent) def get_force(self, component_info=None, data=None, component_position=None): components = [] append_components = components.append for _ in range(component_info.plate_count): (component_position, plate) = QRTPacket._get_exact(RTForcePlate, data, component_position) force_list = [] for _ in range(plate.force_count): (component_position, force) = QRTPacket._get_exact(RTForce, data, component_position) force_list.append(force) append_components((plate, force_list)) return components<|docstring|>Get force data.<|endoftext|>
da0c189efa86637659560e81b3832ffbc2a7db720eebaa156d59a4d04f346cc9
@ComponentGetter(QRTComponentType.ComponentForceSingle, RTForceComponent) def get_force_single(self, component_info=None, data=None, component_position=None): 'Get a single force data channel.' components = [] append_components = components.append for _ in range(component_info.plate_count): (component_position, plate) = QRTPacket._get_exact(RTForcePlateSingle, data, component_position) (component_position, force) = QRTPacket._get_exact(RTForce, data, component_position) append_components((plate, force)) return components
Get a single force data channel.
qtm/packet.py
get_force_single
qualisys/qualisys_python_sdk
24
python
@ComponentGetter(QRTComponentType.ComponentForceSingle, RTForceComponent) def get_force_single(self, component_info=None, data=None, component_position=None): components = [] append_components = components.append for _ in range(component_info.plate_count): (component_position, plate) = QRTPacket._get_exact(RTForcePlateSingle, data, component_position) (component_position, force) = QRTPacket._get_exact(RTForce, data, component_position) append_components((plate, force)) return components
@ComponentGetter(QRTComponentType.ComponentForceSingle, RTForceComponent) def get_force_single(self, component_info=None, data=None, component_position=None): components = [] append_components = components.append for _ in range(component_info.plate_count): (component_position, plate) = QRTPacket._get_exact(RTForcePlateSingle, data, component_position) (component_position, force) = QRTPacket._get_exact(RTForce, data, component_position) append_components((plate, force)) return components<|docstring|>Get a single force data channel.<|endoftext|>
2fb20efcdee4453629576331573ec0ed6b5c116e3401975ba937f51168d480aa
@ComponentGetter(QRTComponentType.Component6d, RT6DComponent) def get_6d(self, component_info=None, data=None, component_position=None): 'Get 6D data.' components = [] append_components = components.append for _ in range(component_info.body_count): (component_position, position) = QRTPacket._get_exact(RT6DBodyPosition, data, component_position) (component_position, matrix) = QRTPacket._get_tuple(RT6DBodyRotation, data, component_position) append_components((position, matrix)) return components
Get 6D data.
qtm/packet.py
get_6d
qualisys/qualisys_python_sdk
24
python
@ComponentGetter(QRTComponentType.Component6d, RT6DComponent) def get_6d(self, component_info=None, data=None, component_position=None): components = [] append_components = components.append for _ in range(component_info.body_count): (component_position, position) = QRTPacket._get_exact(RT6DBodyPosition, data, component_position) (component_position, matrix) = QRTPacket._get_tuple(RT6DBodyRotation, data, component_position) append_components((position, matrix)) return components
@ComponentGetter(QRTComponentType.Component6d, RT6DComponent) def get_6d(self, component_info=None, data=None, component_position=None): components = [] append_components = components.append for _ in range(component_info.body_count): (component_position, position) = QRTPacket._get_exact(RT6DBodyPosition, data, component_position) (component_position, matrix) = QRTPacket._get_tuple(RT6DBodyRotation, data, component_position) append_components((position, matrix)) return components<|docstring|>Get 6D data.<|endoftext|>
1d6bd7e47f13a5d067369345ecc41f0b000118b9bae4f4619a4008de3b5b3ad5
@ComponentGetter(QRTComponentType.Component6dRes, RT6DComponent) def get_6d_residual(self, component_info=None, data=None, component_position=None): 'Get 6D data with residual.' components = [] append_components = components.append for _ in range(component_info.body_count): (component_position, position) = QRTPacket._get_exact(RT6DBodyPosition, data, component_position) (component_position, matrix) = QRTPacket._get_tuple(RT6DBodyRotation, data, component_position) (component_position, residual) = QRTPacket._get_exact(RT6DBodyResidual, data, component_position) append_components((position, matrix, residual)) return components
Get 6D data with residual.
qtm/packet.py
get_6d_residual
qualisys/qualisys_python_sdk
24
python
@ComponentGetter(QRTComponentType.Component6dRes, RT6DComponent) def get_6d_residual(self, component_info=None, data=None, component_position=None): components = [] append_components = components.append for _ in range(component_info.body_count): (component_position, position) = QRTPacket._get_exact(RT6DBodyPosition, data, component_position) (component_position, matrix) = QRTPacket._get_tuple(RT6DBodyRotation, data, component_position) (component_position, residual) = QRTPacket._get_exact(RT6DBodyResidual, data, component_position) append_components((position, matrix, residual)) return components
@ComponentGetter(QRTComponentType.Component6dRes, RT6DComponent) def get_6d_residual(self, component_info=None, data=None, component_position=None): components = [] append_components = components.append for _ in range(component_info.body_count): (component_position, position) = QRTPacket._get_exact(RT6DBodyPosition, data, component_position) (component_position, matrix) = QRTPacket._get_tuple(RT6DBodyRotation, data, component_position) (component_position, residual) = QRTPacket._get_exact(RT6DBodyResidual, data, component_position) append_components((position, matrix, residual)) return components<|docstring|>Get 6D data with residual.<|endoftext|>
0a6cfd367c90ba0e883fe1ca071fab22250ddc4a8d5f3483b81e0623e3d4f812
@ComponentGetter(QRTComponentType.Component6dEuler, RT6DComponent) def get_6d_euler(self, component_info=None, data=None, component_position=None): 'Get 6D data with euler rotations.' components = [] append_components = components.append for _ in range(component_info.body_count): (component_position, position) = QRTPacket._get_exact(RT6DBodyPosition, data, component_position) (component_position, euler) = QRTPacket._get_exact(RT6DBodyEuler, data, component_position) append_components((position, euler)) return components
Get 6D data with euler rotations.
qtm/packet.py
get_6d_euler
qualisys/qualisys_python_sdk
24
python
@ComponentGetter(QRTComponentType.Component6dEuler, RT6DComponent) def get_6d_euler(self, component_info=None, data=None, component_position=None): components = [] append_components = components.append for _ in range(component_info.body_count): (component_position, position) = QRTPacket._get_exact(RT6DBodyPosition, data, component_position) (component_position, euler) = QRTPacket._get_exact(RT6DBodyEuler, data, component_position) append_components((position, euler)) return components
@ComponentGetter(QRTComponentType.Component6dEuler, RT6DComponent) def get_6d_euler(self, component_info=None, data=None, component_position=None): components = [] append_components = components.append for _ in range(component_info.body_count): (component_position, position) = QRTPacket._get_exact(RT6DBodyPosition, data, component_position) (component_position, euler) = QRTPacket._get_exact(RT6DBodyEuler, data, component_position) append_components((position, euler)) return components<|docstring|>Get 6D data with euler rotations.<|endoftext|>
4d93d223fb3a061be3ef5f7b3b4dd562a381c5d15e1be4bf3531de96f24623fd
@ComponentGetter(QRTComponentType.Component6dEulerRes, RT6DComponent) def get_6d_euler_residual(self, component_info=None, data=None, component_position=None): 'Get 6D data with residuals and euler rotations.' components = [] append_components = components.append for _ in range(component_info.body_count): (component_position, position) = QRTPacket._get_exact(RT6DBodyPosition, data, component_position) (component_position, euler) = QRTPacket._get_exact(RT6DBodyEuler, data, component_position) (component_position, residual) = QRTPacket._get_exact(RT6DBodyResidual, data, component_position) append_components((position, euler, residual)) return components
Get 6D data with residuals and euler rotations.
qtm/packet.py
get_6d_euler_residual
qualisys/qualisys_python_sdk
24
python
@ComponentGetter(QRTComponentType.Component6dEulerRes, RT6DComponent) def get_6d_euler_residual(self, component_info=None, data=None, component_position=None): components = [] append_components = components.append for _ in range(component_info.body_count): (component_position, position) = QRTPacket._get_exact(RT6DBodyPosition, data, component_position) (component_position, euler) = QRTPacket._get_exact(RT6DBodyEuler, data, component_position) (component_position, residual) = QRTPacket._get_exact(RT6DBodyResidual, data, component_position) append_components((position, euler, residual)) return components
@ComponentGetter(QRTComponentType.Component6dEulerRes, RT6DComponent) def get_6d_euler_residual(self, component_info=None, data=None, component_position=None): components = [] append_components = components.append for _ in range(component_info.body_count): (component_position, position) = QRTPacket._get_exact(RT6DBodyPosition, data, component_position) (component_position, euler) = QRTPacket._get_exact(RT6DBodyEuler, data, component_position) (component_position, residual) = QRTPacket._get_exact(RT6DBodyResidual, data, component_position) append_components((position, euler, residual)) return components<|docstring|>Get 6D data with residuals and euler rotations.<|endoftext|>
88dd8cbebf329ff2db4f8cfac393131e501b4bf2e5ba24c000d8aab9d36ecfa9
@ComponentGetter(QRTComponentType.ComponentImage, RTImageComponent) def get_image(self, component_info=None, data=None, component_position=None): 'Get image.' components = [] append_components = components.append for _ in range(component_info.image_count): (component_position, image_info) = QRTPacket._get_exact(RTImage, data, component_position) append_components((image_info, data[component_position:(component_position + image_info.image_size)])) component_position += image_info.image_size return components
Get image.
qtm/packet.py
get_image
qualisys/qualisys_python_sdk
24
python
@ComponentGetter(QRTComponentType.ComponentImage, RTImageComponent) def get_image(self, component_info=None, data=None, component_position=None): components = [] append_components = components.append for _ in range(component_info.image_count): (component_position, image_info) = QRTPacket._get_exact(RTImage, data, component_position) append_components((image_info, data[component_position:(component_position + image_info.image_size)])) component_position += image_info.image_size return components
@ComponentGetter(QRTComponentType.ComponentImage, RTImageComponent) def get_image(self, component_info=None, data=None, component_position=None): components = [] append_components = components.append for _ in range(component_info.image_count): (component_position, image_info) = QRTPacket._get_exact(RTImage, data, component_position) append_components((image_info, data[component_position:(component_position + image_info.image_size)])) component_position += image_info.image_size return components<|docstring|>Get image.<|endoftext|>
c9debb4854e543fb4adf33e4cba10a68ad2881b68874f7ba62603b67397904b4
@ComponentGetter(QRTComponentType.Component3d, RT3DComponent) def get_3d_markers(self, component_info=None, data=None, component_position=None): 'Get 3D markers.' return self._get_3d_markers(RT3DMarkerPosition, component_info, data, component_position)
Get 3D markers.
qtm/packet.py
get_3d_markers
qualisys/qualisys_python_sdk
24
python
@ComponentGetter(QRTComponentType.Component3d, RT3DComponent) def get_3d_markers(self, component_info=None, data=None, component_position=None): return self._get_3d_markers(RT3DMarkerPosition, component_info, data, component_position)
@ComponentGetter(QRTComponentType.Component3d, RT3DComponent) def get_3d_markers(self, component_info=None, data=None, component_position=None): return self._get_3d_markers(RT3DMarkerPosition, component_info, data, component_position)<|docstring|>Get 3D markers.<|endoftext|>
989c655f1f067617c2348c04cea5cbeb18aaea52472c36922fb0b082bc7c7809
@ComponentGetter(QRTComponentType.Component3dRes, RT3DComponent) def get_3d_markers_residual(self, component_info=None, data=None, component_position=None): 'Get 3D markers with residual.' return self._get_3d_markers(RT3DMarkerPositionResidual, component_info, data, component_position)
Get 3D markers with residual.
qtm/packet.py
get_3d_markers_residual
qualisys/qualisys_python_sdk
24
python
@ComponentGetter(QRTComponentType.Component3dRes, RT3DComponent) def get_3d_markers_residual(self, component_info=None, data=None, component_position=None): return self._get_3d_markers(RT3DMarkerPositionResidual, component_info, data, component_position)
@ComponentGetter(QRTComponentType.Component3dRes, RT3DComponent) def get_3d_markers_residual(self, component_info=None, data=None, component_position=None): return self._get_3d_markers(RT3DMarkerPositionResidual, component_info, data, component_position)<|docstring|>Get 3D markers with residual.<|endoftext|>
02561f6ef946d5ca361f35fda9d1e64b80f31e8553f0a0ff152402c53a95a667
@ComponentGetter(QRTComponentType.Component3dNoLabels, RT3DComponent) def get_3d_markers_no_label(self, component_info=None, data=None, component_position=None): 'Get 3D markers without label.' return self._get_3d_markers(RT3DMarkerPositionNoLabel, component_info, data, component_position)
Get 3D markers without label.
qtm/packet.py
get_3d_markers_no_label
qualisys/qualisys_python_sdk
24
python
@ComponentGetter(QRTComponentType.Component3dNoLabels, RT3DComponent) def get_3d_markers_no_label(self, component_info=None, data=None, component_position=None): return self._get_3d_markers(RT3DMarkerPositionNoLabel, component_info, data, component_position)
@ComponentGetter(QRTComponentType.Component3dNoLabels, RT3DComponent) def get_3d_markers_no_label(self, component_info=None, data=None, component_position=None): return self._get_3d_markers(RT3DMarkerPositionNoLabel, component_info, data, component_position)<|docstring|>Get 3D markers without label.<|endoftext|>
8685680e80a41f80d567d8944fbd2bf6b2308eecd4bf12912806d0d526903592
@ComponentGetter(QRTComponentType.Component3dNoLabelsRes, RT3DComponent) def get_3d_markers_no_label_residual(self, component_info=None, data=None, component_position=None): 'Get 3D markers without label with residual.' return self._get_3d_markers(RT3DMarkerPositionNoLabelResidual, component_info, data, component_position)
Get 3D markers without label with residual.
qtm/packet.py
get_3d_markers_no_label_residual
qualisys/qualisys_python_sdk
24
python
@ComponentGetter(QRTComponentType.Component3dNoLabelsRes, RT3DComponent) def get_3d_markers_no_label_residual(self, component_info=None, data=None, component_position=None): return self._get_3d_markers(RT3DMarkerPositionNoLabelResidual, component_info, data, component_position)
@ComponentGetter(QRTComponentType.Component3dNoLabelsRes, RT3DComponent) def get_3d_markers_no_label_residual(self, component_info=None, data=None, component_position=None): return self._get_3d_markers(RT3DMarkerPositionNoLabelResidual, component_info, data, component_position)<|docstring|>Get 3D markers without label with residual.<|endoftext|>
66b10634c1c8d7851fb4891717c905c1f7ccc959c47d6ddb1af86b9d34013126
@ComponentGetter(QRTComponentType.Component2d, RT2DComponent) def get_2d_markers(self, component_info=None, data=None, component_position=None, index=None): 'Get 2D markers.\n\n :param index: Specify which camera to get 2D from, will be returned as\n first entry in the returned array.\n ' return self._get_2d_markers(data, component_info, component_position, index=index)
Get 2D markers. :param index: Specify which camera to get 2D from, will be returned as first entry in the returned array.
qtm/packet.py
get_2d_markers
qualisys/qualisys_python_sdk
24
python
@ComponentGetter(QRTComponentType.Component2d, RT2DComponent) def get_2d_markers(self, component_info=None, data=None, component_position=None, index=None): 'Get 2D markers.\n\n :param index: Specify which camera to get 2D from, will be returned as\n first entry in the returned array.\n ' return self._get_2d_markers(data, component_info, component_position, index=index)
@ComponentGetter(QRTComponentType.Component2d, RT2DComponent) def get_2d_markers(self, component_info=None, data=None, component_position=None, index=None): 'Get 2D markers.\n\n :param index: Specify which camera to get 2D from, will be returned as\n first entry in the returned array.\n ' return self._get_2d_markers(data, component_info, component_position, index=index)<|docstring|>Get 2D markers. :param index: Specify which camera to get 2D from, will be returned as first entry in the returned array.<|endoftext|>
2b50094dd9fcb237b0f6e6aa8f41f3bff696c88f4aa96f412976a4c6ecb0158b
@ComponentGetter(QRTComponentType.Component2dLin, RT2DComponent) def get_2d_markers_linearized(self, component_info=None, data=None, component_position=None, index=None): 'Get 2D linearized markers.\n\n :param index: Specify which camera to get 2D from, will be returned as\n first entry in the returned array.\n ' return self._get_2d_markers(data, component_info, component_position, index=index)
Get 2D linearized markers. :param index: Specify which camera to get 2D from, will be returned as first entry in the returned array.
qtm/packet.py
get_2d_markers_linearized
qualisys/qualisys_python_sdk
24
python
@ComponentGetter(QRTComponentType.Component2dLin, RT2DComponent) def get_2d_markers_linearized(self, component_info=None, data=None, component_position=None, index=None): 'Get 2D linearized markers.\n\n :param index: Specify which camera to get 2D from, will be returned as\n first entry in the returned array.\n ' return self._get_2d_markers(data, component_info, component_position, index=index)
@ComponentGetter(QRTComponentType.Component2dLin, RT2DComponent) def get_2d_markers_linearized(self, component_info=None, data=None, component_position=None, index=None): 'Get 2D linearized markers.\n\n :param index: Specify which camera to get 2D from, will be returned as\n first entry in the returned array.\n ' return self._get_2d_markers(data, component_info, component_position, index=index)<|docstring|>Get 2D linearized markers. :param index: Specify which camera to get 2D from, will be returned as first entry in the returned array.<|endoftext|>
23a6a611acc946a289a2e561fec942a7015b6e2435917d6b43a35853c36825e4
@ComponentGetter(QRTComponentType.ComponentSkeleton, RTSkeletonComponent) def get_skeletons(self, component_info=None, data=None, component_position=None): 'Get skeletons\n ' components = [] append_components = components.append for _ in range(component_info.skeleton_count): (component_position, info) = QRTPacket._get_exact(RTSegmentCount, data, component_position) segments = [] for __ in range(info.segment_count): (component_position, segment) = QRTPacket._get_exact(RTSegmentId, data, component_position) (component_position, position) = QRTPacket._get_exact(RTSegmentPosition, data, component_position) (component_position, rotation) = QRTPacket._get_exact(RTSegmentRotation, data, component_position) segments.append((segment.id, position, rotation)) append_components(segments) return components
Get skeletons
qtm/packet.py
get_skeletons
qualisys/qualisys_python_sdk
24
python
@ComponentGetter(QRTComponentType.ComponentSkeleton, RTSkeletonComponent) def get_skeletons(self, component_info=None, data=None, component_position=None): '\n ' components = [] append_components = components.append for _ in range(component_info.skeleton_count): (component_position, info) = QRTPacket._get_exact(RTSegmentCount, data, component_position) segments = [] for __ in range(info.segment_count): (component_position, segment) = QRTPacket._get_exact(RTSegmentId, data, component_position) (component_position, position) = QRTPacket._get_exact(RTSegmentPosition, data, component_position) (component_position, rotation) = QRTPacket._get_exact(RTSegmentRotation, data, component_position) segments.append((segment.id, position, rotation)) append_components(segments) return components
@ComponentGetter(QRTComponentType.ComponentSkeleton, RTSkeletonComponent) def get_skeletons(self, component_info=None, data=None, component_position=None): '\n ' components = [] append_components = components.append for _ in range(component_info.skeleton_count): (component_position, info) = QRTPacket._get_exact(RTSegmentCount, data, component_position) segments = [] for __ in range(info.segment_count): (component_position, segment) = QRTPacket._get_exact(RTSegmentId, data, component_position) (component_position, position) = QRTPacket._get_exact(RTSegmentPosition, data, component_position) (component_position, rotation) = QRTPacket._get_exact(RTSegmentRotation, data, component_position) segments.append((segment.id, position, rotation)) append_components(segments) return components<|docstring|>Get skeletons<|endoftext|>
0492bdec4a14e9aaf3d4f49f66d35bb5b505265ef5292b8f0fde0fc26d3c9656
@ComponentGetter(QRTComponentType.ComponentGazeVector, RTGazeVectorComponent) def get_gaze_vectors(self, component_info=None, data=None, component_position=None): 'Get gaze vectors\n ' components = [] append_components = components.append for _ in range(component_info.vector_count): (component_position, info) = QRTPacket._get_exact(RTGazeVectorInfo, data, component_position) samples = [] if (info.sample_count > 0): for _ in range(info.sample_count): (component_position, unit_vector) = QRTPacket._get_exact(RTGazeVectorUnitVector, data, component_position) (component_position, position) = QRTPacket._get_exact(RTGazeVectorPosition, data, component_position) samples.append((unit_vector, position)) append_components((info, samples)) return components
Get gaze vectors
qtm/packet.py
get_gaze_vectors
qualisys/qualisys_python_sdk
24
python
@ComponentGetter(QRTComponentType.ComponentGazeVector, RTGazeVectorComponent) def get_gaze_vectors(self, component_info=None, data=None, component_position=None): '\n ' components = [] append_components = components.append for _ in range(component_info.vector_count): (component_position, info) = QRTPacket._get_exact(RTGazeVectorInfo, data, component_position) samples = [] if (info.sample_count > 0): for _ in range(info.sample_count): (component_position, unit_vector) = QRTPacket._get_exact(RTGazeVectorUnitVector, data, component_position) (component_position, position) = QRTPacket._get_exact(RTGazeVectorPosition, data, component_position) samples.append((unit_vector, position)) append_components((info, samples)) return components
@ComponentGetter(QRTComponentType.ComponentGazeVector, RTGazeVectorComponent) def get_gaze_vectors(self, component_info=None, data=None, component_position=None): '\n ' components = [] append_components = components.append for _ in range(component_info.vector_count): (component_position, info) = QRTPacket._get_exact(RTGazeVectorInfo, data, component_position) samples = [] if (info.sample_count > 0): for _ in range(info.sample_count): (component_position, unit_vector) = QRTPacket._get_exact(RTGazeVectorUnitVector, data, component_position) (component_position, position) = QRTPacket._get_exact(RTGazeVectorPosition, data, component_position) samples.append((unit_vector, position)) append_components((info, samples)) return components<|docstring|>Get gaze vectors<|endoftext|>
2adf42218cd6a81f292c150a53ffc27405f5dfc6770c879521b0737e1daadce8
@ComponentGetter(QRTComponentType.ComponentEyeTracker, RTEyeTrackerComponent) def get_eye_trackers(self, component_info=None, data=None, component_position=None): 'Get eye trackers\n ' components = [] append_components = components.append for _ in range(component_info.eye_tracker_count): (component_position, info) = QRTPacket._get_exact(RTEyeTrackerInfo, data, component_position) samples = [] if (info.sample_count > 0): for _ in range(info.sample_count): (component_position, diameter) = QRTPacket._get_exact(RTEyeTrackerDiameter, data, component_position) samples.append(diameter) append_components((info, samples)) return components
Get eye trackers
qtm/packet.py
get_eye_trackers
qualisys/qualisys_python_sdk
24
python
@ComponentGetter(QRTComponentType.ComponentEyeTracker, RTEyeTrackerComponent) def get_eye_trackers(self, component_info=None, data=None, component_position=None): '\n ' components = [] append_components = components.append for _ in range(component_info.eye_tracker_count): (component_position, info) = QRTPacket._get_exact(RTEyeTrackerInfo, data, component_position) samples = [] if (info.sample_count > 0): for _ in range(info.sample_count): (component_position, diameter) = QRTPacket._get_exact(RTEyeTrackerDiameter, data, component_position) samples.append(diameter) append_components((info, samples)) return components
@ComponentGetter(QRTComponentType.ComponentEyeTracker, RTEyeTrackerComponent) def get_eye_trackers(self, component_info=None, data=None, component_position=None): '\n ' components = [] append_components = components.append for _ in range(component_info.eye_tracker_count): (component_position, info) = QRTPacket._get_exact(RTEyeTrackerInfo, data, component_position) samples = [] if (info.sample_count > 0): for _ in range(info.sample_count): (component_position, diameter) = QRTPacket._get_exact(RTEyeTrackerDiameter, data, component_position) samples.append(diameter) append_components((info, samples)) return components<|docstring|>Get eye trackers<|endoftext|>
6f7c8dec5961b1b7757bc0fb9bfda6ecf24cf5087ea0ff919527aba7a47a0b0f
def to_categorical(y, nb_classes=None): 'Converts a class vector (integers) to binary class matrix.\n\n E.g. for use with categorical_crossentropy.\n\n # Arguments\n y: class vector to be converted into a matrix\n (integers from 0 to nb_classes).\n nb_classes: total number of classes.\n\n # Returns\n A binary matrix representation of the input.\n ' y = np.array(y, dtype='int').ravel() if (not nb_classes): nb_classes = (np.max(y) + 1) n = y.shape[0] categorical = np.zeros((n, nb_classes)) categorical[(np.arange(n), y)] = 1 return categorical
Converts a class vector (integers) to binary class matrix. E.g. for use with categorical_crossentropy. # Arguments y: class vector to be converted into a matrix (integers from 0 to nb_classes). nb_classes: total number of classes. # Returns A binary matrix representation of the input.
keras/utils/np_utils.py
to_categorical
digimatronics/keras
150
python
def to_categorical(y, nb_classes=None): 'Converts a class vector (integers) to binary class matrix.\n\n E.g. for use with categorical_crossentropy.\n\n # Arguments\n y: class vector to be converted into a matrix\n (integers from 0 to nb_classes).\n nb_classes: total number of classes.\n\n # Returns\n A binary matrix representation of the input.\n ' y = np.array(y, dtype='int').ravel() if (not nb_classes): nb_classes = (np.max(y) + 1) n = y.shape[0] categorical = np.zeros((n, nb_classes)) categorical[(np.arange(n), y)] = 1 return categorical
def to_categorical(y, nb_classes=None): 'Converts a class vector (integers) to binary class matrix.\n\n E.g. for use with categorical_crossentropy.\n\n # Arguments\n y: class vector to be converted into a matrix\n (integers from 0 to nb_classes).\n nb_classes: total number of classes.\n\n # Returns\n A binary matrix representation of the input.\n ' y = np.array(y, dtype='int').ravel() if (not nb_classes): nb_classes = (np.max(y) + 1) n = y.shape[0] categorical = np.zeros((n, nb_classes)) categorical[(np.arange(n), y)] = 1 return categorical<|docstring|>Converts a class vector (integers) to binary class matrix. E.g. for use with categorical_crossentropy. # Arguments y: class vector to be converted into a matrix (integers from 0 to nb_classes). nb_classes: total number of classes. # Returns A binary matrix representation of the input.<|endoftext|>
8211c605f6880ddc8008244157c6e09d0c377d7f6c4a0ebed57793c1a8ca615c
def convert_kernel(kernel, dim_ordering=None): 'Converts a Numpy kernel matrix from Theano format to TensorFlow format.\n\n Also works reciprocally, since the transformation is its own inverse.\n\n # Arguments\n kernel: Numpy array (4D or 5D).\n dim_ordering: the data format.\n\n # Returns\n The converted kernel.\n\n # Raises\n ValueError: in case of invalid kernel shape or invalid dim_ordering.\n ' if (dim_ordering is None): dim_ordering = K.image_dim_ordering() if (not (4 <= kernel.ndim <= 5)): raise ValueError('Invalid kernel shape:', kernel.shape) slices = [slice(None, None, (- 1)) for _ in range(kernel.ndim)] no_flip = (slice(None, None), slice(None, None)) if (dim_ordering == 'th'): slices[:2] = no_flip elif (dim_ordering == 'tf'): slices[(- 2):] = no_flip else: raise ValueError('Invalid dim_ordering:', dim_ordering) return np.copy(kernel[slices])
Converts a Numpy kernel matrix from Theano format to TensorFlow format. Also works reciprocally, since the transformation is its own inverse. # Arguments kernel: Numpy array (4D or 5D). dim_ordering: the data format. # Returns The converted kernel. # Raises ValueError: in case of invalid kernel shape or invalid dim_ordering.
keras/utils/np_utils.py
convert_kernel
digimatronics/keras
150
python
def convert_kernel(kernel, dim_ordering=None): 'Converts a Numpy kernel matrix from Theano format to TensorFlow format.\n\n Also works reciprocally, since the transformation is its own inverse.\n\n # Arguments\n kernel: Numpy array (4D or 5D).\n dim_ordering: the data format.\n\n # Returns\n The converted kernel.\n\n # Raises\n ValueError: in case of invalid kernel shape or invalid dim_ordering.\n ' if (dim_ordering is None): dim_ordering = K.image_dim_ordering() if (not (4 <= kernel.ndim <= 5)): raise ValueError('Invalid kernel shape:', kernel.shape) slices = [slice(None, None, (- 1)) for _ in range(kernel.ndim)] no_flip = (slice(None, None), slice(None, None)) if (dim_ordering == 'th'): slices[:2] = no_flip elif (dim_ordering == 'tf'): slices[(- 2):] = no_flip else: raise ValueError('Invalid dim_ordering:', dim_ordering) return np.copy(kernel[slices])
def convert_kernel(kernel, dim_ordering=None): 'Converts a Numpy kernel matrix from Theano format to TensorFlow format.\n\n Also works reciprocally, since the transformation is its own inverse.\n\n # Arguments\n kernel: Numpy array (4D or 5D).\n dim_ordering: the data format.\n\n # Returns\n The converted kernel.\n\n # Raises\n ValueError: in case of invalid kernel shape or invalid dim_ordering.\n ' if (dim_ordering is None): dim_ordering = K.image_dim_ordering() if (not (4 <= kernel.ndim <= 5)): raise ValueError('Invalid kernel shape:', kernel.shape) slices = [slice(None, None, (- 1)) for _ in range(kernel.ndim)] no_flip = (slice(None, None), slice(None, None)) if (dim_ordering == 'th'): slices[:2] = no_flip elif (dim_ordering == 'tf'): slices[(- 2):] = no_flip else: raise ValueError('Invalid dim_ordering:', dim_ordering) return np.copy(kernel[slices])<|docstring|>Converts a Numpy kernel matrix from Theano format to TensorFlow format. Also works reciprocally, since the transformation is its own inverse. # Arguments kernel: Numpy array (4D or 5D). dim_ordering: the data format. # Returns The converted kernel. # Raises ValueError: in case of invalid kernel shape or invalid dim_ordering.<|endoftext|>
ebb843798b7ad1655688609c27c947dcefe46c6ff3e899349eda06db516baead
def conv_output_length(input_length, filter_size, border_mode, stride, dilation=1): 'Determines output length of a convolution given input length.\n\n # Arguments\n input_length: integer.\n filter_size: integer.\n border_mode: one of "same", "valid", "full".\n stride: integer.\n dilation: dilation rate, integer.\n\n # Returns\n The output length (integer).\n ' if (input_length is None): return None assert (border_mode in {'same', 'valid', 'full'}) dilated_filter_size = (filter_size + ((filter_size - 1) * (dilation - 1))) if (border_mode == 'same'): output_length = input_length elif (border_mode == 'valid'): output_length = ((input_length - dilated_filter_size) + 1) elif (border_mode == 'full'): output_length = ((input_length + dilated_filter_size) - 1) return (((output_length + stride) - 1) // stride)
Determines output length of a convolution given input length. # Arguments input_length: integer. filter_size: integer. border_mode: one of "same", "valid", "full". stride: integer. dilation: dilation rate, integer. # Returns The output length (integer).
keras/utils/np_utils.py
conv_output_length
digimatronics/keras
150
python
def conv_output_length(input_length, filter_size, border_mode, stride, dilation=1): 'Determines output length of a convolution given input length.\n\n # Arguments\n input_length: integer.\n filter_size: integer.\n border_mode: one of "same", "valid", "full".\n stride: integer.\n dilation: dilation rate, integer.\n\n # Returns\n The output length (integer).\n ' if (input_length is None): return None assert (border_mode in {'same', 'valid', 'full'}) dilated_filter_size = (filter_size + ((filter_size - 1) * (dilation - 1))) if (border_mode == 'same'): output_length = input_length elif (border_mode == 'valid'): output_length = ((input_length - dilated_filter_size) + 1) elif (border_mode == 'full'): output_length = ((input_length + dilated_filter_size) - 1) return (((output_length + stride) - 1) // stride)
def conv_output_length(input_length, filter_size, border_mode, stride, dilation=1): 'Determines output length of a convolution given input length.\n\n # Arguments\n input_length: integer.\n filter_size: integer.\n border_mode: one of "same", "valid", "full".\n stride: integer.\n dilation: dilation rate, integer.\n\n # Returns\n The output length (integer).\n ' if (input_length is None): return None assert (border_mode in {'same', 'valid', 'full'}) dilated_filter_size = (filter_size + ((filter_size - 1) * (dilation - 1))) if (border_mode == 'same'): output_length = input_length elif (border_mode == 'valid'): output_length = ((input_length - dilated_filter_size) + 1) elif (border_mode == 'full'): output_length = ((input_length + dilated_filter_size) - 1) return (((output_length + stride) - 1) // stride)<|docstring|>Determines output length of a convolution given input length. # Arguments input_length: integer. filter_size: integer. border_mode: one of "same", "valid", "full". stride: integer. dilation: dilation rate, integer. # Returns The output length (integer).<|endoftext|>
295c4f31a829dede1fc1e84e0cf5531c4c3fd1d528291816ce7de78074610a20
def conv_input_length(output_length, filter_size, border_mode, stride): 'Determines input length of a convolution given output length.\n\n # Arguments\n output_length: integer.\n filter_size: integer.\n border_mode: one of "same", "valid", "full".\n stride: integer.\n\n # Returns\n The input length (integer).\n ' if (output_length is None): return None assert (border_mode in {'same', 'valid', 'full'}) if (border_mode == 'same'): pad = (filter_size // 2) elif (border_mode == 'valid'): pad = 0 elif (border_mode == 'full'): pad = (filter_size - 1) return ((((output_length - 1) * stride) - (2 * pad)) + filter_size)
Determines input length of a convolution given output length. # Arguments output_length: integer. filter_size: integer. border_mode: one of "same", "valid", "full". stride: integer. # Returns The input length (integer).
keras/utils/np_utils.py
conv_input_length
digimatronics/keras
150
python
def conv_input_length(output_length, filter_size, border_mode, stride): 'Determines input length of a convolution given output length.\n\n # Arguments\n output_length: integer.\n filter_size: integer.\n border_mode: one of "same", "valid", "full".\n stride: integer.\n\n # Returns\n The input length (integer).\n ' if (output_length is None): return None assert (border_mode in {'same', 'valid', 'full'}) if (border_mode == 'same'): pad = (filter_size // 2) elif (border_mode == 'valid'): pad = 0 elif (border_mode == 'full'): pad = (filter_size - 1) return ((((output_length - 1) * stride) - (2 * pad)) + filter_size)
def conv_input_length(output_length, filter_size, border_mode, stride): 'Determines input length of a convolution given output length.\n\n # Arguments\n output_length: integer.\n filter_size: integer.\n border_mode: one of "same", "valid", "full".\n stride: integer.\n\n # Returns\n The input length (integer).\n ' if (output_length is None): return None assert (border_mode in {'same', 'valid', 'full'}) if (border_mode == 'same'): pad = (filter_size // 2) elif (border_mode == 'valid'): pad = 0 elif (border_mode == 'full'): pad = (filter_size - 1) return ((((output_length - 1) * stride) - (2 * pad)) + filter_size)<|docstring|>Determines input length of a convolution given output length. # Arguments output_length: integer. filter_size: integer. border_mode: one of "same", "valid", "full". stride: integer. # Returns The input length (integer).<|endoftext|>
78a630ce9696d3694ac4f6e99eba784984f33fda3bb004b73794424b5afce1db
def _find_puzzle_section(self, thr_img): '\n Finds the biggest square in the image (that should be the puzzle)\n After the coordinates of the corners are found (top-lef, top-right,\n bottom-left, bottom-right), the perspective is warped so that\n puzzle_img contains only the puzzle.\n :param thr_img:\n :return:\n ' (img, contours, h) = cv2.findContours(thr_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) biggest = [] max_area = (- 1) for i in contours: area = cv2.contourArea(i) if (area > 100): perimeter = cv2.arcLength(i, True) approx = cv2.approxPolyDP(i, (0.02 * perimeter), True) if ((area > max_area) and (len(approx) == 4)): biggest = approx max_area = area if (not len(biggest)): raise PuzzleNotFound (p1, p2, p3, p4) = uniformize_points(biggest[0][0], biggest[1][0], biggest[2][0], biggest[3][0]) self._puzzle_coords.extend([p1, p2, p3, p4]) pts1 = np.float32([[p1, p2, p3, p4]]) pts2 = np.float32([[0, 0], [(self.PUZZLE_SIZE - 1), 0], [0, (self.PUZZLE_SIZE - 1)], [(self.PUZZLE_SIZE - 1), (self.PUZZLE_SIZE - 1)]]) matrix = cv2.getPerspectiveTransform(pts1, pts2) puzzle_img = cv2.warpPerspective(self.img_gray, matrix, (self.PUZZLE_SIZE, self.PUZZLE_SIZE)) if (max_area > (self.PUZZLE_SIZE ** 2)): puzzle_img = cv2.GaussianBlur(puzzle_img, (5, 5), 0) if self.debug_mode: color_white = (255, 255, 255) poly_points = np.array([[p1[0], p1[1]], [p2[0], p2[1]], [p4[0], p4[1]], [p3[0], p3[1]]], dtype=np.int32) cv2.polylines(img, [poly_points], isClosed=True, color=color_white, thickness=3) img_show(thr_img) return puzzle_img
Finds the biggest square in the image (that should be the puzzle) After the coordinates of the corners are found (top-lef, top-right, bottom-left, bottom-right), the perspective is warped so that puzzle_img contains only the puzzle. :param thr_img: :return:
sudoku_solver/finder.py
_find_puzzle_section
bbuhai/sudoku-solver
0
python
def _find_puzzle_section(self, thr_img): '\n Finds the biggest square in the image (that should be the puzzle)\n After the coordinates of the corners are found (top-lef, top-right,\n bottom-left, bottom-right), the perspective is warped so that\n puzzle_img contains only the puzzle.\n :param thr_img:\n :return:\n ' (img, contours, h) = cv2.findContours(thr_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) biggest = [] max_area = (- 1) for i in contours: area = cv2.contourArea(i) if (area > 100): perimeter = cv2.arcLength(i, True) approx = cv2.approxPolyDP(i, (0.02 * perimeter), True) if ((area > max_area) and (len(approx) == 4)): biggest = approx max_area = area if (not len(biggest)): raise PuzzleNotFound (p1, p2, p3, p4) = uniformize_points(biggest[0][0], biggest[1][0], biggest[2][0], biggest[3][0]) self._puzzle_coords.extend([p1, p2, p3, p4]) pts1 = np.float32([[p1, p2, p3, p4]]) pts2 = np.float32([[0, 0], [(self.PUZZLE_SIZE - 1), 0], [0, (self.PUZZLE_SIZE - 1)], [(self.PUZZLE_SIZE - 1), (self.PUZZLE_SIZE - 1)]]) matrix = cv2.getPerspectiveTransform(pts1, pts2) puzzle_img = cv2.warpPerspective(self.img_gray, matrix, (self.PUZZLE_SIZE, self.PUZZLE_SIZE)) if (max_area > (self.PUZZLE_SIZE ** 2)): puzzle_img = cv2.GaussianBlur(puzzle_img, (5, 5), 0) if self.debug_mode: color_white = (255, 255, 255) poly_points = np.array([[p1[0], p1[1]], [p2[0], p2[1]], [p4[0], p4[1]], [p3[0], p3[1]]], dtype=np.int32) cv2.polylines(img, [poly_points], isClosed=True, color=color_white, thickness=3) img_show(thr_img) return puzzle_img
def _find_puzzle_section(self, thr_img): '\n Finds the biggest square in the image (that should be the puzzle)\n After the coordinates of the corners are found (top-lef, top-right,\n bottom-left, bottom-right), the perspective is warped so that\n puzzle_img contains only the puzzle.\n :param thr_img:\n :return:\n ' (img, contours, h) = cv2.findContours(thr_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) biggest = [] max_area = (- 1) for i in contours: area = cv2.contourArea(i) if (area > 100): perimeter = cv2.arcLength(i, True) approx = cv2.approxPolyDP(i, (0.02 * perimeter), True) if ((area > max_area) and (len(approx) == 4)): biggest = approx max_area = area if (not len(biggest)): raise PuzzleNotFound (p1, p2, p3, p4) = uniformize_points(biggest[0][0], biggest[1][0], biggest[2][0], biggest[3][0]) self._puzzle_coords.extend([p1, p2, p3, p4]) pts1 = np.float32([[p1, p2, p3, p4]]) pts2 = np.float32([[0, 0], [(self.PUZZLE_SIZE - 1), 0], [0, (self.PUZZLE_SIZE - 1)], [(self.PUZZLE_SIZE - 1), (self.PUZZLE_SIZE - 1)]]) matrix = cv2.getPerspectiveTransform(pts1, pts2) puzzle_img = cv2.warpPerspective(self.img_gray, matrix, (self.PUZZLE_SIZE, self.PUZZLE_SIZE)) if (max_area > (self.PUZZLE_SIZE ** 2)): puzzle_img = cv2.GaussianBlur(puzzle_img, (5, 5), 0) if self.debug_mode: color_white = (255, 255, 255) poly_points = np.array([[p1[0], p1[1]], [p2[0], p2[1]], [p4[0], p4[1]], [p3[0], p3[1]]], dtype=np.int32) cv2.polylines(img, [poly_points], isClosed=True, color=color_white, thickness=3) img_show(thr_img) return puzzle_img<|docstring|>Finds the biggest square in the image (that should be the puzzle) After the coordinates of the corners are found (top-lef, top-right, bottom-left, bottom-right), the perspective is warped so that puzzle_img contains only the puzzle. :param thr_img: :return:<|endoftext|>
55f2e6b96cecb17000936d40c7b1d35d4f1be55828490c9be547abc21d2f62a7
def _get_puzzle_matrix(self, puzzle_img): '\n Returns a 9x9 matrix with the found digits.\n\n Puzzles may have different font sizes and because of that multiple iterations\n are required to find the best width / height.\n\n Another idea is to remove the sudoku grid first and then use the hierarchy\n from findContours to retrieve only the top-level contours.\n (http://answers.opencv.org/question/53293/how-to-remove-line-on-music-sheet/)\n :param img:\n :param original:\n :return:\n ' img_copy = np.copy(puzzle_img) img_color = cv2.cvtColor(img_copy, cv2.COLOR_GRAY2BGR) (i, contours, _) = cv2.findContours(puzzle_img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3)) erode = cv2.erode(img_copy, kernel) img_dilate = cv2.dilate(erode, kernel) trained_knn = get_trained_knn() sudoku_matrix_final = [] (min_w, max_w) = (5, 40) (min_h, max_h) = (44, 59) step = 0 coords_digits_fun = [] coords_digits_final = [] for _ in xrange(33): coords_digits = [] sudoku_matrix = np.empty((9, 9), dtype=np.object) step += 1 i = 0 for cnt in contours: if (cv2.contourArea(cnt) < 20): continue (x, y, w, h) = cv2.boundingRect(cnt) if ((min_w < w < max_w) and ((min_h - step) < h < (max_h - step))): a = (y / 50) b = (x / 50) if ((a, b) in coords_digits): break roi = img_dilate[(y:(y + h), x:(x + w))] digit = cv2.resize(roi, (self.DIGIT_RESIZE_W, self.DIGIT_RESIZE_H)) num_total_px = (self.DIGIT_RESIZE_H * self.DIGIT_RESIZE_W) test_data = digit.reshape(((- 1), num_total_px)).astype(np.float32) (_, result, _, _) = trained_knn.findNearest(test_data, k=1) coords_digits.append((a, b)) coords_digits_fun.append(((x + 3), (y + 3), int(result[(0, 0)]), i)) sudoku_matrix[(a, b)] = int(result[(0, 0)]) i += 1 if (len(coords_digits) > 16): if (not len(sudoku_matrix_final)): sudoku_matrix_final = np.copy(sudoku_matrix) coords_digits_final = deepcopy(coords_digits_fun) else: len_matrix = len(sudoku_matrix[np.where((sudoku_matrix > 0))]) len_final = len(sudoku_matrix_final[np.where((sudoku_matrix_final > 0))]) if (len_matrix > len_final): coords_digits_final = deepcopy(coords_digits_fun) sudoku_matrix_final = np.copy(sudoku_matrix) if self.debug_mode: for (x, y, digit, idx) in coords_digits_final: idx = str(idx) digit = str(digit) cv2.putText(img_color, digit, (x, y), cv2.FONT_HERSHEY_PLAIN, fontScale=1.5, color=(0, 0, 240), thickness=1, lineType=cv2.LINE_AA) img_show(img_color) return sudoku_matrix_final
Returns a 9x9 matrix with the found digits. Puzzles may have different font sizes and because of that multiple iterations are required to find the best width / height. Another idea is to remove the sudoku grid first and then use the hierarchy from findContours to retrieve only the top-level contours. (http://answers.opencv.org/question/53293/how-to-remove-line-on-music-sheet/) :param img: :param original: :return:
sudoku_solver/finder.py
_get_puzzle_matrix
bbuhai/sudoku-solver
0
python
def _get_puzzle_matrix(self, puzzle_img): '\n Returns a 9x9 matrix with the found digits.\n\n Puzzles may have different font sizes and because of that multiple iterations\n are required to find the best width / height.\n\n Another idea is to remove the sudoku grid first and then use the hierarchy\n from findContours to retrieve only the top-level contours.\n (http://answers.opencv.org/question/53293/how-to-remove-line-on-music-sheet/)\n :param img:\n :param original:\n :return:\n ' img_copy = np.copy(puzzle_img) img_color = cv2.cvtColor(img_copy, cv2.COLOR_GRAY2BGR) (i, contours, _) = cv2.findContours(puzzle_img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3)) erode = cv2.erode(img_copy, kernel) img_dilate = cv2.dilate(erode, kernel) trained_knn = get_trained_knn() sudoku_matrix_final = [] (min_w, max_w) = (5, 40) (min_h, max_h) = (44, 59) step = 0 coords_digits_fun = [] coords_digits_final = [] for _ in xrange(33): coords_digits = [] sudoku_matrix = np.empty((9, 9), dtype=np.object) step += 1 i = 0 for cnt in contours: if (cv2.contourArea(cnt) < 20): continue (x, y, w, h) = cv2.boundingRect(cnt) if ((min_w < w < max_w) and ((min_h - step) < h < (max_h - step))): a = (y / 50) b = (x / 50) if ((a, b) in coords_digits): break roi = img_dilate[(y:(y + h), x:(x + w))] digit = cv2.resize(roi, (self.DIGIT_RESIZE_W, self.DIGIT_RESIZE_H)) num_total_px = (self.DIGIT_RESIZE_H * self.DIGIT_RESIZE_W) test_data = digit.reshape(((- 1), num_total_px)).astype(np.float32) (_, result, _, _) = trained_knn.findNearest(test_data, k=1) coords_digits.append((a, b)) coords_digits_fun.append(((x + 3), (y + 3), int(result[(0, 0)]), i)) sudoku_matrix[(a, b)] = int(result[(0, 0)]) i += 1 if (len(coords_digits) > 16): if (not len(sudoku_matrix_final)): sudoku_matrix_final = np.copy(sudoku_matrix) coords_digits_final = deepcopy(coords_digits_fun) else: len_matrix = len(sudoku_matrix[np.where((sudoku_matrix > 0))]) len_final = len(sudoku_matrix_final[np.where((sudoku_matrix_final > 0))]) if (len_matrix > len_final): coords_digits_final = deepcopy(coords_digits_fun) sudoku_matrix_final = np.copy(sudoku_matrix) if self.debug_mode: for (x, y, digit, idx) in coords_digits_final: idx = str(idx) digit = str(digit) cv2.putText(img_color, digit, (x, y), cv2.FONT_HERSHEY_PLAIN, fontScale=1.5, color=(0, 0, 240), thickness=1, lineType=cv2.LINE_AA) img_show(img_color) return sudoku_matrix_final
def _get_puzzle_matrix(self, puzzle_img): '\n Returns a 9x9 matrix with the found digits.\n\n Puzzles may have different font sizes and because of that multiple iterations\n are required to find the best width / height.\n\n Another idea is to remove the sudoku grid first and then use the hierarchy\n from findContours to retrieve only the top-level contours.\n (http://answers.opencv.org/question/53293/how-to-remove-line-on-music-sheet/)\n :param img:\n :param original:\n :return:\n ' img_copy = np.copy(puzzle_img) img_color = cv2.cvtColor(img_copy, cv2.COLOR_GRAY2BGR) (i, contours, _) = cv2.findContours(puzzle_img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3)) erode = cv2.erode(img_copy, kernel) img_dilate = cv2.dilate(erode, kernel) trained_knn = get_trained_knn() sudoku_matrix_final = [] (min_w, max_w) = (5, 40) (min_h, max_h) = (44, 59) step = 0 coords_digits_fun = [] coords_digits_final = [] for _ in xrange(33): coords_digits = [] sudoku_matrix = np.empty((9, 9), dtype=np.object) step += 1 i = 0 for cnt in contours: if (cv2.contourArea(cnt) < 20): continue (x, y, w, h) = cv2.boundingRect(cnt) if ((min_w < w < max_w) and ((min_h - step) < h < (max_h - step))): a = (y / 50) b = (x / 50) if ((a, b) in coords_digits): break roi = img_dilate[(y:(y + h), x:(x + w))] digit = cv2.resize(roi, (self.DIGIT_RESIZE_W, self.DIGIT_RESIZE_H)) num_total_px = (self.DIGIT_RESIZE_H * self.DIGIT_RESIZE_W) test_data = digit.reshape(((- 1), num_total_px)).astype(np.float32) (_, result, _, _) = trained_knn.findNearest(test_data, k=1) coords_digits.append((a, b)) coords_digits_fun.append(((x + 3), (y + 3), int(result[(0, 0)]), i)) sudoku_matrix[(a, b)] = int(result[(0, 0)]) i += 1 if (len(coords_digits) > 16): if (not len(sudoku_matrix_final)): sudoku_matrix_final = np.copy(sudoku_matrix) coords_digits_final = deepcopy(coords_digits_fun) else: len_matrix = len(sudoku_matrix[np.where((sudoku_matrix > 0))]) len_final = len(sudoku_matrix_final[np.where((sudoku_matrix_final > 0))]) if (len_matrix > len_final): coords_digits_final = deepcopy(coords_digits_fun) sudoku_matrix_final = np.copy(sudoku_matrix) if self.debug_mode: for (x, y, digit, idx) in coords_digits_final: idx = str(idx) digit = str(digit) cv2.putText(img_color, digit, (x, y), cv2.FONT_HERSHEY_PLAIN, fontScale=1.5, color=(0, 0, 240), thickness=1, lineType=cv2.LINE_AA) img_show(img_color) return sudoku_matrix_final<|docstring|>Returns a 9x9 matrix with the found digits. Puzzles may have different font sizes and because of that multiple iterations are required to find the best width / height. Another idea is to remove the sudoku grid first and then use the hierarchy from findContours to retrieve only the top-level contours. (http://answers.opencv.org/question/53293/how-to-remove-line-on-music-sheet/) :param img: :param original: :return:<|endoftext|>
c348578b1225b6dcc7edd0065b264f39aa8c0b991323016e8e849e5135f1c83d
@ix.ContainerProperty(timfest_bands) def appearances(self, key): 'key get blah blah blah' self._cb.gets += 1 return self._dict[key]
key get blah blah blah
indexedproperty/test/test_cp.py
appearances
NJDFan/indexedproperty
4
python
@ix.ContainerProperty(timfest_bands) def appearances(self, key): self._cb.gets += 1 return self._dict[key]
@ix.ContainerProperty(timfest_bands) def appearances(self, key): self._cb.gets += 1 return self._dict[key]<|docstring|>key get blah blah blah<|endoftext|>
e07c6456cf09f23ebbc68dfacf14be7e35474f0b3673399a02bf9e686dd576af
@appearances.setter def appearances(self, key, value): 'key set blah blah blah' self._cb.sets += 1 self._dict[key] = value
key set blah blah blah
indexedproperty/test/test_cp.py
appearances
NJDFan/indexedproperty
4
python
@appearances.setter def appearances(self, key, value): self._cb.sets += 1 self._dict[key] = value
@appearances.setter def appearances(self, key, value): self._cb.sets += 1 self._dict[key] = value<|docstring|>key set blah blah blah<|endoftext|>
c9973eca9c3d64f07187df8b98f8e7dc86ef93089d7284575e9f8cd49f09ba9b
@appearances.deleter def appearances(self, key): 'key del blah blah blah' self._cb.dels += 1 self._dict[key] = 0
key del blah blah blah
indexedproperty/test/test_cp.py
appearances
NJDFan/indexedproperty
4
python
@appearances.deleter def appearances(self, key): self._cb.dels += 1 self._dict[key] = 0
@appearances.deleter def appearances(self, key): self._cb.dels += 1 self._dict[key] = 0<|docstring|>key del blah blah blah<|endoftext|>
d3736467544822cc9101a5716fa1cb1856b8d5fc6c05676e2011f0b773619c2d
def plot_venn(lit_vocab, lex_vocab, file='venn_plot.png'): 'The function takes two sets as arguments and draws a Venn diagram \n that shows the intersection between the two sets.\n The legend includes the size of each set and the size \n of the intersection with the other set as a percentage.\n ' plt.figure(figsize=(8, 8)) lit_abs = len(lit_vocab) lex_abs = len(lex_vocab) inter_abs = len(lit_vocab.intersection(lex_vocab)) lit_per = '{:.0%}'.format((inter_abs / lit_abs)) lex_per = '{:.0%}'.format((inter_abs / lex_abs)) lit_legend = f'literary ({str(lit_abs)}) {lit_per} overlap' lex_legend = f'lexical ({str(lex_abs)}) {lex_per} overlap' c = venn2([lit_vocab, lex_vocab], (lit_legend, lex_legend)) c.get_patch_by_id('10').set_color('#fdb515') c.get_patch_by_id('01').set_color('#003262') c.get_patch_by_id('11').set_color('#bc9b6a') plt.savefig(f'viz/{file}', bbox_inches='tight') return
The function takes two sets as arguments and draws a Venn diagram that shows the intersection between the two sets. The legend includes the size of each set and the size of the intersection with the other set as a percentage.
_build/jupyter_execute/3_Vocabularies/3_1_Lit_Lex_Vocab.py
plot_venn
niekveldhuis/compass
8
python
def plot_venn(lit_vocab, lex_vocab, file='venn_plot.png'): 'The function takes two sets as arguments and draws a Venn diagram \n that shows the intersection between the two sets.\n The legend includes the size of each set and the size \n of the intersection with the other set as a percentage.\n ' plt.figure(figsize=(8, 8)) lit_abs = len(lit_vocab) lex_abs = len(lex_vocab) inter_abs = len(lit_vocab.intersection(lex_vocab)) lit_per = '{:.0%}'.format((inter_abs / lit_abs)) lex_per = '{:.0%}'.format((inter_abs / lex_abs)) lit_legend = f'literary ({str(lit_abs)}) {lit_per} overlap' lex_legend = f'lexical ({str(lex_abs)}) {lex_per} overlap' c = venn2([lit_vocab, lex_vocab], (lit_legend, lex_legend)) c.get_patch_by_id('10').set_color('#fdb515') c.get_patch_by_id('01').set_color('#003262') c.get_patch_by_id('11').set_color('#bc9b6a') plt.savefig(f'viz/{file}', bbox_inches='tight') return
def plot_venn(lit_vocab, lex_vocab, file='venn_plot.png'): 'The function takes two sets as arguments and draws a Venn diagram \n that shows the intersection between the two sets.\n The legend includes the size of each set and the size \n of the intersection with the other set as a percentage.\n ' plt.figure(figsize=(8, 8)) lit_abs = len(lit_vocab) lex_abs = len(lex_vocab) inter_abs = len(lit_vocab.intersection(lex_vocab)) lit_per = '{:.0%}'.format((inter_abs / lit_abs)) lex_per = '{:.0%}'.format((inter_abs / lex_abs)) lit_legend = f'literary ({str(lit_abs)}) {lit_per} overlap' lex_legend = f'lexical ({str(lex_abs)}) {lex_per} overlap' c = venn2([lit_vocab, lex_vocab], (lit_legend, lex_legend)) c.get_patch_by_id('10').set_color('#fdb515') c.get_patch_by_id('01').set_color('#003262') c.get_patch_by_id('11').set_color('#bc9b6a') plt.savefig(f'viz/{file}', bbox_inches='tight') return<|docstring|>The function takes two sets as arguments and draws a Venn diagram that shows the intersection between the two sets. The legend includes the size of each set and the size of the intersection with the other set as a percentage.<|endoftext|>
fc55366d0471d4a7c7f4634d2d8da57fc55b2a51f00d0917e2d845fa758b5fae
def generate_launch_description(): '\n Returns ROS2 LaunchDescription object.\n ' gzclient = True realSpeed = False multiInstance = False port = 11345 urdf = 'reinforcement_learning/mara_robot_gripper_140_train.urdf' return ut_launch.generateLaunchDescriptionMara(gzclient, realSpeed, multiInstance, port, urdf)
Returns ROS2 LaunchDescription object.
examples/PHANTOMX/debug/mara_debug.launch.py
generate_launch_description
kkonen/gym-gazebo2
0
python
def generate_launch_description(): '\n \n ' gzclient = True realSpeed = False multiInstance = False port = 11345 urdf = 'reinforcement_learning/mara_robot_gripper_140_train.urdf' return ut_launch.generateLaunchDescriptionMara(gzclient, realSpeed, multiInstance, port, urdf)
def generate_launch_description(): '\n \n ' gzclient = True realSpeed = False multiInstance = False port = 11345 urdf = 'reinforcement_learning/mara_robot_gripper_140_train.urdf' return ut_launch.generateLaunchDescriptionMara(gzclient, realSpeed, multiInstance, port, urdf)<|docstring|>Returns ROS2 LaunchDescription object.<|endoftext|>
04dba9022e00413eb1c88d4ee5f3198c07b33312a401b26c8a6fa24e4cb94d61
def test_optimization_validation(): 'Test that evaluator targets must have at least on calculation\n layer set.' target = EvaluatorTarget(id='name', data_set_ids=['data-set-1'], denominators={'Density': '1.0 * g / mL'}) with pytest.raises(ValidationError): EvaluatorTarget(**{**target.dict(), 'allow_direct_simulation': False})
Test that evaluator targets must have at least on calculation layer set.
nonbonded/tests/library/models/test_targets.py
test_optimization_validation
SimonBoothroyd/nonbonded
5
python
def test_optimization_validation(): 'Test that evaluator targets must have at least on calculation\n layer set.' target = EvaluatorTarget(id='name', data_set_ids=['data-set-1'], denominators={'Density': '1.0 * g / mL'}) with pytest.raises(ValidationError): EvaluatorTarget(**{**target.dict(), 'allow_direct_simulation': False})
def test_optimization_validation(): 'Test that evaluator targets must have at least on calculation\n layer set.' target = EvaluatorTarget(id='name', data_set_ids=['data-set-1'], denominators={'Density': '1.0 * g / mL'}) with pytest.raises(ValidationError): EvaluatorTarget(**{**target.dict(), 'allow_direct_simulation': False})<|docstring|>Test that evaluator targets must have at least on calculation layer set.<|endoftext|>
614fd419c841f1081c26f7bb91731861d4eb9519c1f4fcd7b459ef67feb89bda
def make_patches(boundaries, patch_length=5): " \n 'tile' the boundaries of a city into patches, like a patchwork quilt\n " longitude_factor = 0.00898 longitude_factor_m = (0.00898 / 1000) latitude_factor = (math.cos((abs(boundaries.bounds[1]) * 0.0174533)) / 111.319) latitude_factor_m = (latitude_factor / 1000) bbox = boundaries.bounds height_degrees = abs((bbox[3] - bbox[1])) height_km = (height_degrees / latitude_factor) width_degrees = abs((bbox[2] - bbox[0])) width_km = (width_degrees / longitude_factor) n_hslicers = math.floor((height_km / patch_length)) n_vslicers = math.floor((width_km / patch_length)) hslicers = [] vslicers = [] for i in range(1, (n_hslicers + 1)): h_increment = ((bbox[3] - bbox[1]) / (n_hslicers + 1)) lat = (bbox[1] + (i * h_increment)) slicer = shapely.geometry.LineString([(bbox[0], lat), (bbox[2], lat)]) hslicers.append(slicer) for i in range(1, (n_vslicers + 1)): v_increment = ((bbox[2] - bbox[0]) / (n_vslicers + 1)) lon = (bbox[0] + (i * v_increment)) slicer = shapely.geometry.LineString([(lon, bbox[1]), (lon, bbox[3])]) hslicers.append(slicer) patches = shapely.geometry.MultiPolygon(polygons=[boundaries]) for slicer in (hslicers + vslicers): patches = shapely.geometry.MultiPolygon(polygons=shapely.ops.split(patches, slicer)) print((('cut' + str(len(list(patches)))) + 'patches')) return list(patches)
'tile' the boundaries of a city into patches, like a patchwork quilt
pedestriansfirst.py
make_patches
ITDP/pedestriansfirst
8
python
def make_patches(boundaries, patch_length=5): " \n \n " longitude_factor = 0.00898 longitude_factor_m = (0.00898 / 1000) latitude_factor = (math.cos((abs(boundaries.bounds[1]) * 0.0174533)) / 111.319) latitude_factor_m = (latitude_factor / 1000) bbox = boundaries.bounds height_degrees = abs((bbox[3] - bbox[1])) height_km = (height_degrees / latitude_factor) width_degrees = abs((bbox[2] - bbox[0])) width_km = (width_degrees / longitude_factor) n_hslicers = math.floor((height_km / patch_length)) n_vslicers = math.floor((width_km / patch_length)) hslicers = [] vslicers = [] for i in range(1, (n_hslicers + 1)): h_increment = ((bbox[3] - bbox[1]) / (n_hslicers + 1)) lat = (bbox[1] + (i * h_increment)) slicer = shapely.geometry.LineString([(bbox[0], lat), (bbox[2], lat)]) hslicers.append(slicer) for i in range(1, (n_vslicers + 1)): v_increment = ((bbox[2] - bbox[0]) / (n_vslicers + 1)) lon = (bbox[0] + (i * v_increment)) slicer = shapely.geometry.LineString([(lon, bbox[1]), (lon, bbox[3])]) hslicers.append(slicer) patches = shapely.geometry.MultiPolygon(polygons=[boundaries]) for slicer in (hslicers + vslicers): patches = shapely.geometry.MultiPolygon(polygons=shapely.ops.split(patches, slicer)) print((('cut' + str(len(list(patches)))) + 'patches')) return list(patches)
def make_patches(boundaries, patch_length=5): " \n \n " longitude_factor = 0.00898 longitude_factor_m = (0.00898 / 1000) latitude_factor = (math.cos((abs(boundaries.bounds[1]) * 0.0174533)) / 111.319) latitude_factor_m = (latitude_factor / 1000) bbox = boundaries.bounds height_degrees = abs((bbox[3] - bbox[1])) height_km = (height_degrees / latitude_factor) width_degrees = abs((bbox[2] - bbox[0])) width_km = (width_degrees / longitude_factor) n_hslicers = math.floor((height_km / patch_length)) n_vslicers = math.floor((width_km / patch_length)) hslicers = [] vslicers = [] for i in range(1, (n_hslicers + 1)): h_increment = ((bbox[3] - bbox[1]) / (n_hslicers + 1)) lat = (bbox[1] + (i * h_increment)) slicer = shapely.geometry.LineString([(bbox[0], lat), (bbox[2], lat)]) hslicers.append(slicer) for i in range(1, (n_vslicers + 1)): v_increment = ((bbox[2] - bbox[0]) / (n_vslicers + 1)) lon = (bbox[0] + (i * v_increment)) slicer = shapely.geometry.LineString([(lon, bbox[1]), (lon, bbox[3])]) hslicers.append(slicer) patches = shapely.geometry.MultiPolygon(polygons=[boundaries]) for slicer in (hslicers + vslicers): patches = shapely.geometry.MultiPolygon(polygons=shapely.ops.split(patches, slicer)) print((('cut' + str(len(list(patches)))) + 'patches')) return list(patches)<|docstring|>'tile' the boundaries of a city into patches, like a patchwork quilt<|endoftext|>
dd37891c82db3257c2674155ff63149eddf937dd51fc0b6e5d7627e6025ccc39
def line_to_tensor(line, all_letters): '\n Turn a line into a <line_length x 1 x n_letters>,\n or an array of one-hot letter vectors\n ' tensor = torch.zeros(len(line), 1, len(all_letters)) for (li, letter) in enumerate(line): tensor[li][0][letter_to_index(letter, all_letters)] = 1 return tensor.unsqueeze(0)
Turn a line into a <line_length x 1 x n_letters>, or an array of one-hot letter vectors
src/trw/datasets/name_nationality.py
line_to_tensor
civodlu/trw
3
python
def line_to_tensor(line, all_letters): '\n Turn a line into a <line_length x 1 x n_letters>,\n or an array of one-hot letter vectors\n ' tensor = torch.zeros(len(line), 1, len(all_letters)) for (li, letter) in enumerate(line): tensor[li][0][letter_to_index(letter, all_letters)] = 1 return tensor.unsqueeze(0)
def line_to_tensor(line, all_letters): '\n Turn a line into a <line_length x 1 x n_letters>,\n or an array of one-hot letter vectors\n ' tensor = torch.zeros(len(line), 1, len(all_letters)) for (li, letter) in enumerate(line): tensor[li][0][letter_to_index(letter, all_letters)] = 1 return tensor.unsqueeze(0)<|docstring|>Turn a line into a <line_length x 1 x n_letters>, or an array of one-hot letter vectors<|endoftext|>
8fe955a955b30c3102df1b840cd6e7c8cef4a670792f042399611b44bd08924e
@pytest.mark.parametrize('command', EXPECTED_COMMANDS) @patch('runners.core.ZephyrBinaryRunner.require', side_effect=require_patch) @patch('runners.core.ZephyrBinaryRunner.check_call') def test_blackmagicprobe_init(cc, req, command, runner_config): 'Test commands using a runner created by constructor.' runner = BlackMagicProbeRunner(runner_config, TEST_GDB_SERIAL) runner.run(command) assert (cc.call_args_list == [call(x) for x in EXPECTED_COMMANDS[command]])
Test commands using a runner created by constructor.
scripts/west_commands/tests/test_blackmagicprobe.py
test_blackmagicprobe_init
TeckKitty/zephyr
70
python
@pytest.mark.parametrize('command', EXPECTED_COMMANDS) @patch('runners.core.ZephyrBinaryRunner.require', side_effect=require_patch) @patch('runners.core.ZephyrBinaryRunner.check_call') def test_blackmagicprobe_init(cc, req, command, runner_config): runner = BlackMagicProbeRunner(runner_config, TEST_GDB_SERIAL) runner.run(command) assert (cc.call_args_list == [call(x) for x in EXPECTED_COMMANDS[command]])
@pytest.mark.parametrize('command', EXPECTED_COMMANDS) @patch('runners.core.ZephyrBinaryRunner.require', side_effect=require_patch) @patch('runners.core.ZephyrBinaryRunner.check_call') def test_blackmagicprobe_init(cc, req, command, runner_config): runner = BlackMagicProbeRunner(runner_config, TEST_GDB_SERIAL) runner.run(command) assert (cc.call_args_list == [call(x) for x in EXPECTED_COMMANDS[command]])<|docstring|>Test commands using a runner created by constructor.<|endoftext|>
615626823251f2c70efe967426c0055c92bd64048fce9fc5d7bfadc07c1687c1
@pytest.mark.parametrize('command', EXPECTED_COMMANDS) @patch('runners.core.ZephyrBinaryRunner.require', side_effect=require_patch) @patch('runners.core.ZephyrBinaryRunner.check_call') def test_blackmagicprobe_create(cc, req, command, runner_config): 'Test commands using a runner created from command line parameters.' args = ['--gdb-serial', TEST_GDB_SERIAL] parser = argparse.ArgumentParser() BlackMagicProbeRunner.add_parser(parser) arg_namespace = parser.parse_args(args) runner = BlackMagicProbeRunner.create(runner_config, arg_namespace) runner.run(command) assert (cc.call_args_list == [call(x) for x in EXPECTED_COMMANDS[command]])
Test commands using a runner created from command line parameters.
scripts/west_commands/tests/test_blackmagicprobe.py
test_blackmagicprobe_create
TeckKitty/zephyr
70
python
@pytest.mark.parametrize('command', EXPECTED_COMMANDS) @patch('runners.core.ZephyrBinaryRunner.require', side_effect=require_patch) @patch('runners.core.ZephyrBinaryRunner.check_call') def test_blackmagicprobe_create(cc, req, command, runner_config): args = ['--gdb-serial', TEST_GDB_SERIAL] parser = argparse.ArgumentParser() BlackMagicProbeRunner.add_parser(parser) arg_namespace = parser.parse_args(args) runner = BlackMagicProbeRunner.create(runner_config, arg_namespace) runner.run(command) assert (cc.call_args_list == [call(x) for x in EXPECTED_COMMANDS[command]])
@pytest.mark.parametrize('command', EXPECTED_COMMANDS) @patch('runners.core.ZephyrBinaryRunner.require', side_effect=require_patch) @patch('runners.core.ZephyrBinaryRunner.check_call') def test_blackmagicprobe_create(cc, req, command, runner_config): args = ['--gdb-serial', TEST_GDB_SERIAL] parser = argparse.ArgumentParser() BlackMagicProbeRunner.add_parser(parser) arg_namespace = parser.parse_args(args) runner = BlackMagicProbeRunner.create(runner_config, arg_namespace) runner.run(command) assert (cc.call_args_list == [call(x) for x in EXPECTED_COMMANDS[command]])<|docstring|>Test commands using a runner created from command line parameters.<|endoftext|>
eaf3c6d68c2dd102ca18c5b9e3e6bc407361c7193069cf8596b6ddf4487cbd8f
def parse_args(): '\n Parse input arguments\n ' parser = argparse.ArgumentParser(description='Train a Fast R-CNN network') parser.add_argument('--dataset', dest='dataset', help='training dataset', default='pascal_voc', type=str) parser.add_argument('--cfg', dest='cfg_file', help='optional config file', default='cfgs/res18.yml', type=str) parser.add_argument('--net', dest='net', help='vgg16, res50, res101, res152', default='res101', type=str) parser.add_argument('--set', dest='set_cfgs', help='set config keys', default=None, nargs=argparse.REMAINDER) parser.add_argument('--load_dir', dest='load_dir', help='directory to load models', default='models', type=str) parser.add_argument('--cuda', dest='cuda', help='whether use CUDA', action='store_true') parser.add_argument('--ls', dest='large_scale', help='whether use large imag scale', action='store_true') parser.add_argument('--mGPUs', dest='mGPUs', help='whether use multiple GPUs', action='store_true') parser.add_argument('--cag', dest='class_agnostic', help='whether perform class_agnostic bbox regression', action='store_true') parser.add_argument('--parallel_type', dest='parallel_type', help='which part of model to parallel, 0: all, 1: model before roi pooling', default=0, type=int) parser.add_argument('--checksession', dest='checksession', help='checksession to load model', default=1, type=int) parser.add_argument('--checkepoch', dest='checkepoch', help='checkepoch to load network', default=1, type=int) parser.add_argument('--checkpoint', dest='checkpoint', help='checkpoint to load network', default=10021, type=int) parser.add_argument('--vis', dest='vis', help='visualization mode', action='store_true') parser.add_argument('--refine', dest='refine', help='whether use refine anchor', action='store_true') args = parser.parse_args() return args
Parse input arguments
test_net.py
parse_args
kevincao91/kevin.ai.vehicle_detection
2
python
def parse_args(): '\n \n ' parser = argparse.ArgumentParser(description='Train a Fast R-CNN network') parser.add_argument('--dataset', dest='dataset', help='training dataset', default='pascal_voc', type=str) parser.add_argument('--cfg', dest='cfg_file', help='optional config file', default='cfgs/res18.yml', type=str) parser.add_argument('--net', dest='net', help='vgg16, res50, res101, res152', default='res101', type=str) parser.add_argument('--set', dest='set_cfgs', help='set config keys', default=None, nargs=argparse.REMAINDER) parser.add_argument('--load_dir', dest='load_dir', help='directory to load models', default='models', type=str) parser.add_argument('--cuda', dest='cuda', help='whether use CUDA', action='store_true') parser.add_argument('--ls', dest='large_scale', help='whether use large imag scale', action='store_true') parser.add_argument('--mGPUs', dest='mGPUs', help='whether use multiple GPUs', action='store_true') parser.add_argument('--cag', dest='class_agnostic', help='whether perform class_agnostic bbox regression', action='store_true') parser.add_argument('--parallel_type', dest='parallel_type', help='which part of model to parallel, 0: all, 1: model before roi pooling', default=0, type=int) parser.add_argument('--checksession', dest='checksession', help='checksession to load model', default=1, type=int) parser.add_argument('--checkepoch', dest='checkepoch', help='checkepoch to load network', default=1, type=int) parser.add_argument('--checkpoint', dest='checkpoint', help='checkpoint to load network', default=10021, type=int) parser.add_argument('--vis', dest='vis', help='visualization mode', action='store_true') parser.add_argument('--refine', dest='refine', help='whether use refine anchor', action='store_true') args = parser.parse_args() return args
def parse_args(): '\n \n ' parser = argparse.ArgumentParser(description='Train a Fast R-CNN network') parser.add_argument('--dataset', dest='dataset', help='training dataset', default='pascal_voc', type=str) parser.add_argument('--cfg', dest='cfg_file', help='optional config file', default='cfgs/res18.yml', type=str) parser.add_argument('--net', dest='net', help='vgg16, res50, res101, res152', default='res101', type=str) parser.add_argument('--set', dest='set_cfgs', help='set config keys', default=None, nargs=argparse.REMAINDER) parser.add_argument('--load_dir', dest='load_dir', help='directory to load models', default='models', type=str) parser.add_argument('--cuda', dest='cuda', help='whether use CUDA', action='store_true') parser.add_argument('--ls', dest='large_scale', help='whether use large imag scale', action='store_true') parser.add_argument('--mGPUs', dest='mGPUs', help='whether use multiple GPUs', action='store_true') parser.add_argument('--cag', dest='class_agnostic', help='whether perform class_agnostic bbox regression', action='store_true') parser.add_argument('--parallel_type', dest='parallel_type', help='which part of model to parallel, 0: all, 1: model before roi pooling', default=0, type=int) parser.add_argument('--checksession', dest='checksession', help='checksession to load model', default=1, type=int) parser.add_argument('--checkepoch', dest='checkepoch', help='checkepoch to load network', default=1, type=int) parser.add_argument('--checkpoint', dest='checkpoint', help='checkpoint to load network', default=10021, type=int) parser.add_argument('--vis', dest='vis', help='visualization mode', action='store_true') parser.add_argument('--refine', dest='refine', help='whether use refine anchor', action='store_true') args = parser.parse_args() return args<|docstring|>Parse input arguments<|endoftext|>
99f50d577b15253e6008317d7e085e79e36e8feacf2c8e39b9beaa3bb4e3ac80
def progress_bar(value, max_value, width=15): 'Print progress bar.\n\n Print a progress bar (utilising the carriage return function).\n\n Parameters\n ----------\n value : :obj:`float` or :obj:`int`\n Number representing the current progress of process.\n\n max_value : :obj:`float` or :obj:`int`\n Maximum possible value in process.\n\n width : :obj:`int`, optional\n Number of characters in the progress bar. Default is 15.\n\n ' progress = round(((value / max_value) * width)) remaining = (width - progress) print((('\rOptimisation Progress: ' + ('+' * progress)) + ('-' * remaining)), end='')
Print progress bar. Print a progress bar (utilising the carriage return function). Parameters ---------- value : :obj:`float` or :obj:`int` Number representing the current progress of process. max_value : :obj:`float` or :obj:`int` Maximum possible value in process. width : :obj:`int`, optional Number of characters in the progress bar. Default is 15.
pracopt/utils.py
progress_bar
RobSumner/pracopt
1
python
def progress_bar(value, max_value, width=15): 'Print progress bar.\n\n Print a progress bar (utilising the carriage return function).\n\n Parameters\n ----------\n value : :obj:`float` or :obj:`int`\n Number representing the current progress of process.\n\n max_value : :obj:`float` or :obj:`int`\n Maximum possible value in process.\n\n width : :obj:`int`, optional\n Number of characters in the progress bar. Default is 15.\n\n ' progress = round(((value / max_value) * width)) remaining = (width - progress) print((('\rOptimisation Progress: ' + ('+' * progress)) + ('-' * remaining)), end=)
def progress_bar(value, max_value, width=15): 'Print progress bar.\n\n Print a progress bar (utilising the carriage return function).\n\n Parameters\n ----------\n value : :obj:`float` or :obj:`int`\n Number representing the current progress of process.\n\n max_value : :obj:`float` or :obj:`int`\n Maximum possible value in process.\n\n width : :obj:`int`, optional\n Number of characters in the progress bar. Default is 15.\n\n ' progress = round(((value / max_value) * width)) remaining = (width - progress) print((('\rOptimisation Progress: ' + ('+' * progress)) + ('-' * remaining)), end=)<|docstring|>Print progress bar. Print a progress bar (utilising the carriage return function). Parameters ---------- value : :obj:`float` or :obj:`int` Number representing the current progress of process. max_value : :obj:`float` or :obj:`int` Maximum possible value in process. width : :obj:`int`, optional Number of characters in the progress bar. Default is 15.<|endoftext|>
9eb5b54907a28d8832c391971ac2a8b5c4c9bad69ec03a4db1014e8103f03e73
def evaluate(algorithm, runs=5, filepath=None, description=None): 'Evaluate optimiser performance.\n\n Evaluate the performance of an optimiser class. Because of the random\n search nature of optimiser classes, sevveral evaulation runs are\n performed and results are averaged.\n\n Parameters\n ----------\n algorithms : :class:`pracopt.optimiser.Optimiser`\n The optimiser algorithm class to run.\n\n runs : :obj:`int`, optional.\n The number of runs to use when evaluating optimiser.\n\n filepath : :obj:`str`, Optional\n File path to save results to (as .mat file). If None, file is not\n saved.\n\n description : :obj:`str`, optional.\n Description string to save with results.\n\n Returns\n -------\n results : :class:`numpy.array`\n Result array. Each row consists of [optimiser step, average time,\n average value].\n I.e. the results are averaged across "runs" by objective function\n step.\n\n ' max_evals = algorithm._max_evaluations f_data = np.zeros((max_evals, runs)) time_data = np.zeros((max_evals, runs)) for i in range(runs): algorithm.reset() print('Analysis run: ', i) algorithm.run() data = algorithm.archive.objective_data(max_evals) f_data[(:, i)] = data[(:, 2)] time_data[(:, i)] = data[(:, 1)] f_average = np.reshape(np.mean(f_data, axis=1), (max_evals, 1)) t_average = np.reshape(np.mean(time_data, axis=1), (max_evals, 1)) iters = np.reshape(np.linspace(1, max_evals, max_evals), (max_evals, 1)) if (filepath is not None): data_dict = {'f_average': f_average, 't_average': t_average, 'iters': iters} if (description is not None): data_dict['description'] = description scipy.io.savemat((filepath + '.mat'), data_dict) return np.concatenate((iters, t_average, f_average), axis=1)
Evaluate optimiser performance. Evaluate the performance of an optimiser class. Because of the random search nature of optimiser classes, sevveral evaulation runs are performed and results are averaged. Parameters ---------- algorithms : :class:`pracopt.optimiser.Optimiser` The optimiser algorithm class to run. runs : :obj:`int`, optional. The number of runs to use when evaluating optimiser. filepath : :obj:`str`, Optional File path to save results to (as .mat file). If None, file is not saved. description : :obj:`str`, optional. Description string to save with results. Returns ------- results : :class:`numpy.array` Result array. Each row consists of [optimiser step, average time, average value]. I.e. the results are averaged across "runs" by objective function step.
pracopt/utils.py
evaluate
RobSumner/pracopt
1
python
def evaluate(algorithm, runs=5, filepath=None, description=None): 'Evaluate optimiser performance.\n\n Evaluate the performance of an optimiser class. Because of the random\n search nature of optimiser classes, sevveral evaulation runs are\n performed and results are averaged.\n\n Parameters\n ----------\n algorithms : :class:`pracopt.optimiser.Optimiser`\n The optimiser algorithm class to run.\n\n runs : :obj:`int`, optional.\n The number of runs to use when evaluating optimiser.\n\n filepath : :obj:`str`, Optional\n File path to save results to (as .mat file). If None, file is not\n saved.\n\n description : :obj:`str`, optional.\n Description string to save with results.\n\n Returns\n -------\n results : :class:`numpy.array`\n Result array. Each row consists of [optimiser step, average time,\n average value].\n I.e. the results are averaged across "runs" by objective function\n step.\n\n ' max_evals = algorithm._max_evaluations f_data = np.zeros((max_evals, runs)) time_data = np.zeros((max_evals, runs)) for i in range(runs): algorithm.reset() print('Analysis run: ', i) algorithm.run() data = algorithm.archive.objective_data(max_evals) f_data[(:, i)] = data[(:, 2)] time_data[(:, i)] = data[(:, 1)] f_average = np.reshape(np.mean(f_data, axis=1), (max_evals, 1)) t_average = np.reshape(np.mean(time_data, axis=1), (max_evals, 1)) iters = np.reshape(np.linspace(1, max_evals, max_evals), (max_evals, 1)) if (filepath is not None): data_dict = {'f_average': f_average, 't_average': t_average, 'iters': iters} if (description is not None): data_dict['description'] = description scipy.io.savemat((filepath + '.mat'), data_dict) return np.concatenate((iters, t_average, f_average), axis=1)
def evaluate(algorithm, runs=5, filepath=None, description=None): 'Evaluate optimiser performance.\n\n Evaluate the performance of an optimiser class. Because of the random\n search nature of optimiser classes, sevveral evaulation runs are\n performed and results are averaged.\n\n Parameters\n ----------\n algorithms : :class:`pracopt.optimiser.Optimiser`\n The optimiser algorithm class to run.\n\n runs : :obj:`int`, optional.\n The number of runs to use when evaluating optimiser.\n\n filepath : :obj:`str`, Optional\n File path to save results to (as .mat file). If None, file is not\n saved.\n\n description : :obj:`str`, optional.\n Description string to save with results.\n\n Returns\n -------\n results : :class:`numpy.array`\n Result array. Each row consists of [optimiser step, average time,\n average value].\n I.e. the results are averaged across "runs" by objective function\n step.\n\n ' max_evals = algorithm._max_evaluations f_data = np.zeros((max_evals, runs)) time_data = np.zeros((max_evals, runs)) for i in range(runs): algorithm.reset() print('Analysis run: ', i) algorithm.run() data = algorithm.archive.objective_data(max_evals) f_data[(:, i)] = data[(:, 2)] time_data[(:, i)] = data[(:, 1)] f_average = np.reshape(np.mean(f_data, axis=1), (max_evals, 1)) t_average = np.reshape(np.mean(time_data, axis=1), (max_evals, 1)) iters = np.reshape(np.linspace(1, max_evals, max_evals), (max_evals, 1)) if (filepath is not None): data_dict = {'f_average': f_average, 't_average': t_average, 'iters': iters} if (description is not None): data_dict['description'] = description scipy.io.savemat((filepath + '.mat'), data_dict) return np.concatenate((iters, t_average, f_average), axis=1)<|docstring|>Evaluate optimiser performance. Evaluate the performance of an optimiser class. Because of the random search nature of optimiser classes, sevveral evaulation runs are performed and results are averaged. Parameters ---------- algorithms : :class:`pracopt.optimiser.Optimiser` The optimiser algorithm class to run. runs : :obj:`int`, optional. The number of runs to use when evaluating optimiser. filepath : :obj:`str`, Optional File path to save results to (as .mat file). If None, file is not saved. description : :obj:`str`, optional. Description string to save with results. Returns ------- results : :class:`numpy.array` Result array. Each row consists of [optimiser step, average time, average value]. I.e. the results are averaged across "runs" by objective function step.<|endoftext|>
237ce1ab8e0c038e8917ed26cff22c33b9cd71a9e456f14af7700bc74690d137
def input_email(self, email): "Make webdriver set 'E-Mail' value." self.driver.find_element(*LoginPageLocators.EMAIL_INPUT_FIELD).send_keys(email) return self
Make webdriver set 'E-Mail' value.
pages/login.py
input_email
testsibirtsv/opncrt_taqc
0
python
def input_email(self, email): self.driver.find_element(*LoginPageLocators.EMAIL_INPUT_FIELD).send_keys(email) return self
def input_email(self, email): self.driver.find_element(*LoginPageLocators.EMAIL_INPUT_FIELD).send_keys(email) return self<|docstring|>Make webdriver set 'E-Mail' value.<|endoftext|>
e83d46583965ece3a782f917b5a26b3786d1bf37e7ae57fc13b70d03c88e4a4f
def input_password(self, password): "Make webdriver set 'Password' value." self.driver.find_element(*LoginPageLocators.PASSWORD_INPUT_FIELD).send_keys(password) return self
Make webdriver set 'Password' value.
pages/login.py
input_password
testsibirtsv/opncrt_taqc
0
python
def input_password(self, password): self.driver.find_element(*LoginPageLocators.PASSWORD_INPUT_FIELD).send_keys(password) return self
def input_password(self, password): self.driver.find_element(*LoginPageLocators.PASSWORD_INPUT_FIELD).send_keys(password) return self<|docstring|>Make webdriver set 'Password' value.<|endoftext|>
43d5af57a088e4cea86733c4d4f5a9221601ab95078cf17d5107d4aa11bc80fe
def login(self): "Make webdriver initiate login by click 'Login' Button" self.driver.find_element(*LoginPageLocators.LOGIN_BUTTON).click() return AccountPage(self.driver)
Make webdriver initiate login by click 'Login' Button
pages/login.py
login
testsibirtsv/opncrt_taqc
0
python
def login(self): self.driver.find_element(*LoginPageLocators.LOGIN_BUTTON).click() return AccountPage(self.driver)
def login(self): self.driver.find_element(*LoginPageLocators.LOGIN_BUTTON).click() return AccountPage(self.driver)<|docstring|>Make webdriver initiate login by click 'Login' Button<|endoftext|>
9437f83140dc15981e3c3c2cc48ef0a2c0074e1c08f122f2ccc9e76bcb4d227c
def put(self, key: Any, value: Any): '\n Store the pair in the hash map\n :param key: key of of the the pair to store\n :param value: value to store\n ' position: int = self._position(self._hash(key)) if (self.entries[position] is None): self.entries[position] = LinkedList() self.entries[position].add(HashNode(key=key, value=value)) else: current = self.entries[position].head while ((current is not None) and (current.value.key != key)): current = current.next if (current is None): self.entries[position].add(HashNode(key=key, value=value)) else: current.value.value = value
Store the pair in the hash map :param key: key of of the the pair to store :param value: value to store
helpers/hash_map.py
put
mvgiacomello/leetcode-solutions
0
python
def put(self, key: Any, value: Any): '\n Store the pair in the hash map\n :param key: key of of the the pair to store\n :param value: value to store\n ' position: int = self._position(self._hash(key)) if (self.entries[position] is None): self.entries[position] = LinkedList() self.entries[position].add(HashNode(key=key, value=value)) else: current = self.entries[position].head while ((current is not None) and (current.value.key != key)): current = current.next if (current is None): self.entries[position].add(HashNode(key=key, value=value)) else: current.value.value = value
def put(self, key: Any, value: Any): '\n Store the pair in the hash map\n :param key: key of of the the pair to store\n :param value: value to store\n ' position: int = self._position(self._hash(key)) if (self.entries[position] is None): self.entries[position] = LinkedList() self.entries[position].add(HashNode(key=key, value=value)) else: current = self.entries[position].head while ((current is not None) and (current.value.key != key)): current = current.next if (current is None): self.entries[position].add(HashNode(key=key, value=value)) else: current.value.value = value<|docstring|>Store the pair in the hash map :param key: key of of the the pair to store :param value: value to store<|endoftext|>
b4718cf6678239b1e3b5019f3a111a2cb341731b1f87074ab2697ba30c8d3907
def get(self, key: Any) -> Any: '\n Retrieve the value of a certain key\n :param key: the key to retrieve its value\n :return: the value of the key or None if key does not exist\n ' position = self._position(self._hash(key)) if (self.entries[position] is None): return None else: current: LinkedListNode = self.entries[position].head while ((current is not None) and (current.value.key != key)): current = current.next return (None if (current is None) else current.value.value)
Retrieve the value of a certain key :param key: the key to retrieve its value :return: the value of the key or None if key does not exist
helpers/hash_map.py
get
mvgiacomello/leetcode-solutions
0
python
def get(self, key: Any) -> Any: '\n Retrieve the value of a certain key\n :param key: the key to retrieve its value\n :return: the value of the key or None if key does not exist\n ' position = self._position(self._hash(key)) if (self.entries[position] is None): return None else: current: LinkedListNode = self.entries[position].head while ((current is not None) and (current.value.key != key)): current = current.next return (None if (current is None) else current.value.value)
def get(self, key: Any) -> Any: '\n Retrieve the value of a certain key\n :param key: the key to retrieve its value\n :return: the value of the key or None if key does not exist\n ' position = self._position(self._hash(key)) if (self.entries[position] is None): return None else: current: LinkedListNode = self.entries[position].head while ((current is not None) and (current.value.key != key)): current = current.next return (None if (current is None) else current.value.value)<|docstring|>Retrieve the value of a certain key :param key: the key to retrieve its value :return: the value of the key or None if key does not exist<|endoftext|>
ba1cde3962df8f53236e3286ccc62e2ac02004ebb71c15eac5081f79ed4727e8
def _hash(self, key: Any) -> int: '\n :param key: the value to get the hash from. Must be able to cast to string\n :return: hash (integer) representative of the key\n ' sum = 1 string = str(key) for char in string: sum = ((sum * self.seed) + ord(char)) return sum
:param key: the value to get the hash from. Must be able to cast to string :return: hash (integer) representative of the key
helpers/hash_map.py
_hash
mvgiacomello/leetcode-solutions
0
python
def _hash(self, key: Any) -> int: '\n :param key: the value to get the hash from. Must be able to cast to string\n :return: hash (integer) representative of the key\n ' sum = 1 string = str(key) for char in string: sum = ((sum * self.seed) + ord(char)) return sum
def _hash(self, key: Any) -> int: '\n :param key: the value to get the hash from. Must be able to cast to string\n :return: hash (integer) representative of the key\n ' sum = 1 string = str(key) for char in string: sum = ((sum * self.seed) + ord(char)) return sum<|docstring|>:param key: the value to get the hash from. Must be able to cast to string :return: hash (integer) representative of the key<|endoftext|>
8e9ac288b51a698c9b73ba3a75a198d279630e80fea89c07837d382d06b9ec4c
def _position(self, hash: int) -> int: '\n :param hash: the hashed value of the key\n :return: the position in the list where value should be stored\n ' if (not isinstance(hash, int)): raise ValueError('hash provided should be an integer') position = (hash % self.size) return position
:param hash: the hashed value of the key :return: the position in the list where value should be stored
helpers/hash_map.py
_position
mvgiacomello/leetcode-solutions
0
python
def _position(self, hash: int) -> int: '\n :param hash: the hashed value of the key\n :return: the position in the list where value should be stored\n ' if (not isinstance(hash, int)): raise ValueError('hash provided should be an integer') position = (hash % self.size) return position
def _position(self, hash: int) -> int: '\n :param hash: the hashed value of the key\n :return: the position in the list where value should be stored\n ' if (not isinstance(hash, int)): raise ValueError('hash provided should be an integer') position = (hash % self.size) return position<|docstring|>:param hash: the hashed value of the key :return: the position in the list where value should be stored<|endoftext|>