Datasets:

function_name
stringlengths
1
63
docstring
stringlengths
50
5.89k
masked_code
stringlengths
50
882k
implementation
stringlengths
169
12.9k
start_line
int32
1
14.6k
end_line
int32
16
14.6k
file_content
stringlengths
274
882k
forward
Evaluate qNoisyExpectedImprovement on the candidate set `X`. Args: X: A `(b) x q x d`-dim Tensor of `(b)` t-batches with `q` `d`-dim design points each. Returns: A `(b)`-dim Tensor of Noisy Expected Improvement values at the given design points `X`.
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved r""" Batch acquisition functions using the reparameterization trick in combination with (quasi) Monte-Carlo sampling. See [Rezende2014reparam]_ and [Wilson2017reparam]_ .. [Rezende2014reparam] D. J. Rezende, S. Mohamed,...
@concatenate_pending_points @t_batch_mode_transform() def forward(self, X: Tensor) -> Tensor: r"""Evaluate qNoisyExpectedImprovement on the candidate set `X`. Args: X: A `(b) x q x d`-dim Tensor of `(b)` t-batches with `q` `d`-dim design points each. Ret...
212
233
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved r""" Batch acquisition functions using the reparameterization trick in combination with (quasi) Monte-Carlo sampling. See [Rezende2014reparam]_ and [Wilson2017reparam]_ .. [Rezende2014reparam] D. J. Rezende, S. Mohamed,...
__init__
q-Probability of Improvement. Args: model: A fitted model. best_f: The best objective value observed so far (assumed noiseless). sampler: The sampler used to draw base samples. Defaults to `SobolQMCNormalSampler(num_samples=500, collapse_batch_dims=True)` objective: The MCAcquisitionObjective u...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved r""" Batch acquisition functions using the reparameterization trick in combination with (quasi) Monte-Carlo sampling. See [Rezende2014reparam]_ and [Wilson2017reparam]_ .. [Rezende2014reparam] D. J. Rezende, S. Mohamed,...
def __init__( self, model: Model, best_f: Union[float, Tensor], sampler: Optional[MCSampler] = None, objective: Optional[MCAcquisitionObjective] = None, X_pending: Optional[Tensor] = None, tau: float = 1e-3, ) -> None: r"""q-Probability of Improvem...
255
290
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved r""" Batch acquisition functions using the reparameterization trick in combination with (quasi) Monte-Carlo sampling. See [Rezende2014reparam]_ and [Wilson2017reparam]_ .. [Rezende2014reparam] D. J. Rezende, S. Mohamed,...
forward
Evaluate qProbabilityOfImprovement on the candidate set `X`. Args: X: A `(b) x q x d`-dim Tensor of `(b)` t-batches with `q` `d`-dim design points each. Returns: A `(b)`-dim Tensor of Probability of Improvement values at the given design points `X`.
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved r""" Batch acquisition functions using the reparameterization trick in combination with (quasi) Monte-Carlo sampling. See [Rezende2014reparam]_ and [Wilson2017reparam]_ .. [Rezende2014reparam] D. J. Rezende, S. Mohamed,...
@concatenate_pending_points @t_batch_mode_transform() def forward(self, X: Tensor) -> Tensor: r"""Evaluate qProbabilityOfImprovement on the candidate set `X`. Args: X: A `(b) x q x d`-dim Tensor of `(b)` t-batches with `q` `d`-dim design points each. Ret...
292
310
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved r""" Batch acquisition functions using the reparameterization trick in combination with (quasi) Monte-Carlo sampling. See [Rezende2014reparam]_ and [Wilson2017reparam]_ .. [Rezende2014reparam] D. J. Rezende, S. Mohamed,...
forward
Evaluate qSimpleRegret on the candidate set `X`. Args: X: A `(b) x q x d`-dim Tensor of `(b)` t-batches with `q` `d`-dim design points each. Returns: A `(b)`-dim Tensor of Simple Regret values at the given design points `X`.
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved r""" Batch acquisition functions using the reparameterization trick in combination with (quasi) Monte-Carlo sampling. See [Rezende2014reparam]_ and [Wilson2017reparam]_ .. [Rezende2014reparam] D. J. Rezende, S. Mohamed,...
@concatenate_pending_points @t_batch_mode_transform() def forward(self, X: Tensor) -> Tensor: r"""Evaluate qSimpleRegret on the candidate set `X`. Args: X: A `(b) x q x d`-dim Tensor of `(b)` t-batches with `q` `d`-dim design points each. Returns: ...
328
345
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved r""" Batch acquisition functions using the reparameterization trick in combination with (quasi) Monte-Carlo sampling. See [Rezende2014reparam]_ and [Wilson2017reparam]_ .. [Rezende2014reparam] D. J. Rezende, S. Mohamed,...
forward
Evaluate qUpperConfidenceBound on the candidate set `X`. Args: X: A `(b) x q x d`-dim Tensor of `(b)` t-batches with `q` `d`-dim design points each. Returns: A `(b)`-dim Tensor of Upper Confidence Bound values at the given design points `X`.
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved r""" Batch acquisition functions using the reparameterization trick in combination with (quasi) Monte-Carlo sampling. See [Rezende2014reparam]_ and [Wilson2017reparam]_ .. [Rezende2014reparam] D. J. Rezende, S. Mohamed,...
@concatenate_pending_points @t_batch_mode_transform() def forward(self, X: Tensor) -> Tensor: r"""Evaluate qUpperConfidenceBound on the candidate set `X`. Args: X: A `(b) x q x d`-dim Tensor of `(b)` t-batches with `q` `d`-dim design points each. Returns...
391
409
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved r""" Batch acquisition functions using the reparameterization trick in combination with (quasi) Monte-Carlo sampling. See [Rezende2014reparam]_ and [Wilson2017reparam]_ .. [Rezende2014reparam] D. J. Rezende, S. Mohamed,...
draw_ocr
Visualize the results of OCR detection and recognition args: image(Image|array): RGB image boxes(list): boxes with shape(N, 4, 2) txts(list): the texts scores(list): txxs corresponding scores drop_score(float): only scores greater than drop_threshold will be visualized font_path: the path of fon...
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
def draw_ocr(image, boxes, txts=None, scores=None, drop_score=0.5, font_path="./doc/simfang.ttf"): """ Visualize the results of OCR detection and recognition args: image(Image|array): RGB image boxes(list): boxes with shape(N, ...
207
245
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
str_count
Count the number of Chinese characters, a single English character and a single number equal to half the length of Chinese characters. args: s(string): the input of string return(int): the number of Chinese characters
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
def str_count(s): """ Count the number of Chinese characters, a single English character and a single number equal to half the length of Chinese characters. args: s(string): the input of string return(int): the number of Chinese characters """ import string count_zh =...
300
321
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
get_express_route_gateway
ExpressRoute gateway resource. API Version: 2020-08-01. :param str express_route_gateway_name: The name of the ExpressRoute gateway. :param str resource_group_name: The name of the resource group.
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from .. import _utilities, _tables from ...
def get_express_route_gateway(express_route_gateway_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetExpressRouteGatewayResult: """ ExpressRoute gateway resource. API...
154
184
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from .. import _utilities, _tables from ...
wait_until_upload_url_changed
Wait until upload proxy url is changed Args: timeout (int): Time to wait for CDI Config. Returns: bool: True if url is equal to uploadProxyURL.
# -*- coding: utf-8 -*- import logging from ocp_resources.constants import PROTOCOL_ERROR_EXCEPTION_DICT from ocp_resources.resource import TIMEOUT, Resource from ocp_resources.utils import TimeoutSampler LOGGER = logging.getLogger(__name__) class CDIConfig(Resource): """ CDIConfig object. """ ap...
def wait_until_upload_url_changed(self, uploadproxy_url, timeout=TIMEOUT): """ Wait until upload proxy url is changed Args: timeout (int): Time to wait for CDI Config. Returns: bool: True if url is equal to uploadProxyURL. """ LOGGER.info( ...
32
57
# -*- coding: utf-8 -*- import logging from ocp_resources.constants import PROTOCOL_ERROR_EXCEPTION_DICT from ocp_resources.resource import TIMEOUT, Resource from ocp_resources.utils import TimeoutSampler LOGGER = logging.getLogger(__name__) class CDIConfig(Resource): """ CDIConfig object. """ ap...
as_padded_tensor
This method pads a list of tokens to ``desired_num_tokens`` and returns that padded list of input tokens as a torch Tensor. If the input token list is longer than ``desired_num_tokens`` then it will be truncated. ``padding_lengths`` is used to provide supplemental padding parameters which are needed in some cases. Fo...
from typing import Dict, List, TypeVar, Generic import warnings import torch import numpy from allennlp.common import Registrable from allennlp.data.tokenizers.token import Token from allennlp.data.vocabulary import Vocabulary TokenType = TypeVar("TokenType", int, List[int], numpy.ndarray) class TokenIndexer(Gener...
def as_padded_tensor( self, tokens: Dict[str, List[TokenType]], desired_num_tokens: Dict[str, int], padding_lengths: Dict[str, int], ) -> Dict[str, torch.Tensor]: """ This method pads a list of tokens to ``desired_num_tokens`` and returns that padded list ...
98
124
from typing import Dict, List, TypeVar, Generic import warnings import torch import numpy from allennlp.common import Registrable from allennlp.data.tokenizers.token import Token from allennlp.data.vocabulary import Vocabulary TokenType = TypeVar("TokenType", int, List[int], numpy.ndarray) class TokenIndexer(Gener...
forward
Run the forward pass for an encoder-decoder model. First feed a batch of source tokens through the encoder. Then, feed the encoder output and previous decoder outputs (i.e., input feeding/teacher forcing) to the decoder to produce the next outputs:: encoder_out = self.encoder(src_tokens, src_lengths) return s...
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import math import numpy as np im...
def forward(self, src_tokens, src_lengths, prev_output_tokens, bert_input, **kwargs): """ Run the forward pass for an encoder-decoder model. First feed a batch of source tokens through the encoder. Then, feed the encoder output and previous decoder outputs (i.e., input feeding/teach...
316
352
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import math import numpy...
forward
Args: src_tokens (LongTensor): tokens in the source language of shape `(batch, src_len)` src_lengths (torch.LongTensor): lengths of each source sentence of shape `(batch)` Returns: dict: - **encoder_out** (Tensor): the last encoder layer's output of shape `(src_len, batch,...
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import math import numpy as np im...
def forward(self, src_tokens, src_lengths): """ Args: src_tokens (LongTensor): tokens in the source language of shape `(batch, src_len)` src_lengths (torch.LongTensor): lengths of each source sentence of shape `(batch)` Returns: ...
534
573
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import math import numpy...
encodeMLM
Args: src_tokens (LongTensor): tokens in the source language of shape `(batch, src_len)` src_lengths (torch.LongTensor): lengths of each source sentence of shape `(batch)` Returns: dict: - **encoder_out** (Tensor): the last encoder layer's output of shape `(src_len, batch,...
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import math import numpy as np im...
def encodeMLM(self, src_tokens, src_lengths, bert_encoder_out): """ Args: src_tokens (LongTensor): tokens in the source language of shape `(batch, src_len)` src_lengths (torch.LongTensor): lengths of each source sentence of shape `(batch)` ...
788
859
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import math import numpy...
extract_features
Similar to *forward* but only return features. Returns: tuple: - the decoder's features of shape `(batch, tgt_len, embed_dim)` - a dictionary with any model-specific outputs
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import math import numpy as np im...
def extract_features(self, prev_output_tokens, encoder_out=None, bert_encoder_out=None, incremental_state=None, **unused): """ Similar to *forward* but only return features. Returns: tuple: - the decoder's features of shape `(batch, tgt_len, embed_dim)` ...
1,029
1,087
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import math import numpy...
extract_features
Similar to *forward* but only return features. Returns: tuple: - the decoder's features of shape `(batch, tgt_len, embed_dim)` - a dictionary with any model-specific outputs
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import math import numpy as np im...
def extract_features(self, prev_output_tokens, encoder_out=None, bert_encoder_out=None, incremental_state=None, **unused): """ Similar to *forward* but only return features. Returns: tuple: - the decoder's features of shape `(batch, tgt_len, embed_dim)` ...
1,232
1,290
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import math import numpy...
preprocess_train_input
Pre-process the training data. This is needed because - The label needs to be extended to be used in the loss fn - We need the same inputs for training and eval so adding fake inputs for DUPLICATE_MASK in training data. Args: features: Dictionary of features for training. labels: Training labels. Returns: Pr...
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
def preprocess_train_input(features, labels): """Pre-process the training data. This is needed because - The label needs to be extended to be used in the loss fn - We need the same inputs for training and eval so adding fake inputs for DUPLICATE_MASK in training data. ...
70
88
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
preprocess_eval_input
Pre-process the eval data. This is needed because: - The label needs to be extended to be used in the loss fn - We need the same inputs for training and eval so adding fake inputs for VALID_PT_MASK in eval data. Args: features: Dictionary of features for evaluation. Returns: Processed evaluation features.
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
def preprocess_eval_input(features): """Pre-process the eval data. This is needed because: - The label needs to be extended to be used in the loss fn - We need the same inputs for training and eval so adding fake inputs for VALID_PT_MASK in eval data. Args: ...
93
113
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
output
Output the given rows in tabular format. Each rows is a list of string values. All rows are expected to have the sam elength. The first row is the table header. Parameters ---------- rows: list(string) List of rows in the table
# Copyright (C) 2017-2019 New York University, # University at Buffalo, # Illinois Institute of Technology. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of th...
def output(self, rows): """Output the given rows in tabular format. Each rows is a list of string values. All rows are expected to have the sam elength. The first row is the table header. Parameters ---------- rows: list(string) List of rows in the table ...
52
87
# Copyright (C) 2017-2019 New York University, # University at Buffalo, # Illinois Institute of Technology. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of th...
ProcessFile
Process and write a file of string resources. :param file_name: path to the file to process. :return: None.
# coding=UTF-8 import os import re import sys class BaseStringScript: # State STATE_SEARCHING='STATE_SEARCHING' STATE_IN_STR='STATE_IN_STR' STATE_IN_PLUR='STATE_IN_PLUR' # Tag types TYPE_STR='TYPE_STR' TYPE_PLUR='TYPE_PLUR' # String tag start/end START_STR = '<string' END_STR = '</string' # ...
def ProcessFile(self, file_name): """ Process and write a file of string resources. :param file_name: path to the file to process. :return: None. """ lines = [] state = self.STATE_SEARCHING curr_tag = [] pending_process_type = None with open(file_name, 'r') as myfile: ...
36
86
# coding=UTF-8 import os import re import sys class BaseStringScript: # State STATE_SEARCHING='STATE_SEARCHING' STATE_IN_STR='STATE_IN_STR' STATE_IN_PLUR='STATE_IN_PLUR' # Tag types TYPE_STR='TYPE_STR' TYPE_PLUR='TYPE_PLUR' # String tag start/end START_STR = '<string' END_STR = '</string' # ...
__init__
Args: backbone: either a backbone module or a mmdet config dict that defines a backbone. The backbone takes a 4D image tensor and returns a sequence of tensors. neck: either a backbone module or a mmdet config dict that defines a neck. The neck takes outputs of backbone and returns a ...
# -*- coding: utf-8 -*- import itertools import logging import numpy as np from collections import OrderedDict from collections.abc import Mapping from typing import Dict, List, Optional, Tuple, Union import torch from omegaconf import DictConfig, OmegaConf from torch import Tensor, nn from detectron2.layers import S...
def __init__( self, backbone: Union[nn.Module, Mapping], neck: Union[nn.Module, Mapping, None] = None, *, pretrained_backbone: Optional[str] = None, output_shapes: List[ShapeSpec], output_names: Optional[List[str]] = None, ): """ Args: ...
44
103
# -*- coding: utf-8 -*- import itertools import logging import numpy as np from collections import OrderedDict from collections.abc import Mapping from typing import Dict, List, Optional, Tuple, Union import torch from omegaconf import DictConfig, OmegaConf from torch import Tensor, nn from detectron2.layers import S...
__init__
Args: detector: a mmdet detector, or a mmdet config dict that defines a detector. size_divisibility: pad input images to multiple of this number pixel_mean: per-channel mean to normalize input image pixel_std: per-channel stddev to normalize input image
# -*- coding: utf-8 -*- import itertools import logging import numpy as np from collections import OrderedDict from collections.abc import Mapping from typing import Dict, List, Optional, Tuple, Union import torch from omegaconf import DictConfig, OmegaConf from torch import Tensor, nn from detectron2.layers import S...
def __init__( self, detector: Union[nn.Module, Mapping], *, # Default is 32 regardless of model: # https://github.com/open-mmlab/mmdetection/tree/master/configs/_base_/datasets size_divisibility=32, pixel_mean: Tuple[float], pixel_std: Tuple[float], ...
130
159
# -*- coding: utf-8 -*- import itertools import logging import numpy as np from collections import OrderedDict from collections.abc import Mapping from typing import Dict, List, Optional, Tuple, Union import torch from omegaconf import DictConfig, OmegaConf from torch import Tensor, nn from detectron2.layers import S...
plot_hpvm_configs
Plot the QoS-speedup information in an HPVM configuration file. It is recommended to profile the config file first (using `profile_configs`) to obtain real speedup numbers. This function creates a `matplotlib.pyplot.Figure`, plots on it, and returns it. :param config_path: Path to the config file (HPVM configuration f...
from pathlib import Path from subprocess import PIPE, CalledProcessError from typing import Iterable, List, Tuple, Union import matplotlib.pyplot as plt PathLike = Union[Path, str] conf_opening, conf_closing = "+++++", "-----" def profile_config_file( binary_path: PathLike, config_path: PathLike, output...
def plot_hpvm_configs( config_path: PathLike, save_to: PathLike = None, show_qos_loss: bool = True, **fig_kwargs, ) -> plt.Figure: """ Plot the QoS-speedup information in an HPVM configuration file. It is recommended to profile the config file first (using `profile_configs`) to obtain re...
101
132
from pathlib import Path from subprocess import PIPE, CalledProcessError from typing import Iterable, List, Tuple, Union import matplotlib.pyplot as plt PathLike = Union[Path, str] conf_opening, conf_closing = "+++++", "-----" def profile_config_file( binary_path: PathLike, config_path: PathLike, output...
make_test_file
Generate a test file containing nothing but zeroes. If the file size is negative, a random size between 1 and 10 Kb will be chosen. If the file name is empty, a random one will be generated. Returns: name: (str) name of the test file generated size: (int) size of the test file generated
# pylint: disable=too-many-lines import os import random import shutil import time import uuid from retval import RetVal from pycryptostring import CryptoString from pymensago.encryption import EncryptionPair from pymensago.hash import blake2hash from pymensago.serverconn import ServerConnection from integration_set...
def make_test_file(path: str, file_size=-1, file_name='') -> RetVal: '''Generate a test file containing nothing but zeroes. If the file size is negative, a random size between 1 and 10 Kb will be chosen. If the file name is empty, a random one will be generated. Returns: name: (str) name of the test file gener...
40
64
# pylint: disable=too-many-lines import os import random import shutil import time import uuid from retval import RetVal from pycryptostring import CryptoString from pymensago.encryption import EncryptionPair from pymensago.hash import blake2hash from pymensago.serverconn import ServerConnection from integration_set...
id_to_svd
Convert ID to SVD. The SVD reconstruction of a matrix with skeleton matrix `B` and ID indices and coefficients `idx` and `proj`, respectively, is:: U, S, V = id_to_svd(B, idx, proj) A = numpy.dot(U, numpy.dot(numpy.diag(S), V.conj().T)) See also :func:`svd`. .. This function automatically detects the matri...
#****************************************************************************** # Copyright (C) 2013 Kenneth L. Ho # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions of source code must retain t...
def id_to_svd(B, idx, proj): """ Convert ID to SVD. The SVD reconstruction of a matrix with skeleton matrix `B` and ID indices and coefficients `idx` and `proj`, respectively, is:: U, S, V = id_to_svd(B, idx, proj) A = numpy.dot(U, numpy.dot(numpy.diag(S), V.conj().T)) See also :f...
732
770
#****************************************************************************** # Copyright (C) 2013 Kenneth L. Ho # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions of source code must retain t...
get
Get an existing NetworkVirtualAppliance resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions o...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities fro...
@staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'NetworkVirtualAppliance': """ Get an existing NetworkVirtualAppliance resource's state with the given name, id, and optional extra properties used t...
329
362
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities fro...
__init__
Initialize Euclidean mesh object. Parameters ---------- mesh : jigsaw_msh_t The underlying jigsaw_msh_t object to hold onto mesh data. Raises ------ TypeError If input mesh is not of `jigsaw_msh_t` type. ValueError If input mesh's `mshID` is not equal to ``euclidean-mesh``. If input mesh has `crs` pro...
"""This module defines classes that handle mesh and mesh operations. This module defines a factory class for mesh, similar to geometry and size function factory class. It also defines concrete mesh types. Currently two concrete mesh types are defined for generic Eucledian mesh and specific 2D Eucledian mesh. """ from ...
def __init__(self, mesh: jigsaw_msh_t) -> None: """Initialize Euclidean mesh object. Parameters ---------- mesh : jigsaw_msh_t The underlying jigsaw_msh_t object to hold onto mesh data. Raises ------ TypeError If input mesh is not of ...
81
115
"""This module defines classes that handle mesh and mesh operations. This module defines a factory class for mesh, similar to geometry and size function factory class. It also defines concrete mesh types. Currently two concrete mesh types are defined for generic Eucledian mesh and specific 2D Eucledian mesh. """ from ...
write
Export the mesh object to the disk Parameters ---------- path : path-like Path to which the mesh should be exported. overwrite : bool, default=False Whether to overwrite, if a file already exists in `path` format : { 'grd', '2dm', 'msh', 'vtk' } Format of the export, SMS-2DM or GRD. Returns ------- None ...
"""This module defines classes that handle mesh and mesh operations. This module defines a factory class for mesh, similar to geometry and size function factory class. It also defines concrete mesh types. Currently two concrete mesh types are defined for generic Eucledian mesh and specific 2D Eucledian mesh. """ from ...
def write( self, path: Union[str, os.PathLike], overwrite: bool = False, format : Literal['grd', '2dm', 'msh', 'vtk'] = 'grd', # pylint: disable=W0622 ) -> None: """Export the mesh object to the disk Parameters ---------- p...
117
164
"""This module defines classes that handle mesh and mesh operations. This module defines a factory class for mesh, similar to geometry and size function factory class. It also defines concrete mesh types. Currently two concrete mesh types are defined for generic Eucledian mesh and specific 2D Eucledian mesh. """ from ...
__init__
Initialize Euclidean 2D mesh object. Parameters ---------- mesh : jigsaw_msh_t The underlying jigsaw_msh_t object to hold onto mesh data. Raises ------ ValueError If number of mesh dimensions is not equal to ``2``.
"""This module defines classes that handle mesh and mesh operations. This module defines a factory class for mesh, similar to geometry and size function factory class. It also defines concrete mesh types. Currently two concrete mesh types are defined for generic Eucledian mesh and specific 2D Eucledian mesh. """ from ...
def __init__(self, mesh: jigsaw_msh_t) -> None: """Initialize Euclidean 2D mesh object. Parameters ---------- mesh : jigsaw_msh_t The underlying jigsaw_msh_t object to hold onto mesh data. Raises ------ ValueError If number of mesh di...
246
269
"""This module defines classes that handle mesh and mesh operations. This module defines a factory class for mesh, similar to geometry and size function factory class. It also defines concrete mesh types. Currently two concrete mesh types are defined for generic Eucledian mesh and specific 2D Eucledian mesh. """ from ...
__call__
Calcluates all the polygons of the mesh and extracts its rings. Parameters ---------- Returns ------- gpd.GeoDataFrame Dataframe containing all rings of the mesh hull polygon. The rings are in the form of `shapely.geometry.LinearRing`. Notes ----- The result of this method is cached, so that multiple calls t...
"""This module defines classes that handle mesh and mesh operations. This module defines a factory class for mesh, similar to geometry and size function factory class. It also defines concrete mesh types. Currently two concrete mesh types are defined for generic Eucledian mesh and specific 2D Eucledian mesh. """ from ...
@lru_cache(maxsize=1) def __call__(self) -> gpd.GeoDataFrame: """Calcluates all the polygons of the mesh and extracts its rings. Parameters ---------- Returns ------- gpd.GeoDataFrame Dataframe containing all rings of the mesh hull polygon. ...
714
752
"""This module defines classes that handle mesh and mesh operations. This module defines a factory class for mesh, similar to geometry and size function factory class. It also defines concrete mesh types. Currently two concrete mesh types are defined for generic Eucledian mesh and specific 2D Eucledian mesh. """ from ...
__call__
Calculates all boundary edges for the mesh. Parameters ---------- Returns ------- gpd.GeoDataFrame Dataframe containing all boundary edges of the mesh in the form of `shapely.geometry.LineString` for each coordinate couple. Notes ----- The result of this method is cached, so that multiple calls to it won...
"""This module defines classes that handle mesh and mesh operations. This module defines a factory class for mesh, similar to geometry and size function factory class. It also defines concrete mesh types. Currently two concrete mesh types are defined for generic Eucledian mesh and specific 2D Eucledian mesh. """ from ...
@lru_cache(maxsize=1) def __call__(self) -> gpd.GeoDataFrame: """Calculates all boundary edges for the mesh. Parameters ---------- Returns ------- gpd.GeoDataFrame Dataframe containing all boundary edges of the mesh in the form of `shapel...
810
841
"""This module defines classes that handle mesh and mesh operations. This module defines a factory class for mesh, similar to geometry and size function factory class. It also defines concrete mesh types. Currently two concrete mesh types are defined for generic Eucledian mesh and specific 2D Eucledian mesh. """ from ...
__call__
Calculates all polygons of the mesh including domain islands Parameters ---------- Returns ------- gpd.GeoDataFrame Dataframe containing all polygons of the mesh. See Also -------- implode() Dataframe with a single combined multipolygon. multipolygon() `shapely` multipolygon shape of combined mesh polygo...
"""This module defines classes that handle mesh and mesh operations. This module defines a factory class for mesh, similar to geometry and size function factory class. It also defines concrete mesh types. Currently two concrete mesh types are defined for generic Eucledian mesh and specific 2D Eucledian mesh. """ from ...
@lru_cache(maxsize=1) def __call__(self) -> gpd.GeoDataFrame: """Calculates all polygons of the mesh including domain islands Parameters ---------- Returns ------- gpd.GeoDataFrame Dataframe containing all polygons of the mesh. See Also ...
921
963
"""This module defines classes that handle mesh and mesh operations. This module defines a factory class for mesh, similar to geometry and size function factory class. It also defines concrete mesh types. Currently two concrete mesh types are defined for generic Eucledian mesh and specific 2D Eucledian mesh. """ from ...
__call__
Creates a mapping between element IDs and associated node IDs. Parameters ---------- Returns ------- dict Mapping between element IDs and associated node Ids Notes ----- The result of this method is cached, so that multiple calls to it won't result in multiple calculations. If the mesh is modified and the cache ...
"""This module defines classes that handle mesh and mesh operations. This module defines a factory class for mesh, similar to geometry and size function factory class. It also defines concrete mesh types. Currently two concrete mesh types are defined for generic Eucledian mesh and specific 2D Eucledian mesh. """ from ...
@lru_cache(maxsize=1) def __call__(self) -> Dict[int, npt.NDArray[int]]: """Creates a mapping between element IDs and associated node IDs. Parameters ---------- Returns ------- dict Mapping between element IDs and associated node Ids Notes ...
1,330
1,354
"""This module defines classes that handle mesh and mesh operations. This module defines a factory class for mesh, similar to geometry and size function factory class. It also defines concrete mesh types. Currently two concrete mesh types are defined for generic Eucledian mesh and specific 2D Eucledian mesh. """ from ...
__call__
Retrieve the dataframe for all boundaries information Parameters ---------- Returns ------- gpd.GeoDataFrame Dataframe containing information for all boundaries shape and type. Notes ----- The result of this method is cached, so that multiple calls to it won't result in multiple calculations. If the mesh is ...
"""This module defines classes that handle mesh and mesh operations. This module defines a factory class for mesh, similar to geometry and size function factory class. It also defines concrete mesh types. Currently two concrete mesh types are defined for generic Eucledian mesh and specific 2D Eucledian mesh. """ from ...
@lru_cache(maxsize=1) def __call__(self) -> gpd.GeoDataFrame: """Retrieve the dataframe for all boundaries information Parameters ---------- Returns ------- gpd.GeoDataFrame Dataframe containing information for all boundaries shape and ty...
1,697
1,744
"""This module defines classes that handle mesh and mesh operations. This module defines a factory class for mesh, similar to geometry and size function factory class. It also defines concrete mesh types. Currently two concrete mesh types are defined for generic Eucledian mesh and specific 2D Eucledian mesh. """ from ...
group_policies_gen
Filter policies using the following steps: 1. Apply prioritization among the policies that are sharing the same policy type and resource type 2. Remove redundant policies that may applicable across different types of resource 3. Filter policies based on type and return :param flat_policies: list of flat policies :retur...
# ------------------------------------------------------------------------- # Copyright (c) 2015-2017 AT&T Intellectual Property # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # ...
def group_policies_gen(flat_policies, config): """Filter policies using the following steps: 1. Apply prioritization among the policies that are sharing the same policy type and resource type 2. Remove redundant policies that may applicable across different types of resource 3. Filter policies based on ...
26
55
# ------------------------------------------------------------------------- # Copyright (c) 2015-2017 AT&T Intellectual Property # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # ...
blackbody
The ratio of the blackbody function for dust at frequency nu over the value for reference frequency ref_freq Arguments --------- nu : float Frequency in GHz. ref_freq : float Reference frequency in GHz. Returns ------- blackbody_ratio : float B(nu, T_dust) / B(nu_ref, T_dust)
from __future__ import print_function from __future__ import absolute_import from __future__ import division import numpy as np __all__ = [ "wigner3j", "get_camb_cl", "scale_dust", ] # MASKED: blackbody function (lines 13-37) def rj2cmb(nu_in): """ Conversion from Rayleigh-Jeans units to CMB te...
def blackbody(nu, ref_freq=353.0): """ The ratio of the blackbody function for dust at frequency nu over the value for reference frequency ref_freq Arguments --------- nu : float Frequency in GHz. ref_freq : float Reference frequency in GHz. Returns ------- blac...
13
37
from __future__ import print_function from __future__ import absolute_import from __future__ import division import numpy as np __all__ = [ "wigner3j", "get_camb_cl", "scale_dust", ] def blackbody(nu, ref_freq=353.0): """ The ratio of the blackbody function for dust at frequency nu over the v...
wigner3j
Wigner 3j symbols computed for all valid values of ``L``, as in: .. math:: \begin{pmatrix} \ell_2 & \ell_3 & L \\ m_2 & m_3 & 0 \\ \end{pmatrix} Arguments --------- l2, m2, l3, m3 : int The ell and m values for which to compute the symbols. Returns ------- fj : array_like Array of size ``l...
from __future__ import print_function from __future__ import absolute_import from __future__ import division import numpy as np __all__ = [ "wigner3j", "get_camb_cl", "scale_dust", ] def blackbody(nu, ref_freq=353.0): """ The ratio of the blackbody function for dust at frequency nu over the v...
def wigner3j(l2, m2, l3, m3): r""" Wigner 3j symbols computed for all valid values of ``L``, as in: .. math:: \begin{pmatrix} \ell_2 & \ell_3 & L \\ m_2 & m_3 & 0 \\ \end{pmatrix} Arguments --------- l2, m2, l3, m3 : int The ell and m values for which...
118
155
from __future__ import print_function from __future__ import absolute_import from __future__ import division import numpy as np __all__ = [ "wigner3j", "get_camb_cl", "scale_dust", ] def blackbody(nu, ref_freq=353.0): """ The ratio of the blackbody function for dust at frequency nu over the v...
__init__
Initialize the event. Args: timestamp: The POSIX timestamp value. usage: A string containing the description string of the timestamp. identifier: The row identifier. full_name: A string containing the full name of the Skype account holder. display_name: A string containing the chosen display name of the acco...
# -*- coding: utf-8 -*- """This file contains a basic Skype SQLite parser.""" import logging from plaso.events import time_events from plaso.parsers import sqlite from plaso.parsers.sqlite_plugins import interface __author__ = 'Joaquin Moreno Garijo (bastionado@gmail.com)' class SkypeChatEvent(time_events.PosixTi...
def __init__( self, timestamp, usage, identifier, full_name, display_name, email, country): """Initialize the event. Args: timestamp: The POSIX timestamp value. usage: A string containing the description string of the timestamp. identifier: The row identifier. full_name: A...
46
70
# -*- coding: utf-8 -*- """This file contains a basic Skype SQLite parser.""" import logging from plaso.events import time_events from plaso.parsers import sqlite from plaso.parsers.sqlite_plugins import interface __author__ = 'Joaquin Moreno Garijo (bastionado@gmail.com)' class SkypeChatEvent(time_events.PosixTi...
ParseFileTransfer
Parse the transfer files. There is no direct relationship between who sends the file and who accepts the file. Args: parser_mediator: A parser mediator object (instance of ParserMediator). row: the row with all information related with the file transfers. query: Optional query string. The default is None. c...
# -*- coding: utf-8 -*- """This file contains a basic Skype SQLite parser.""" import logging from plaso.events import time_events from plaso.parsers import sqlite from plaso.parsers.sqlite_plugins import interface __author__ = 'Joaquin Moreno Garijo (bastionado@gmail.com)' class SkypeChatEvent(time_events.PosixTi...
def ParseFileTransfer( self, parser_mediator, row, cache=None, database=None, query=None, **unused_kwargs): """Parse the transfer files. There is no direct relationship between who sends the file and who accepts the file. Args: parser_mediator: A parser mediator object (instance ...
369
446
# -*- coding: utf-8 -*- """This file contains a basic Skype SQLite parser.""" import logging from plaso.events import time_events from plaso.parsers import sqlite from plaso.parsers.sqlite_plugins import interface __author__ = 'Joaquin Moreno Garijo (bastionado@gmail.com)' class SkypeChatEvent(time_events.PosixTi...
set_figure_params
Set resolution/size, styling and format of figures. Parameters ---------- scanpy Init default values for :obj:`matplotlib.rcParams` suited for Scanpy. dpi Resolution of rendered figures - this influences the size of figures in notebooks. dpi_save Resolution of saved figures. This should typically be higher...
import inspect import sys from enum import IntEnum from pathlib import Path from time import time from logging import getLevelName from typing import Tuple, Union, Any, List, Iterable, TextIO, Optional from . import logging from .logging import _set_log_level, _set_log_file, RootLogger _VERBOSITY_TO_LOGLEVEL = { ...
def set_figure_params( self, scanpy: bool = True, dpi: int = 80, dpi_save: int = 150, frameon: bool = True, vector_friendly: bool = True, fontsize: int = 14, color_map: Optional[str] = None, format: Union[str, Iterable[str]] = "pdf", tr...
349
410
import inspect import sys from enum import IntEnum from pathlib import Path from time import time from logging import getLevelName from typing import Tuple, Union, Any, List, Iterable, TextIO, Optional from . import logging from .logging import _set_log_level, _set_log_file, RootLogger _VERBOSITY_TO_LOGLEVEL = { ...
request_endpoint
Request the speech service endpoint Args: audio: Input data frame speech_config: Choice between scoring and output_folder: LUIS app ID case: LUIS subscription key lexical: Minimum confidence score for LUIS result, between 0.00 and 1.00 Returns: df: Scoring data frame with predicted intents and ...
''' SPEECH-TO-TEXT USING MICROSOFT SPEECH API ''' ''' nonstoptimm@gmail.com ''' # Import required packages import os import glob import json import logging import codecs import helper as he import azure.cognitiveservices.speech as speechsdk import params as pa # Load and set configuration parameters pa.get_config() ...
def request_endpoint(audio, speech_config, output_directory, lexical): """Request the speech service endpoint Args: audio: Input data frame speech_config: Choice between scoring and output_folder: LUIS app ID case: LUIS subscription key lexical: Minimum confidence score ...
17
35
''' SPEECH-TO-TEXT USING MICROSOFT SPEECH API ''' ''' nonstoptimm@gmail.com ''' # Import required packages import os import glob import json import logging import codecs import helper as he import azure.cognitiveservices.speech as speechsdk import params as pa # Load and set configuration parameters pa.get_config() ...
write_transcription
Write transcription to file Args: text: Processed recognition as string output_directory: Output directory for the file Returns: Writes output to file
''' SPEECH-TO-TEXT USING MICROSOFT SPEECH API ''' ''' nonstoptimm@gmail.com ''' # Import required packages import os import glob import json import logging import codecs import helper as he import azure.cognitiveservices.speech as speechsdk import params as pa # Load and set configuration parameters pa.get_config() ...
def write_transcription(output_directory, text): """Write transcription to file Args: text: Processed recognition as string output_directory: Output directory for the file Returns: Writes output to file """ if not os.path.exists(f'{output_directory}/transcriptions.txt'): ...
65
79
''' SPEECH-TO-TEXT USING MICROSOFT SPEECH API ''' ''' nonstoptimm@gmail.com ''' # Import required packages import os import glob import json import logging import codecs import helper as he import azure.cognitiveservices.speech as speechsdk import params as pa # Load and set configuration parameters pa.get_config() ...
main
Main function for STT-functionality Args: speech_files: Directory of audio files to be transcribed output_directory: Output directory for the file lexical: Boolean to enable extended lexical version of STT-result enable_proxy: Boolean to enable proxy function in case you need it *argv: Proxy informa...
''' SPEECH-TO-TEXT USING MICROSOFT SPEECH API ''' ''' nonstoptimm@gmail.com ''' # Import required packages import os import glob import json import logging import codecs import helper as he import azure.cognitiveservices.speech as speechsdk import params as pa # Load and set configuration parameters pa.get_config() ...
def main(speech_files, output_directory, lexical = False, enable_proxy = False, *argv): """Main function for STT-functionality Args: speech_files: Directory of audio files to be transcribed output_directory: Output directory for the file lexical: Boolean to enable extended lexical versio...
81
112
''' SPEECH-TO-TEXT USING MICROSOFT SPEECH API ''' ''' nonstoptimm@gmail.com ''' # Import required packages import os import glob import json import logging import codecs import helper as he import azure.cognitiveservices.speech as speechsdk import params as pa # Load and set configuration parameters pa.get_config() ...
save_checkpoint
Save model, optimizer, scheduler and training stats to file. Args: params: It is returned by :func:`get_params`. model: The training model.
#!/usr/bin/env python3 # Copyright 2021 Xiaomi Corp. (authors: Fangjun Kuang # Mingshuang Luo) # # See ../../../../LICENSE for clarification regarding multiple authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use th...
def save_checkpoint( params: AttributeDict, model: nn.Module, optimizer: torch.optim.Optimizer, scheduler: torch.optim.lr_scheduler._LRScheduler, rank: int = 0, ) -> None: """Save model, optimizer, scheduler and training stats to file. Args: params: It is returned by :func:`ge...
232
265
#!/usr/bin/env python3 # Copyright 2021 Xiaomi Corp. (authors: Fangjun Kuang # Mingshuang Luo) # # See ../../../../LICENSE for clarification regarding multiple authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use th...
compute_validation_loss
Run the validation process. The validation loss is saved in `params.valid_loss`.
#!/usr/bin/env python3 # Copyright 2021 Xiaomi Corp. (authors: Fangjun Kuang # Mingshuang Luo) # # See ../../../../LICENSE for clarification regarding multiple authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use th...
def compute_validation_loss( params: AttributeDict, model: nn.Module, graph_compiler: CtcTrainingGraphCompiler, valid_dl: torch.utils.data.DataLoader, world_size: int = 1, ) -> MetricsTracker: """Run the validation process. The validation loss is saved in `params.valid_loss`. """ mod...
338
373
#!/usr/bin/env python3 # Copyright 2021 Xiaomi Corp. (authors: Fangjun Kuang # Mingshuang Luo) # # See ../../../../LICENSE for clarification regarding multiple authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use th...
__exists_replicas
Internal method to check if a replica exists at a given site. :param rse_id: The RSE id. :param scope: The scope of the file. :param name: The name of the file. :param path: The path of the replica. :param session: The database session in use.
# -*- coding: utf-8 -*- # Copyright 2013-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
@read_session def __exists_replicas(rse_id, scope=None, name=None, path=None, session=None): """ Internal method to check if a replica exists at a given site. :param rse_id: The RSE id. :param scope: The scope of the file. :param name: The name of the file. :param path: The path of the replica. ...
142
176
# -*- coding: utf-8 -*- # Copyright 2013-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
list_bad_replicas_history
List the bad file replicas history. Method only used by necromancer :param limit: The maximum number of replicas returned. :param thread: The assigned thread for this necromancer. :param total_threads: The total number of threads of all necromancers. :param session: The database session in use.
# -*- coding: utf-8 -*- # Copyright 2013-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
@read_session def list_bad_replicas_history(limit=10000, thread=None, total_threads=None, session=None): """ List the bad file replicas history. Method only used by necromancer :param limit: The maximum number of replicas returned. :param thread: The assigned thread for this necromancer. :param tot...
225
246
# -*- coding: utf-8 -*- # Copyright 2013-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
declare_bad_file_replicas
Declare a list of bad replicas. :param pfns: The list of PFNs. :param reason: The reason of the loss. :param issuer: The issuer account. :param status: The status of the file (SUSPICIOUS or BAD). :param session: The database session in use.
# -*- coding: utf-8 -*- # Copyright 2013-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
@transactional_session def declare_bad_file_replicas(pfns, reason, issuer, status=BadFilesStatus.BAD, session=None): """ Declare a list of bad replicas. :param pfns: The list of PFNs. :param reason: The reason of the loss. :param issuer: The issuer account. :param status: The status of the file...
465
481
# -*- coding: utf-8 -*- # Copyright 2013-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
list_bad_replicas
List RSE File replicas with no locks. :param limit: The maximum number of replicas returned. :param thread: The assigned thread for this necromancer. :param total_threads: The total number of threads of all necromancers. :param session: The database session in use. :returns: a list of dictionary {'scope' scope, 'name...
# -*- coding: utf-8 -*- # Copyright 2013-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
@read_session def list_bad_replicas(limit=10000, thread=None, total_threads=None, session=None): """ List RSE File replicas with no locks. :param limit: The maximum number of replicas returned. :param thread: The assigned thread for this necromancer. :param total_threads: The total number of thread...
540
578
# -*- coding: utf-8 -*- # Copyright 2013-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
__bulk_add_file_dids
Bulk add new dids. :param dids: the list of files. :param account: The account owner. :param session: The database session in use. :returns: True is successful.
# -*- coding: utf-8 -*- # Copyright 2013-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
@transactional_session def __bulk_add_file_dids(files, account, dataset_meta=None, session=None): """ Bulk add new dids. :param dids: the list of files. :param account: The account owner. :param session: The database session in use. :returns: True is successful. """ condition = [] f...
1,370
1,402
# -*- coding: utf-8 -*- # Copyright 2013-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
add_replica
Add File replica. :param rse_id: the rse id. :param scope: the scope name. :param name: The data identifier name. :param bytes: the size of the file. :param account: The account owner. :param md5: The md5 checksum. :param adler32: The adler32 checksum. :param pfn: Physical file name (for nondeterministic rse). :param ...
# -*- coding: utf-8 -*- # Copyright 2013-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
@transactional_session def add_replica(rse_id, scope, name, bytes, account, adler32=None, md5=None, dsn=None, pfn=None, meta=None, rules=[], tombstone=None, session=None): """ Add File replica. :param rse_id: the rse id. :param scope: the scope name. :param name: The data identifier name. :para...
1,572
1,598
# -*- coding: utf-8 -*- # Copyright 2013-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
get_source_replicas
Get soruce replicas for a specific scope:name. :param scope: The scope of the did. :param name: The name of the did. :param soruce_rses: Possible RSE_ids to filter on. :param session: The db session in use. :returns: List of SQLAlchemy Replica Objects
# -*- coding: utf-8 -*- # Copyright 2013-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
@transactional_session def get_source_replicas(scope, name, source_rses=None, session=None): """ Get soruce replicas for a specific scope:name. :param scope: The scope of the did. :param name: The name of the did. :param soruce_rses: Possible RSE_ids to filter on. :param s...
2,223
2,243
# -*- coding: utf-8 -*- # Copyright 2013-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
get_source_replicas_for_dataset
Get file replicas for all files of a dataset. :param scope: The scope of the dataset. :param name: The name of the dataset. :param source_rses: Possible source RSE_ids to filter on. :param total_threads: Total threads :param thread_id: This thread :param session: The db session in us...
# -*- coding: utf-8 -*- # Copyright 2013-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
@transactional_session def get_source_replicas_for_dataset(scope, name, source_rses=None, total_threads=None, thread_id=None, session=None): """ Get file replicas for all files of a dataset. :param scope: The scope of the data...
2,392
2,451
# -*- coding: utf-8 -*- # Copyright 2013-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
list_dataset_replicas_bulk
:param names_by_intscope: The dictionary of internal scopes pointing at the list of names. :param session: Database session to use. :returns: A list of dictionaries containing the dataset replicas with associated metrics and timestamps
# -*- coding: utf-8 -*- # Copyright 2013-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
@stream_session def list_dataset_replicas_bulk(names_by_intscope, session=None): """ :param names_by_intscope: The dictionary of internal scopes pointing at the list of names. :param session: Database session to use. :returns: A list of dictionaries containing the dataset replicas with as...
2,643
2,680
# -*- coding: utf-8 -*- # Copyright 2013-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
list_dataset_replicas_vp
List dataset replicas for a DID (scope:name) using the Virtual Placement service. NOTICE: This is an RnD function and might change or go away at any time. :param scope: The scope of the dataset. :param name: The name of the dataset. :param deep: Lookup at the file level. :param session: Database session to use. :ret...
# -*- coding: utf-8 -*- # Copyright 2013-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
@stream_session def list_dataset_replicas_vp(scope, name, deep=False, session=None, logger=logging.log): """ List dataset replicas for a DID (scope:name) using the Virtual Placement service. NOTICE: This is an RnD function and might change or go away at any time. :param scope: The scope of the dat...
2,683
2,734
# -*- coding: utf-8 -*- # Copyright 2013-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
list_datasets_per_rse
List datasets at a RSE. :param rse: the rse id. :param filters: dictionary of attributes by which the results should be filtered. :param limit: limit number. :param session: Database session to use. :returns: A list of dict dataset replicas
# -*- coding: utf-8 -*- # Copyright 2013-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
@stream_session def list_datasets_per_rse(rse_id, filters=None, limit=None, session=None): """ List datasets at a RSE. :param rse: the rse id. :param filters: dictionary of attributes by which the results should be filtered. :param limit: limit number. :param session: Database session to use. ...
2,737
2,790
# -*- coding: utf-8 -*- # Copyright 2013-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
get_bad_pfns
Returns a list of bad PFNs :param limit: The maximum number of replicas returned. :param thread: The assigned thread for this minos instance. :param total_threads: The total number of minos threads. :param session: The database session in use. returns: list of PFNs {'pfn': pfn, 'state': state, 'reason': reason, 'acco...
# -*- coding: utf-8 -*- # Copyright 2013-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
@read_session def get_bad_pfns(limit=10000, thread=None, total_threads=None, session=None): """ Returns a list of bad PFNs :param limit: The maximum number of replicas returned. :param thread: The assigned thread for this minos instance. :param total_threads: The total number of minos threads. ...
2,970
2,989
# -*- coding: utf-8 -*- # Copyright 2013-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
add_bad_pfns
Add bad PFNs. :param pfns: the list of new files. :param account: The account who declared the bad replicas. :param state: One of the possible states : BAD, SUSPICIOUS, TEMPORARY_UNAVAILABLE. :param reason: A string describing the reason of the loss. :param expires_at: Specify a timeout for the TEMPORARY_UNAVAILABLE r...
# -*- coding: utf-8 -*- # Copyright 2013-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
@transactional_session def add_bad_pfns(pfns, account, state, reason=None, expires_at=None, session=None): """ Add bad PFNs. :param pfns: the list of new files. :param account: The account who declared the bad replicas. :param state: One of the possible states : BAD, SUSPICIOUS, TEMPORARY_UNAVAILAB...
3,072
3,108
# -*- coding: utf-8 -*- # Copyright 2013-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
list_expired_temporary_unavailable_replicas
List the expired temporary unavailable replicas :param total_workers: Number of total workers. :param worker_number: id of the executing worker. :param limit: The maximum number of replicas returned. :param session: The database session in use.
# -*- coding: utf-8 -*- # Copyright 2013-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
@read_session def list_expired_temporary_unavailable_replicas(total_workers, worker_number, limit=10000, session=None): """ List the expired temporary unavailable replicas :param total_workers: Number of total workers. :param worker_number: id of the executing worker. :param limit: Th...
3,111
3,130
# -*- coding: utf-8 -*- # Copyright 2013-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
get_replicas_state
Method used by the necromancer to get all the replicas of a DIDs :param scope: The scope of the file. :param name: The name of the file. :param session: The database session in use. :returns: A dictionary with the list of states as keys and the rse_ids as value
# -*- coding: utf-8 -*- # Copyright 2013-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
@read_session def get_replicas_state(scope=None, name=None, session=None): """ Method used by the necromancer to get all the replicas of a DIDs :param scope: The scope of the file. :param name: The name of the file. :param session: The database session in use. :returns: A dictionary with the li...
3,133
3,151
# -*- coding: utf-8 -*- # Copyright 2013-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
set_tombstone
Sets a tombstone on a replica. :param rse_id: ID of RSE. :param scope: scope of the replica DID. :param name: name of the replica DID. :param tombstone: the tombstone to set. Default is OBSOLETE :param session: database session in use.
# -*- coding: utf-8 -*- # Copyright 2013-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
@transactional_session def set_tombstone(rse_id, scope, name, tombstone=OBSOLETE, session=None): """ Sets a tombstone on a replica. :param rse_id: ID of RSE. :param scope: scope of the replica DID. :param name: name of the replica DID. :param tombstone: the tombstone to set. Default is OBSOLETE...
3,250
3,283
# -*- coding: utf-8 -*- # Copyright 2013-2021 CERN # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
inverse_deriv2
Second derivative of the inverse link function g^(-1)(z). Parameters ---------- z : array_like `z` is usually the linear predictor for a GLM or GEE model. Returns ------- g^(-1)''(z) : ndarray The value of the second derivative of the inverse of the link function Notes ----- This method should be overwri...
''' Defines the link functions to be used with GLM and GEE families. ''' import numpy as np import scipy.stats FLOAT_EPS = np.finfo(float).eps class Link(object): """ A generic link function for one-parameter exponential family. `Link` does nothing, but lays out the methods expected of any subclass. ...
def inverse_deriv2(self, z): """ Second derivative of the inverse link function g^(-1)(z). Parameters ---------- z : array_like `z` is usually the linear predictor for a GLM or GEE model. Returns ------- g^(-1)''(z) : ndarray ...
710
735
''' Defines the link functions to be used with GLM and GEE families. ''' import numpy as np import scipy.stats FLOAT_EPS = np.finfo(float).eps class Link(object): """ A generic link function for one-parameter exponential family. `Link` does nothing, but lays out the methods expected of any subclass. ...
_default_hashfunc
Default hash function is variable-length version of Python's builtin hash. :param content: data that needs to hash. :return: return a decimal number.
# Created by SylvanasSun in 2017.10.17 # !/usr/bin/python # -*- coding: utf-8 -*- import collections import jieba from jieba import analyse # TODO: Change default hash algorithms to the other algorithms of high-performance. # MASKED: _default_hashfunc function (lines 11-29) # TODO: Change default toknizer to the c...
def _default_hashfunc(content, hashbits): """ Default hash function is variable-length version of Python's builtin hash. :param content: data that needs to hash. :return: return a decimal number. """ if content == "": return 0 x = ord(content[0]) << 7 m = 1000003 mask = 2 *...
11
29
# Created by SylvanasSun in 2017.10.17 # !/usr/bin/python # -*- coding: utf-8 -*- import collections import jieba from jieba import analyse # TODO: Change default hash algorithms to the other algorithms of high-performance. def _default_hashfunc(content, hashbits): """ Default hash function is variable-lengt...
__init__
:param data: data that needs to be encode. :param keyword_weight_pair: maximum pair number of the keyword-weight list. :param hash_bit_number: maximum bit number for hashcode. :param hashfunc: hash function,its first parameter must be data that needs to be encode and the second parameter must be hash b...
# Created by SylvanasSun in 2017.10.17 # !/usr/bin/python # -*- coding: utf-8 -*- import collections import jieba from jieba import analyse # TODO: Change default hash algorithms to the other algorithms of high-performance. def _default_hashfunc(content, hashbits): """ Default hash function is variable-lengt...
def __init__(self, data, keyword_weight_pair=20, hash_bit_number=64, hashfunc=None, tokenizer_func=None): """ :param data: data that needs to be encode. :param keyword_weight_pair: maximum pair number of the keyword-weight list. :param hash_bit_number: maximum bit number for hashcode...
54
83
# Created by SylvanasSun in 2017.10.17 # !/usr/bin/python # -*- coding: utf-8 -*- import collections import jieba from jieba import analyse # TODO: Change default hash algorithms to the other algorithms of high-performance. def _default_hashfunc(content, hashbits): """ Default hash function is variable-lengt...
is_equal
Determine two simhash are similar or not similar. :param another: another simhash. :param limit: a limit of the similarity. :return: if similarity greater than limit return true and else return false.
# Created by SylvanasSun in 2017.10.17 # !/usr/bin/python # -*- coding: utf-8 -*- import collections import jieba from jieba import analyse # TODO: Change default hash algorithms to the other algorithms of high-performance. def _default_hashfunc(content, hashbits): """ Default hash function is variable-lengt...
def is_equal(self, another, limit=0.8): """ Determine two simhash are similar or not similar. :param another: another simhash. :param limit: a limit of the similarity. :return: if similarity greater than limit return true and else return false. """ if another...
139
161
# Created by SylvanasSun in 2017.10.17 # !/usr/bin/python # -*- coding: utf-8 -*- import collections import jieba from jieba import analyse # TODO: Change default hash algorithms to the other algorithms of high-performance. def _default_hashfunc(content, hashbits): """ Default hash function is variable-lengt...
hamming_distance
Compute hamming distance,hamming distance is a total number of different bits of two binary numbers. :param another: another simhash value. :return: a hamming distance that current simhash and another simhash.
# Created by SylvanasSun in 2017.10.17 # !/usr/bin/python # -*- coding: utf-8 -*- import collections import jieba from jieba import analyse # TODO: Change default hash algorithms to the other algorithms of high-performance. def _default_hashfunc(content, hashbits): """ Default hash function is variable-lengt...
def hamming_distance(self, another): """ Compute hamming distance,hamming distance is a total number of different bits of two binary numbers. :param another: another simhash value. :return: a hamming distance that current simhash and another simhash. """ x = (self.ha...
163
175
# Created by SylvanasSun in 2017.10.17 # !/usr/bin/python # -*- coding: utf-8 -*- import collections import jieba from jieba import analyse # TODO: Change default hash algorithms to the other algorithms of high-performance. def _default_hashfunc(content, hashbits): """ Default hash function is variable-lengt...
process_20_newsgroups
Process 20 newsgroups into (data, target, metadata) format. Parameters ---------- unpack_dir: path The interim parent directory the dataset files have been unpacked into. extract_dir: str Name of the directory of the unpacked files relative to the unpack_dir. Note that opts: dict default {"subset":"all", "rem...
""" Custom dataset processing/generation functions should be added to this file """ import pathlib from sklearn.datasets import fetch_20newsgroups from functools import partial from src import workflow, paths from src.log import logger import src.log.debug from tqdm.auto import tqdm from .. import paths from ..log ...
def process_20_newsgroups(*, extract_dir='20_newsgroups', metadata=None, unpack_dir=None, opts={"subset":"all", "remove":"('headers', 'footers', 'quotes')"}): """ Process 20 newsgroups into (data, target, metadata) format. Parameters ---------- u...
23
58
""" Custom dataset processing/generation functions should be added to this file """ import pathlib from sklearn.datasets import fetch_20newsgroups from functools import partial from src import workflow, paths from src.log import logger import src.log.debug from tqdm.auto import tqdm from .. import paths from ..log ...
flatten_args
Converts a dictionary of dictionarys and lists into a flat table. Args: args_in: dictionary containing a hierachy of dictionaries and lists. Leaf values can be strings, bools, numbers.. Returns: A flat dictionary with keys separated by '.' and string values.
# Lint as: python3 # Copyright 2020 The DMLab2D Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
def flatten_args(args_in): """Converts a dictionary of dictionarys and lists into a flat table. Args: args_in: dictionary containing a hierachy of dictionaries and lists. Leaf values can be strings, bools, numbers.. Returns: A flat dictionary with keys separated by '.' and string values. """ a...
50
62
# Lint as: python3 # Copyright 2020 The DMLab2D Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
__init__
Convolutional model :param kwargs: window_size: int stride_size: int test_percentage: float n_features: int n_outputs: int
from random import shuffle from models.RainbowModelLeaveRecsOut import RainbowModelLeaveRecsOut from tensorflow.keras.layers import Conv1D, MaxPooling1D, Flatten, Dense, Dropout # type: ignore from tensorflow.keras.models import Sequential # type: ignore import numpy as np from utils.Recording import Recording from ...
def __init__(self, **kwargs): """ Convolutional model :param kwargs: window_size: int stride_size: int test_percentage: float n_features: int n_outputs: int """ # hyper params to instance vars self.window_si...
13
34
from random import shuffle from models.RainbowModelLeaveRecsOut import RainbowModelLeaveRecsOut from tensorflow.keras.layers import Conv1D, MaxPooling1D, Flatten, Dense, Dropout # type: ignore from tensorflow.keras.models import Sequential # type: ignore import numpy as np from utils.Recording import Recording from ...
pol2cart
Function that converts polar coordinates to cartesian coordinates. Args: rho (torch.Tensor): Tensor of arbitrary shape. phi (torch.Tensor): Tensor of same arbitrary shape. Returns: torch.Tensor, torch.Tensor: Tensor with same shape as input. Example: >>> rho = torch.rand(1, 3, 3) >>> phi = torch....
from typing import Tuple import torch import torch.nn as nn import torch.nn.functional as F from kornia.constants import pi __all__ = [ # functional api "rad2deg", "deg2rad", "pol2cart", "cart2pol", "convert_points_from_homogeneous", "convert_points_to_homogeneous", "convert_affinematr...
def pol2cart(rho: torch.Tensor, phi: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: r"""Function that converts polar coordinates to cartesian coordinates. Args: rho (torch.Tensor): Tensor of arbitrary shape. phi (torch.Tensor): Tensor of same arbitrary shape. Returns: torch.Te...
75
96
from typing import Tuple import torch import torch.nn as nn import torch.nn.functional as F from kornia.constants import pi __all__ = [ # functional api "rad2deg", "deg2rad", "pol2cart", "cart2pol", "convert_points_from_homogeneous", "convert_points_to_homogeneous", "convert_affinematr...
cart2pol
Function that converts cartesian coordinates to polar coordinates. Args: rho (torch.Tensor): Tensor of arbitrary shape. phi (torch.Tensor): Tensor of same arbitrary shape. eps (float): To avoid division by zero. Default is 1e-8 Returns: torch.Tensor, torch.Tensor: Tensor with same shape as input. Exa...
from typing import Tuple import torch import torch.nn as nn import torch.nn.functional as F from kornia.constants import pi __all__ = [ # functional api "rad2deg", "deg2rad", "pol2cart", "cart2pol", "convert_points_from_homogeneous", "convert_points_to_homogeneous", "convert_affinematr...
def cart2pol(x: torch.Tensor, y: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.Tensor, torch.Tensor]: """Function that converts cartesian coordinates to polar coordinates. Args: rho (torch.Tensor): Tensor of arbitrary shape. phi (torch.Tensor): Tensor of same arbitrary shape. eps (flo...
99
121
from typing import Tuple import torch import torch.nn as nn import torch.nn.functional as F from kornia.constants import pi __all__ = [ # functional api "rad2deg", "deg2rad", "pol2cart", "cart2pol", "convert_points_from_homogeneous", "convert_points_to_homogeneous", "convert_affinematr...
rotation_matrix_to_angle_axis
Convert 3x3 rotation matrix to Rodrigues vector. Args: rotation_matrix (torch.Tensor): rotation matrix. Returns: torch.Tensor: Rodrigues vector transformation. Shape: - Input: :math:`(N, 3, 3)` - Output: :math:`(N, 3)` Example: >>> input = torch.rand(2, 3, 3) # Nx3x3 >>> output = rotation_m...
from typing import Tuple import torch import torch.nn as nn import torch.nn.functional as F from kornia.constants import pi __all__ = [ # functional api "rad2deg", "deg2rad", "pol2cart", "cart2pol", "convert_points_from_homogeneous", "convert_points_to_homogeneous", "convert_affinematr...
def rotation_matrix_to_angle_axis( rotation_matrix: torch.Tensor) -> torch.Tensor: r"""Convert 3x3 rotation matrix to Rodrigues vector. Args: rotation_matrix (torch.Tensor): rotation matrix. Returns: torch.Tensor: Rodrigues vector transformation. Shape: - Input: :math:...
295
322
from typing import Tuple import torch import torch.nn as nn import torch.nn.functional as F from kornia.constants import pi __all__ = [ # functional api "rad2deg", "deg2rad", "pol2cart", "cart2pol", "convert_points_from_homogeneous", "convert_points_to_homogeneous", "convert_affinematr...
normalize_quaternion
Normalizes a quaternion. The quaternion should be in (x, y, z, w) format. Args: quaternion (torch.Tensor): a tensor containing a quaternion to be normalized. The tensor can be of shape :math:`(*, 4)`. eps (Optional[bool]): small value to avoid division by zero. Default: 1e-12. Return: torch.Te...
from typing import Tuple import torch import torch.nn as nn import torch.nn.functional as F from kornia.constants import pi __all__ = [ # functional api "rad2deg", "deg2rad", "pol2cart", "cart2pol", "convert_points_from_homogeneous", "convert_points_to_homogeneous", "convert_affinematr...
def normalize_quaternion(quaternion: torch.Tensor, eps: float = 1e-12) -> torch.Tensor: r"""Normalizes a quaternion. The quaternion should be in (x, y, z, w) format. Args: quaternion (torch.Tensor): a tensor containing a quaternion to be normalized. The tensor can...
409
436
from typing import Tuple import torch import torch.nn as nn import torch.nn.functional as F from kornia.constants import pi __all__ = [ # functional api "rad2deg", "deg2rad", "pol2cart", "cart2pol", "convert_points_from_homogeneous", "convert_points_to_homogeneous", "convert_affinematr...
quaternion_log_to_exp
Applies exponential map to log quaternion. The quaternion should be in (x, y, z, w) format. Args: quaternion (torch.Tensor): a tensor containing a quaternion to be converted. The tensor can be of shape :math:`(*, 3)`. Return: torch.Tensor: the quaternion exponential map of shape :math:`(*, 4)`. Example...
from typing import Tuple import torch import torch.nn as nn import torch.nn.functional as F from kornia.constants import pi __all__ = [ # functional api "rad2deg", "deg2rad", "pol2cart", "cart2pol", "convert_points_from_homogeneous", "convert_points_to_homogeneous", "convert_affinematr...
def quaternion_log_to_exp(quaternion: torch.Tensor, eps: float = 1e-8) -> torch.Tensor: r"""Applies exponential map to log quaternion. The quaternion should be in (x, y, z, w) format. Args: quaternion (torch.Tensor): a tensor containing a quaternion to be convert...
552
588
from typing import Tuple import torch import torch.nn as nn import torch.nn.functional as F from kornia.constants import pi __all__ = [ # functional api "rad2deg", "deg2rad", "pol2cart", "cart2pol", "convert_points_from_homogeneous", "convert_points_to_homogeneous", "convert_affinematr...
quaternion_exp_to_log
Applies the log map to a quaternion. The quaternion should be in (x, y, z, w) format. Args: quaternion (torch.Tensor): a tensor containing a quaternion to be converted. The tensor can be of shape :math:`(*, 4)`. Return: torch.Tensor: the quaternion log map of shape :math:`(*, 3)`. Example: >>> quat...
from typing import Tuple import torch import torch.nn as nn import torch.nn.functional as F from kornia.constants import pi __all__ = [ # functional api "rad2deg", "deg2rad", "pol2cart", "cart2pol", "convert_points_from_homogeneous", "convert_points_to_homogeneous", "convert_affinematr...
def quaternion_exp_to_log(quaternion: torch.Tensor, eps: float = 1e-8) -> torch.Tensor: r"""Applies the log map to a quaternion. The quaternion should be in (x, y, z, w) format. Args: quaternion (torch.Tensor): a tensor containing a quaternion to be converted. Th...
591
627
from typing import Tuple import torch import torch.nn as nn import torch.nn.functional as F from kornia.constants import pi __all__ = [ # functional api "rad2deg", "deg2rad", "pol2cart", "cart2pol", "convert_points_from_homogeneous", "convert_points_to_homogeneous", "convert_affinematr...
normalize_pixel_coordinates
Normalize pixel coordinates between -1 and 1. Normalized, -1 if on extreme left, 1 if on extreme right (x = w-1). Args: pixel_coordinates (torch.Tensor): the grid with pixel coordinates. Shape can be :math:`(*, 2)`. width (int): the maximum width in the x-axis. height (int): the maximum height in th...
from typing import Tuple import torch import torch.nn as nn import torch.nn.functional as F from kornia.constants import pi __all__ = [ # functional api "rad2deg", "deg2rad", "pol2cart", "cart2pol", "convert_points_from_homogeneous", "convert_points_to_homogeneous", "convert_affinematr...
def normalize_pixel_coordinates( pixel_coordinates: torch.Tensor, height: int, width: int, eps: float = 1e-8) -> torch.Tensor: r"""Normalize pixel coordinates between -1 and 1. Normalized, -1 if on extreme left, 1 if on extreme right (x = w-1). Args: pixel_coordinat...
689
720
from typing import Tuple import torch import torch.nn as nn import torch.nn.functional as F from kornia.constants import pi __all__ = [ # functional api "rad2deg", "deg2rad", "pol2cart", "cart2pol", "convert_points_from_homogeneous", "convert_points_to_homogeneous", "convert_affinematr...
denormalize_pixel_coordinates
Denormalize pixel coordinates. The input is assumed to be -1 if on extreme left, 1 if on extreme right (x = w-1). Args: pixel_coordinates (torch.Tensor): the normalized grid coordinates. Shape can be :math:`(*, 2)`. width (int): the maximum width in the x-axis. height (int): the maximum height in th...
from typing import Tuple import torch import torch.nn as nn import torch.nn.functional as F from kornia.constants import pi __all__ = [ # functional api "rad2deg", "deg2rad", "pol2cart", "cart2pol", "convert_points_from_homogeneous", "convert_points_to_homogeneous", "convert_affinematr...
def denormalize_pixel_coordinates( pixel_coordinates: torch.Tensor, height: int, width: int, eps: float = 1e-8) -> torch.Tensor: r"""Denormalize pixel coordinates. The input is assumed to be -1 if on extreme left, 1 if on extreme right (x = w-1). Args: pixel_coo...
723
753
from typing import Tuple import torch import torch.nn as nn import torch.nn.functional as F from kornia.constants import pi __all__ = [ # functional api "rad2deg", "deg2rad", "pol2cart", "cart2pol", "convert_points_from_homogeneous", "convert_points_to_homogeneous", "convert_affinematr...
normalize_pixel_coordinates3d
Normalize pixel coordinates between -1 and 1. Normalized, -1 if on extreme left, 1 if on extreme right (x = w-1). Args: pixel_coordinates (torch.Tensor): the grid with pixel coordinates. Shape can be :math:`(*, 3)`. depth (int): the maximum depth in the z-axis. height (int): the maximum height in th...
from typing import Tuple import torch import torch.nn as nn import torch.nn.functional as F from kornia.constants import pi __all__ = [ # functional api "rad2deg", "deg2rad", "pol2cart", "cart2pol", "convert_points_from_homogeneous", "convert_points_to_homogeneous", "convert_affinematr...
def normalize_pixel_coordinates3d( pixel_coordinates: torch.Tensor, depth: int, height: int, width: int, eps: float = 1e-8) -> torch.Tensor: r"""Normalize pixel coordinates between -1 and 1. Normalized, -1 if on extreme left, 1 if on extreme right (x = w-1). Args: ...
756
787
from typing import Tuple import torch import torch.nn as nn import torch.nn.functional as F from kornia.constants import pi __all__ = [ # functional api "rad2deg", "deg2rad", "pol2cart", "cart2pol", "convert_points_from_homogeneous", "convert_points_to_homogeneous", "convert_affinematr...
denormalize_pixel_coordinates3d
Denormalize pixel coordinates. The input is assumed to be -1 if on extreme left, 1 if on extreme right (x = w-1). Args: pixel_coordinates (torch.Tensor): the normalized grid coordinates. Shape can be :math:`(*, 3)`. depth (int): the maximum depth in the x-axis. height (int): the maximum height in th...
from typing import Tuple import torch import torch.nn as nn import torch.nn.functional as F from kornia.constants import pi __all__ = [ # functional api "rad2deg", "deg2rad", "pol2cart", "cart2pol", "convert_points_from_homogeneous", "convert_points_to_homogeneous", "convert_affinematr...
def denormalize_pixel_coordinates3d( pixel_coordinates: torch.Tensor, depth: int, height: int, width: int, eps: float = 1e-8) -> torch.Tensor: r"""Denormalize pixel coordinates. The input is assumed to be -1 if on extreme left, 1 if on extreme right (x = w-1). A...
790
823
from typing import Tuple import torch import torch.nn as nn import torch.nn.functional as F from kornia.constants import pi __all__ = [ # functional api "rad2deg", "deg2rad", "pol2cart", "cart2pol", "convert_points_from_homogeneous", "convert_points_to_homogeneous", "convert_affinematr...
get
Get an existing SqlPoolsV3 resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options ...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities fro...
@staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'SqlPoolsV3': """ Get an existing SqlPoolsV3 resource's state with the given name, id, and optional extra properties used to qualify the lookup. ...
209
236
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities fro...
act
Returns actions for each agent in this list. Args: agents: A list of agent objects. obs: A list of matching observations per agent. action_space: The action space for the environment using this model. is_communicative: Whether the action depends on communication observations as well. Returns a list of act...
'''Module to manage and advanced game state''' from collections import defaultdict import numpy as np from . import constants from . import characters from . import utility class ForwardModel(object): """Class for helping with the [forward] modeling of the game state.""" def run(self, num_times...
@staticmethod def act(agents, obs, action_space, is_communicative=False): """Returns actions for each agent in this list. Args: agents: A list of agent objects. obs: A list of matching observations per agent. action_space: The action space for the environment using...
84
123
'''Module to manage and advanced game state''' from collections import defaultdict import numpy as np from . import constants from . import characters from . import utility class ForwardModel(object): """Class for helping with the [forward] modeling of the game state.""" def run(self, num_times...
get_index_page
Handle requests which urls don't end with '.html' (for example, '/doc/') We don't need any generator here, because such urls are equivalent to the same urls with 'index.html' at the end. :param page_path: str :return: str
import copy import datetime import glob import json import os import sys import threading from os import path from urllib.parse import urlparse, urljoin, ParseResult import xmltodict import yaml from bs4 import BeautifulSoup from flask import Flask, render_template, Response, send_from_directory, request from flask.vi...
@app.route('/<path:page_path>') def get_index_page(page_path): """ Handle requests which urls don't end with '.html' (for example, '/doc/') We don't need any generator here, because such urls are equivalent to the same urls with 'index.html' at the end. :param page_path: str :return: str "...
468
481
import copy import datetime import glob import json import os import sys import threading from os import path from urllib.parse import urlparse, urljoin, ParseResult import xmltodict import yaml from bs4 import BeautifulSoup from flask import Flask, render_template, Response, send_from_directory, request from flask.vi...
mean_precision_k
Mean precision at rank k Parameters ---------- y_true : array-like, shape = [n_samples] Ground truth (true relevance labels). y_score : array-like, shape = [n_samples] Predicted scores. k : int Rank. Returns ------- mean precision @k : float
# https://github.com/iliaschalkidis/lmtc-eurlex57k/blob/master/metrics.py from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score import numpy as np # MASKED: mean_precision_k function (lines 12-32) def m...
def mean_precision_k(y_true, y_score, k=10): """Mean precision at rank k Parameters ---------- y_true : array-like, shape = [n_samples] Ground truth (true relevance labels). y_score : array-like, shape = [n_samples] Predicted scores. k : int Rank. Returns ------- ...
12
32
# https://github.com/iliaschalkidis/lmtc-eurlex57k/blob/master/metrics.py from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score import numpy as np def mean_precision_k(y_true, y_score, k=10): """Mean ...
mean_recall_k
Mean recall at rank k Parameters ---------- y_true : array-like, shape = [n_samples] Ground truth (true relevance labels). y_score : array-like, shape = [n_samples] Predicted scores. k : int Rank. Returns ------- mean recall @k : float
# https://github.com/iliaschalkidis/lmtc-eurlex57k/blob/master/metrics.py from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score import numpy as np def mean_precision_k(y_true, y_score, k=10): """Mean ...
def mean_recall_k(y_true, y_score, k=10): """Mean recall at rank k Parameters ---------- y_true : array-like, shape = [n_samples] Ground truth (true relevance labels). y_score : array-like, shape = [n_samples] Predicted scores. k : int Rank. Returns ------- me...
35
55
# https://github.com/iliaschalkidis/lmtc-eurlex57k/blob/master/metrics.py from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score import numpy as np def mean_precision_k(y_true, y_score, k=10): """Mean ...
mean_ndcg_score
Normalized discounted cumulative gain (NDCG) at rank k Parameters ---------- y_true : array-like, shape = [n_samples] Ground truth (true relevance labels). y_score : array-like, shape = [n_samples] Predicted scores. k : int Rank. gains : str Whether gains should be "exponential" (default) or "linear". R...
# https://github.com/iliaschalkidis/lmtc-eurlex57k/blob/master/metrics.py from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score import numpy as np def mean_precision_k(y_true, y_score, k=10): """Mean ...
def mean_ndcg_score(y_true, y_score, k=10, gains="exponential"): """Normalized discounted cumulative gain (NDCG) at rank k Parameters ---------- y_true : array-like, shape = [n_samples] Ground truth (true relevance labels). y_score : array-like, shape = [n_samples] Predicted scores. ...
58
80
# https://github.com/iliaschalkidis/lmtc-eurlex57k/blob/master/metrics.py from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score import numpy as np def mean_precision_k(y_true, y_score, k=10): """Mean ...
mean_rprecision_k
Mean precision at rank k Parameters ---------- y_true : array-like, shape = [n_samples] Ground truth (true relevance labels). y_score : array-like, shape = [n_samples] Predicted scores. k : int Rank. Returns ------- mean precision @k : float
# https://github.com/iliaschalkidis/lmtc-eurlex57k/blob/master/metrics.py from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score import numpy as np def mean_precision_k(y_true, y_score, k=10): """Mean ...
def mean_rprecision_k(y_true, y_score, k=10): """Mean precision at rank k Parameters ---------- y_true : array-like, shape = [n_samples] Ground truth (true relevance labels). y_score : array-like, shape = [n_samples] Predicted scores. k : int Rank. Returns -------...
83
103
# https://github.com/iliaschalkidis/lmtc-eurlex57k/blob/master/metrics.py from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score import numpy as np def mean_precision_k(y_true, y_score, k=10): """Mean ...
ranking_recall_score
Recall at rank k Parameters ---------- y_true : array-like, shape = [n_samples] Ground truth (true relevance labels). y_score : array-like, shape = [n_samples] Predicted scores. k : int Rank. Returns ------- precision @k : float
# https://github.com/iliaschalkidis/lmtc-eurlex57k/blob/master/metrics.py from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score import numpy as np def mean_precision_k(y_true, y_score, k=10): """Mean ...
def ranking_recall_score(y_true, y_score, k=10): # https://ils.unc.edu/courses/2013_spring/inls509_001/lectures/10-EvaluationMetrics.pdf """Recall at rank k Parameters ---------- y_true : array-like, shape = [n_samples] Ground truth (true relevance labels). y_score : array-like, shape = ...
106
135
# https://github.com/iliaschalkidis/lmtc-eurlex57k/blob/master/metrics.py from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score import numpy as np def mean_precision_k(y_true, y_score, k=10): """Mean ...
ranking_precision_score
Precision at rank k Parameters ---------- y_true : array-like, shape = [n_samples] Ground truth (true relevance labels). y_score : array-like, shape = [n_samples] Predicted scores. k : int Rank. Returns ------- precision @k : float
# https://github.com/iliaschalkidis/lmtc-eurlex57k/blob/master/metrics.py from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score import numpy as np def mean_precision_k(y_true, y_score, k=10): """Mean ...
def ranking_precision_score(y_true, y_score, k=10): """Precision at rank k Parameters ---------- y_true : array-like, shape = [n_samples] Ground truth (true relevance labels). y_score : array-like, shape = [n_samples] Predicted scores. k : int Rank. Returns ------...
138
165
# https://github.com/iliaschalkidis/lmtc-eurlex57k/blob/master/metrics.py from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score import numpy as np def mean_precision_k(y_true, y_score, k=10): """Mean ...
ranking_rprecision_score
Precision at rank k Parameters ---------- y_true : array-like, shape = [n_samples] Ground truth (true relevance labels). y_score : array-like, shape = [n_samples] Predicted scores. k : int Rank. Returns ------- precision @k : float
# https://github.com/iliaschalkidis/lmtc-eurlex57k/blob/master/metrics.py from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score import numpy as np def mean_precision_k(y_true, y_score, k=10): """Mean ...
def ranking_rprecision_score(y_true, y_score, k=10): """Precision at rank k Parameters ---------- y_true : array-like, shape = [n_samples] Ground truth (true relevance labels). y_score : array-like, shape = [n_samples] Predicted scores. k : int Rank. Returns -----...
168
197
# https://github.com/iliaschalkidis/lmtc-eurlex57k/blob/master/metrics.py from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score import numpy as np def mean_precision_k(y_true, y_score, k=10): """Mean ...
average_precision_score
Average precision at rank k Parameters ---------- y_true : array-like, shape = [n_samples] Ground truth (true relevance labels). y_score : array-like, shape = [n_samples] Predicted scores. k : int Rank. Returns ------- average precision @k : float
# https://github.com/iliaschalkidis/lmtc-eurlex57k/blob/master/metrics.py from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score import numpy as np def mean_precision_k(y_true, y_score, k=10): """Mean ...
def average_precision_score(y_true, y_score, k=10): """Average precision at rank k Parameters ---------- y_true : array-like, shape = [n_samples] Ground truth (true relevance labels). y_score : array-like, shape = [n_samples] Predicted scores. k : int Rank. Returns ...
200
242
# https://github.com/iliaschalkidis/lmtc-eurlex57k/blob/master/metrics.py from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score import numpy as np def mean_precision_k(y_true, y_score, k=10): """Mean ...
dcg_score
Discounted cumulative gain (DCG) at rank k Parameters ---------- y_true : array-like, shape = [n_samples] Ground truth (true relevance labels). y_score : array-like, shape = [n_samples] Predicted scores. k : int Rank. gains : str Whether gains should be "exponential" (default) or "linear". Returns -----...
# https://github.com/iliaschalkidis/lmtc-eurlex57k/blob/master/metrics.py from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score import numpy as np def mean_precision_k(y_true, y_score, k=10): """Mean ...
def dcg_score(y_true, y_score, k=10, gains="exponential"): """Discounted cumulative gain (DCG) at rank k Parameters ---------- y_true : array-like, shape = [n_samples] Ground truth (true relevance labels). y_score : array-like, shape = [n_samples] Predicted scores. k : int ...
245
273
# https://github.com/iliaschalkidis/lmtc-eurlex57k/blob/master/metrics.py from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score import numpy as np def mean_precision_k(y_true, y_score, k=10): """Mean ...
ndcg_score
Normalized discounted cumulative gain (NDCG) at rank k Parameters ---------- y_true : array-like, shape = [n_samples] Ground truth (true relevance labels). y_score : array-like, shape = [n_samples] Predicted scores. k : int Rank. gains : str Whether gains should be "exponential" (default) or "linear". R...
# https://github.com/iliaschalkidis/lmtc-eurlex57k/blob/master/metrics.py from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score import numpy as np def mean_precision_k(y_true, y_score, k=10): """Mean ...
def ndcg_score(y_true, y_score, k=10, gains="exponential"): """Normalized discounted cumulative gain (NDCG) at rank k Parameters ---------- y_true : array-like, shape = [n_samples] Ground truth (true relevance labels). y_score : array-like, shape = [n_samples] Predicted scores. k...
276
294
# https://github.com/iliaschalkidis/lmtc-eurlex57k/blob/master/metrics.py from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score import numpy as np def mean_precision_k(y_true, y_score, k=10): """Mean ...
dcg_from_ranking
Discounted cumulative gain (DCG) at rank k Parameters ---------- y_true : array-like, shape = [n_samples] Ground truth (true relevance labels). ranking : array-like, shape = [k] Document indices, i.e., ranking[0] is the index of top-ranked document, ranking[1] is the index of second-ranked docum...
# https://github.com/iliaschalkidis/lmtc-eurlex57k/blob/master/metrics.py from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score import numpy as np def mean_precision_k(y_true, y_score, k=10): """Mean ...
def dcg_from_ranking(y_true, ranking): """Discounted cumulative gain (DCG) at rank k Parameters ---------- y_true : array-like, shape = [n_samples] Ground truth (true relevance labels). ranking : array-like, shape = [k] Document indices, i.e., ranking[0] is the index of t...
299
321
# https://github.com/iliaschalkidis/lmtc-eurlex57k/blob/master/metrics.py from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score import numpy as np def mean_precision_k(y_true, y_score, k=10): """Mean ...
ndcg_from_ranking
Normalized discounted cumulative gain (NDCG) at rank k Parameters ---------- y_true : array-like, shape = [n_samples] Ground truth (true relevance labels). ranking : array-like, shape = [k] Document indices, i.e., ranking[0] is the index of top-ranked document, ranking[1] is the index of second-...
# https://github.com/iliaschalkidis/lmtc-eurlex57k/blob/master/metrics.py from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score import numpy as np def mean_precision_k(y_true, y_score, k=10): """Mean ...
def ndcg_from_ranking(y_true, ranking): """Normalized discounted cumulative gain (NDCG) at rank k Parameters ---------- y_true : array-like, shape = [n_samples] Ground truth (true relevance labels). ranking : array-like, shape = [k] Document indices, i.e., ranking[0] is t...
324
344
# https://github.com/iliaschalkidis/lmtc-eurlex57k/blob/master/metrics.py from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score import numpy as np def mean_precision_k(y_true, y_score, k=10): """Mean ...
fold_loaders
Loading a specific fold as train and test data loader. If no fold number is provided it returns the next fold. It returns a randomly sampled subset of the original data set. Args: fold: fold number to return Returns: (train data loader, test data loader)
import torch class KFold: def __init__(self, dataset, n_fold=10, batch_size=32, num_workers=0, pin_memory=False): self.fold = 0 self.batch_size = batch_size self.num_workers = num_workers self.pin_memory = pin_memory self.dataset = dataset self.n_fold = n_fold ...
def fold_loaders(self, fold=-1): """ Loading a specific fold as train and test data loader. If no fold number is provided it returns the next fold. It returns a randomly sampled subset of the original data set. Args: fold: fold number to return Returns: ...
35
62
import torch class KFold: def __init__(self, dataset, n_fold=10, batch_size=32, num_workers=0, pin_memory=False): self.fold = 0 self.batch_size = batch_size self.num_workers = num_workers self.pin_memory = pin_memory self.dataset = dataset self.n_fold = n_fold ...
__init__
" INPUT PARAMETER 1) num_visible: number of visible units in the RBM INPUT PARAMETER 2) num_hidden: number of hidden units in the RBM INPUT PARAMETER 3) main_dir: main directory to put the models, data and summary directories INPUT PARAMETER 4) model_name: name of the model you wanna save the data INPUT PARAMETER 5) ...
import tensorflow as tf import numpy as np import os import matplotlib.pyplot as plt from tqdm import tqdm class RBM(object): # MASKED: __init__ function (lines 9-72) def sample_prob(self,probs,rand): """ takes a tensor of probabilitiesas from a sigmoidal activation and sample from all ...
def __init__(self,num_visible,num_hidden,visible_unit_type='bin',main_dir='/Users/chamalgomes/Documents/Python/GitLab/DeepLearning/KAI PROJECT/rbm/models', model_name='rbm_model',gibbs_sampling_steps=1,learning_rate=0.01,momentum=0.9,l2=0.001,batch_size=10, num_epochs=10,stddev=0.1,ver...
9
72
import tensorflow as tf import numpy as np import os import matplotlib.pyplot as plt from tqdm import tqdm class RBM(object): def __init__(self,num_visible,num_hidden,visible_unit_type='bin',main_dir='/Users/chamalgomes/Documents/Python/GitLab/DeepLearning/KAI PROJECT/rbm/models', model_na...
__init__
Initializes the AVL Node. Args: data (dict, optional): {Key:Value} pair. Defaults to None.
class NoNodeData(Exception): pass class AVLNode(object): # MASKED: __init__ function (lines 7-18) def __str__(self) -> str: """Prints single AVL Node to stdout Raises: NoNodeData: If no data is present in the node Returns: str: output string """ ...
def __init__(self, key=None, value=None) -> None: """Initializes the AVL Node. Args: data (dict, optional): {Key:Value} pair. Defaults to None. """ super().__init__() self.key = key self.value = value self.left = None self.right = None ...
7
18
class NoNodeData(Exception): pass class AVLNode(object): def __init__(self, key=None, value=None) -> None: """Initializes the AVL Node. Args: data (dict, optional): {Key:Value} pair. Defaults to None. """ super().__init__() self.key = key self.valu...
__str__
Prints single AVL Node to stdout Raises: NoNodeData: If no data is present in the node Returns: str: output string
class NoNodeData(Exception): pass class AVLNode(object): def __init__(self, key=None, value=None) -> None: """Initializes the AVL Node. Args: data (dict, optional): {Key:Value} pair. Defaults to None. """ super().__init__() self.key = key self.valu...
def __str__(self) -> str: """Prints single AVL Node to stdout Raises: NoNodeData: If no data is present in the node Returns: str: output string """ if self.key: out = "data: {0}\nleft: {1}\nright: {2}\n".format( (self.key,...
20
33
class NoNodeData(Exception): pass class AVLNode(object): def __init__(self, key=None, value=None) -> None: """Initializes the AVL Node. Args: data (dict, optional): {Key:Value} pair. Defaults to None. """ super().__init__() self.key = key self.valu...
__init__
Daniel: careful about RAM usage. See: https://github.com/BerkeleyAutomation/baselines-fork/issues/9 For this we can assume that in the replay buffer, the teacher samples come first, and are fixed ahead of time, so our 'starting' index for adding into the replay buffer should be offset by this quantity.
"""Similar to DDPG except we only need obs and act, not the reward, etc. """ import numpy as np class RingBuffer(object): def __init__(self, maxlen, shape, dtype='float32'): self.maxlen = maxlen self.start = 0 self.length = 0 if dtype == 'uint8': # Daniel: special case...
def __init__(self, limit, action_shape, observation_shape, dtype='float32', do_valid=False): """Daniel: careful about RAM usage. See: https://github.com/BerkeleyAutomation/baselines-fork/issues/9 For this we can assume that in the replay buffer, the teacher samples ...
68
85
"""Similar to DDPG except we only need obs and act, not the reward, etc. """ import numpy as np class RingBuffer(object): def __init__(self, maxlen, shape, dtype='float32'): self.maxlen = maxlen self.start = 0 self.length = 0 if dtype == 'uint8': # Daniel: special case...
date_to_decimal_year
Convert a date to decimal year. Args: date (str): Date as a string. format (str, optional): Format of the date if a conversion is needed. Returns: float: Decimal year corresponding to the date.
import datetime import os import shutil import subprocess import urllib.request from contextlib import closing import numpy as np import pandas as pd import requests import wbml.out __all__ = [ "DependencyError", "resource", "dependency", "asserted_dependency", "split_df", "data_path", "d...
def date_to_decimal_year(date, format=None): """Convert a date to decimal year. Args: date (str): Date as a string. format (str, optional): Format of the date if a conversion is needed. Returns: float: Decimal year corresponding to the date. """ if format: date = da...
173
197
import datetime import os import shutil import subprocess import urllib.request from contextlib import closing import numpy as np import pandas as pd import requests import wbml.out __all__ = [ "DependencyError", "resource", "dependency", "asserted_dependency", "split_df", "data_path", "d...
__call__
Call function to augment common fields in results. Args: results (dict): Result dict contains the data to augment. Returns: dict: The result dict contains the data that is augmented with different scales and flips.
# Copyright (c) OpenMMLab. All rights reserved. import mmcv import warnings from copy import deepcopy from mmdet.datasets.builder import PIPELINES from mmdet.datasets.pipelines import Compose @PIPELINES.register_module() class MultiScaleFlipAug3D(object): """Test-time augmentation with multiple scales and flippi...
def __call__(self, results): """Call function to augment common fields in results. Args: results (dict): Result dict contains the data to augment. Returns: dict: The result dict contains the data that is augmented with \ different scales and flips. ...
66
111
# Copyright (c) OpenMMLab. All rights reserved. import mmcv import warnings from copy import deepcopy from mmdet.datasets.builder import PIPELINES from mmdet.datasets.pipelines import Compose @PIPELINES.register_module() class MultiScaleFlipAug3D(object): """Test-time augmentation with multiple scales and flippi...