matlok - Python Src Code Datasets (base)
Collection
Python code from leading AI research and tools repositories
•
2 items
•
Updated
•
1
name
stringlengths 1
152
| class_name
stringlengths 1
51
| class_bases
stringlengths 0
159
⌀ | is_member
bool 2
classes | args
stringlengths 0
804
| class_docstr
stringlengths 4
8.19k
⌀ | class_docstr_tok
stringlengths 2
11.6k
⌀ | docstr
stringlengths 0
11.4k
⌀ | docstr_tok
stringlengths 2
13.4k
⌀ | returns
stringlengths 0
260
⌀ | code
stringlengths 21
52.4k
⌀ | code_tok
stringlengths 33
92.8k
⌀ | lstart
int64 1
1.75k
| lend
int64 5
1.75k
| raises
stringclasses 16
values | filename
stringlengths 5
66
| file_path
stringlengths 12
161
| imports
stringlengths 0
1.77k
| total_objects
int64 15
15
| num_classes
float64 1
7
⌀ | num_imports
int64 0
14
| num_functions
int64 0
15
| num_all_bases
float64 0
9
⌀ | num_methods
float64 1
14
⌀ | num_bases
float64 1
7
⌀ | label_desc
stringlengths 69
1.05k
| label_desc_len
int64 69
1.05k
| label_id
stringclasses 15
values | __index_level_0__
int64 468
2.35M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
_fit_sklearn_model_with_active_run | global | null | false | pandas_df | null | null | null | null | mlflow | def _fit_sklearn_model_with_active_run(pandas_df):
run_id = mlflow.active_run().info.run_id
_fit_sklearn(pandas_df)
return mlflow.get_run(run_id)
| ["def","_fit_sklearn_model_with_active_run","(","pandas_df",")",":","run_id","=","mlflow.active_run","(",")",".info.run_id","_fit_sklearn","(","pandas_df",")","return","mlflow.get_run","(","run_id",")"] | 32 | 35 | null | test_spark_datasource_autologging_crossframework.py | mlflow/tests/spark/autologging/datasource/test_spark_datasource_autologging_crossframework.py | import time
import numpy
import pytest
from sklearn.linear_model import LinearRegression
import mlflow
import mlflow.spark
from tests.spark.autologging.utils import _assert_spark_data_logged | 15 | null | 7 | 8 | null | null | null | Use image node_id 3 for calling a global function with example usage: _fit_sklearn_model_with_active_run(pandas_df) and returns: mlflow | 135 | node_id 3 | 1,357,874 |
test_super | TestGaussianNoise | unittest | true | self | A unittest class for testing the GaussianNoise postprocessor. | ["A","unittest","class","for","testing","the","GaussianNoise","postprocessor","."] | null | null | null | def test_super(self):
gan = GaussianNoise(scale=0.1)
self.assertTrue(gan.is_fitted)
self.assertFalse(gan._apply_fit)
self.assertTrue(gan._apply_predict)
gan.fit(preds=np.array([0.1, 0.2, 0.3]))
| ["def","test_super","(","self",")",":","gan","=","GaussianNoise","(","scale=0.1",")","self.assertTrue","(","gan.is_fitted",")","self.assertFalse","(","gan._apply_fit",")","self.assertTrue","(","gan._apply_predict",")","gan.fit","(","preds=np.array","(","[","0.1",",","0.2",",","0.3","]",")",")"] | 104 | 109 | null | test_gaussian_noise.py | adversarial-robustness-toolbox/tests/defences/test_gaussian_noise.py | import logging
import unittest
import numpy
from art.defences.postprocessor import GaussianNoise
from art.utils import load_dataset
from tests.utils import master_seed, get_image_classifier_kr_tf, get_image_classifier_kr_tf_binary | 15 | 1 | 6 | 0 | 1 | 7 | 1 | Use image node_id 7 for calling the TestGaussianNoise obj's underlying member method code with example usage: obj.test_super() without return types | 147 | node_id 7 | 235,295 |
setUpClass | TestHighConfidence | unittest | true | cls | A unittest class for testing the HighConfidence postprocessor. | ["A","unittest","class","for","testing","the","HighConfidence","postprocessor","."] | null | null | null | def setUpClass(cls):
(x_train, y_train), (x_test, y_test), _, _ = load_dataset("mnist")
cls.mnist = (x_train, y_train), (x_test, y_test)
| ["def","setUpClass","(","cls",")",":","(","x_train",",","y_train",")",",","(","x_test",",","y_test",")",",","_",",","_","=","load_dataset","(","``","mnist","''",")","cls.mnist","=","(","x_train",",","y_train",")",",","(","x_test",",","y_test",")"] | 37 | 39 | null | test_high_confidence.py | adversarial-robustness-toolbox/tests/defences/test_high_confidence.py | import logging
import unittest
import numpy
from art.defences.postprocessor import HighConfidence
from art.utils import load_dataset
from tests.utils import master_seed, get_image_classifier_kr_tf, get_image_classifier_kr_tf_binary | 15 | 1 | 6 | 0 | 1 | 7 | 1 | Use image node_id 1 for calling the TestHighConfidence obj's underlying member method code with example usage: obj.setUpClass(cls) without return types | 151 | node_id 1 | 235,296 |
test_ThompsonSamplerInfeasible | ThompsonSamplerTest | TestCase | true | self | null | null | null | null | null | def test_ThompsonSamplerInfeasible(self) -> None:
generator = ThompsonSampler(min_weight=0.9)
generator.fit(
# pyre-fixme[6]: For 1st param expected `List[List[List[Union[None,
# bool, float, int, str]]]]` but got `List[List[List[int]]]`.
Xs=self.Xs,
# pyre-fixme[6]: For 2nd param expected `List[List[float]]` but got
# `List[List[int]]`.
Ys=self.Ys,
# pyre-fixme[6]: For 3rd param expected `List[List[float]]` but got
# `List[List[int]]`.
Yvars=self.Yvars,
# pyre-fixme[6]: For 4th param expected `List[List[Union[None, bool,
# float, int, str]]]` but got `List[List[int]]`.
parameter_values=self.parameter_values,
outcome_names=self.outcome_names,
)
with self.assertRaises(ModelError):
generator.gen(
n=3,
# pyre-fixme[6]: For 2nd param expected `List[List[Union[None, bool,
# float, int, str]]]` but got `List[List[int]]`.
parameter_values=self.parameter_values,
objective_weights=np.ones(1),
)
| ["def","test_ThompsonSamplerInfeasible","(","self",")","-",">","None",":","generator","=","ThompsonSampler","(","min_weight=0.9",")","generator.fit","(","#","pyre-fixme","[","6","]",":","For","1st","param","expected","`","List","[","List","[","List","[","Union","[","None",",","#","bool",",","float",",","int",",","str","]","]","]","]","`","but","got","`","List","[","List","[","List","[","int","]","]","]","`",".","Xs=self.Xs",",","#","pyre-fixme","[","6","]",":","For","2nd","param","expected","`","List","[","List","[","float","]","]","`","but","got","#","`","List","[","List","[","int","]","]","`",".","Ys=self.Ys",",","#","pyre-fixme","[","6","]",":","For","3rd","param","expected","`","List","[","List","[","float","]","]","`","but","got","#","`","List","[","List","[","int","]","]","`",".","Yvars=self.Yvars",",","#","pyre-fixme","[","6","]",":","For","4th","param","expected","`","List","[","List","[","Union","[","None",",","bool",",","#","float",",","int",",","str","]","]","]","`","but","got","`","List","[","List","[","int","]","]","`",".","parameter_values=self.parameter_values",",","outcome_names=self.outcome_names",",",")","with","self.assertRaises","(","ModelError",")",":","generator.gen","(","n=3",",","#","pyre-fixme","[","6","]",":","For","2nd","param","expected","`","List","[","List","[","Union","[","None",",","bool",",","#","float",",","int",",","str","]","]","]","`","but","got","`","List","[","List","[","int","]","]","`",".","parameter_values=self.parameter_values",",","objective_weights=np.ones","(","1",")",",",")"] | 174 | 198 | null | test_thompson.py | Ax/ax/models/tests/test_thompson.py | import numpy
from ax.exceptions.model import ModelError
from ax.models.discrete.thompson import ThompsonSampler
from ax.utils.common.testutils import TestCase | 15 | 1 | 4 | 0 | 1 | 9 | 1 | Use image node_id 6 for calling the ThompsonSamplerTest obj's underlying member method code with example usage: obj.test_ThompsonSamplerInfeasible() without return types | 169 | node_id 6 | 9,540 |
_maybe_clause | global | null | false | clause | null | null | null | null | unknown | def _maybe_clause(clause: Optional[str]) -> Sequence[str]:
return [clause] if clause is not None else []
| ["def","_maybe_clause","(","clause",":","Optional","[","str","]",")","-",">","Sequence","[","str","]",":","return","[","clause","]","if","clause","is","not","None","else","[","]"] | 40 | 41 | null | store_ext.py | tfx/tfx/orchestration/portable/mlmd/store_ext.py | import collections
import itertools
from typing import Callable, Mapping, Optional, Sequence, Union
from tfx.dsl.compiler import compiler_utils
from tfx.dsl.compiler import constants
from tfx.orchestration.experimental.core import constants
from tfx.orchestration.portable.mlmd import event_lib
from tfx.orchestration.portable.mlmd import filter_query_builder
import ml_metadata | 15 | null | 9 | 6 | null | null | null | Use image node_id 2 for calling a global function with example usage: _maybe_clause(clause) and returns: unknown | 112 | node_id 2 | 2,198,856 |
__init__ | EventSievesConfiguration | SievesConfiguration | true | self | null | null | null | null | EventSievesConfiguration | def __init__(self):
super(EventSievesConfiguration, self).__init__()
self.run_evaluation = True
self.sieves_order = [
(RelationType.SAME_HEAD_LEMMA, 1.0),
(RelationType.EXACT_STRING, 1.0),
(RelationType.WIKIPEDIA_DISAMBIGUATION, 0.1),
(RelationType.WORD_EMBEDDING_MATCH, 0.7),
(RelationType.WIKIPEDIA_REDIRECT_LINK, 0.1),
(RelationType.FUZZY_HEAD_FIT, 0.5),
(RelationType.FUZZY_FIT, 1.0),
(RelationType.WITHIN_DOC_COREF, 1.0),
(RelationType.WIKIPEDIA_TITLE_PARENTHESIS, 0.1),
(RelationType.WIKIPEDIA_BE_COMP, 0.1),
(RelationType.WIKIPEDIA_CATEGORY, 0.1),
(RelationType.VERBOCEAN_MATCH, 0.1),
(RelationType.WORDNET_DERIVATIONALLY, 1.0),
]
| ["def","__init__","(","self",")",":","super","(","EventSievesConfiguration",",","self",")",".__init__","(",")","self.run_evaluation","=","True","self.sieves_order","=","[","(","RelationType.SAME_HEAD_LEMMA",",","1.0",")",",","(","RelationType.EXACT_STRING",",","1.0",")",",","(","RelationType.WIKIPEDIA_DISAMBIGUATION",",","0.1",")",",","(","RelationType.WORD_EMBEDDING_MATCH",",","0.7",")",",","(","RelationType.WIKIPEDIA_REDIRECT_LINK",",","0.1",")",",","(","RelationType.FUZZY_HEAD_FIT",",","0.5",")",",","(","RelationType.FUZZY_FIT",",","1.0",")",",","(","RelationType.WITHIN_DOC_COREF",",","1.0",")",",","(","RelationType.WIKIPEDIA_TITLE_PARENTHESIS",",","0.1",")",",","(","RelationType.WIKIPEDIA_BE_COMP",",","0.1",")",",","(","RelationType.WIKIPEDIA_CATEGORY",",","0.1",")",",","(","RelationType.VERBOCEAN_MATCH",",","0.1",")",",","(","RelationType.WORDNET_DERIVATIONALLY",",","1.0",")",",","]"] | 59 | 78 | null | sieves_config.py | nlp-architect/nlp_architect/models/cross_doc_coref/sieves_config.py | from typing import List, Tuple
from nlp_architect.data.cdc_resources.relations.relation_types_enums import RelationType | 15 | 3 | 2 | 0 | 3 | 1 | 1 | Use image node_id 1 to create a new EventSievesConfiguration object from inherited base classes: SievesConfiguration with example: obj = EventSievesConfiguration() | 163 | node_id 1 | 1,443,098 |
simple_segmentation_example | global | null | false | null | null | null | null | null | def simple_segmentation_example():
"Perfect results!"
parameters = legion_parameters()
parameters.eps = 0.02
parameters.alpha = 0.005
parameters.betta = 0.1
parameters.gamma = 7.0
parameters.teta = 0.9
parameters.lamda = 0.1
parameters.teta_x = -0.5
parameters.teta_p = 7.0
parameters.Wz = 0.7
parameters.mu = 0.01
parameters.fi = 3.0
parameters.teta_xz = 0.1
parameters.teta_zx = 0.1
parameters.ENABLE_POTENTIONAL = False
template_dynamic_legion(
81,
2500,
2500,
conn_type=conn_type.GRID_FOUR,
params=parameters,
stimulus=[
1,
1,
1,
0,
0,
0,
0,
0,
0,
1,
1,
1,
0,
0,
1,
1,
1,
1,
1,
1,
1,
0,
0,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
1,
1,
1,
0,
0,
0,
0,
0,
0,
1,
1,
1,
1,
1,
1,
1,
0,
0,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
1,
1,
1,
1,
0,
0,
0,
0,
0,
1,
1,
1,
1,
0,
0,
0,
0,
0,
],
separate_repr=[
[0, 1, 2, 9, 10, 11, 18, 19, 20],
[
14,
15,
16,
17,
23,
24,
25,
26,
33,
34,
35,
42,
43,
44,
51,
52,
53,
],
[
45,
46,
47,
48,
54,
55,
56,
57,
63,
64,
65,
66,
72,
73,
74,
75,
],
],
)
| ["def","simple_segmentation_example","(",")",":","``","Perfect","results","!","''","parameters","=","legion_parameters","(",")","parameters.eps","=","0.02","parameters.alpha","=","0.005","parameters.betta","=","0.1","parameters.gamma","=","7.0","parameters.teta","=","0.9","parameters.lamda","=","0.1","parameters.teta_x","=","-0.5","parameters.teta_p","=","7.0","parameters.Wz","=","0.7","parameters.mu","=","0.01","parameters.fi","=","3.0","parameters.teta_xz","=","0.1","parameters.teta_zx","=","0.1","parameters.ENABLE_POTENTIONAL","=","False","template_dynamic_legion","(","81",",","2500",",","2500",",","conn_type=conn_type.GRID_FOUR",",","params=parameters",",","stimulus=","[","1",",","1",",","1",",","0",",","0",",","0",",","0",",","0",",","0",",","1",",","1",",","1",",","0",",","0",",","1",",","1",",","1",",","1",",","1",",","1",",","1",",","0",",","0",",","1",",","1",",","1",",","1",",","0",",","0",",","0",",","0",",","0",",","0",",","1",",","1",",","1",",","0",",","0",",","0",",","0",",","0",",","0",",","1",",","1",",","1",",","1",",","1",",","1",",","1",",","0",",","0",",","1",",","1",",","1",",","1",",","1",",","1",",","1",",","0",",","0",",","0",",","0",",","0",",","1",",","1",",","1",",","1",",","0",",","0",",","0",",","0",",","0",",","1",",","1",",","1",",","1",",","0",",","0",",","0",",","0",",","0",",","]",",","separate_repr=","[","[","0",",","1",",","2",",","9",",","10",",","11",",","18",",","19",",","20","]",",","[","14",",","15",",","16",",","17",",","23",",","24",",","25",",","26",",","33",",","34",",","35",",","42",",","43",",","44",",","51",",","52",",","53",",","]",",","[","45",",","46",",","47",",","48",",","54",",","55",",","56",",","57",",","63",",","64",",","65",",","66",",","72",",","73",",","74",",","75",",","]",",","]",",",")"] | 94 | 126 | null | legion_examples.py | pyclustering/pyclustering/nnet/examples/legion_examples.py | from pyclustering.utils import draw_dynamics
from pyclustering.nnet.legion import legion_network, legion_parameters
from pyclustering.nnet import * | 15 | null | 3 | 12 | null | null | null | Use image node_id 12 for calling a global function with example usage: simple_segmentation_example() without return types | 121 | node_id 12 | 1,634,375 |
|
forward | ConstantGate | torch.nn | true | self,inp | null | null | null | null | idx, score | def forward(self, inp):
idx = torch.zeros(
(inp.shape[0], self.top_k),
dtype=torch.int64,
device=inp.device,
)
score = (
torch.ones((inp.shape[0], 1, self.top_k), device=inp.device)
/ 2
)
return idx, score
| ["def","forward","(","self",",","inp",")",":","idx","=","torch.zeros","(","(","inp.shape","[","0","]",",","self.top_k",")",",","dtype=torch.int64",",","device=inp.device",",",")","score","=","(","torch.ones","(","(","inp.shape","[","0","]",",","1",",","self.top_k",")",",","device=inp.device",")","\/","2",")","return","idx",",","score"] | 16 | 20 | null | test_zero.py | thu-pacman-faster-moe/tests/test_zero.py | import os
import sys
import json
import torch
from fmoe.layers import _fmoe_general_global_forward
from fmoe import FMoETransformerMLP
from test_ddp import _run_distributed | 15 | 1 | 7 | 4 | 1 | 2 | 1 | Use image node_id 2 for calling the ConstantGate obj's underlying member method code with example usage: obj.forward(inp) and returns: idx, score | 146 | node_id 2 | 2,201,994 |
__init__ | ConstantGate | torch.nn | true | self,d_model,num_expert,world_size,top_k | null | null | null | null | ConstantGate | def __init__(self, d_model, num_expert, world_size, top_k=1):
super().__init__()
self.top_k = top_k
| ["def","__init__","(","self",",","d_model",",","num_expert",",","world_size",",","top_k=1",")",":","super","(",")",".__init__","(",")","self.top_k","=","top_k"] | 12 | 14 | null | test_zero.py | thu-pacman-faster-moe/tests/test_zero.py | import os
import sys
import json
import torch
from fmoe.layers import _fmoe_general_global_forward
from fmoe import FMoETransformerMLP
from test_ddp import _run_distributed | 15 | 1 | 7 | 4 | 1 | 2 | 1 | Use image node_id 1 to create a new ConstantGate object from inherited base classes: torch.nn with example: obj = ConstantGate(d_model, num_expert, world_size, top_k) | 166 | node_id 1 | 2,201,993 |
test_GetLastPoint | RandomModelTest | TestCase | true | self | null | null | null | null | null | def test_GetLastPoint(self) -> None:
generated_points = np.array([[1, 2, 3], [4, 5, 6]])
RandomModelWithPoints = RandomModel(
generated_points=generated_points
)
result = RandomModelWithPoints._get_last_point()
expected = torch.tensor([[4], [5], [6]])
comparison = result == expected
# pyre-fixme[16]: `bool` has no attribute `any`.
self.assertEqual(comparison.any(), True)
| ["def","test_GetLastPoint","(","self",")","-",">","None",":","generated_points","=","np.array","(","[","[","1",",","2",",","3","]",",","[","4",",","5",",","6","]","]",")","RandomModelWithPoints","=","RandomModel","(","generated_points=generated_points",")","result","=","RandomModelWithPoints._get_last_point","(",")","expected","=","torch.tensor","(","[","[","4","]",",","[","5","]",",","[","6","]","]",")","comparison","=","result","==","expected","#","pyre-fixme","[","16","]",":","`","bool","`","has","no","attribute","`","any","`",".","self.assertEqual","(","comparison.any","(",")",",","True",")"] | 74 | 81 | null | test_random.py | Ax/ax/models/tests/test_random.py | import numpy
import torch
from ax.models.random.base import RandomModel
from ax.utils.common.testutils import TestCase
from ax.utils.common.typeutils import not_none | 15 | 1 | 5 | 0 | 1 | 8 | 1 | Use image node_id 8 for calling the RandomModelTest obj's underlying member method code with example usage: obj.test_GetLastPoint() without return types | 152 | node_id 8 | 9,517 |
get_config | global | null | false | null | null | null | null | config, args | def get_config():
parser = argparse.ArgumentParser(
"Global Config Argument Parser", allow_abbrev=False
)
parser.add_argument(
"--config_yaml",
required=True,
type=str,
help="the configuration file for this experiment.",
)
parser.add_argument(
"--resume",
type=str,
help="a specified logging path to resume training.\
It will fall back to run from initialization if no latest checkpoint are found.",
)
parser.add_argument(
"--test", type=str, help="a specified logging path to test"
)
args, _ = parser.parse_known_args()
config = get_user_config(args.config_yaml)
add_cfg_to_argparser(config, parser)
args = parser.parse_args()
update_cfg_with_argparser(config, args)
check_config_conflicts(config)
# print(config)
return config, args
| ["def","get_config","(",")",":","parser","=","argparse.ArgumentParser","(","``","Global","Config","Argument","Parser","''",",","allow_abbrev=False",")","parser.add_argument","(","``","--","config_yaml","''",",","required=True",",","type=str",",","help=","''","the","configuration","file","for","this","experiment",".","``",",",")","parser.add_argument","(","``","--","resume","''",",","type=str",",","help=","''","a","specified","logging","path","to","resume","training.\\","It","will","fall","back","to","run","from","initialization","if","no","latest","checkpoint","are","found",".","``",",",")","parser.add_argument","(","``","--","test","''",",","type=str",",","help=","''","a","specified","logging","path","to","test","''",")","args",",","_","=","parser.parse_known_args","(",")","config","=","get_user_config","(","args.config_yaml",")","add_cfg_to_argparser","(","config",",","parser",")","args","=","parser.parse_args","(",")","update_cfg_with_argparser","(","config",",","args",")","check_config_conflicts","(","config",")","#","print","(","config",")","return","config",",","args"] | 123 | 138 | null | config.py | OpenPrompt/openprompt/config.py | import argparse
from yacs.config import CfgNode
import sys
from openprompt.utils.utils import check_config_conflicts
from .default_config import get_default_config
from openprompt.utils.logging import logger
import os | 15 | null | 7 | 8 | null | null | null | Use image node_id 8 for calling a global function with example usage: get_config() and returns: config, args | 109 | node_id 8 | 152,524 |
|
save_config_to_yaml | global | null | false | config | null | null | null | null | null | def save_config_to_yaml(config):
from contextlib import redirect_stdout
saved_yaml_path = os.path.join(config.logging.path, "config.yaml")
with open(saved_yaml_path, "w") as f:
with redirect_stdout(f):
print(config.dump())
logger.info("Config saved as {}".format(saved_yaml_path))
| ["def","save_config_to_yaml","(","config",")",":","from","contextlib","import","redirect_stdout","saved_yaml_path","=","os.path.join","(","config.logging.path",",","``","config.yaml","''",")","with","open","(","saved_yaml_path",",","``","w","''",")","as","f",":","with","redirect_stdout","(","f",")",":","print","(","config.dump","(",")",")","logger.info","(","``","Config","saved","as","{","}","''",".format","(","saved_yaml_path",")",")"] | 116 | 121 | null | config.py | OpenPrompt/openprompt/config.py | import argparse
from yacs.config import CfgNode
import sys
from openprompt.utils.utils import check_config_conflicts
from .default_config import get_default_config
from openprompt.utils.logging import logger
import os | 15 | null | 7 | 8 | null | null | null | Use image node_id 7 for calling a global function with example usage: save_config_to_yaml(config) without return types | 118 | node_id 7 | 152,523 |
update_cfg_with_argparser | global | null | false | cfg,args,prefix | null | null | null | null | null | def update_cfg_with_argparser(cfg, args, prefix=None):
r"""To support update cfg with command line"""
for key in cfg:
value = cfg[key]
full_key_name = (
prefix + "." + key if prefix is not None else key
)
if isinstance(value, CfgNode):
update_cfg_with_argparser(
value, args, prefix=full_key_name
)
else:
v = getattr(args, full_key_name)
if type(v) != type(value):
raise TypeError
if v != value:
cfg[key] = v
print(
"Update key {}, value {} -> {}".format(
full_key_name, value, v
)
)
| ["def","update_cfg_with_argparser","(","cfg",",","args",",","prefix=None",")",":","r","''","''","''","To","support","update","cfg","with","command","line","''","''","''","for","key","in","cfg",":","value","=","cfg","[","key","]","full_key_name","=","(","prefix","+","``",".","''","+","key","if","prefix","is","not","None","else","key",")","if","isinstance","(","value",",","CfgNode",")",":","update_cfg_with_argparser","(","value",",","args",",","prefix=full_key_name",")","else",":","v","=","getattr","(","args",",","full_key_name",")","if","type","(","v",")","!","=","type","(","value",")",":","raise","TypeError","if","v","!","=","value",":","cfg","[","key","]","=","v","print","(","``","Update","key","{","}",",","value","{","}","-",">","{","}","''",".format","(","full_key_name",",","value",",","v",")",")"] | 99 | 113 | null | config.py | OpenPrompt/openprompt/config.py | import argparse
from yacs.config import CfgNode
import sys
from openprompt.utils.utils import check_config_conflicts
from .default_config import get_default_config
from openprompt.utils.logging import logger
import os | 15 | null | 7 | 8 | null | null | null | Use image node_id 6 for calling a global function with example usage: update_cfg_with_argparser(cfg, args, prefix) without return types | 135 | node_id 6 | 152,522 |
test_ConvertBounds | RandomModelTest | TestCase | true | self | null | null | null | null | null | def test_ConvertBounds(self) -> None:
bounds = [(1.0, 2.0), (3.0, 4.0), (5.0, 6.0)]
bounds_result = self.random_model._convert_bounds(bounds)
bounds_expected = torch.tensor(
[[1, 3, 5], [2, 4, 6]], dtype=torch.double
)
bounds_comparison = bounds_result == bounds_expected
# pyre-fixme[16]: `bool` has no attribute `any`.
self.assertEqual(bounds_comparison.any(), True)
# pyre-fixme[6]: For 1st param expected `List[Tuple[float, float]]` but got
# `None`.
self.assertEqual(self.random_model._convert_bounds(None), None)
| ["def","test_ConvertBounds","(","self",")","-",">","None",":","bounds","=","[","(","1.0",",","2.0",")",",","(","3.0",",","4.0",")",",","(","5.0",",","6.0",")","]","bounds_result","=","self.random_model._convert_bounds","(","bounds",")","bounds_expected","=","torch.tensor","(","[","[","1",",","3",",","5","]",",","[","2",",","4",",","6","]","]",",","dtype=torch.double",")","bounds_comparison","=","bounds_result","==","bounds_expected","#","pyre-fixme","[","16","]",":","`","bool","`","has","no","attribute","`","any","`",".","self.assertEqual","(","bounds_comparison.any","(",")",",","True",")","#","pyre-fixme","[","6","]",":","For","1st","param","expected","`","List","[","Tuple","[","float",",","float","]","]","`","but","got","#","`","None","`",".","self.assertEqual","(","self.random_model._convert_bounds","(","None",")",",","None",")"] | 63 | 72 | null | test_random.py | Ax/ax/models/tests/test_random.py | import numpy
import torch
from ax.models.random.base import RandomModel
from ax.utils.common.testutils import TestCase
from ax.utils.common.typeutils import not_none | 15 | 1 | 5 | 0 | 1 | 8 | 1 | Use image node_id 7 for calling the RandomModelTest obj's underlying member method code with example usage: obj.test_ConvertBounds() without return types | 153 | node_id 7 | 9,516 |
test_ConvertInequalityConstraints | RandomModelTest | TestCase | true | self | null | null | null | null | null | def test_ConvertInequalityConstraints(self) -> None:
A = np.array([[1, 2], [3, 4]])
b = np.array([[5], [6]])
A_result, b_result = not_none(
self.random_model._convert_inequality_constraints((A, b))
)
A_expected = torch.tensor([[1, 2], [3, 4]], dtype=torch.double)
b_expected = torch.tensor([[5], [6]], dtype=torch.double)
A_comparison = A_result == A_expected
b_comparison = b_result == b_expected
self.assertEqual(A_comparison.any(), True)
self.assertEqual(b_comparison.any(), True)
self.assertEqual(
self.random_model._convert_inequality_constraints(None), None
)
| ["def","test_ConvertInequalityConstraints","(","self",")","-",">","None",":","A","=","np.array","(","[","[","1",",","2","]",",","[","3",",","4","]","]",")","b","=","np.array","(","[","[","5","]",",","[","6","]","]",")","A_result",",","b_result","=","not_none","(","self.random_model._convert_inequality_constraints","(","(","A",",","b",")",")",")","A_expected","=","torch.tensor","(","[","[","1",",","2","]",",","[","3",",","4","]","]",",","dtype=torch.double",")","b_expected","=","torch.tensor","(","[","[","5","]",",","[","6","]","]",",","dtype=torch.double",")","A_comparison","=","A_result","==","A_expected","b_comparison","=","b_result","==","b_expected","self.assertEqual","(","A_comparison.any","(",")",",","True",")","self.assertEqual","(","b_comparison.any","(",")",",","True",")","self.assertEqual","(","self.random_model._convert_inequality_constraints","(","None",")",",","None",")"] | 49 | 61 | null | test_random.py | Ax/ax/models/tests/test_random.py | import numpy
import torch
from ax.models.random.base import RandomModel
from ax.utils.common.testutils import TestCase
from ax.utils.common.typeutils import not_none | 15 | 1 | 5 | 0 | 1 | 8 | 1 | Use image node_id 6 for calling the RandomModelTest obj's underlying member method code with example usage: obj.test_ConvertInequalityConstraints() without return types | 168 | node_id 6 | 9,515 |
test_ConvertEqualityConstraints | RandomModelTest | TestCase | true | self | null | null | null | null | null | def test_ConvertEqualityConstraints(self) -> None:
fixed_features = {3: 0.7, 1: 0.5}
d = 4
C, c = not_none(
self.random_model._convert_equality_constraints(
d, fixed_features
)
)
c_expected = torch.tensor([[0.5], [0.7]], dtype=torch.double)
C_expected = torch.tensor(
[[0, 1, 0, 0], [0, 0, 0, 1]], dtype=torch.double
)
c_comparison = c == c_expected
C_comparison = C == C_expected
self.assertEqual(c_comparison.any(), True)
self.assertEqual(C_comparison.any(), True)
self.assertEqual(
self.random_model._convert_equality_constraints(d, None), None
)
| ["def","test_ConvertEqualityConstraints","(","self",")","-",">","None",":","fixed_features","=","{","3",":","0.7",",","1",":","0.5","}","d","=","4","C",",","c","=","not_none","(","self.random_model._convert_equality_constraints","(","d",",","fixed_features",")",")","c_expected","=","torch.tensor","(","[","[","0.5","]",",","[","0.7","]","]",",","dtype=torch.double",")","C_expected","=","torch.tensor","(","[","[","0",",","1",",","0",",","0","]",",","[","0",",","0",",","0",",","1","]","]",",","dtype=torch.double",")","c_comparison","=","c","==","c_expected","C_comparison","=","C","==","C_expected","self.assertEqual","(","c_comparison.any","(",")",",","True",")","self.assertEqual","(","C_comparison.any","(",")",",","True",")","self.assertEqual","(","self.random_model._convert_equality_constraints","(","d",",","None",")",",","None",")"] | 35 | 47 | null | test_random.py | Ax/ax/models/tests/test_random.py | import numpy
import torch
from ax.models.random.base import RandomModel
from ax.utils.common.testutils import TestCase
from ax.utils.common.typeutils import not_none | 15 | 1 | 5 | 0 | 1 | 8 | 1 | Use image node_id 5 for calling the RandomModelTest obj's underlying member method code with example usage: obj.test_ConvertEqualityConstraints() without return types | 166 | node_id 5 | 9,514 |
add_cfg_to_argparser | global | null | false | cfg,parser,prefix | null | null | null | null | null | def add_cfg_to_argparser(cfg, parser, prefix=None):
r"""To support argument parser style in addition to yaml style"""
for key in cfg:
value = cfg[key]
full_key_name = (
prefix + "." + key if prefix is not None else key
)
if isinstance(value, CfgNode):
add_cfg_to_argparser(
value, parser=parser, prefix=full_key_name
)
else:
if type(value) in [str, int, float]:
parser.add_argument(
"--" + full_key_name,
type=type(value),
default=value,
)
elif type(value) in [tuple, list]:
parser.add_argument(
"--" + full_key_name,
type=type(value),
default=value,
nargs="+",
)
elif type(value) == bool:
parser.add_argument(
"--" + full_key_name,
action="store_{}".format(not value).lower(),
)
elif type(value) == type(None):
parser.add_argument(
"--" + full_key_name, default=None
)
else:
raise NotImplementedError(
"The type of config value is not supported"
)
| ["def","add_cfg_to_argparser","(","cfg",",","parser",",","prefix=None",")",":","r","''","''","''","To","support","argument","parser","style","in","addition","to","yaml","style","''","''","''","for","key","in","cfg",":","value","=","cfg","[","key","]","full_key_name","=","(","prefix","+","``",".","''","+","key","if","prefix","is","not","None","else","key",")","if","isinstance","(","value",",","CfgNode",")",":","add_cfg_to_argparser","(","value",",","parser=parser",",","prefix=full_key_name",")","else",":","if","type","(","value",")","in","[","str",",","int",",","float","]",":","parser.add_argument","(","``","--","''","+","full_key_name",",","type=type","(","value",")",",","default=value",",",")","elif","type","(","value",")","in","[","tuple",",","list","]",":","parser.add_argument","(","``","--","''","+","full_key_name",",","type=type","(","value",")",",","default=value",",","nargs=","''","+","''",",",")","elif","type","(","value",")","==","bool",":","parser.add_argument","(","``","--","''","+","full_key_name",",","action=","''","store_","{","}","''",".format","(","not","value",")",".lower","(",")",",",")","elif","type","(","value",")","==","type","(","None",")",":","parser.add_argument","(","``","--","''","+","full_key_name",",","default=None",")","else",":","raise","NotImplementedError","(","``","The","type","of","config","value","is","not","supported","''",")"] | 78 | 96 | null | config.py | OpenPrompt/openprompt/config.py | import argparse
from yacs.config import CfgNode
import sys
from openprompt.utils.utils import check_config_conflicts
from .default_config import get_default_config
from openprompt.utils.logging import logger
import os | 15 | null | 7 | 8 | null | null | null | Use image node_id 5 for calling a global function with example usage: add_cfg_to_argparser(cfg, parser, prefix) without return types | 132 | node_id 5 | 152,521 |
_get_node_live_artifacts | global | null | false | store | null | null | null | null | store | def _get_node_live_artifacts(
store: mlmd.MetadataStore,
*,
pipeline_id: str,
node_id: str,
pipeline_run_id: Optional[str] = None,
) -> Sequence[mlmd.proto.Artifact]:
"""Gets all LIVE node artifacts.
Args:
store: A MetadataStore object.
pipeline_id: The pipeline ID.
node_id: The node ID.
pipeline_run_id: The pipeline run ID that the node belongs to. Only
artifacts from the specified pipeline run are returned if specified.
Returns:
A list of LIVE artifacts of the given pipeline node.
"""
artifact_state_filter_query = f"state = {mlmd.proto.Artifact.State.Name(mlmd.proto.Artifact.LIVE)}"
node_context_name = compiler_utils.node_context_name(
pipeline_id, node_id
)
node_filter_query = q.And(
[
f'contexts_0.type = "{constants.NODE_CONTEXT_TYPE_NAME}"',
f'contexts_0.name = "{node_context_name}"',
]
)
artifact_filter_query = q.And(
[
node_filter_query,
artifact_state_filter_query,
]
)
if pipeline_run_id:
artifact_filter_query.append(
q.And(
[
f'contexts_1.type = "{constants.PIPELINE_RUN_CONTEXT_TYPE_NAME}"',
f'contexts_1.name = "{pipeline_run_id}"',
]
)
)
return store.get_artifacts(
list_options=mlmd.ListOptions(
filter_query=str(artifact_filter_query)
)
)
| ["def","_get_node_live_artifacts","(","store",":","mlmd.MetadataStore",",","*",",","pipeline_id",":","str",",","node_id",":","str",",","pipeline_run_id",":","Optional","[","str","]","=","None",",",")","-",">","Sequence","[","mlmd.proto.Artifact","]",":","``","''","''","Gets","all","LIVE","node","artifacts",".","Args",":","store",":","A","MetadataStore","object",".","pipeline_id",":","The","pipeline","ID",".","node_id",":","The","node","ID",".","pipeline_run_id",":","The","pipeline","run","ID","that","the","node","belongs","to",".","Only","artifacts","from","the","specified","pipeline","run","are","returned","if","specified",".","Returns",":","A","list","of","LIVE","artifacts","of","the","given","pipeline","node.","``","''","''","artifact_state_filter_query","=","f","''","state","=","{","mlmd.proto.Artifact.State.Name","(","mlmd.proto.Artifact.LIVE",")","}","''","node_context_name","=","compiler_utils.node_context_name","(","pipeline_id",",","node_id",")","node_filter_query","=","q.And","(","[","f'contexts_0.type","=","``","{","constants.NODE_CONTEXT_TYPE_NAME","}","''","'",",","f'contexts_0.name","=","``","{","node_context_name","}","''","'",",","]",")","artifact_filter_query","=","q.And","(","[","node_filter_query",",","artifact_state_filter_query",",","]",")","if","pipeline_run_id",":","artifact_filter_query.append","(","q.And","(","[","f'contexts_1.type","=","``","{","constants.PIPELINE_RUN_CONTEXT_TYPE_NAME","}","''","'",",","f'contexts_1.name","=","``","{","pipeline_run_id","}","''","'",",","]",")",")","return","store.get_artifacts","(","list_options=mlmd.ListOptions","(","filter_query=str","(","artifact_filter_query",")",")",")"] | 44 | 87 | null | store_ext.py | tfx/tfx/orchestration/portable/mlmd/store_ext.py | import collections
import itertools
from typing import Callable, Mapping, Optional, Sequence, Union
from tfx.dsl.compiler import compiler_utils
from tfx.dsl.compiler import constants
from tfx.orchestration.experimental.core import constants
from tfx.orchestration.portable.mlmd import event_lib
from tfx.orchestration.portable.mlmd import filter_query_builder
import ml_metadata | 15 | null | 9 | 6 | null | null | null | Use image node_id 3 for calling a global function with example usage: _get_node_live_artifacts(store) and returns: store | 120 | node_id 3 | 2,198,857 |
get_node_executions | global | null | false | store | null | null | null | null | store | def get_node_executions(
store: mlmd.MetadataStore,
*,
pipeline_id: str,
node_id: str,
pipeline_run_id: Optional[str] = None,
order_by: mlmd.OrderByField = mlmd.OrderByField.ID,
is_asc: bool = True,
execution_states: Optional[
Sequence["mlmd.proto.Execution.State"]
] = None,
min_last_update_time_since_epoch: Optional[int] = None,
) -> Sequence[mlmd.proto.Execution]:
"""Gets all node executions.
Args:
store: A MetadataStore object.
pipeline_id: The pipeline ID.
node_id: The node ID.
pipeline_run_id: The pipeline run ID that the node belongs to. Only
executions from the specified pipeline run are returned if specified.
order_by: The field of execution to order results by.
is_asc: If True, the results will be returned in the ascending order. If
False, the result will be returned in the descending order.
execution_states: The MLMD execution state(s) to pull LIVE artifacts from.
If not specified or is empty, will consider all MLMD execution states.
min_last_update_time_since_epoch: The minimum update time of MLMD executions
in the format of milliseconds since the unix epoch. If not specified, will
consider all MLMD executions.
Returns:
A list of executions of the given pipeline node.
"""
node_context_name = compiler_utils.node_context_name(
pipeline_id, node_id
)
node_executions_filter_queries = []
node_executions_filter_queries.append(
q.And(
[
f'contexts_0.type = "{constants.NODE_CONTEXT_TYPE_NAME}"',
f'contexts_0.name = "{node_context_name}"',
]
)
)
if pipeline_run_id:
node_executions_filter_queries.append(
q.And(
[
f'contexts_1.type = "{constants.PIPELINE_RUN_CONTEXT_TYPE_NAME}"',
f'contexts_1.name = "{pipeline_run_id}"',
]
)
)
if execution_states:
states_str = ",".join(
[
mlmd.proto.Execution.State.Name(state)
for state in execution_states
]
)
states_filter_query = f"last_known_state IN ({states_str})"
node_executions_filter_queries.append(states_filter_query)
if min_last_update_time_since_epoch:
node_executions_filter_queries.append(
f"last_update_time_since_epoch >= {min_last_update_time_since_epoch}"
)
return store.get_executions(
list_options=mlmd.ListOptions(
filter_query=str(q.And(node_executions_filter_queries)),
order_by=order_by,
is_asc=is_asc,
)
)
| ["def","get_node_executions","(","store",":","mlmd.MetadataStore",",","*",",","pipeline_id",":","str",",","node_id",":","str",",","pipeline_run_id",":","Optional","[","str","]","=","None",",","order_by",":","mlmd.OrderByField","=","mlmd.OrderByField.ID",",","is_asc",":","bool","=","True",",","execution_states",":","Optional","[","Sequence","[","``","mlmd.proto.Execution.State","''","]","]","=","None",",","min_last_update_time_since_epoch",":","Optional","[","int","]","=","None",",",")","-",">","Sequence","[","mlmd.proto.Execution","]",":","``","''","''","Gets","all","node","executions",".","Args",":","store",":","A","MetadataStore","object",".","pipeline_id",":","The","pipeline","ID",".","node_id",":","The","node","ID",".","pipeline_run_id",":","The","pipeline","run","ID","that","the","node","belongs","to",".","Only","executions","from","the","specified","pipeline","run","are","returned","if","specified",".","order_by",":","The","field","of","execution","to","order","results","by",".","is_asc",":","If","True",",","the","results","will","be","returned","in","the","ascending","order",".","If","False",",","the","result","will","be","returned","in","the","descending","order",".","execution_states",":","The","MLMD","execution","state","(","s",")","to","pull","LIVE","artifacts","from",".","If","not","specified","or","is","empty",",","will","consider","all","MLMD","execution","states",".","min_last_update_time_since_epoch",":","The","minimum","update","time","of","MLMD","executions","in","the","format","of","milliseconds","since","the","unix","epoch",".","If","not","specified",",","will","consider","all","MLMD","executions",".","Returns",":","A","list","of","executions","of","the","given","pipeline","node.","``","''","''","node_context_name","=","compiler_utils.node_context_name","(","pipeline_id",",","node_id",")","node_executions_filter_queries","=","[","]","node_executions_filter_queries.append","(","q.And","(","[","f'contexts_0.type","=","``","{","constants.NODE_CONTEXT_TYPE_NAME","}","''","'",",","f'contexts_0.name","=","``","{","node_context_name","}","''","'",",","]",")",")","if","pipeline_run_id",":","node_executions_filter_queries.append","(","q.And","(","[","f'contexts_1.type","=","``","{","constants.PIPELINE_RUN_CONTEXT_TYPE_NAME","}","''","'",",","f'contexts_1.name","=","``","{","pipeline_run_id","}","''","'",",","]",")",")","if","execution_states",":","states_str","=","``",",","''",".join","(","[","mlmd.proto.Execution.State.Name","(","state",")","for","state","in","execution_states","]",")","states_filter_query","=","f","''","last_known_state","IN","(","{","states_str","}",")","''","node_executions_filter_queries.append","(","states_filter_query",")","if","min_last_update_time_since_epoch",":","node_executions_filter_queries.append","(","f","''","last_update_time_since_epoch",">","=","{","min_last_update_time_since_epoch","}","''",")","return","store.get_executions","(","list_options=mlmd.ListOptions","(","filter_query=str","(","q.And","(","node_executions_filter_queries",")",")",",","order_by=order_by",",","is_asc=is_asc",",",")",")"] | 90 | 154 | null | store_ext.py | tfx/tfx/orchestration/portable/mlmd/store_ext.py | import collections
import itertools
from typing import Callable, Mapping, Optional, Sequence, Union
from tfx.dsl.compiler import compiler_utils
from tfx.dsl.compiler import constants
from tfx.orchestration.experimental.core import constants
from tfx.orchestration.portable.mlmd import event_lib
from tfx.orchestration.portable.mlmd import filter_query_builder
import ml_metadata | 15 | null | 9 | 6 | null | null | null | Use image node_id 4 for calling a global function with example usage: get_node_executions(store) and returns: store | 115 | node_id 4 | 2,198,858 |
__init__ | Distribution | object | true | self,generator | Sampling distribution for mystic optimizers
| ["Sampling","distribution","for","mystic","optimizers"] | generate a sampling distribution with interface dist(size=None)
input::
- generator: a 'distribution' method from scipy.stats or numpy.random
- rng: a mystic.random_state object [default: random_state('numpy.random')]
- args: positional arguments for the distribtution object
- kwds: keyword arguments for the distribution object
note::
this method only accepts numpy.random methods with the keyword 'size',
and only accepts random_state objects built with module='numpy.random'
note::
generator may be a method object or a string of 'module.object';
similarly, rng may be a random_state object or a string of 'module'
note::
Distributions d1,d2 may be combined by adding data (i.e. d1(n) + d2(n)),
or by adding probabilitiies as Distribution(d1,d2); the former uses
the addition operator and produces a new unnormalized Distribution,
while the latter produces a new Distribution which randomly chooses from
the Distributions provided
note::
a normalization factor can be incorporated through the multiplication
or division operator, and is stored in the Distribution as 'norm'
| ["generate","a","sampling","distribution","with","interface","dist","(","size=None",")","input",":",":","-","generator",":","a","'distribution","'","method","from","scipy.stats","or","numpy.random","-","rng",":","a","mystic.random_state","object","[","default",":","random_state","(","'numpy.random","'",")","]","-","args",":","positional","arguments","for","the","distribtution","object","-","kwds",":","keyword","arguments","for","the","distribution","object","note",":",":","this","method","only","accepts","numpy.random","methods","with","the","keyword","'size","'",",","and","only","accepts","random_state","objects","built","with","module='numpy.random'","note",":",":","generator","may","be","a","method","object","or","a","string","of","'module.object","'",";","similarly",",","rng","may","be","a","random_state","object","or","a","string","of","'module'","note",":",":","Distributions","d1",",","d2","may","be","combined","by","adding","data","(","i.e",".","d1","(","n",")","+","d2","(","n",")",")",",","or","by","adding","probabilitiies","as","Distribution","(","d1",",","d2",")",";","the","former","uses","the","addition","operator","and","produces","a","new","unnormalized","Distribution",",","while","the","latter","produces","a","new","Distribution","which","randomly","chooses","from","the","Distributions","provided","note",":",":","a","normalization","factor","can","be","incorporated","through","the","multiplication","or","division","operator",",","and","is","stored","in","the","Distribution","as","'norm","'"] | Distribution | def __init__(self, generator=None, *args, **kwds):
"""
generate a sampling distribution with interface dist(size=None)
input::
- generator: a 'distribution' method from scipy.stats or numpy.random
- rng: a mystic.random_state object [default: random_state('numpy.random')]
- args: positional arguments for the distribtution object
- kwds: keyword arguments for the distribution object
note::
this method only accepts numpy.random methods with the keyword 'size',
and only accepts random_state objects built with module='numpy.random'
note::
generator may be a method object or a string of 'module.object';
similarly, rng may be a random_state object or a string of 'module'
note::
Distributions d1,d2 may be combined by adding data (i.e. d1(n) + d2(n)),
or by adding probabilitiies as Distribution(d1,d2); the former uses
the addition operator and produces a new unnormalized Distribution,
while the latter produces a new Distribution which randomly chooses from
the Distributions provided
note::
a normalization factor can be incorporated through the multiplication
or division operator, and is stored in the Distribution as 'norm'
""" # XXX: generate Distribution from list of Distributions?
self.norm = kwds.pop("norm", 1) + 0
if isinstance(generator, Distribution):
if kwds:
msg = "keyword arguments are invalid with {0} instance".format(
self.__class__.__name__
)
raise TypeError(msg)
if not args:
self._type = generator._type
self.rvs = generator.rvs
self.repr = generator.repr
self.norm *= generator.norm
return
# args can only support additional distribution instances
for arg in args:
if not isinstance(arg, Distribution): # raise TypeError
generator += arg
# use choice from multiple distributions
import numpy as np
generator = (generator,) + args
rep = (
lambda di: "{0}".format(di).split("(", 1)[-1][:-1]
if di._type == "join"
else "{0}".format(di)
)
sig = ", ".join(rep(i) for i in generator)
self.repr = lambda cls, fac: (
"{0}({1}".format(cls, sig)
+ (")" if fac == 1 else ", norm={0})".format(fac))
)
self.rvs = lambda size=None: np.choose(
np.random.choice(range(len(generator)), size=size),
tuple(d(size) for d in generator),
)
self._type = "join"
return
from mystic.tools import random_state
rng = kwds.pop("rng", random_state(module="numpy.random"))
if isinstance(rng, str):
rng = random_state(module=rng)
mod = "numpy.random"
if generator is None:
generator = rng.random
mod = rng.__name__
elif isinstance(generator, str):
from importlib import import_module
if "." in generator:
mod, generator = generator.rsplit(".", 1)
mod = import_module(mod)
else:
mod = rng
generator = getattr(mod, generator)
mod = mod.__name__
if getattr(generator, "rvs", False):
d = generator(*args, **kwds)
self.rvs = lambda size=None: d.rvs(
size=size, random_state=rng
)
name = getattr(
generator, "name", None
) # XXX: also try __name__?
mod = "scipy.stats" # XXX: assumed due to 'd.rvs'
else:
d = getattr(rng, generator.__name__)
self.rvs = lambda size=None: d(size=size, *args, **kwds)
name = generator.__name__
mod = getattr(
rng, "__name__", "numpy.random"
) # XXX: bad default?
name = "'{0}.{1}'".format(mod, name) if name else ""
sig = ", ".join(str(i) for i in args)
kwd = ", ".join("{0}={1}".format(i, j) for i, j in kwds.items())
# nrm = '' if self.norm == 1 else 'norm={0}'.format(self.norm)
# kwd = '{0}, {1}'.format(kwd, nrm) if (kwd and nrm) else (kwd or nrm)
sig = (
"{0}, {1}".format(sig, kwd) if (sig and kwd) else (sig or kwd)
)
if name and sig:
name += ", "
# sig = ", rng='{0}')".format(rng.__name__)
self.repr = lambda cls, fac: (
"{0}({1}".format(cls, name)
+ sig
+ (
""
if fac == 1
else (
(", " if (name or sig) else "")
+ "norm={0}".format(fac)
)
)
+ ")"
)
self._type = "base"
return
| ["def","__init__","(","self",",","generator=None",",","*","args",",","*","*","kwds",")",":","``","''","''","generate","a","sampling","distribution","with","interface","dist","(","size=None",")","input",":",":","-","generator",":","a","'distribution","'","method","from","scipy.stats","or","numpy.random","-","rng",":","a","mystic.random_state","object","[","default",":","random_state","(","'numpy.random","'",")","]","-","args",":","positional","arguments","for","the","distribtution","object","-","kwds",":","keyword","arguments","for","the","distribution","object","note",":",":","this","method","only","accepts","numpy.random","methods","with","the","keyword","'size","'",",","and","only","accepts","random_state","objects","built","with","module='numpy.random'","note",":",":","generator","may","be","a","method","object","or","a","string","of","'module.object","'",";","similarly",",","rng","may","be","a","random_state","object","or","a","string","of","'module'","note",":",":","Distributions","d1",",","d2","may","be","combined","by","adding","data","(","i.e",".","d1","(","n",")","+","d2","(","n",")",")",",","or","by","adding","probabilitiies","as","Distribution","(","d1",",","d2",")",";","the","former","uses","the","addition","operator","and","produces","a","new","unnormalized","Distribution",",","while","the","latter","produces","a","new","Distribution","which","randomly","chooses","from","the","Distributions","provided","note",":",":","a","normalization","factor","can","be","incorporated","through","the","multiplication","or","division","operator",",","and","is","stored","in","the","Distribution","as","'norm'","``","''","''","#","XXX",":","generate","Distribution","from","list","of","Distributions","?","self.norm","=","kwds.pop","(","``","norm","''",",","1",")","+","0","if","isinstance","(","generator",",","Distribution",")",":","if","kwds",":","msg","=","``","keyword","arguments","are","invalid","with","{","0","}","instance","''",".format","(","self.__class__.__name__",")","raise","TypeError","(","msg",")","if","not","args",":","self._type","=","generator._type","self.rvs","=","generator.rvs","self.repr","=","generator.repr","self.norm","*","=","generator.norm","return","#","args","can","only","support","additional","distribution","instances","for","arg","in","args",":","if","not","isinstance","(","arg",",","Distribution",")",":","#","raise","TypeError","generator","+=","arg","#","use","choice","from","multiple","distributions","import","numpy","as","np","generator","=","(","generator",",",")","+","args","rep","=","(","lambda","di",":","``","{","0","}","''",".format","(","di",")",".split","(","``","(","``",",","1",")","[","-1","]","[",":","-1","]","if","di._type","==","``","join","''","else","``","{","0","}","''",".format","(","di",")",")","sig","=","``",",","``",".join","(","rep","(","i",")","for","i","in","generator",")","self.repr","=","lambda","cls",",","fac",":","(","``","{","0","}","(","{","1","}","''",".format","(","cls",",","sig",")","+","(","``",")","''","if","fac","==","1","else","``",",","norm=","{","0","}",")","''",".format","(","fac",")",")",")","self.rvs","=","lambda","size=None",":","np.choose","(","np.random.choice","(","range","(","len","(","generator",")",")",",","size=size",")",",","tuple","(","d","(","size",")","for","d","in","generator",")",",",")","self._type","=","``","join","''","return","from","mystic.tools","import","random_state","rng","=","kwds.pop","(","``","rng","''",",","random_state","(","module=","''","numpy.random","''",")",")","if","isinstance","(","rng",",","str",")",":","rng","=","random_state","(","module=rng",")","mod","=","``","numpy.random","''","if","generator","is","None",":","generator","=","rng.random","mod","=","rng.__name__","elif","isinstance","(","generator",",","str",")",":","from","importlib","import","import_module","if","``",".","''","in","generator",":","mod",",","generator","=","generator.rsplit","(","``",".","``",",","1",")","mod","=","import_module","(","mod",")","else",":","mod","=","rng","generator","=","getattr","(","mod",",","generator",")","mod","=","mod.__name__","if","getattr","(","generator",",","``","rvs","''",",","False",")",":","d","=","generator","(","*","args",",","*","*","kwds",")","self.rvs","=","lambda","size=None",":","d.rvs","(","size=size",",","random_state=rng",")","name","=","getattr","(","generator",",","``","name","''",",","None",")","#","XXX",":","also","try","__name__","?","mod","=","``","scipy.stats","''","#","XXX",":","assumed","due","to","'d.rvs'","else",":","d","=","getattr","(","rng",",","generator.__name__",")","self.rvs","=","lambda","size=None",":","d","(","size=size",",","*","args",",","*","*","kwds",")","name","=","generator.__name__","mod","=","getattr","(","rng",",","``","__name__","''",",","``","numpy.random","''",")","#","XXX",":","bad","default","?","name","=","``","'","{","0","}",".","{","1","}","'","''",".format","(","mod",",","name",")","if","name","else","``","''","sig","=","``",",","``",".join","(","str","(","i",")","for","i","in","args",")","kwd","=","``",",","``",".join","(","``","{","0","}","=","{","1","}","''",".format","(","i",",","j",")","for","i",",","j","in","kwds.items","(",")",")","#","nrm","=","``","if","self.norm","==","1","else","'norm=","{","0","}","'.format","(","self.norm",")","#","kwd","=","'","{","0","}",",","{","1","}","'.format","(","kwd",",","nrm",")","if","(","kwd","and","nrm",")","else","(","kwd","or","nrm",")","sig","=","(","``","{","0","}",",","{","1","}","''",".format","(","sig",",","kwd",")","if","(","sig","and","kwd",")","else","(","sig","or","kwd",")",")","if","name","and","sig",":","name","+=","``",",","``","#","sig","=","``",",","rng=","'","{","0","}","'",")","''",".format","(","rng.__name__",")","self.repr","=","lambda","cls",",","fac",":","(","``","{","0","}","(","{","1","}","''",".format","(","cls",",","name",")","+","sig","+","(","``","''","if","fac","==","1","else","(","(","``",",","``","if","(","name","or","sig",")","else","``","''",")","+","``","norm=","{","0","}","''",".format","(","fac",")",")",")","+","``",")","''",")","self._type","=","``","base","''","return"] | 55 | 144 | null | __init__.py | mystic/mystic/math/__init__.py | from .poly import polyeval, poly1d
from .grid import gridpts, samplepts, fillpts
from .approx import almostEqual, tolerance
from .approx import approx_equal
from .None import discrete
from .None import distance | 15 | 1 | 6 | 0 | 1 | 7 | 1 | Use image node_id 1 to create a new Distribution object from inherited base classes: object with example: obj = Distribution(generator) | 135 | node_id 1 | 1,406,721 |
__call__ | Distribution | object | true | self,size | Sampling distribution for mystic optimizers
| ["Sampling","distribution","for","mystic","optimizers"] | generate a sample of given size (tuple) from the distribution | ["generate","a","sample","of","given","size","(","tuple",")","from","the","distribution"] | unknown | def __call__(self, size=None):
"""generate a sample of given size (tuple) from the distribution"""
return self.norm * self.rvs(size)
| ["def","__call__","(","self",",","size=None",")",":","``","''","''","generate","a","sample","of","given","size","(","tuple",")","from","the","distribution","''","''","''","return","self.norm","*","self.rvs","(","size",")"] | 145 | 147 | null | __init__.py | mystic/mystic/math/__init__.py | from .poly import polyeval, poly1d
from .grid import gridpts, samplepts, fillpts
from .approx import almostEqual, tolerance
from .approx import approx_equal
from .None import discrete
from .None import distance | 15 | 1 | 6 | 0 | 1 | 7 | 1 | Use image node_id 2 for calling the Distribution obj's underlying member method code with example usage: obj.__call__(size) and returns: unknown | 144 | node_id 2 | 1,406,722 |
__repr__ | Distribution | object | true | self | Sampling distribution for mystic optimizers
| ["Sampling","distribution","for","mystic","optimizers"] | null | null | self | def __repr__(self):
return self.repr(self.__class__.__name__, self.norm)
| ["def","__repr__","(","self",")",":","return","self.repr","(","self.__class__.__name__",",","self.norm",")"] | 148 | 149 | null | __init__.py | mystic/mystic/math/__init__.py | from .poly import polyeval, poly1d
from .grid import gridpts, samplepts, fillpts
from .approx import almostEqual, tolerance
from .approx import approx_equal
from .None import discrete
from .None import distance | 15 | 1 | 6 | 0 | 1 | 7 | 1 | Use image node_id 3 for calling the Distribution obj's underlying member method code with example usage: obj.__repr__() and returns: self | 137 | node_id 3 | 1,406,723 |
__add__ | Distribution | object | true | self,dist | Sampling distribution for mystic optimizers
| ["Sampling","distribution","for","mystic","optimizers"] | null | null | new | def __add__(self, dist):
if not isinstance(dist, Distribution):
msg = "unsupported operand type(s) for +: '{0}' and '{1}'".format(
self.__class__.__name__, type(dist)
)
raise TypeError(msg)
# add data from multiple distributions
new = Distribution()
first = "{0}".format(self)
second = "{0}".format(dist)
if self._type == "add":
first = first.split("(", 1)[-1][:-1]
if dist._type == "add":
second = second.split("(", 1)[-1][:-1]
new.repr = lambda cls, fac: (
"{0}({1} + {2}".format(cls, first, second)
+ (")" if fac == 1 else ", norm={0})".format(fac))
)
new.rvs = lambda size=None: (self(size) + dist(size))
new._type = "add"
new.norm = 1
return new
| ["def","__add__","(","self",",","dist",")",":","if","not","isinstance","(","dist",",","Distribution",")",":","msg","=","``","unsupported","operand","type","(","s",")","for","+",":","'","{","0","}","'","and","'","{","1","}","'","''",".format","(","self.__class__.__name__",",","type","(","dist",")",")","raise","TypeError","(","msg",")","#","add","data","from","multiple","distributions","new","=","Distribution","(",")","first","=","``","{","0","}","''",".format","(","self",")","second","=","``","{","0","}","''",".format","(","dist",")","if","self._type","==","``","add","''",":","first","=","first.split","(","``","(","``",",","1",")","[","-1","]","[",":","-1","]","if","dist._type","==","``","add","''",":","second","=","second.split","(","``","(","``",",","1",")","[","-1","]","[",":","-1","]","new.repr","=","lambda","cls",",","fac",":","(","``","{","0","}","(","{","1","}","+","{","2","}","''",".format","(","cls",",","first",",","second",")","+","(","``",")","''","if","fac","==","1","else","``",",","norm=","{","0","}",")","''",".format","(","fac",")",")",")","new.rvs","=","lambda","size=None",":","(","self","(","size",")","+","dist","(","size",")",")","new._type","=","``","add","''","new.norm","=","1","return","new"] | 150 | 164 | null | __init__.py | mystic/mystic/math/__init__.py | from .poly import polyeval, poly1d
from .grid import gridpts, samplepts, fillpts
from .approx import almostEqual, tolerance
from .approx import approx_equal
from .None import discrete
from .None import distance | 15 | 1 | 6 | 0 | 1 | 7 | 1 | Use image node_id 4 for calling the Distribution obj's underlying member method code with example usage: obj.__add__(dist) and returns: new | 139 | node_id 4 | 1,406,724 |
convert_cfg_to_dict | global | null | false | cfg_node,key_list | null | null | null | null | cfg_node,cfg_dict | def convert_cfg_to_dict(cfg_node, key_list=[]):
"""Convert a config node to dictionary"""
if not isinstance(cfg_node, CfgNode):
if type(cfg_node) not in _VALID_TYPES:
print(
"Key {} with value {} is not a valid type; valid types: {}".format(
".".join(key_list), type(cfg_node), _VALID_TYPES
),
)
return cfg_node
else:
cfg_dict = dict(cfg_node)
for k, v in cfg_dict.items():
cfg_dict[k] = convert_cfg_to_dict(v, key_list + [k])
return cfg_dict
| ["def","convert_cfg_to_dict","(","cfg_node",",","key_list=","[","]",")",":","``","''","''","Convert","a","config","node","to","dictionary","''","''","''","if","not","isinstance","(","cfg_node",",","CfgNode",")",":","if","type","(","cfg_node",")","not","in","_VALID_TYPES",":","print","(","``","Key","{","}","with","value","{","}","is","not","a","valid","type",";","valid","types",":","{","}","''",".format","(","``",".","``",".join","(","key_list",")",",","type","(","cfg_node",")",",","_VALID_TYPES",")",",",")","return","cfg_node","else",":","cfg_dict","=","dict","(","cfg_node",")","for","k",",","v","in","cfg_dict.items","(",")",":","cfg_dict","[","k","]","=","convert_cfg_to_dict","(","v",",","key_list","+","[","k","]",")","return","cfg_dict"] | 65 | 76 | null | config.py | OpenPrompt/openprompt/config.py | import argparse
from yacs.config import CfgNode
import sys
from openprompt.utils.utils import check_config_conflicts
from .default_config import get_default_config
from openprompt.utils.logging import logger
import os | 15 | null | 7 | 8 | null | null | null | Use image node_id 4 for calling a global function with example usage: convert_cfg_to_dict(cfg_node, key_list) and returns: cfg_node, cfg_dict | 141 | node_id 4 | 152,520 |
get_live_output_artifacts_of_node_by_output_key | global | null | false | store | null | null | null | null | output_artifacts_by_output_key,dict,dict | def get_live_output_artifacts_of_node_by_output_key(
store: mlmd.MetadataStore,
*,
pipeline_id: str,
node_id: str,
pipeline_run_id: Optional[str] = None,
execution_states: Optional[
Sequence["mlmd.proto.Execution.State"]
] = None,
) -> Mapping[str, Sequence[Sequence[mlmd.proto.Artifact]]]:
"""Get LIVE output artifacts of the given node grouped by output key.
The LIVE output artifacts associated with an output key are represented as a
list of a list of artifacts.
1. The outer list represents artifacts generated across all executions.
2. The inner list represents artifacts generated by one execution.
3. Elements in the outer list are returned in descending order of the creation
time of the execution associated with them.
4. Elements in the inner list have no order guarantee.
5. If no LIVE output artifacts found for one execution, an empty list will be
returned.
Args:
store: A MetadataStore object.
pipeline_id: A pipeline ID.
node_id: A node ID.
pipeline_run_id: The pipeline run ID that the node belongs to. Only
artifacts from the specified pipeline run are returned if specified.
execution_states: The MLMD execution state(s) to pull LIVE artifacts from.
If not specified or is empty, will consider MLMD execution states in
[COMPLETE, CACHED].
Returns:
A mapping from output key to all output artifacts from the given node.
"""
# Step 1: Get LIVE artifacts attributed to node with `node_id`.
live_artifacts = _get_node_live_artifacts(
store,
pipeline_id=pipeline_id,
node_id=node_id,
pipeline_run_id=pipeline_run_id,
)
if not live_artifacts:
return {}
# Step 2: Get executions associated with node that created `live_artifacts`
# ordered by execution creation time in descending order.
# These executions should satisfy the constraint:
# min (execution update time) >= min (artifact create time)
min_live_artifact_create_time = min(
[a.create_time_since_epoch for a in live_artifacts], default=0
)
# Within one transaction that updates both artifacts and execution, the
# timestamp of execution is larger or equal than that of the artifacts.
# Apply time skew for the artifacts created before cl/574333630 is rolled out.
# TODO(b/275231956): Remove the following 2 lines if we are sure that there
# are no more artifacts older than the timestamp.
if (
min_live_artifact_create_time
< orchestration_constants.TIME_SKEW_DATE
):
min_live_artifact_create_time -= 24 * 3600 * 1000
executions_ordered_by_desc_creation_time = get_node_executions(
store,
pipeline_id=pipeline_id,
node_id=node_id,
pipeline_run_id=pipeline_run_id,
order_by=mlmd.OrderByField.CREATE_TIME,
is_asc=False,
execution_states=execution_states,
min_last_update_time_since_epoch=min_live_artifact_create_time,
)
if not executions_ordered_by_desc_creation_time:
return {}
# Step 3: Get output events by executions obtained in step 2.
events_by_executions = store.get_events_by_execution_ids(
_ids(executions_ordered_by_desc_creation_time)
)
output_events = [
e
for e in events_by_executions
if event_lib.is_valid_output_event(e)
]
# Step 4: Construct and return `output_artifacts_by_output_key` from events.
#
# Create a mapping from execution_id to an empty list first to make sure
# iteration orders of output_events_by_execution_id and
# output_artifacts_map_by_execution_id are both in desc order of execution's
# creation time.
#
# The desc order is guaranteed by execution_ids and dict is guaranteed to be
# iterated in the insertion order of keys.
output_events_by_execution_id = {
execution.id: []
for execution in executions_ordered_by_desc_creation_time
}
for event in output_events:
output_events_by_execution_id[event.execution_id].append(
event
)
artifact_ids_by_output_key_map_by_execution_id = {}
for exec_id, events in output_events_by_execution_id.items():
output_artifacts_map = (
event_lib.reconstruct_artifact_id_multimap(events)
)
artifact_ids_by_output_key_map_by_execution_id[
exec_id
] = output_artifacts_map
output_artifacts_by_output_key = collections.defaultdict(list)
# Keep only LIVE output artifacts when constructing the result.
live_artifacts_by_id = {a.id: a for a in live_artifacts}
for (
artifact_ids_by_output_key
) in artifact_ids_by_output_key_map_by_execution_id.values():
for (
output_key,
artifact_ids,
) in artifact_ids_by_output_key.items():
live_output_artifacts = [
live_artifacts_by_id[artifact_id]
for artifact_id in artifact_ids
if artifact_id in live_artifacts_by_id
]
output_artifacts_by_output_key[output_key].append(
live_output_artifacts
)
return output_artifacts_by_output_key
| ["def","get_live_output_artifacts_of_node_by_output_key","(","store",":","mlmd.MetadataStore",",","*",",","pipeline_id",":","str",",","node_id",":","str",",","pipeline_run_id",":","Optional","[","str","]","=","None",",","execution_states",":","Optional","[","Sequence","[","``","mlmd.proto.Execution.State","''","]","]","=","None",",",")","-",">","Mapping","[","str",",","Sequence","[","Sequence","[","mlmd.proto.Artifact","]","]","]",":","``","''","''","Get","LIVE","output","artifacts","of","the","given","node","grouped","by","output","key",".","The","LIVE","output","artifacts","associated","with","an","output","key","are","represented","as","a","list","of","a","list","of","artifacts",".","1",".","The","outer","list","represents","artifacts","generated","across","all","executions",".","2",".","The","inner","list","represents","artifacts","generated","by","one","execution",".","3",".","Elements","in","the","outer","list","are","returned","in","descending","order","of","the","creation","time","of","the","execution","associated","with","them",".","4",".","Elements","in","the","inner","list","have","no","order","guarantee",".","5",".","If","no","LIVE","output","artifacts","found","for","one","execution",",","an","empty","list","will","be","returned",".","Args",":","store",":","A","MetadataStore","object",".","pipeline_id",":","A","pipeline","ID",".","node_id",":","A","node","ID",".","pipeline_run_id",":","The","pipeline","run","ID","that","the","node","belongs","to",".","Only","artifacts","from","the","specified","pipeline","run","are","returned","if","specified",".","execution_states",":","The","MLMD","execution","state","(","s",")","to","pull","LIVE","artifacts","from",".","If","not","specified","or","is","empty",",","will","consider","MLMD","execution","states","in","[","COMPLETE",",","CACHED","]",".","Returns",":","A","mapping","from","output","key","to","all","output","artifacts","from","the","given","node.","``","''","''","#","Step","1",":","Get","LIVE","artifacts","attributed","to","node","with","`","node_id","`",".","live_artifacts","=","_get_node_live_artifacts","(","store",",","pipeline_id=pipeline_id",",","node_id=node_id",",","pipeline_run_id=pipeline_run_id",",",")","if","not","live_artifacts",":","return","{","}","#","Step","2",":","Get","executions","associated","with","node","that","created","`","live_artifacts","`","#","ordered","by","execution","creation","time","in","descending","order",".","#","These","executions","should","satisfy","the","constraint",":","#","min","(","execution","update","time",")",">","=","min","(","artifact","create","time",")","min_live_artifact_create_time","=","min","(","[","a.create_time_since_epoch","for","a","in","live_artifacts","]",",","default=0",")","#","Within","one","transaction","that","updates","both","artifacts","and","execution",",","the","#","timestamp","of","execution","is","larger","or","equal","than","that","of","the","artifacts",".","#","Apply","time","skew","for","the","artifacts","created","before","cl\/574333630","is","rolled","out",".","#","TODO","(","b\/275231956",")",":","Remove","the","following","2","lines","if","we","are","sure","that","there","#","are","no","more","artifacts","older","than","the","timestamp",".","if","(","min_live_artifact_create_time","<","orchestration_constants.TIME_SKEW_DATE",")",":","min_live_artifact_create_time","-=","24","*","3600","*","1000","executions_ordered_by_desc_creation_time","=","get_node_executions","(","store",",","pipeline_id=pipeline_id",",","node_id=node_id",",","pipeline_run_id=pipeline_run_id",",","order_by=mlmd.OrderByField.CREATE_TIME",",","is_asc=False",",","execution_states=execution_states",",","min_last_update_time_since_epoch=min_live_artifact_create_time",",",")","if","not","executions_ordered_by_desc_creation_time",":","return","{","}","#","Step","3",":","Get","output","events","by","executions","obtained","in","step","2.","events_by_executions","=","store.get_events_by_execution_ids","(","_ids","(","executions_ordered_by_desc_creation_time",")",")","output_events","=","[","e","for","e","in","events_by_executions","if","event_lib.is_valid_output_event","(","e",")","]","#","Step","4",":","Construct","and","return","`","output_artifacts_by_output_key","`","from","events",".","#","#","Create","a","mapping","from","execution_id","to","an","empty","list","first","to","make","sure","#","iteration","orders","of","output_events_by_execution_id","and","#","output_artifacts_map_by_execution_id","are","both","in","desc","order","of","execution's","#","creation","time",".","#","#","The","desc","order","is","guaranteed","by","execution_ids","and","dict","is","guaranteed","to","be","#","iterated","in","the","insertion","order","of","keys",".","output_events_by_execution_id","=","{","execution.id",":","[","]","for","execution","in","executions_ordered_by_desc_creation_time","}","for","event","in","output_events",":","output_events_by_execution_id","[","event.execution_id","]",".append","(","event",")","artifact_ids_by_output_key_map_by_execution_id","=","{","}","for","exec_id",",","events","in","output_events_by_execution_id.items","(",")",":","output_artifacts_map","=","(","event_lib.reconstruct_artifact_id_multimap","(","events",")",")","artifact_ids_by_output_key_map_by_execution_id","[","exec_id","]","=","output_artifacts_map","output_artifacts_by_output_key","=","collections.defaultdict","(","list",")","#","Keep","only","LIVE","output","artifacts","when","constructing","the","result",".","live_artifacts_by_id","=","{","a.id",":","a","for","a","in","live_artifacts","}","for","(","artifact_ids_by_output_key",")","in","artifact_ids_by_output_key_map_by_execution_id.values","(",")",":","for","(","output_key",",","artifact_ids",",",")","in","artifact_ids_by_output_key.items","(",")",":","live_output_artifacts","=","[","live_artifacts_by_id","[","artifact_id","]","for","artifact_id","in","artifact_ids","if","artifact_id","in","live_artifacts_by_id","]","output_artifacts_by_output_key","[","output_key","]",".append","(","live_output_artifacts",")","return","output_artifacts_by_output_key"] | 157 | 273 | null | store_ext.py | tfx/tfx/orchestration/portable/mlmd/store_ext.py | import collections
import itertools
from typing import Callable, Mapping, Optional, Sequence, Union
from tfx.dsl.compiler import compiler_utils
from tfx.dsl.compiler import constants
from tfx.orchestration.experimental.core import constants
from tfx.orchestration.portable.mlmd import event_lib
from tfx.orchestration.portable.mlmd import filter_query_builder
import ml_metadata | 15 | null | 9 | 6 | null | null | null | Use image node_id 5 for calling a global function with example usage: get_live_output_artifacts_of_node_by_output_key(store) and returns: output_artifacts_by_output_key, dict, dict | 180 | node_id 5 | 2,198,859 |
test_zero_fwd | global | null | false | num_expert,batch_size,d_hidden,world_size | null | null | null | null | null | def test_zero_fwd(
num_expert=2, batch_size=4, d_hidden=8, world_size=1
):
_run_distributed(
"_test_zero_fwd",
1,
{
"num_expert": num_expert,
"batch_size": batch_size,
"d_hidden": d_hidden,
},
script=__file__,
)
| ["def","test_zero_fwd","(","num_expert=2",",","batch_size=4",",","d_hidden=8",",","world_size=1",")",":","_run_distributed","(","``","_test_zero_fwd","''",",","1",",","{","``","num_expert","''",":","num_expert",",","``","batch_size","''",":","batch_size",",","``","d_hidden","''",":","d_hidden",",","}",",","script=__file__",",",")"] | 23 | 32 | null | test_zero.py | thu-pacman-faster-moe/tests/test_zero.py | import os
import sys
import json
import torch
from fmoe.layers import _fmoe_general_global_forward
from fmoe import FMoETransformerMLP
from test_ddp import _run_distributed | 15 | null | 7 | 4 | null | null | null | Use image node_id 1 for calling a global function with example usage: test_zero_fwd(num_expert, batch_size, d_hidden, world_size) without return types | 150 | node_id 1 | 2,201,995 |
_test_zero_fwd | global | null | false | num_expert,batch_size,d_hidden,world_size | null | null | null | null | null | def _test_zero_fwd(
num_expert=2, batch_size=4, d_hidden=8, world_size=1
):
inp = torch.rand(batch_size, d_hidden).cuda()
gate = torch.zeros(batch_size, dtype=torch.int64).cuda()
x = _fmoe_general_global_forward(
inp, gate, lambda x, y: x, num_expert, world_size
)
| ["def","_test_zero_fwd","(","num_expert=2",",","batch_size=4",",","d_hidden=8",",","world_size=1",")",":","inp","=","torch.rand","(","batch_size",",","d_hidden",")",".cuda","(",")","gate","=","torch.zeros","(","batch_size",",","dtype=torch.int64",")",".cuda","(",")","x","=","_fmoe_general_global_forward","(","inp",",","gate",",","lambda","x",",","y",":","x",",","num_expert",",","world_size",")"] | 34 | 38 | null | test_zero.py | thu-pacman-faster-moe/tests/test_zero.py | import os
import sys
import json
import torch
from fmoe.layers import _fmoe_general_global_forward
from fmoe import FMoETransformerMLP
from test_ddp import _run_distributed | 15 | null | 7 | 4 | null | null | null | Use image node_id 2 for calling a global function with example usage: _test_zero_fwd(num_expert, batch_size, d_hidden, world_size) without return types | 151 | node_id 2 | 2,201,996 |
test_zero_transformer | global | null | false | num_expert,batch_size,d_hidden,world_size | null | null | null | null | null | def test_zero_transformer(
num_expert=2, batch_size=4, d_hidden=8, world_size=1
):
_run_distributed(
"_test_zero_transformer",
1,
{
"num_expert": num_expert,
"batch_size": batch_size,
"d_hidden": d_hidden,
},
script=__file__,
)
| ["def","test_zero_transformer","(","num_expert=2",",","batch_size=4",",","d_hidden=8",",","world_size=1",")",":","_run_distributed","(","``","_test_zero_transformer","''",",","1",",","{","``","num_expert","''",":","num_expert",",","``","batch_size","''",":","batch_size",",","``","d_hidden","''",":","d_hidden",",","}",",","script=__file__",",",")"] | 41 | 50 | null | test_zero.py | thu-pacman-faster-moe/tests/test_zero.py | import os
import sys
import json
import torch
from fmoe.layers import _fmoe_general_global_forward
from fmoe import FMoETransformerMLP
from test_ddp import _run_distributed | 15 | null | 7 | 4 | null | null | null | Use image node_id 3 for calling a global function with example usage: test_zero_transformer(num_expert, batch_size, d_hidden, world_size) without return types | 158 | node_id 3 | 2,201,997 |
_test_zero_transformer | global | null | false | num_expert,batch_size,d_hidden,world_size | null | null | null | null | null | def _test_zero_transformer(
num_expert=2, batch_size=4, d_hidden=8, world_size=1
):
inp = torch.rand(batch_size, d_hidden).cuda()
mask = torch.zeros(inp.shape[0], dtype=torch.long)
mask[1] = 1
mask_dict = {1: torch.zeros(d_hidden).cuda()}
model = FMoETransformerMLP(
num_expert,
d_hidden,
d_hidden * 4,
world_size,
gate=ConstantGate,
mask=mask,
mask_dict=mask_dict,
).cuda()
oup = model(inp)
| ["def","_test_zero_transformer","(","num_expert=2",",","batch_size=4",",","d_hidden=8",",","world_size=1",")",":","inp","=","torch.rand","(","batch_size",",","d_hidden",")",".cuda","(",")","mask","=","torch.zeros","(","inp.shape","[","0","]",",","dtype=torch.long",")","mask","[","1","]","=","1","mask_dict","=","{","1",":","torch.zeros","(","d_hidden",")",".cuda","(",")","}","model","=","FMoETransformerMLP","(","num_expert",",","d_hidden",",","d_hidden","*","4",",","world_size",",","gate=ConstantGate",",","mask=mask",",","mask_dict=mask_dict",",",")",".cuda","(",")","oup","=","model","(","inp",")"] | 52 | 61 | null | test_zero.py | thu-pacman-faster-moe/tests/test_zero.py | import os
import sys
import json
import torch
from fmoe.layers import _fmoe_general_global_forward
from fmoe import FMoETransformerMLP
from test_ddp import _run_distributed | 15 | null | 7 | 4 | null | null | null | Use image node_id 4 for calling a global function with example usage: _test_zero_transformer(num_expert, batch_size, d_hidden, world_size) without return types | 159 | node_id 4 | 2,201,998 |
setUp | TestHighConfidence | unittest | true | self | A unittest class for testing the HighConfidence postprocessor. | ["A","unittest","class","for","testing","the","HighConfidence","postprocessor","."] | null | null | null | def setUp(self):
master_seed(seed=1234)
| ["def","setUp","(","self",")",":","master_seed","(","seed=1234",")"] | 41 | 42 | null | test_high_confidence.py | adversarial-robustness-toolbox/tests/defences/test_high_confidence.py | import logging
import unittest
import numpy
from art.defences.postprocessor import HighConfidence
from art.utils import load_dataset
from tests.utils import master_seed, get_image_classifier_kr_tf, get_image_classifier_kr_tf_binary | 15 | 1 | 6 | 0 | 1 | 7 | 1 | Use image node_id 2 for calling the TestHighConfidence obj's underlying member method code with example usage: obj.setUp() without return types | 143 | node_id 2 | 235,297 |
test_difference | TestIntervalIndex | null | true | self,closed,sort | null | null | null | null | null | def test_difference(self, closed, sort):
index = IntervalIndex.from_arrays(
[1, 0, 3, 2], [1, 2, 3, 4], closed=closed
)
result = index.difference(index[:1], sort=sort)
expected = index[1:]
if sort is None:
expected = expected.sort_values()
tm.assert_index_equal(result, expected)
# GH 19101: empty result, same dtype
result = index.difference(index, sort=sort)
expected = empty_index(dtype="int64", closed=closed)
tm.assert_index_equal(result, expected)
# GH 19101: empty result, different dtypes
other = IntervalIndex.from_arrays(
index.left.astype("float64"), index.right, closed=closed
)
result = index.difference(other, sort=sort)
tm.assert_index_equal(result, expected)
| ["def","test_difference","(","self",",","closed",",","sort",")",":","index","=","IntervalIndex.from_arrays","(","[","1",",","0",",","3",",","2","]",",","[","1",",","2",",","3",",","4","]",",","closed=closed",")","result","=","index.difference","(","index","[",":1","]",",","sort=sort",")","expected","=","index","[","1",":","]","if","sort","is","None",":","expected","=","expected.sort_values","(",")","tm.assert_index_equal","(","result",",","expected",")","#","GH","19101",":","empty","result",",","same","dtype","result","=","index.difference","(","index",",","sort=sort",")","expected","=","empty_index","(","dtype=","''","int64","''",",","closed=closed",")","tm.assert_index_equal","(","result",",","expected",")","#","GH","19101",":","empty","result",",","different","dtypes","other","=","IntervalIndex.from_arrays","(","index.left.astype","(","``","float64","''",")",",","index.right",",","closed=closed",")","result","=","index.difference","(","other",",","sort=sort",")","tm.assert_index_equal","(","result",",","expected",")"] | 131 | 149 | null | test_setops.py | pandas/pandas/tests/indexes/interval/test_setops.py | import numpy
import pytest
from pandas import Index, IntervalIndex, Timestamp, interval_range
import pandas._testing | 15 | 1 | 4 | 2 | 0 | 8 | null | Use image node_id 6 for calling the TestIntervalIndex obj's underlying member method code with example usage: obj.test_difference(closed, sort) without return types | 164 | node_id 6 | 1,514,638 |
test_ThompsonSamplerUniformWeights | ThompsonSamplerTest | TestCase | true | self | null | null | null | null | null | def test_ThompsonSamplerUniformWeights(self) -> None:
generator = ThompsonSampler(min_weight=0.0, uniform_weights=True)
generator.fit(
# pyre-fixme[6]: For 1st param expected `List[List[List[Union[None,
# bool, float, int, str]]]]` but got `List[List[List[int]]]`.
Xs=self.Xs,
# pyre-fixme[6]: For 2nd param expected `List[List[float]]` but got
# `List[List[int]]`.
Ys=self.Ys,
# pyre-fixme[6]: For 3rd param expected `List[List[float]]` but got
# `List[List[int]]`.
Yvars=self.Yvars,
# pyre-fixme[6]: For 4th param expected `List[List[Union[None, bool,
# float, int, str]]]` but got `List[List[int]]`.
parameter_values=self.parameter_values,
outcome_names=self.outcome_names,
)
arms, weights, _ = generator.gen(
n=3,
# pyre-fixme[6]: For 2nd param expected `List[List[Union[None, bool,
# float, int, str]]]` but got `List[List[int]]`.
parameter_values=self.parameter_values,
objective_weights=np.ones(1),
)
self.assertEqual(arms, [[4, 4], [3, 3], [2, 2]])
for weight, expected_weight in zip(weights, [1.0, 1.0, 1.0]):
self.assertAlmostEqual(weight, expected_weight, 1)
| ["def","test_ThompsonSamplerUniformWeights","(","self",")","-",">","None",":","generator","=","ThompsonSampler","(","min_weight=0.0",",","uniform_weights=True",")","generator.fit","(","#","pyre-fixme","[","6","]",":","For","1st","param","expected","`","List","[","List","[","List","[","Union","[","None",",","#","bool",",","float",",","int",",","str","]","]","]","]","`","but","got","`","List","[","List","[","List","[","int","]","]","]","`",".","Xs=self.Xs",",","#","pyre-fixme","[","6","]",":","For","2nd","param","expected","`","List","[","List","[","float","]","]","`","but","got","#","`","List","[","List","[","int","]","]","`",".","Ys=self.Ys",",","#","pyre-fixme","[","6","]",":","For","3rd","param","expected","`","List","[","List","[","float","]","]","`","but","got","#","`","List","[","List","[","int","]","]","`",".","Yvars=self.Yvars",",","#","pyre-fixme","[","6","]",":","For","4th","param","expected","`","List","[","List","[","Union","[","None",",","bool",",","#","float",",","int",",","str","]","]","]","`","but","got","`","List","[","List","[","int","]","]","`",".","parameter_values=self.parameter_values",",","outcome_names=self.outcome_names",",",")","arms",",","weights",",","_","=","generator.gen","(","n=3",",","#","pyre-fixme","[","6","]",":","For","2nd","param","expected","`","List","[","List","[","Union","[","None",",","bool",",","#","float",",","int",",","str","]","]","]","`","but","got","`","List","[","List","[","int","]","]","`",".","parameter_values=self.parameter_values",",","objective_weights=np.ones","(","1",")",",",")","self.assertEqual","(","arms",",","[","[","4",",","4","]",",","[","3",",","3","]",",","[","2",",","2","]","]",")","for","weight",",","expected_weight","in","zip","(","weights",",","[","1.0",",","1.0",",","1.0","]",")",":","self.assertAlmostEqual","(","weight",",","expected_weight",",","1",")"] | 146 | 172 | null | test_thompson.py | Ax/ax/models/tests/test_thompson.py | import numpy
from ax.exceptions.model import ModelError
from ax.models.discrete.thompson import ThompsonSampler
from ax.utils.common.testutils import TestCase | 15 | 1 | 4 | 0 | 1 | 9 | 1 | Use image node_id 5 for calling the ThompsonSamplerTest obj's underlying member method code with example usage: obj.test_ThompsonSamplerUniformWeights() without return types | 173 | node_id 5 | 9,539 |
test_ThompsonSamplerMinWeight | ThompsonSamplerTest | TestCase | true | self | null | null | null | null | null | def test_ThompsonSamplerMinWeight(self) -> None:
generator = ThompsonSampler(min_weight=0.01)
generator.fit(
# pyre-fixme[6]: For 1st param expected `List[List[List[Union[None,
# bool, float, int, str]]]]` but got `List[List[List[int]]]`.
Xs=self.Xs,
# pyre-fixme[6]: For 2nd param expected `List[List[float]]` but got
# `List[List[int]]`.
Ys=self.Ys,
# pyre-fixme[6]: For 3rd param expected `List[List[float]]` but got
# `List[List[int]]`.
Yvars=self.Yvars,
# pyre-fixme[6]: For 4th param expected `List[List[Union[None, bool,
# float, int, str]]]` but got `List[List[int]]`.
parameter_values=self.parameter_values,
outcome_names=self.outcome_names,
)
arms, weights, _ = generator.gen(
n=5,
# pyre-fixme[6]: For 2nd param expected `List[List[Union[None, bool,
# float, int, str]]]` but got `List[List[int]]`.
parameter_values=self.parameter_values,
objective_weights=np.ones(1),
)
self.assertEqual(arms, [[4, 4], [3, 3], [2, 2]])
for weight, expected_weight in zip(
weights, [3 * i for i in [0.725, 0.225, 0.05]]
):
self.assertAlmostEqual(weight, expected_weight, 1)
| ["def","test_ThompsonSamplerMinWeight","(","self",")","-",">","None",":","generator","=","ThompsonSampler","(","min_weight=0.01",")","generator.fit","(","#","pyre-fixme","[","6","]",":","For","1st","param","expected","`","List","[","List","[","List","[","Union","[","None",",","#","bool",",","float",",","int",",","str","]","]","]","]","`","but","got","`","List","[","List","[","List","[","int","]","]","]","`",".","Xs=self.Xs",",","#","pyre-fixme","[","6","]",":","For","2nd","param","expected","`","List","[","List","[","float","]","]","`","but","got","#","`","List","[","List","[","int","]","]","`",".","Ys=self.Ys",",","#","pyre-fixme","[","6","]",":","For","3rd","param","expected","`","List","[","List","[","float","]","]","`","but","got","#","`","List","[","List","[","int","]","]","`",".","Yvars=self.Yvars",",","#","pyre-fixme","[","6","]",":","For","4th","param","expected","`","List","[","List","[","Union","[","None",",","bool",",","#","float",",","int",",","str","]","]","]","`","but","got","`","List","[","List","[","int","]","]","`",".","parameter_values=self.parameter_values",",","outcome_names=self.outcome_names",",",")","arms",",","weights",",","_","=","generator.gen","(","n=5",",","#","pyre-fixme","[","6","]",":","For","2nd","param","expected","`","List","[","List","[","Union","[","None",",","bool",",","#","float",",","int",",","str","]","]","]","`","but","got","`","List","[","List","[","int","]","]","`",".","parameter_values=self.parameter_values",",","objective_weights=np.ones","(","1",")",",",")","self.assertEqual","(","arms",",","[","[","4",",","4","]",",","[","3",",","3","]",",","[","2",",","2","]","]",")","for","weight",",","expected_weight","in","zip","(","weights",",","[","3","*","i","for","i","in","[","0.725",",","0.225",",","0.05","]","]",")",":","self.assertAlmostEqual","(","weight",",","expected_weight",",","1",")"] | 116 | 144 | null | test_thompson.py | Ax/ax/models/tests/test_thompson.py | import numpy
from ax.exceptions.model import ModelError
from ax.models.discrete.thompson import ThompsonSampler
from ax.utils.common.testutils import TestCase | 15 | 1 | 4 | 0 | 1 | 9 | 1 | Use image node_id 4 for calling the ThompsonSamplerTest obj's underlying member method code with example usage: obj.test_ThompsonSamplerMinWeight() without return types | 168 | node_id 4 | 9,538 |
test_ThompsonSamplerValidation | ThompsonSamplerTest | TestCase | true | self | null | null | null | null | null | def test_ThompsonSamplerValidation(self) -> None:
generator = ThompsonSampler(min_weight=0.01)
# all Xs are not the same
with self.assertRaises(ValueError):
generator.fit(
Xs=[
[[1, 1], [2, 2], [3, 3], [4, 4]],
[[1, 1], [2, 2], [4, 4]],
],
# pyre-fixme[6]: For 2nd param expected `List[List[float]]` but got
# `List[List[int]]`.
Ys=self.Ys,
# pyre-fixme[6]: For 3rd param expected `List[List[float]]` but got
# `List[List[int]]`.
Yvars=self.Yvars,
# pyre-fixme[6]: For 4th param expected `List[List[Union[None, bool,
# float, int, str]]]` but got `List[List[int]]`.
parameter_values=self.parameter_values,
outcome_names=self.outcome_names,
)
# multiple observations per parameterization
with self.assertRaises(ValueError):
generator.fit(
Xs=[[[1, 1], [2, 2], [2, 2]]],
# pyre-fixme[6]: For 2nd param expected `List[List[float]]` but got
# `List[List[int]]`.
Ys=self.Ys,
# pyre-fixme[6]: For 3rd param expected `List[List[float]]` but got
# `List[List[int]]`.
Yvars=self.Yvars,
# pyre-fixme[6]: For 4th param expected `List[List[Union[None, bool,
# float, int, str]]]` but got `List[List[int]]`.
parameter_values=self.parameter_values,
outcome_names=self.outcome_names,
)
# these are not the same observations, so should not error
generator.fit(
Xs=[[[1, 1], [2.0, 2], [2, 2]]],
# pyre-fixme[6]: For 2nd param expected `List[List[float]]` but got
# `List[List[int]]`.
Ys=self.Ys,
# pyre-fixme[6]: For 3rd param expected `List[List[float]]` but got
# `List[List[int]]`.
Yvars=self.Yvars,
# pyre-fixme[6]: For 4th param expected `List[List[Union[None, bool,
# float, int, str]]]` but got `List[List[int]]`.
parameter_values=self.parameter_values,
outcome_names=self.outcome_names,
)
# requires objective weights
with self.assertRaises(ValueError):
# pyre-fixme[6]: For 2nd param expected `List[List[Union[None, bool,
# float, int, str]]]` but got `List[List[int]]`.
generator.gen(
5, self.parameter_values, objective_weights=None
)
| ["def","test_ThompsonSamplerValidation","(","self",")","-",">","None",":","generator","=","ThompsonSampler","(","min_weight=0.01",")","#","all","Xs","are","not","the","same","with","self.assertRaises","(","ValueError",")",":","generator.fit","(","Xs=","[","[","[","1",",","1","]",",","[","2",",","2","]",",","[","3",",","3","]",",","[","4",",","4","]","]",",","[","[","1",",","1","]",",","[","2",",","2","]",",","[","4",",","4","]","]",",","]",",","#","pyre-fixme","[","6","]",":","For","2nd","param","expected","`","List","[","List","[","float","]","]","`","but","got","#","`","List","[","List","[","int","]","]","`",".","Ys=self.Ys",",","#","pyre-fixme","[","6","]",":","For","3rd","param","expected","`","List","[","List","[","float","]","]","`","but","got","#","`","List","[","List","[","int","]","]","`",".","Yvars=self.Yvars",",","#","pyre-fixme","[","6","]",":","For","4th","param","expected","`","List","[","List","[","Union","[","None",",","bool",",","#","float",",","int",",","str","]","]","]","`","but","got","`","List","[","List","[","int","]","]","`",".","parameter_values=self.parameter_values",",","outcome_names=self.outcome_names",",",")","#","multiple","observations","per","parameterization","with","self.assertRaises","(","ValueError",")",":","generator.fit","(","Xs=","[","[","[","1",",","1","]",",","[","2",",","2","]",",","[","2",",","2","]","]","]",",","#","pyre-fixme","[","6","]",":","For","2nd","param","expected","`","List","[","List","[","float","]","]","`","but","got","#","`","List","[","List","[","int","]","]","`",".","Ys=self.Ys",",","#","pyre-fixme","[","6","]",":","For","3rd","param","expected","`","List","[","List","[","float","]","]","`","but","got","#","`","List","[","List","[","int","]","]","`",".","Yvars=self.Yvars",",","#","pyre-fixme","[","6","]",":","For","4th","param","expected","`","List","[","List","[","Union","[","None",",","bool",",","#","float",",","int",",","str","]","]","]","`","but","got","`","List","[","List","[","int","]","]","`",".","parameter_values=self.parameter_values",",","outcome_names=self.outcome_names",",",")","#","these","are","not","the","same","observations",",","so","should","not","error","generator.fit","(","Xs=","[","[","[","1",",","1","]",",","[","2.0",",","2","]",",","[","2",",","2","]","]","]",",","#","pyre-fixme","[","6","]",":","For","2nd","param","expected","`","List","[","List","[","float","]","]","`","but","got","#","`","List","[","List","[","int","]","]","`",".","Ys=self.Ys",",","#","pyre-fixme","[","6","]",":","For","3rd","param","expected","`","List","[","List","[","float","]","]","`","but","got","#","`","List","[","List","[","int","]","]","`",".","Yvars=self.Yvars",",","#","pyre-fixme","[","6","]",":","For","4th","param","expected","`","List","[","List","[","Union","[","None",",","bool",",","#","float",",","int",",","str","]","]","]","`","but","got","`","List","[","List","[","int","]","]","`",".","parameter_values=self.parameter_values",",","outcome_names=self.outcome_names",",",")","#","requires","objective","weights","with","self.assertRaises","(","ValueError",")",":","#","pyre-fixme","[","6","]",":","For","2nd","param","expected","`","List","[","List","[","Union","[","None",",","bool",",","#","float",",","int",",","str","]","]","]","`","but","got","`","List","[","List","[","int","]","]","`",".","generator.gen","(","5",",","self.parameter_values",",","objective_weights=None",")"] | 60 | 114 | null | test_thompson.py | Ax/ax/models/tests/test_thompson.py | import numpy
from ax.exceptions.model import ModelError
from ax.models.discrete.thompson import ThompsonSampler
from ax.utils.common.testutils import TestCase | 15 | 1 | 4 | 0 | 1 | 9 | 1 | Use image node_id 3 for calling the ThompsonSamplerTest obj's underlying member method code with example usage: obj.test_ThompsonSamplerValidation() without return types | 169 | node_id 3 | 9,537 |
test_ThompsonSampler | ThompsonSamplerTest | TestCase | true | self | null | null | null | null | null | def test_ThompsonSampler(self) -> None:
generator = ThompsonSampler(min_weight=0.0)
generator.fit(
# pyre-fixme[6]: For 1st param expected `List[List[List[Union[None,
# bool, float, int, str]]]]` but got `List[List[List[int]]]`.
Xs=self.Xs,
# pyre-fixme[6]: For 2nd param expected `List[List[float]]` but got
# `List[List[int]]`.
Ys=self.Ys,
# pyre-fixme[6]: For 3rd param expected `List[List[float]]` but got
# `List[List[int]]`.
Yvars=self.Yvars,
# pyre-fixme[6]: For 4th param expected `List[List[Union[None, bool,
# float, int, str]]]` but got `List[List[int]]`.
parameter_values=self.parameter_values,
outcome_names=self.outcome_names,
)
arms, weights, gen_metadata = generator.gen(
n=3,
# pyre-fixme[6]: For 2nd param expected `List[List[Union[None, bool,
# float, int, str]]]` but got `List[List[int]]`.
parameter_values=self.parameter_values,
objective_weights=np.ones(1),
)
self.assertEqual(arms, [[4, 4], [3, 3], [2, 2]])
for weight, expected_weight in zip(
weights, [3 * i for i in [0.725, 0.225, 0.05]]
):
self.assertAlmostEqual(weight, expected_weight, 1)
self.assertEqual(len(gen_metadata["arms_to_weights"]), 4)
| ["def","test_ThompsonSampler","(","self",")","-",">","None",":","generator","=","ThompsonSampler","(","min_weight=0.0",")","generator.fit","(","#","pyre-fixme","[","6","]",":","For","1st","param","expected","`","List","[","List","[","List","[","Union","[","None",",","#","bool",",","float",",","int",",","str","]","]","]","]","`","but","got","`","List","[","List","[","List","[","int","]","]","]","`",".","Xs=self.Xs",",","#","pyre-fixme","[","6","]",":","For","2nd","param","expected","`","List","[","List","[","float","]","]","`","but","got","#","`","List","[","List","[","int","]","]","`",".","Ys=self.Ys",",","#","pyre-fixme","[","6","]",":","For","3rd","param","expected","`","List","[","List","[","float","]","]","`","but","got","#","`","List","[","List","[","int","]","]","`",".","Yvars=self.Yvars",",","#","pyre-fixme","[","6","]",":","For","4th","param","expected","`","List","[","List","[","Union","[","None",",","bool",",","#","float",",","int",",","str","]","]","]","`","but","got","`","List","[","List","[","int","]","]","`",".","parameter_values=self.parameter_values",",","outcome_names=self.outcome_names",",",")","arms",",","weights",",","gen_metadata","=","generator.gen","(","n=3",",","#","pyre-fixme","[","6","]",":","For","2nd","param","expected","`","List","[","List","[","Union","[","None",",","bool",",","#","float",",","int",",","str","]","]","]","`","but","got","`","List","[","List","[","int","]","]","`",".","parameter_values=self.parameter_values",",","objective_weights=np.ones","(","1",")",",",")","self.assertEqual","(","arms",",","[","[","4",",","4","]",",","[","3",",","3","]",",","[","2",",","2","]","]",")","for","weight",",","expected_weight","in","zip","(","weights",",","[","3","*","i","for","i","in","[","0.725",",","0.225",",","0.05","]","]",")",":","self.assertAlmostEqual","(","weight",",","expected_weight",",","1",")","self.assertEqual","(","len","(","gen_metadata","[","``","arms_to_weights","''","]",")",",","4",")"] | 29 | 58 | null | test_thompson.py | Ax/ax/models/tests/test_thompson.py | import numpy
from ax.exceptions.model import ModelError
from ax.models.discrete.thompson import ThompsonSampler
from ax.utils.common.testutils import TestCase | 15 | 1 | 4 | 0 | 1 | 9 | 1 | Use image node_id 2 for calling the ThompsonSamplerTest obj's underlying member method code with example usage: obj.test_ThompsonSampler() without return types | 159 | node_id 2 | 9,536 |
setUp | ThompsonSamplerTest | TestCase | true | self | null | null | null | null | null | def setUp(self) -> None:
self.Xs = [
[[1, 1], [2, 2], [3, 3], [4, 4]]
] # 4 arms, each of dimensionality 2
self.Ys = [[1, 2, 3, 4]]
self.Yvars = [[1, 1, 1, 1]]
self.parameter_values = [[1, 2, 3, 4], [1, 2, 3, 4]]
self.outcome_names = ["x", "y"] # not used for regular TS
self.multiple_metrics_Xs = [
[[1, 1], [2, 2], [3, 3], [4, 4]],
[[1, 1], [2, 2], [3, 3], [4, 4]],
] # 2 metrics, 4 arms, each of dimensionality 2
self.multiple_metrics_Ys = [[1, 2, 3, 4], [0, 0, 0, 1]]
self.multiple_metrics_Yvars = [[1, 1, 1, 1], [1, 1, 1, 1]]
| ["def","setUp","(","self",")","-",">","None",":","self.Xs","=","[","[","[","1",",","1","]",",","[","2",",","2","]",",","[","3",",","3","]",",","[","4",",","4","]","]","]","#","4","arms",",","each","of","dimensionality","2","self.Ys","=","[","[","1",",","2",",","3",",","4","]","]","self.Yvars","=","[","[","1",",","1",",","1",",","1","]","]","self.parameter_values","=","[","[","1",",","2",",","3",",","4","]",",","[","1",",","2",",","3",",","4","]","]","self.outcome_names","=","[","``","x","''",",","``","y","''","]","#","not","used","for","regular","TS","self.multiple_metrics_Xs","=","[","[","[","1",",","1","]",",","[","2",",","2","]",",","[","3",",","3","]",",","[","4",",","4","]","]",",","[","[","1",",","1","]",",","[","2",",","2","]",",","[","3",",","3","]",",","[","4",",","4","]","]",",","]","#","2","metrics",",","4","arms",",","each","of","dimensionality","2","self.multiple_metrics_Ys","=","[","[","1",",","2",",","3",",","4","]",",","[","0",",","0",",","0",",","1","]","]","self.multiple_metrics_Yvars","=","[","[","1",",","1",",","1",",","1","]",",","[","1",",","1",",","1",",","1","]","]"] | 15 | 27 | null | test_thompson.py | Ax/ax/models/tests/test_thompson.py | import numpy
from ax.exceptions.model import ModelError
from ax.models.discrete.thompson import ThompsonSampler
from ax.utils.common.testutils import TestCase | 15 | 1 | 4 | 0 | 1 | 9 | 1 | Use image node_id 1 for calling the ThompsonSamplerTest obj's underlying member method code with example usage: obj.setUp() without return types | 144 | node_id 1 | 9,535 |
test_decimals_0_1 | TestHighConfidence | unittest | true | self | A unittest class for testing the HighConfidence postprocessor. | ["A","unittest","class","for","testing","the","HighConfidence","postprocessor","."] | Test with cutoff of 0.1. | ["Test","with","cutoff","of","0.1","."] | null | def test_decimals_0_1(self):
"""
Test with cutoff of 0.1.
"""
(_, _), (x_test, _) = self.mnist
classifier = get_image_classifier_kr_tf()
preds = classifier.predict(x_test[0:1])
postprocessor = HighConfidence(cutoff=0.1)
post_preds = postprocessor(preds=preds)
classifier_prediction_expected = np.asarray(
[
[
0.12109935,
0.0498215,
0.0993958,
0.06410096,
0.11366928,
0.04645343,
0.06419807,
0.30685693,
0.07616714,
0.05823757,
]
],
dtype=np.float32,
)
post_classifier_prediction_expected = np.asarray(
[
[
0.12109935,
0.0,
0.0,
0.0,
0.11366928,
0.0,
0.0,
0.30685693,
0.0,
0.0,
]
],
dtype=np.float32,
)
np.testing.assert_array_almost_equal(
preds, classifier_prediction_expected, decimal=4
)
np.testing.assert_array_almost_equal(
post_preds, post_classifier_prediction_expected, decimal=4
)
| ["def","test_decimals_0_1","(","self",")",":","``","''","''","Test","with","cutoff","of","0.1.","``","''","''","(","_",",","_",")",",","(","x_test",",","_",")","=","self.mnist","classifier","=","get_image_classifier_kr_tf","(",")","preds","=","classifier.predict","(","x_test","[","0:1","]",")","postprocessor","=","HighConfidence","(","cutoff=0.1",")","post_preds","=","postprocessor","(","preds=preds",")","classifier_prediction_expected","=","np.asarray","(","[","[","0.12109935",",","0.0498215",",","0.0993958",",","0.06410096",",","0.11366928",",","0.04645343",",","0.06419807",",","0.30685693",",","0.07616714",",","0.05823757",",","]","]",",","dtype=np.float32",",",")","post_classifier_prediction_expected","=","np.asarray","(","[","[","0.12109935",",","0.0",",","0.0",",","0.0",",","0.11366928",",","0.0",",","0.0",",","0.30685693",",","0.0",",","0.0",",","]","]",",","dtype=np.float32",",",")","np.testing.assert_array_almost_equal","(","preds",",","classifier_prediction_expected",",","decimal=4",")","np.testing.assert_array_almost_equal","(","post_preds",",","post_classifier_prediction_expected",",","decimal=4",")"] | 44 | 76 | null | test_high_confidence.py | adversarial-robustness-toolbox/tests/defences/test_high_confidence.py | import logging
import unittest
import numpy
from art.defences.postprocessor import HighConfidence
from art.utils import load_dataset
from tests.utils import master_seed, get_image_classifier_kr_tf, get_image_classifier_kr_tf_binary | 15 | 1 | 6 | 0 | 1 | 7 | 1 | Use image node_id 3 for calling the TestHighConfidence obj's underlying member method code with example usage: obj.test_decimals_0_1() without return types | 155 | node_id 3 | 235,298 |
test_decimals_0_2 | TestHighConfidence | unittest | true | self | A unittest class for testing the HighConfidence postprocessor. | ["A","unittest","class","for","testing","the","HighConfidence","postprocessor","."] | Test with cutoff of 0.2. | ["Test","with","cutoff","of","0.2","."] | null | def test_decimals_0_2(self):
"""
Test with cutoff of 0.2.
"""
(_, _), (x_test, _) = self.mnist
classifier = get_image_classifier_kr_tf()
preds = classifier.predict(x_test[0:1])
postprocessor = HighConfidence(cutoff=0.2)
post_preds = postprocessor(preds=preds)
classifier_prediction_expected = np.asarray(
[
[
0.12109935,
0.0498215,
0.0993958,
0.06410096,
0.11366928,
0.04645343,
0.06419807,
0.30685693,
0.07616714,
0.05823757,
]
],
dtype=np.float32,
)
post_classifier_prediction_expected = np.asarray(
[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.30685693, 0.0, 0.0]],
dtype=np.float32,
)
np.testing.assert_array_almost_equal(
preds, classifier_prediction_expected, decimal=4
)
np.testing.assert_array_almost_equal(
post_preds, post_classifier_prediction_expected, decimal=4
)
| ["def","test_decimals_0_2","(","self",")",":","``","''","''","Test","with","cutoff","of","0.2.","``","''","''","(","_",",","_",")",",","(","x_test",",","_",")","=","self.mnist","classifier","=","get_image_classifier_kr_tf","(",")","preds","=","classifier.predict","(","x_test","[","0:1","]",")","postprocessor","=","HighConfidence","(","cutoff=0.2",")","post_preds","=","postprocessor","(","preds=preds",")","classifier_prediction_expected","=","np.asarray","(","[","[","0.12109935",",","0.0498215",",","0.0993958",",","0.06410096",",","0.11366928",",","0.04645343",",","0.06419807",",","0.30685693",",","0.07616714",",","0.05823757",",","]","]",",","dtype=np.float32",",",")","post_classifier_prediction_expected","=","np.asarray","(","[","[","0.0",",","0.0",",","0.0",",","0.0",",","0.0",",","0.0",",","0.0",",","0.30685693",",","0.0",",","0.0","]","]",",","dtype=np.float32",",",")","np.testing.assert_array_almost_equal","(","preds",",","classifier_prediction_expected",",","decimal=4",")","np.testing.assert_array_almost_equal","(","post_preds",",","post_classifier_prediction_expected",",","decimal=4",")"] | 78 | 110 | null | test_high_confidence.py | adversarial-robustness-toolbox/tests/defences/test_high_confidence.py | import logging
import unittest
import numpy
from art.defences.postprocessor import HighConfidence
from art.utils import load_dataset
from tests.utils import master_seed, get_image_classifier_kr_tf, get_image_classifier_kr_tf_binary | 15 | 1 | 6 | 0 | 1 | 7 | 1 | Use image node_id 4 for calling the TestHighConfidence obj's underlying member method code with example usage: obj.test_decimals_0_2() without return types | 155 | node_id 4 | 235,299 |
test_binary_decimals_0_5 | TestHighConfidence | unittest | true | self | A unittest class for testing the HighConfidence postprocessor. | ["A","unittest","class","for","testing","the","HighConfidence","postprocessor","."] | Test with cutoff of 0.5 for binary classifier. | ["Test","with","cutoff","of","0.5","for","binary","classifier","."] | null | def test_binary_decimals_0_5(self):
"""
Test with cutoff of 0.5 for binary classifier.
"""
(_, _), (x_test, _) = self.mnist
classifier = get_image_classifier_kr_tf_binary()
preds = classifier.predict(x_test[0:1])
postprocessor = HighConfidence(cutoff=0.5)
post_preds = postprocessor(preds=preds)
classifier_prediction_expected = np.asarray(
[[0.5301345]], dtype=np.float32
)
post_classifier_prediction_expected = np.asarray(
[[0.5301345]], dtype=np.float32
)
np.testing.assert_array_almost_equal(
preds, classifier_prediction_expected, decimal=4
)
np.testing.assert_array_almost_equal(
post_preds, post_classifier_prediction_expected, decimal=4
)
| ["def","test_binary_decimals_0_5","(","self",")",":","``","''","''","Test","with","cutoff","of","0.5","for","binary","classifier.","``","''","''","(","_",",","_",")",",","(","x_test",",","_",")","=","self.mnist","classifier","=","get_image_classifier_kr_tf_binary","(",")","preds","=","classifier.predict","(","x_test","[","0:1","]",")","postprocessor","=","HighConfidence","(","cutoff=0.5",")","post_preds","=","postprocessor","(","preds=preds",")","classifier_prediction_expected","=","np.asarray","(","[","[","0.5301345","]","]",",","dtype=np.float32",")","post_classifier_prediction_expected","=","np.asarray","(","[","[","0.5301345","]","]",",","dtype=np.float32",")","np.testing.assert_array_almost_equal","(","preds",",","classifier_prediction_expected",",","decimal=4",")","np.testing.assert_array_almost_equal","(","post_preds",",","post_classifier_prediction_expected",",","decimal=4",")"] | 112 | 126 | null | test_high_confidence.py | adversarial-robustness-toolbox/tests/defences/test_high_confidence.py | import logging
import unittest
import numpy
from art.defences.postprocessor import HighConfidence
from art.utils import load_dataset
from tests.utils import master_seed, get_image_classifier_kr_tf, get_image_classifier_kr_tf_binary | 15 | 1 | 6 | 0 | 1 | 7 | 1 | Use image node_id 5 for calling the TestHighConfidence obj's underlying member method code with example usage: obj.test_binary_decimals_0_5() without return types | 162 | node_id 5 | 235,300 |
test_RandomModelGenSamples | RandomModelTest | TestCase | true | self | null | null | null | null | null | def test_RandomModelGenSamples(self) -> None:
with self.assertRaises(NotImplementedError):
self.random_model._gen_samples(n=1, tunable_d=1)
| ["def","test_RandomModelGenSamples","(","self",")","-",">","None",":","with","self.assertRaises","(","NotImplementedError",")",":","self.random_model._gen_samples","(","n=1",",","tunable_d=1",")"] | 25 | 27 | null | test_random.py | Ax/ax/models/tests/test_random.py | import numpy
import torch
from ax.models.random.base import RandomModel
from ax.utils.common.testutils import TestCase
from ax.utils.common.typeutils import not_none | 15 | 1 | 5 | 0 | 1 | 8 | 1 | Use image node_id 3 for calling the RandomModelTest obj's underlying member method code with example usage: obj.test_RandomModelGenSamples() without return types | 161 | node_id 3 | 9,512 |
test_binary_decimals_0_6 | TestHighConfidence | unittest | true | self | A unittest class for testing the HighConfidence postprocessor. | ["A","unittest","class","for","testing","the","HighConfidence","postprocessor","."] | Test with cutoff of 0.6 for binary classifier. | ["Test","with","cutoff","of","0.6","for","binary","classifier","."] | null | def test_binary_decimals_0_6(self):
"""
Test with cutoff of 0.6 for binary classifier.
"""
(_, _), (x_test, _) = self.mnist
classifier = get_image_classifier_kr_tf_binary()
preds = classifier.predict(x_test[0:1])
postprocessor = HighConfidence(cutoff=0.6)
post_preds = postprocessor(preds=preds)
classifier_prediction_expected = np.asarray(
[[0.5301345]], dtype=np.float32
)
post_classifier_prediction_expected = np.asarray(
[[0.0]], dtype=np.float32
)
np.testing.assert_array_almost_equal(
preds, classifier_prediction_expected, decimal=4
)
np.testing.assert_array_almost_equal(
post_preds, post_classifier_prediction_expected, decimal=4
)
| ["def","test_binary_decimals_0_6","(","self",")",":","``","''","''","Test","with","cutoff","of","0.6","for","binary","classifier.","``","''","''","(","_",",","_",")",",","(","x_test",",","_",")","=","self.mnist","classifier","=","get_image_classifier_kr_tf_binary","(",")","preds","=","classifier.predict","(","x_test","[","0:1","]",")","postprocessor","=","HighConfidence","(","cutoff=0.6",")","post_preds","=","postprocessor","(","preds=preds",")","classifier_prediction_expected","=","np.asarray","(","[","[","0.5301345","]","]",",","dtype=np.float32",")","post_classifier_prediction_expected","=","np.asarray","(","[","[","0.0","]","]",",","dtype=np.float32",")","np.testing.assert_array_almost_equal","(","preds",",","classifier_prediction_expected",",","decimal=4",")","np.testing.assert_array_almost_equal","(","post_preds",",","post_classifier_prediction_expected",",","decimal=4",")"] | 128 | 142 | null | test_high_confidence.py | adversarial-robustness-toolbox/tests/defences/test_high_confidence.py | import logging
import unittest
import numpy
from art.defences.postprocessor import HighConfidence
from art.utils import load_dataset
from tests.utils import master_seed, get_image_classifier_kr_tf, get_image_classifier_kr_tf_binary | 15 | 1 | 6 | 0 | 1 | 7 | 1 | Use image node_id 6 for calling the TestHighConfidence obj's underlying member method code with example usage: obj.test_binary_decimals_0_6() without return types | 162 | node_id 6 | 235,301 |
convert | Converter | ImageConverter | true | self,_from,_to | null | null | Converts the image from SVG to PDF using chrome. | ["Converts","the","image","from","SVG","to","PDF","using","chrome","."] | True | def convert(self, _from: str, _to: str) -> bool:
"""Converts the image from SVG to PDF using chrome."""
with open(_from, "r") as f:
svg = f.read()
HTML = (
"<html><head><style>body {margin: 0; }</style><script>function init() {const element = document.querySelector('svg');const positionInfo = element.getBoundingClientRect();const height = positionInfo.height;const width = positionInfo.width;const style = document.createElement('style');style.innerHTML = `@page {margin: 0; size: ${width}px ${height}px}`;document.head.appendChild(style); }window.onload = init;</script></head><body>%s</body></html>"
% (svg)
)
temp_name = f"{_from}.html"
with open(temp_name, "w") as f:
f.write(HTML)
chromium = self.chromium_command()
code = self.command_runner(chromium, _to, temp_name)
if code != 0:
chrome = self.chrome_command()
code = self.command_runner(chrome, _to, temp_name)
if code != 0:
logger.error(
"Fail to convert svg to pdf. Make sure Chromium or Chrome is installed."
)
exit(1)
return True
| ["def","convert","(","self",",","_from",":","str",",","_to",":","str",")","-",">","bool",":","``","''","''","Converts","the","image","from","SVG","to","PDF","using","chrome",".","''","''","''","with","open","(","_from",",","``","r","''",")","as","f",":","svg","=","f.read","(",")","HTML","=","(","``","<","html",">","<","head",">","<","style",">","body","{","margin",":","0",";","}","<","\/style",">","<","script",">","function","init","(",")","{","const","element","=","document.querySelector","(","'svg","'",")",";","const","positionInfo","=","element.getBoundingClientRect","(",")",";","const","height","=","positionInfo.height",";","const","width","=","positionInfo.width",";","const","style","=","document.createElement","(","'style","'",")",";","style.innerHTML","=","`","@","page","{","margin",":","0",";","size",":","$","{","width","}","px","$","{","height","}","px","}","`",";","document.head.appendChild","(","style",")",";","}","window.onload","=","init",";","<","\/script",">","<","\/head",">","<","body",">","%","s","<","\/body",">","<","\/html",">","''","%","(","svg",")",")","temp_name","=","f","''","{","_from","}",".html","''","with","open","(","temp_name",",","``","w","''",")","as","f",":","f.write","(","HTML",")","chromium","=","self.chromium_command","(",")","code","=","self.command_runner","(","chromium",",","_to",",","temp_name",")","if","code","!","=","0",":","chrome","=","self.chrome_command","(",")","code","=","self.command_runner","(","chrome",",","_to",",","temp_name",")","if","code","!","=","0",":","logger.error","(","``","Fail","to","convert","svg","to","pdf",".","Make","sure","Chromium","or","Chrome","is","installed",".","''",")","exit","(","1",")","return","True"] | 71 | 89 | null | convert-svg-to-pdf.py | sympy/doc/ext/convert-svg-to-pdf.py | from __future__ import annotations
from sphinx.transforms.post_transforms.images import ImageConverter
from sphinx.util import logging
import os
import platform
from typing import Any
from sphinx.application import Sphinx | 15 | 1 | 7 | 1 | 1 | 5 | 1 | Use image node_id 5 for calling the Converter obj's underlying member method code with example usage: obj.convert(_from, _to) and returns: True | 143 | node_id 5 | 2,029,278 |
_setup | RunnerTrafficMetricsMiddleware | null | true | self,metrics_client | null | null | null | null | null | def _setup(
self,
metrics_client: "PrometheusClient" = Provide[
BentoMLContainer.metrics_client
],
):
self.metrics_client = metrics_client
self.metrics_request_duration = metrics_client.Histogram(
namespace=self.namespace,
name="request_duration_seconds",
documentation="runner RPC duration in seconds",
labelnames=[
"endpoint",
"service_name",
"service_version",
"http_response_code",
"runner_name",
],
)
self.metrics_request_total = metrics_client.Counter(
namespace=self.namespace,
name="request_total",
documentation="Total number of runner RPC",
labelnames=[
"endpoint",
"service_name",
"service_version",
"http_response_code",
"runner_name",
],
)
self.metrics_request_in_progress = metrics_client.Gauge(
namespace=self.namespace,
name="request_in_progress",
documentation="Total number of runner RPC in progress now",
labelnames=[
"endpoint",
"service_name",
"service_version",
"runner_name",
],
multiprocess_mode="livesum",
)
self._is_setup = True
| ["def","_setup","(","self",",","metrics_client",":","``","PrometheusClient","''","=","Provide","[","BentoMLContainer.metrics_client","]",",",")",":","self.metrics_client","=","metrics_client","self.metrics_request_duration","=","metrics_client.Histogram","(","namespace=self.namespace",",","name=","''","request_duration_seconds","''",",","documentation=","''","runner","RPC","duration","in","seconds","''",",","labelnames=","[","``","endpoint","''",",","``","service_name","''",",","``","service_version","''",",","``","http_response_code","''",",","``","runner_name","''",",","]",",",")","self.metrics_request_total","=","metrics_client.Counter","(","namespace=self.namespace",",","name=","''","request_total","''",",","documentation=","''","Total","number","of","runner","RPC","''",",","labelnames=","[","``","endpoint","''",",","``","service_name","''",",","``","service_version","''",",","``","http_response_code","''",",","``","runner_name","''",",","]",",",")","self.metrics_request_in_progress","=","metrics_client.Gauge","(","namespace=self.namespace",",","name=","''","request_in_progress","''",",","documentation=","''","Total","number","of","runner","RPC","in","progress","now","''",",","labelnames=","[","``","endpoint","''",",","``","service_name","''",",","``","service_version","''",",","``","runner_name","''",",","]",",","multiprocess_mode=","''","livesum","''",",",")","self._is_setup","=","True"] | 150 | 187 | null | instruments.py | BentoML/src/bentoml/_internal/server/http/instruments.py | from __future__ import annotations
import contextvars
import logging
from timeit import default_timer
from typing import TYPE_CHECKING
from simple_di import Provide
from simple_di import inject
from ...configuration.containers import BentoMLContainer
from ...context import component_context | 15 | 2 | 9 | 0 | 0 | 2 | null | Use image node_id 2 for calling the RunnerTrafficMetricsMiddleware obj's underlying member method code with example usage: obj._setup(metrics_client) without return types | 170 | node_id 2 | 14,515 |
command_runner | Converter | ImageConverter | true | self,chrome,_to,temp_name | null | null | null | null | os,int | def command_runner(
self, chrome: str | None, _to: str, temp_name: str
) -> int:
if not chrome:
return 1
command = f"{chrome} --headless --disable-gpu --disable-software-rasterizer --print-to-pdf={_to} {temp_name}"
logger.error(command)
return os.system(command)
| ["def","command_runner","(","self",",","chrome",":","str","|","None",",","_to",":","str",",","temp_name",":","str",")","-",">","int",":","if","not","chrome",":","return","1","command","=","f","''","{","chrome","}","--","headless","--","disable-gpu","--","disable-software-rasterizer","--","print-to-pdf=","{","_to","}","{","temp_name","}","''","logger.error","(","command",")","return","os.system","(","command",")"] | 64 | 69 | null | convert-svg-to-pdf.py | sympy/doc/ext/convert-svg-to-pdf.py | from __future__ import annotations
from sphinx.transforms.post_transforms.images import ImageConverter
from sphinx.util import logging
import os
import platform
from typing import Any
from sphinx.application import Sphinx | 15 | 1 | 7 | 1 | 1 | 5 | 1 | Use image node_id 4 for calling the Converter obj's underlying member method code with example usage: obj.command_runner(chrome, _to, temp_name) and returns: os, int | 165 | node_id 4 | 2,029,277 |
chromium_command | Converter | ImageConverter | true | self | null | null | null | null | None,None,str,str,str+path+str,path,str | def chromium_command(self) -> str | None:
if platform.win32_ver()[0]:
if os.system("where chromium") == 0:
return "chromium"
path = os.path.join(
os.environ["PROGRAMW6432"],
"Chromium\\Application\\chrome.exe",
)
if os.path.exists(path):
return f'"{path}"'
return None
if os.system("chromium --version") == 0:
return "chromium"
if platform.mac_ver()[0]:
path = "/Applications/Chromium.app/Contents/MacOS/Chromium"
if os.path.exists(path):
return path
elif platform.libc_ver()[0]:
if os.system("chromium-browser --version") == 0:
return "chromium-browser"
return None
| ["def","chromium_command","(","self",")","-",">","str","|","None",":","if","platform.win32_ver","(",")","[","0","]",":","if","os.system","(","``","where","chromium","''",")","==","0",":","return","``","chromium","''","path","=","os.path.join","(","os.environ","[","``","PROGRAMW6432","''","]",",","``","Chromium\\\\Application\\\\chrome.exe","''",",",")","if","os.path.exists","(","path",")",":","return","f","'","''","{","path","}","''","'","return","None","if","os.system","(","``","chromium","--","version","''",")","==","0",":","return","``","chromium","''","if","platform.mac_ver","(",")","[","0","]",":","path","=","``","\/Applications\/Chromium.app\/Contents\/MacOS\/Chromium","''","if","os.path.exists","(","path",")",":","return","path","elif","platform.libc_ver","(",")","[","0","]",":","if","os.system","(","``","chromium-browser","--","version","''",")","==","0",":","return","``","chromium-browser","''","return","None"] | 44 | 61 | null | convert-svg-to-pdf.py | sympy/doc/ext/convert-svg-to-pdf.py | from __future__ import annotations
from sphinx.transforms.post_transforms.images import ImageConverter
from sphinx.util import logging
import os
import platform
from typing import Any
from sphinx.application import Sphinx | 15 | 1 | 7 | 1 | 1 | 5 | 1 | Use image node_id 3 for calling the Converter obj's underlying member method code with example usage: obj.chromium_command() and returns: None, None, str, str, str, path, str, path, str | 185 | node_id 3 | 2,029,276 |
_test_texture_as_input | TestShapeShifter | TestBase | true | self,sign_gradients,use_spectral,soft_clip | null | null | null | null | background, image_frame, y_,current_image | def _test_texture_as_input(
self, sign_gradients, use_spectral, soft_clip
):
# We must start a new graph
tf.reset_default_graph()
# Only import if object detection module is available
from art.estimators.object_detection.tensorflow_faster_rcnn import (
TensorFlowFasterRCNN,
)
from art.attacks.evasion.shapeshifter import ShapeShifter
# Define object detector
images = tf.Variable(
initial_value=np.zeros([1, 28, 28, 1]), dtype=tf.float32
)
obj_dec = TensorFlowFasterRCNN(images=images)
# Create labels
result = obj_dec.predict(self.x_test_mnist[:1].astype(np.float32))
groundtruth_boxes_list = [result[i]["boxes"] for i in range(1)]
groundtruth_classes_list = [result[i]["labels"] for i in range(1)]
groundtruth_weights_list = [
np.ones_like(r) for r in groundtruth_classes_list
]
y = {
"groundtruth_boxes_list": groundtruth_boxes_list,
"groundtruth_classes_list": groundtruth_classes_list,
"groundtruth_weights_list": groundtruth_weights_list,
}
# Define random transform
def random_transform(x):
background = np.random.rand(*x.shape)
image_frame = np.random.rand(*(list(x.shape[:-1]) + [4]))
y_ = y.copy()
y_["groundtruth_boxes_list"][0] = (
y_["groundtruth_boxes_list"][0] + np.random.rand()
)
y_["groundtruth_weights_list"][0] = (
y_["groundtruth_weights_list"][0] + np.random.rand()
)
return background, image_frame, y_
# Define attack
attack = ShapeShifter(
estimator=obj_dec,
random_transform=random_transform,
box_classifier_weight=1.0,
box_localizer_weight=1.0,
rpn_classifier_weight=1.0,
rpn_localizer_weight=1.0,
box_iou_threshold=0.3,
box_victim_weight=1.0,
box_target_weight=1.0,
box_victim_cw_weight=1.0,
box_victim_cw_confidence=1.0,
box_target_cw_weight=1.0,
box_target_cw_confidence=1.0,
rpn_iou_threshold=0.3,
rpn_background_weight=1.0,
rpn_foreground_weight=1.0,
rpn_cw_weight=1.0,
rpn_cw_confidence=1.0,
similarity_weight=1.0,
learning_rate=0.1,
optimizer="MomentumOptimizer",
momentum=0.01,
decay=0.01,
sign_gradients=sign_gradients,
random_size=2,
max_iter=2,
texture_as_input=True,
use_spectral=use_spectral,
soft_clip=soft_clip,
)
# Define rendering function
def rendering_function(
background_phd, image_frame_phd, current_texture
):
current_image = background_phd + current_texture
current_image = tf.clip_by_value(current_image, 0, 1)
return current_image
# Targeted attack
adv_x = attack.generate(
x=self.x_test_mnist[:1].astype(np.float32),
label=y,
target_class=2,
victim_class=5,
rendering_function=rendering_function,
)
self.assertTrue(adv_x.shape == (1, 28, 28, 1))
# Untargeted attack
adv_x = attack.generate(
x=self.x_test_mnist[:1].astype(np.float32),
label=y,
target_class=8,
victim_class=8,
rendering_function=rendering_function,
)
self.assertTrue(adv_x.shape == (1, 28, 28, 1))
| ["def","_test_texture_as_input","(","self",",","sign_gradients",",","use_spectral",",","soft_clip",")",":","#","We","must","start","a","new","graph","tf.reset_default_graph","(",")","#","Only","import","if","object","detection","module","is","available","from","art.estimators.object_detection.tensorflow_faster_rcnn","import","(","TensorFlowFasterRCNN",",",")","from","art.attacks.evasion.shapeshifter","import","ShapeShifter","#","Define","object","detector","images","=","tf.Variable","(","initial_value=np.zeros","(","[","1",",","28",",","28",",","1","]",")",",","dtype=tf.float32",")","obj_dec","=","TensorFlowFasterRCNN","(","images=images",")","#","Create","labels","result","=","obj_dec.predict","(","self.x_test_mnist","[",":1","]",".astype","(","np.float32",")",")","groundtruth_boxes_list","=","[","result","[","i","]","[","``","boxes","''","]","for","i","in","range","(","1",")","]","groundtruth_classes_list","=","[","result","[","i","]","[","``","labels","''","]","for","i","in","range","(","1",")","]","groundtruth_weights_list","=","[","np.ones_like","(","r",")","for","r","in","groundtruth_classes_list","]","y","=","{","``","groundtruth_boxes_list","''",":","groundtruth_boxes_list",",","``","groundtruth_classes_list","''",":","groundtruth_classes_list",",","``","groundtruth_weights_list","''",":","groundtruth_weights_list",",","}","#","Define","random","transform","def","random_transform","(","x",")",":","background","=","np.random.rand","(","*","x.shape",")","image_frame","=","np.random.rand","(","*","(","list","(","x.shape","[",":","-1","]",")","+","[","4","]",")",")","y_","=","y.copy","(",")","y_","[","``","groundtruth_boxes_list","''","]","[","0","]","=","(","y_","[","``","groundtruth_boxes_list","''","]","[","0","]","+","np.random.rand","(",")",")","y_","[","``","groundtruth_weights_list","''","]","[","0","]","=","(","y_","[","``","groundtruth_weights_list","''","]","[","0","]","+","np.random.rand","(",")",")","return","background",",","image_frame",",","y_","#","Define","attack","attack","=","ShapeShifter","(","estimator=obj_dec",",","random_transform=random_transform",",","box_classifier_weight=1.0",",","box_localizer_weight=1.0",",","rpn_classifier_weight=1.0",",","rpn_localizer_weight=1.0",",","box_iou_threshold=0.3",",","box_victim_weight=1.0",",","box_target_weight=1.0",",","box_victim_cw_weight=1.0",",","box_victim_cw_confidence=1.0",",","box_target_cw_weight=1.0",",","box_target_cw_confidence=1.0",",","rpn_iou_threshold=0.3",",","rpn_background_weight=1.0",",","rpn_foreground_weight=1.0",",","rpn_cw_weight=1.0",",","rpn_cw_confidence=1.0",",","similarity_weight=1.0",",","learning_rate=0.1",",","optimizer=","''","MomentumOptimizer","''",",","momentum=0.01",",","decay=0.01",",","sign_gradients=sign_gradients",",","random_size=2",",","max_iter=2",",","texture_as_input=True",",","use_spectral=use_spectral",",","soft_clip=soft_clip",",",")","#","Define","rendering","function","def","rendering_function","(","background_phd",",","image_frame_phd",",","current_texture",")",":","current_image","=","background_phd","+","current_texture","current_image","=","tf.clip_by_value","(","current_image",",","0",",","1",")","return","current_image","#","Targeted","attack","adv_x","=","attack.generate","(","x=self.x_test_mnist","[",":1","]",".astype","(","np.float32",")",",","label=y",",","target_class=2",",","victim_class=5",",","rendering_function=rendering_function",",",")","self.assertTrue","(","adv_x.shape","==","(","1",",","28",",","28",",","1",")",")","#","Untargeted","attack","adv_x","=","attack.generate","(","x=self.x_test_mnist","[",":1","]",".astype","(","np.float32",")",",","label=y",",","target_class=8",",","victim_class=8",",","rendering_function=rendering_function",",",")","self.assertTrue","(","adv_x.shape","==","(","1",",","28",",","28",",","1",")",")"] | 139 | 235 | null | test_shapeshifter.py | adversarial-robustness-toolbox/tests/attacks/test_shapeshifter.py | from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import unittest
import importlib
import tensorflow
import numpy
from tests.utils import TestBase, master_seed | 15 | 1 | 7 | 0 | 1 | 6 | 1 | Use image node_id 5 for calling the TestShapeShifter obj's underlying member method code with example usage: obj._test_texture_as_input(sign_gradients, use_spectral, soft_clip) and returns: background, image_frame, y_, current_image | 234 | node_id 5 | 234,965 |
test_check_params | TestShapeShifter | TestBase | true | self | null | null | null | null | null | def test_check_params(self):
from art.estimators.object_detection import TensorFlowFasterRCNN
from art.attacks.evasion import ShapeShifter
images = tf.Variable(
initial_value=np.zeros([1, 28, 28, 1]), dtype=tf.float32
)
obj_dec = TensorFlowFasterRCNN(images=images)
with self.assertRaises(ValueError):
_ = ShapeShifter(obj_dec, random_transform="1")
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
box_classifier_weight=1,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
box_classifier_weight=-1.0,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
box_localizer_weight=1,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
box_localizer_weight=-1.0,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
rpn_classifier_weight=1,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
rpn_classifier_weight=-1.0,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
rpn_localizer_weight=1,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
rpn_localizer_weight=-1.0,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
box_iou_threshold=1,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
box_iou_threshold=-1.0,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
box_victim_weight=1,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
box_victim_weight=-1.0,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
box_target_weight=1,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
box_target_weight=-1.0,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
box_victim_cw_weight=1,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
box_victim_cw_weight=-1.0,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
box_victim_cw_confidence=1,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
box_victim_cw_confidence=-1.0,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
box_target_cw_weight=1,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
box_target_cw_weight=-1.0,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
box_target_cw_confidence=1,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
box_target_cw_confidence=-1.0,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
rpn_iou_threshold=1,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
rpn_iou_threshold=-1.0,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
rpn_background_weight=1,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
rpn_background_weight=-1.0,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
rpn_foreground_weight=1,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
rpn_foreground_weight=-1.0,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
rpn_cw_weight=1,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
rpn_cw_weight=-1.0,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
rpn_cw_confidence=1,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
rpn_cw_confidence=-1.0,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
similarity_weight=1,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
similarity_weight=-1.0,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
learning_rate=1,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
learning_rate=-1.0,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
optimizer="test",
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
optimizer="MomentumOptimizer",
momentum=1,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
optimizer="MomentumOptimizer",
momentum=-1.0,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
optimizer="RMSPropOptimizer",
momentum=0.5,
decay="1",
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
optimizer="RMSPropOptimizer",
momentum=0.5,
decay=-1.0,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
optimizer="RMSPropOptimizer",
momentum=0.5,
decay=2.0,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
sign_gradients="true",
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
random_size=1.0,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
random_size=-1,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
max_iter=1.0,
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec, random_transform=lambda x: x + 1e-10, max_iter=-1
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
texture_as_input="true",
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
use_spectral="true",
)
with self.assertRaises(ValueError):
_ = ShapeShifter(
obj_dec,
random_transform=lambda x: x + 1e-10,
soft_clip="true",
)
| ["def","test_check_params","(","self",")",":","from","art.estimators.object_detection","import","TensorFlowFasterRCNN","from","art.attacks.evasion","import","ShapeShifter","images","=","tf.Variable","(","initial_value=np.zeros","(","[","1",",","28",",","28",",","1","]",")",",","dtype=tf.float32",")","obj_dec","=","TensorFlowFasterRCNN","(","images=images",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=","''","1","''",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","box_classifier_weight=1",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","box_classifier_weight=-1.0",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","box_localizer_weight=1",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","box_localizer_weight=-1.0",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","rpn_classifier_weight=1",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","rpn_classifier_weight=-1.0",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","rpn_localizer_weight=1",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","rpn_localizer_weight=-1.0",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","box_iou_threshold=1",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","box_iou_threshold=-1.0",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","box_victim_weight=1",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","box_victim_weight=-1.0",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","box_target_weight=1",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","box_target_weight=-1.0",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","box_victim_cw_weight=1",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","box_victim_cw_weight=-1.0",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","box_victim_cw_confidence=1",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","box_victim_cw_confidence=-1.0",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","box_target_cw_weight=1",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","box_target_cw_weight=-1.0",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","box_target_cw_confidence=1",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","box_target_cw_confidence=-1.0",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","rpn_iou_threshold=1",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","rpn_iou_threshold=-1.0",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","rpn_background_weight=1",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","rpn_background_weight=-1.0",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","rpn_foreground_weight=1",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","rpn_foreground_weight=-1.0",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","rpn_cw_weight=1",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","rpn_cw_weight=-1.0",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","rpn_cw_confidence=1",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","rpn_cw_confidence=-1.0",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","similarity_weight=1",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","similarity_weight=-1.0",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","learning_rate=1",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","learning_rate=-1.0",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","optimizer=","''","test","''",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","optimizer=","''","MomentumOptimizer","''",",","momentum=1",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","optimizer=","''","MomentumOptimizer","''",",","momentum=-1.0",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","optimizer=","''","RMSPropOptimizer","''",",","momentum=0.5",",","decay=","''","1","''",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","optimizer=","''","RMSPropOptimizer","''",",","momentum=0.5",",","decay=-1.0",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","optimizer=","''","RMSPropOptimizer","''",",","momentum=0.5",",","decay=2.0",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","sign_gradients=","''","true","''",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","random_size=1.0",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","random_size=-1",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","max_iter=1.0",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","max_iter=-1",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","texture_as_input=","''","true","''",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","use_spectral=","''","true","''",",",")","with","self.assertRaises","(","ValueError",")",":","_","=","ShapeShifter","(","obj_dec",",","random_transform=lambda","x",":","x","+","1e-10",",","soft_clip=","''","true","''",",",")"] | 237 | 380 | null | test_shapeshifter.py | adversarial-robustness-toolbox/tests/attacks/test_shapeshifter.py | from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import unittest
import importlib
import tensorflow
import numpy
from tests.utils import TestBase, master_seed | 15 | 1 | 7 | 0 | 1 | 6 | 1 | Use image node_id 6 for calling the TestShapeShifter obj's underlying member method code with example usage: obj.test_check_params() without return types | 153 | node_id 6 | 234,966 |
This dataset is a subset of the matlok python copilot datasets. Please refer to the Multimodal Python Copilot Training Overview for more details on how to use this dataset.
Each row contains python code, either a class method or a global function, imported modules, base classes (if any), exceptions (ordered based off the code), returns (ordered based off the code), arguments (ordered based off the code), and more.
{
"args": "string",
"class_bases": "string",
"class_docstr": "string",
"class_docstr_tok": "string",
"class_name": "string",
"code": "string",
"code_tok": "string",
"docstr": "string",
"docstr_tok": "string",
"file_path": "string",
"filename": "string",
"imports": "string",
"is_member": "bool",
"label_desc": "string",
"label_desc_len": "int64",
"label_id": "string",
"lend": "int64",
"lstart": "int64",
"name": "string",
"num_all_bases": "float64",
"num_bases": "float64",
"num_classes": "float64",
"num_functions": "int64",
"num_imports": "int64",
"num_methods": "float64",
"raises": "string",
"returns": "string",
"total_objects": "int64"
}
from datasets import load_dataset
ds = load_dataset("matlok/python-copilot-training-from-many-repos-large", data_dir="files")