project_name stringlengths 6 104 | file_name stringlengths 4 89 | full_name stringlengths 1 102 | func_name stringlengths 1 85 | docstring stringlengths 13 836 | docstring_tokens listlengths 4 122 | code stringlengths 23 39.7k | code_tokens stringlengths 29 44.6k | url int64 3 986k |
|---|---|---|---|---|---|---|---|---|
ViCCo-Group/thingsvision | helper.py | create_test_images | create_test_images | Create an artificial image dataset to be used for performing tests. | [
"Create",
"an",
"artificial",
"image",
"dataset",
"to",
"be",
"used",
"for",
"performing",
"tests."
] | def create_test_images(n_samples: int=NUM_SAMPLES) -> None:
if not os.path.exists(OUT_PATH):
os.makedirs(OUT_PATH)
if not os.path.exists(TEST_PATH):
test_img_1 = skimage.data.hubble_deep_field()
test_img_2 = skimage.data.coffee()
test_imgs = list(map(lambda x: x / x.max(), [test_... | ['def', 'create_test_images(n_samples:', 'int=NUM_SAMPLES)', '->', 'None:', 'if', 'not', 'os.path.exists(OUT_PATH):', 'os.makedirs(OUT_PATH)', 'if', 'not', 'os.path.exists(TEST_PATH):', 'test_img_1', '=', 'skimage.data.hubble_deep_field()', 'test_img_2', '=', 'skimage.data.coffee()', 'test_imgs', '=', 'list(map(lambda'... | 916,130 |
alteia-ai/ICSS | trainer.py | Trainer.load_weights | load_weights | Only to infer (doesn't load scheduler and optimizer state). | [
"Only",
"to",
"infer",
"(doesn't",
"load",
"scheduler",
"and",
"optimizer",
"state)."
] | def load_weights(self, path_weights: str) -> None:
print(path_weights)
try:
self.net = jit.load(path_weights, map_location=self.device)
except:
checkpoint = torch.load(path_weights)
self.net.load_state_dict(checkpoint['net'])
logging.info('%s Weights loaded', time.strftime('%m/%d... | ['def', 'load_weights(self,', 'path_weights:', 'str)', '->', 'None:', 'print(path_weights)', 'try:', 'self.net', '=', 'jit.load(path_weights,', 'map_location=self.device)', 'except:', 'checkpoint', '=', 'torch.load(path_weights)', "self.net.load_state_dict(checkpoint['net'])", "logging.info('%s", 'Weights', "loaded',",... | 597,008 |
jimtin/Stock_Comparison | test_path.py | TestSpecialPaths.test_reused_SpecialResolver | test_reused_SpecialResolver | Passing additional args and kwargs to SpecialResolver should be passed through to each invocation of the function in appdirs. | [
"Passing",
"additional",
"args",
"and",
"kwargs",
"to",
"SpecialResolver",
"should",
"be",
"passed",
"through",
"to",
"each",
"invocation",
"of",
"the",
"function",
"in",
"appdirs."
] | def test_reused_SpecialResolver(self):
appdirs = importlib.import_module('appdirs')
adp = SpecialResolver(Path, version='1.0')
res = adp.user.config
expected = appdirs.user_config_dir(version='1.0')
assert res == expected | ['def', 'test_reused_SpecialResolver(self):', 'appdirs', '=', "importlib.import_module('appdirs')", 'adp', '=', 'SpecialResolver(Path,', "version='1.0')", 'res', '=', 'adp.user.config', 'expected', '=', "appdirs.user_config_dir(version='1.0')", 'assert', 'res', '==', 'expected'] | 384,382 |
voxel51/fiftyone | collections.py | SampleCollection.delete_evaluation | delete_evaluation | Deletes the evaluation results associated with the given evaluation key from this collection. | [
"Deletes",
"the",
"evaluation",
"results",
"associated",
"with",
"the",
"given",
"evaluation",
"key",
"from",
"this",
"collection."
] | def delete_evaluation(self, eval_key):
foev.EvaluationMethod.delete_run(self, eval_key) | ['def', 'delete_evaluation(self,', 'eval_key):', 'foev.EvaluationMethod.delete_run(self,', 'eval_key)'] | 582,778 |
JIA-HONG-CHU/Swin-Transformer-add-EncNet-DaNet-DraNet-for---on-Statelite-Dataset | test_backbone.py | is_norm | is_norm | Check if is one of the norms. | [
"Check",
"if",
"is",
"one",
"of",
"the",
"norms."
] | def is_norm(modules):
if isinstance(modules, (GroupNorm, _BatchNorm)):
return True
return False | ['def', 'is_norm(modules):', 'if', 'isinstance(modules,', '(GroupNorm,', '_BatchNorm)):', 'return', 'True', 'return', 'False'] | 905,642 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | base_command.py | RequirementCommand.populate_requirement_set | populate_requirement_set | Marshal cmd line args into a requirement set. | [
"Marshal",
"cmd",
"line",
"args",
"into",
"a",
"requirement",
"set."
] | def populate_requirement_set(requirement_set, args, options, finder, session, name, wheel_cache):
for filename in options.constraints:
for req_to_add in parse_requirements(filename, constraint=True, finder=finder, options=options, session=session, wheel_cache=wheel_cache):
req_to_add.is_direct =... | ['def', 'populate_requirement_set(requirement_set,', 'args,', 'options,', 'finder,', 'session,', 'name,', 'wheel_cache):', 'for', 'filename', 'in', 'options.constraints:', 'for', 'req_to_add', 'in', 'parse_requirements(filename,', 'constraint=True,', 'finder=finder,', 'options=options,', 'session=session,', 'wheel_cach... | 950,035 |
Kvatsx/Artificial-Intelligence-Assignments | datetime.py | datetime.time | time | Return the time part, with tzinfo None. | [
"Return",
"the",
"time",
"part,",
"with",
"tzinfo",
"None."
] | def time(self):
return time(self.hour, self.minute, self.second, self.microsecond) | ['def', 'time(self):', 'return', 'time(self.hour,', 'self.minute,', 'self.second,', 'self.microsecond)'] | 36,651 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | nb_102a.py | create_anchors | create_anchors | Create anchor of `sizes`, `ratios` and `scales`. | [
"Create",
"anchor",
"of",
"`sizes`,",
"`ratios`",
"and",
"`scales`."
] | def create_anchors(sizes, ratios, scales, flatten=True):
aspects = [[[s * math.sqrt(r), s * math.sqrt(1 / r)] for s in scales] for r in ratios]
aspects = torch.tensor(aspects).view(-1, 2)
anchors = []
for (h, w) in sizes:
sized_aspects = 4 * (aspects * torch.tensor([2 / h, 2 / w])).unsqueeze(0)
... | ['def', 'create_anchors(sizes,', 'ratios,', 'scales,', 'flatten=True):', 'aspects', '=', '[[[s', '*', 'math.sqrt(r),', 's', '*', 'math.sqrt(1', '/', 'r)]', 'for', 's', 'in', 'scales]', 'for', 'r', 'in', 'ratios]', 'aspects', '=', 'torch.tensor(aspects).view(-1,', '2)', 'anchors', '=', '[]', 'for', '(h,', 'w)', 'in', 's... | 32,596 |
kubeflow/pipelines | _container_op.py | create_and_append | create_and_append | Create a list (if needed) and appends an item to it. | [
"Create",
"a",
"list",
"(if",
"needed)",
"and",
"appends",
"an",
"item",
"to",
"it."
] | def create_and_append(current_list: Union[List[T], None], item: T) -> List[T]:
current_list = current_list or []
current_list.append(item)
return current_list | ['def', 'create_and_append(current_list:', 'Union[List[T],', 'None],', 'item:', 'T)', '->', 'List[T]:', 'current_list', '=', 'current_list', 'or', '[]', 'current_list.append(item)', 'return', 'current_list'] | 780,107 |
wandb/wandb | test_gcp.py | test_from_default_gcloud | test_from_default_gcloud | Test constructing gcp environment in a region read by the gcloud CLI. | [
"Test",
"constructing",
"gcp",
"environment",
"in",
"a",
"region",
"read",
"by",
"the",
"gcloud",
"CLI."
] | def test_from_default_gcloud(mocker):
mocker.patch('wandb.sdk.launch.environment.gcp_environment.subprocess.check_output', return_value=b'us-central1')
environment = GcpEnvironment.from_default(verify=False)
assert environment.region == 'us-central1' | ['def', 'test_from_default_gcloud(mocker):', "mocker.patch('wandb.sdk.launch.environment.gcp_environment.subprocess.check_output',", "return_value=b'us-central1')", 'environment', '=', 'GcpEnvironment.from_default(verify=False)', 'assert', 'environment.region', '==', "'us-central1'"] | 941,271 |
Speedwagon13/CS-3600-Introduction-to-- | test_io.py | MockNonBlockWriterIO.block_on | block_on | Block when a given char is encountered. | [
"Block",
"when",
"a",
"given",
"char",
"is",
"encountered."
] | def block_on(self, char):
self._blocker_char = char | ['def', 'block_on(self,', 'char):', 'self._blocker_char', '=', 'char'] | 219,614 |
stevehuanghe/multi_label_zsl | pytorch_misc.py | argsort_desc | argsort_desc | Returns the indices that sort scores descending in a smart way :param scores: Numpy array of arbitrary size :return: an array of size [numel(scores), dim(scores)] where each row is the index you'd need to get the score. | [
"Returns",
"the",
"indices",
"that",
"sort",
"scores",
"descending",
"in",
"a",
"smart",
"way",
":param",
"scores:",
"Numpy",
"array",
"of",
"arbitrary",
"size",
":return:",
"an",
"array",
"of",
"size",
"[numel(scores),",
"dim(scores)]",
"where",
"each",
"row",
... | def argsort_desc(scores):
return np.column_stack(np.unravel_index(np.argsort(-scores.ravel()), scores.shape)) | ['def', 'argsort_desc(scores):', 'return', 'np.column_stack(np.unravel_index(np.argsort(-scores.ravel()),', 'scores.shape))'] | 644,500 |
jwwangchn/NWD | test_head.py | test_ssd_head_get_bboxes | test_ssd_head_get_bboxes | Test SSD Head get_bboxes in torch and onnxruntime env. | [
"Test",
"SSD",
"Head",
"get_bboxes",
"in",
"torch",
"and",
"onnxruntime",
"env."
] | def test_ssd_head_get_bboxes():
ssd_model = ssd_config()
s = 300
img_metas = [{'img_shape_for_onnx': torch.Tensor([s, s]), 'scale_factor': np.ones(4), 'pad_shape': (s, s, 3), 'img_shape': (s, s, 2)}]
ssd_head_data = 'ssd_head_get_bboxes.pkl'
feats = mmcv.load(osp.join(data_path, ssd_head_data))
... | ['def', 'test_ssd_head_get_bboxes():', 'ssd_model', '=', 'ssd_config()', 's', '=', '300', 'img_metas', '=', "[{'img_shape_for_onnx':", 'torch.Tensor([s,', 's]),', "'scale_factor':", 'np.ones(4),', "'pad_shape':", '(s,', 's,', '3),', "'img_shape':", '(s,', 's,', '2)}]', 'ssd_head_data', '=', "'ssd_head_get_bboxes.pkl'",... | 725,109 |
gradio-app/gradio | analytics.py | analytics_enabled | analytics_enabled | Returns: True if analytics are enabled, False otherwise. | [
"Returns:",
"True",
"if",
"analytics",
"are",
"enabled,",
"False",
"otherwise."
] | def analytics_enabled() -> bool:
return os.getenv('GRADIO_ANALYTICS_ENABLED', 'True') == 'True' | ['def', 'analytics_enabled()', '->', 'bool:', 'return', "os.getenv('GRADIO_ANALYTICS_ENABLED',", "'True')", '==', "'True'"] | 578,811 |
datature/portal | global_store.py | GlobalStore.update_targeted_folder | update_targeted_folder | Update the cache given the folder path :param new_path: The path of the folder. | [
"Update",
"the",
"cache",
"given",
"the",
"folder",
"path",
":param",
"new_path:",
"The",
"path",
"of",
"the",
"folder."
] | def update_targeted_folder(self, new_path):
self._targeted_folders_.update_folder(new_path)
seriliazable_folders = jsonpickle.encode(self._targeted_folders_)
self._store_['targeted_folders'] = seriliazable_folders
self._save_store_() | ['def', 'update_targeted_folder(self,', 'new_path):', 'self._targeted_folders_.update_folder(new_path)', 'seriliazable_folders', '=', 'jsonpickle.encode(self._targeted_folders_)', "self._store_['targeted_folders']", '=', 'seriliazable_folders', 'self._save_store_()'] | 820,976 |
enuguru/artificial_intelligence_and_machine_ | _compat.py | to_unicode | to_unicode | Decodes input_bytes to text if needed. | [
"Decodes",
"input_bytes",
"to",
"text",
"if",
"needed."
] | def to_unicode(input_bytes, encoding='utf-8'):
if not isinstance(input_bytes, string_types):
input_bytes = input_bytes.decode(encoding)
return input_bytes | ['def', 'to_unicode(input_bytes,', "encoding='utf-8'):", 'if', 'not', 'isinstance(input_bytes,', 'string_types):', 'input_bytes', '=', 'input_bytes.decode(encoding)', 'return', 'input_bytes'] | 157,972 |
bachiraoun/fullrmc | Constraint.py | Constraint.data | data | Constraint's current calculated data. | [
"Constraint's",
"current",
"calculated",
"data."
] | def data(self):
return self.__data | ['def', 'data(self):', 'return', 'self.__data'] | 213,759 |
NEISSproject/tf2_neiss_nlp | multiheadattention.py | matmul_with_relative_representations | matmul_with_relative_representations | Multiplies :obj:`a` with the relative representations :obj:`b`. | [
"Multiplies",
":obj:`a`",
"with",
"the",
"relative",
"representations",
":obj:`b`."
] | def matmul_with_relative_representations(a, b, transpose_b=False):
shapes = shape_list(a)
(batch, head, time) = (shapes[0], shapes[1], shapes[2])
a = tf.transpose(a, perm=[2, 0, 1, 3])
a = tf.reshape(a, [time, batch * head, -1])
c = tf.matmul(a, b, transpose_b=transpose_b)
c = tf.reshape(c, [tim... | ['def', 'matmul_with_relative_representations(a,', 'b,', 'transpose_b=False):', 'shapes', '=', 'shape_list(a)', '(batch,', 'head,', 'time)', '=', '(shapes[0],', 'shapes[1],', 'shapes[2])', 'a', '=', 'tf.transpose(a,', 'perm=[2,', '0,', '1,', '3])', 'a', '=', 'tf.reshape(a,', '[time,', 'batch', '*', 'head,', '-1])', 'c'... | 915,738 |
Eric3911/OpenAGI | gpu_rnnt.py | MultiblankGPURNNT.compute_cost_and_score | compute_cost_and_score | Compute both the loss and the gradients. | [
"Compute",
"both",
"the",
"loss",
"and",
"the",
"gradients."
] | def compute_cost_and_score(self, acts: torch.Tensor, grads: Optional[torch.Tensor], costs: torch.Tensor, labels: torch.Tensor, label_lengths: torch.Tensor, input_lengths: torch.Tensor) -> global_constants.RNNTStatus:
training = grads is not None
if training:
grads *= 0.0
(_, (denom, alphas, betas, l... | ['def', 'compute_cost_and_score(self,', 'acts:', 'torch.Tensor,', 'grads:', 'Optional[torch.Tensor],', 'costs:', 'torch.Tensor,', 'labels:', 'torch.Tensor,', 'label_lengths:', 'torch.Tensor,', 'input_lengths:', 'torch.Tensor)', '->', 'global_constants.RNNTStatus:', 'training', '=', 'grads', 'is', 'not', 'None', 'if', '... | 272,716 |
eddylau328/fyp-artificial-intelligence-ac-control-device | _cloud_sdk.py | load_authorized_user_credentials | load_authorized_user_credentials | Loads an authorized user credential. | [
"Loads",
"an",
"authorized",
"user",
"credential."
] | def load_authorized_user_credentials(info):
return google.oauth2.credentials.Credentials.from_authorized_user_info(info) | ['def', 'load_authorized_user_credentials(info):', 'return', 'google.oauth2.credentials.Credentials.from_authorized_user_info(info)'] | 214,566 |
rifqind/Agent-Programs-3KS1 | png.py | Test.testTrnsArray | testTrnsArray | Test that reading a type 2 PNG with tRNS chunk yields each row as an array (using asDirect). | [
"Test",
"that",
"reading",
"a",
"type",
"2",
"PNG",
"with",
"tRNS",
"chunk",
"yields",
"each",
"row",
"as",
"an",
"array",
"(using",
"asDirect)."
] | def testTrnsArray(self):
r = Reader(bytes=_pngsuite['tbrn2c08'])
list(r.asDirect()[2])[0].tostring | ['def', 'testTrnsArray(self):', 'r', '=', "Reader(bytes=_pngsuite['tbrn2c08'])", 'list(r.asDirect()[2])[0].tostring'] | 46,085 |
OpenMDAO/OpenMDAO-Framework | caseset.py | CaseSet.issuperset | issuperset | Return True if every Case in the given CaseSet is in this one. | [
"Return",
"True",
"if",
"every",
"Case",
"in",
"the",
"given",
"CaseSet",
"is",
"in",
"this",
"one."
] | def issuperset(self, case_set):
self._check_compatability(case_set)
return self._tupset.issuperset(case_set._tupset) | ['def', 'issuperset(self,', 'case_set):', 'self._check_compatability(case_set)', 'return', 'self._tupset.issuperset(case_set._tupset)'] | 275,331 |
AlperHuseyn/artificial-intelligence-and-machine-learning-with-python | gallonomics.py | create_auto_mpg_model | create_auto_mpg_model | Create a 2-layer Sequential model for auto-mpg prediction. | [
"Create",
"a",
"2-layer",
"Sequential",
"model",
"for",
"auto-mpg",
"prediction."
] | def create_auto_mpg_model(input_dim, name=None):
model = Sequential(name=name)
model.add(Dense(64, activation='relu', input_dim=input_dim, name='Hidden1'))
model.add(Dense(64, activation='relu', name='Hidden2'))
model.add(Dense(1, activation='linear', name='output'))
model.summary()
model.compil... | ['def', 'create_auto_mpg_model(input_dim,', 'name=None):', 'model', '=', 'Sequential(name=name)', 'model.add(Dense(64,', "activation='relu',", 'input_dim=input_dim,', "name='Hidden1'))", 'model.add(Dense(64,', "activation='relu',", "name='Hidden2'))", 'model.add(Dense(1,', "activation='linear',", "name='output'))", 'mo... | 36,121 |
facebookarchive/git-review | commit.py | get_working_dir_commit | get_working_dir_commit | get_working_dir_commit(repo) --> commit Get a fake Commit object representing the changes currently in the working directory. | [
"get_working_dir_commit(repo)",
"-->",
"commit",
"Get",
"a",
"fake",
"Commit",
"object",
"representing",
"the",
"changes",
"currently",
"in",
"the",
"working",
"directory."
] | def get_working_dir_commit(repo):
tree = repo.getWorkingDir()
if not tree:
tree = '<none>'
parents = [constants.COMMIT_INDEX]
author = _get_bogus_author()
committer = _get_bogus_author()
comment = 'Uncomitted changes in the working directory'
return Commit(repo, constants.COMMIT_WD, ... | ['def', 'get_working_dir_commit(repo):', 'tree', '=', 'repo.getWorkingDir()', 'if', 'not', 'tree:', 'tree', '=', "'<none>'", 'parents', '=', '[constants.COMMIT_INDEX]', 'author', '=', '_get_bogus_author()', 'committer', '=', '_get_bogus_author()', 'comment', '=', "'Uncomitted", 'changes', 'in', 'the', 'working', "direc... | 202,442 |
dibyaghosh/gcsl | builder_test.py | ComponentBuilderTest.test_add_group_conflict | test_add_group_conflict | Tests adding a duplicate group. | [
"Tests",
"adding",
"a",
"duplicate",
"group."
] | def test_add_group_conflict(self):
builder = DummyBuilder()
builder.add_group('test')
with self.assertRaises(ValueError):
builder.add_group('test')
self.assertListEqual(builder.group_names, ['test']) | ['def', 'test_add_group_conflict(self):', 'builder', '=', 'DummyBuilder()', "builder.add_group('test')", 'with', 'self.assertRaises(ValueError):', "builder.add_group('test')", 'self.assertListEqual(builder.group_names,', "['test'])"] | 201,669 |
sek788432/Waymo-2D-Object-Detection | metrics.py | padded_sequence_accuracy | padded_sequence_accuracy | Percentage of times that predictions matches labels everywhere (non-0). | [
"Percentage",
"of",
"times",
"that",
"predictions",
"matches",
"labels",
"everywhere",
"(non-0)."
] | def padded_sequence_accuracy(logits, labels):
with tf.name_scope('padded_sequence_accuracy'):
(logits, labels) = _pad_tensors_to_same_length(logits, labels)
weights = tf.cast(tf.not_equal(labels, 0), tf.float32)
outputs = tf.cast(tf.argmax(logits, axis=-1), tf.int32)
padded_labels = ... | ['def', 'padded_sequence_accuracy(logits,', 'labels):', 'with', "tf.name_scope('padded_sequence_accuracy'):", '(logits,', 'labels)', '=', '_pad_tensors_to_same_length(logits,', 'labels)', 'weights', '=', 'tf.cast(tf.not_equal(labels,', '0),', 'tf.float32)', 'outputs', '=', 'tf.cast(tf.argmax(logits,', 'axis=-1),', 'tf.... | 972,852 |
facebookresearch/mtenv | env.py | get_list_of_func_to_make_envs | get_list_of_func_to_make_envs | Return a list of functions to construct the MetaWorld environments and a mapping of environment ids to tasks. | [
"Return",
"a",
"list",
"of",
"functions",
"to",
"construct",
"the",
"MetaWorld",
"environments",
"and",
"a",
"mapping",
"of",
"environment",
"ids",
"to",
"tasks."
] | def get_list_of_func_to_make_envs(benchmark: Optional[metaworld.Benchmark], benchmark_name: str, env_id_to_task_map: Optional[EnvIdToTaskMapType], should_perform_reward_normalization: bool=True, task_name: str='pick-place-v1', num_copies_per_env: int=1) -> Tuple[List[Any], Dict[str, Any]]:
if not benchmark:
... | ['def', 'get_list_of_func_to_make_envs(benchmark:', 'Optional[metaworld.Benchmark],', 'benchmark_name:', 'str,', 'env_id_to_task_map:', 'Optional[EnvIdToTaskMapType],', 'should_perform_reward_normalization:', 'bool=True,', 'task_name:', "str='pick-place-v1',", 'num_copies_per_env:', 'int=1)', '->', 'Tuple[List[Any],', ... | 642,692 |
accel-brain/accel-brain-code | deep_boltzmann_machines.py | DeepBoltzmannMachines.load_parameters | load_parameters | Load parameters to files. | [
"Load",
"parameters",
"to",
"files."
] | def load_parameters(self, filename, ctx=None, strict=True):
checkpoint = torch.load(filename)
self.epoch = checkpoint['epoch']
self.__loss_list = checkpoint['loss'].tolist()
filename_list = self.__rename_file(filename)
for i in range(len(filename_list)):
checkpoint = torch.load(filename_list... | ['def', 'load_parameters(self,', 'filename,', 'ctx=None,', 'strict=True):', 'checkpoint', '=', 'torch.load(filename)', 'self.epoch', '=', "checkpoint['epoch']", 'self.__loss_list', '=', "checkpoint['loss'].tolist()", 'filename_list', '=', 'self.__rename_file(filename)', 'for', 'i', 'in', 'range(len(filename_list)):', '... | 6,999 |
pykale/pykale | multiomics_datasets.py | MultiomicsDataset.num_modalities | num_modalities | Returns the number of modalities in the dataset. | [
"Returns",
"the",
"number",
"of",
"modalities",
"in",
"the",
"dataset."
] | def num_modalities(self) -> int:
return self._num_modalities | ['def', 'num_modalities(self)', '->', 'int:', 'return', 'self._num_modalities'] | 819,692 |
rudranil723/mini-main | xml_serializer.py | getInnerText | getInnerText | Get all the inner text of a DOM node (recursively). | [
"Get",
"all",
"the",
"inner",
"text",
"of",
"a",
"DOM",
"node",
"(recursively)."
] | def getInnerText(node):
inner_text = []
for child in node.childNodes:
if child.nodeType == child.TEXT_NODE or child.nodeType == child.CDATA_SECTION_NODE:
inner_text.append(child.data)
elif child.nodeType == child.ELEMENT_NODE:
inner_text.extend(getInnerText(child))
... | ['def', 'getInnerText(node):', 'inner_text', '=', '[]', 'for', 'child', 'in', 'node.childNodes:', 'if', 'child.nodeType', '==', 'child.TEXT_NODE', 'or', 'child.nodeType', '==', 'child.CDATA_SECTION_NODE:', 'inner_text.append(child.data)', 'elif', 'child.nodeType', '==', 'child.ELEMENT_NODE:', 'inner_text.extend(getInne... | 315,666 |
interpretml/DiCE | private_data_interface.py | PrivateData.get_mads | get_mads | Computes Median Absolute Deviation of features. | [
"Computes",
"Median",
"Absolute",
"Deviation",
"of",
"features."
] | def get_mads(self, normalized=True):
if normalized is False:
return self.mad.copy()
else:
mads = {}
for feature in self.continuous_feature_names:
if feature in self.mad:
mads[feature] = self.mad[feature] / (self.permitted_range[feature][1] - self.permitted_ran... | ['def', 'get_mads(self,', 'normalized=True):', 'if', 'normalized', 'is', 'False:', 'return', 'self.mad.copy()', 'else:', 'mads', '=', '{}', 'for', 'feature', 'in', 'self.continuous_feature_names:', 'if', 'feature', 'in', 'self.mad:', 'mads[feature]', '=', 'self.mad[feature]', '/', '(self.permitted_range[feature][1]', '... | 550,176 |
pyronear/pyro-vision | utils.py | model_from_hf_hub | model_from_hf_hub | Instantiate & load a pretrained model from HF hub. | [
"Instantiate",
"&",
"load",
"a",
"pretrained",
"model",
"from",
"HF",
"hub."
] | def model_from_hf_hub(repo_id: str, **kwargs: Any) -> nn.Module:
with open(hf_hub_download(repo_id, filename='config.json', **kwargs), 'rb') as f:
cfg = json.load(f)
model = models.__dict__[cfg['arch']](num_classes=len(cfg['classes']), pretrained=False)
model.default_cfg.update(cfg)
state_dict =... | ['def', 'model_from_hf_hub(repo_id:', 'str,', '**kwargs:', 'Any)', '->', 'nn.Module:', 'with', 'open(hf_hub_download(repo_id,', "filename='config.json',", '**kwargs),', "'rb')", 'as', 'f:', 'cfg', '=', 'json.load(f)', 'model', '=', "models.__dict__[cfg['arch']](num_classes=len(cfg['classes']),", 'pretrained=False)', 'm... | 809,423 |
Ruturaj123/Flowchart-Detection | debug_test.py | DebugClassifierTest.testLogisticRegression_MatrixData | testLogisticRegression_MatrixData | Tests binary classification using matrix data as input. | [
"Tests",
"binary",
"classification",
"using",
"matrix",
"data",
"as",
"input."
] | def testLogisticRegression_MatrixData(self):
classifier = debug.DebugClassifier(config=run_config.RunConfig(tf_random_seed=1))
input_fn = test_data.iris_input_logistic_fn
classifier.fit(input_fn=input_fn, steps=5)
scores = classifier.evaluate(input_fn=input_fn, steps=1)
self._assertInRange(0.0, 1.0,... | ['def', 'testLogisticRegression_MatrixData(self):', 'classifier', '=', 'debug.DebugClassifier(config=run_config.RunConfig(tf_random_seed=1))', 'input_fn', '=', 'test_data.iris_input_logistic_fn', 'classifier.fit(input_fn=input_fn,', 'steps=5)', 'scores', '=', 'classifier.evaluate(input_fn=input_fn,', 'steps=1)', 'self.... | 603,855 |
KalleHallden/InstaAutomator | _tifffile.py | read_uic3tag | read_uic3tag | Read MetaMorph STK UIC3Tag from file and return as dictionary. | [
"Read",
"MetaMorph",
"STK",
"UIC3Tag",
"from",
"file",
"and",
"return",
"as",
"dictionary."
] | def read_uic3tag(fh, byteorder, dtype, plane_count):
assert dtype == '2I' and byteorder == '<'
values = fh.read_array('<u4', 2 * plane_count).reshape(plane_count, 2)
return {'wavelengths': values[:, 0] / values[:, 1]} | ['def', 'read_uic3tag(fh,', 'byteorder,', 'dtype,', 'plane_count):', 'assert', 'dtype', '==', "'2I'", 'and', 'byteorder', '==', "'<'", 'values', '=', "fh.read_array('<u4',", '2', '*', 'plane_count).reshape(plane_count,', '2)', 'return', "{'wavelengths':", 'values[:,', '0]', '/', 'values[:,', '1]}'] | 242,501 |
open-mmlab/mmtracking | visualization.py | imshow_tracks | imshow_tracks | Show the tracks on the input image. | [
"Show",
"the",
"tracks",
"on",
"the",
"input",
"image."
] | def imshow_tracks(*args, backend='cv2', **kwargs):
if backend == 'cv2':
return _cv2_show_tracks(*args, **kwargs)
elif backend == 'plt':
return _plt_show_tracks(*args, **kwargs)
else:
raise NotImplementedError() | ['def', 'imshow_tracks(*args,', "backend='cv2',", '**kwargs):', 'if', 'backend', '==', "'cv2':", 'return', '_cv2_show_tracks(*args,', '**kwargs)', 'elif', 'backend', '==', "'plt':", 'return', '_plt_show_tracks(*args,', '**kwargs)', 'else:', 'raise', 'NotImplementedError()'] | 625,708 |
Westlake-AI/openmixup | relative_loc.py | image_to_patches | image_to_patches | Crop split_per_side x split_per_side patches from input image. | [
"Crop",
"split_per_side",
"x",
"split_per_side",
"patches",
"from",
"input",
"image."
] | def image_to_patches(img):
split_per_side = 3
patch_jitter = 21
(h, w) = img.size
h_grid = h // split_per_side
w_grid = w // split_per_side
h_patch = h_grid - patch_jitter
w_patch = w_grid - patch_jitter
assert h_patch > 0 and w_patch > 0
patches = []
for i in range(split_per_sid... | ['def', 'image_to_patches(img):', 'split_per_side', '=', '3', 'patch_jitter', '=', '21', '(h,', 'w)', '=', 'img.size', 'h_grid', '=', 'h', '//', 'split_per_side', 'w_grid', '=', 'w', '//', 'split_per_side', 'h_patch', '=', 'h_grid', '-', 'patch_jitter', 'w_patch', '=', 'w_grid', '-', 'patch_jitter', 'assert', 'h_patch'... | 252,328 |
meghdadFar/snlp | cleaning.py | clean_text | clean_text | Tokenize and clean text, by matching it against keep_pattern and droping and replacing provided patterns. | [
"Tokenize",
"and",
"clean",
"text,",
"by",
"matching",
"it",
"against",
"keep_pattern",
"and",
"droping",
"and",
"replacing",
"provided",
"patterns."
] | def clean_text(text: str, keep_pattern: str='[a-zA-Z0-9!.,?]', drop_patterns: Set[str]=set([]), replace: Dict={}, maxlen: int=15, lower=False) -> str:
if not isinstance(text, str):
raise TypeError('Input must be a string.')
if len(text) == 0:
raise ValueError('Input must be a non empty string.')... | ['def', 'clean_text(text:', 'str,', 'keep_pattern:', "str='[a-zA-Z0-9!.,?]',", 'drop_patterns:', 'Set[str]=set([]),', 'replace:', 'Dict={},', 'maxlen:', 'int=15,', 'lower=False)', '->', 'str:', 'if', 'not', 'isinstance(text,', 'str):', 'raise', "TypeError('Input", 'must', 'be', 'a', "string.')", 'if', 'len(text)', '=='... | 878,893 |
sunishsheth2009/ChatterBot | expression.py | Select.column | column | return a new select() construct with the given column expression added to its columns clause. | [
"return",
"a",
"new",
"select()",
"construct",
"with",
"the",
"given",
"column",
"expression",
"added",
"to",
"its",
"columns",
"clause."
] | def column(self, column):
self.append_column(column) | ['def', 'column(self,', 'column):', 'self.append_column(column)'] | 534,925 |
43Carrig/recurrent_neural_networks_practice | linear_operator.py | LinearOperator.is_square | is_square | Return `True/False` depending on if this operator is square. | [
"Return",
"`True/False`",
"depending",
"on",
"if",
"this",
"operator",
"is",
"square."
] | def is_square(self):
auto_square_check = self.domain_dimension == self.range_dimension
if self._is_square_set_or_implied_by_hints is False and auto_square_check:
raise ValueError('User set is_square hint to False, but the operator was square.')
if self._is_square_set_or_implied_by_hints is None:
... | ['def', 'is_square(self):', 'auto_square_check', '=', 'self.domain_dimension', '==', 'self.range_dimension', 'if', 'self._is_square_set_or_implied_by_hints', 'is', 'False', 'and', 'auto_square_check:', 'raise', "ValueError('User", 'set', 'is_square', 'hint', 'to', 'False,', 'but', 'the', 'operator', 'was', "square.')",... | 339,255 |
tencent-ailab/TriNet | dictionary.py | Dictionary.pad_to_multiple_ | pad_to_multiple_ | Pad Dictionary size to be a multiple of *padding_factor*. | [
"Pad",
"Dictionary",
"size",
"to",
"be",
"a",
"multiple",
"of",
"*padding_factor*."
] | def pad_to_multiple_(self, padding_factor):
if padding_factor > 1:
i = 0
while len(self) % padding_factor != 0:
symbol = 'madeupword{:04d}'.format(i)
self.add_symbol(symbol, n=0)
i += 1 | ['def', 'pad_to_multiple_(self,', 'padding_factor):', 'if', 'padding_factor', '>', '1:', 'i', '=', '0', 'while', 'len(self)', '%', 'padding_factor', '!=', '0:', 'symbol', '=', "'madeupword{:04d}'.format(i)", 'self.add_symbol(symbol,', 'n=0)', 'i', '+=', '1'] | 425,133 |
weimin17/Object-Detection_HelmetDetection | tokenizer.py | Subtokenizer.decode | decode | Converts list of int subtokens ids into a string. | [
"Converts",
"list",
"of",
"int",
"subtokens",
"ids",
"into",
"a",
"string."
] | def decode(self, subtokens):
if isinstance(subtokens, np.ndarray):
subtokens = subtokens.tolist()
if not subtokens:
return ''
assert isinstance(subtokens, list) and isinstance(subtokens[0], int), 'Subtokens argument passed into decode() must be a list of integers.'
return _unicode_to_nat... | ['def', 'decode(self,', 'subtokens):', 'if', 'isinstance(subtokens,', 'np.ndarray):', 'subtokens', '=', 'subtokens.tolist()', 'if', 'not', 'subtokens:', 'return', "''", 'assert', 'isinstance(subtokens,', 'list)', 'and', 'isinstance(subtokens[0],', 'int),', "'Subtokens", 'argument', 'passed', 'into', 'decode()', 'must',... | 761,259 |
Kvatsx/Artificial-Intelligence-Assignments | ultratb.py | SyntaxTB.stb2text | stb2text | Convert a structured traceback (a list) to a string. | [
"Convert",
"a",
"structured",
"traceback",
"(a",
"list)",
"to",
"a",
"string."
] | def stb2text(self, stb):
return ''.join(stb) | ['def', 'stb2text(self,', 'stb):', 'return', "''.join(stb)"] | 38,267 |
huawei-noah/xingtian | run_remote_worker.py | call_in_npu | call_in_npu | Call function based on NPU devices. | [
"Call",
"function",
"based",
"on",
"NPU",
"devices."
] | def call_in_npu(config, id, worker_id, worker_path):
env = os.environ.copy()
sub_pid_list = []
npu_call_path = os.path.join(config['device_folder'], 'npu')
if not os.path.exists(npu_call_path):
os.makedirs(npu_call_path, exist_ok=True)
if 'PYTHONPATH' in env:
env['PYTHONPATH'] = '{}:... | ['def', 'call_in_npu(config,', 'id,', 'worker_id,', 'worker_path):', 'env', '=', 'os.environ.copy()', 'sub_pid_list', '=', '[]', 'npu_call_path', '=', "os.path.join(config['device_folder'],", "'npu')", 'if', 'not', 'os.path.exists(npu_call_path):', 'os.makedirs(npu_call_path,', 'exist_ok=True)', 'if', "'PYTHONPATH'", '... | 968,381 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | tree.py | Param.position_index | position_index | Property for the positional index of a paramter. | [
"Property",
"for",
"the",
"positional",
"index",
"of",
"a",
"paramter."
] | def position_index(self):
index = self.parent.children.index(self)
try:
keyword_only_index = self.parent.children.index('*')
if index > keyword_only_index:
index -= 2
except ValueError:
pass
try:
keyword_only_index = self.parent.children.index('/')
if ... | ['def', 'position_index(self):', 'index', '=', 'self.parent.children.index(self)', 'try:', 'keyword_only_index', '=', "self.parent.children.index('*')", 'if', 'index', '>', 'keyword_only_index:', 'index', '-=', '2', 'except', 'ValueError:', 'pass', 'try:', 'keyword_only_index', '=', "self.parent.children.index('/')", '... | 454,045 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | summaries.py | stack_images | stack_images | Stack and reshape images to see compression effects. | [
"Stack",
"and",
"reshape",
"images",
"to",
"see",
"compression",
"effects."
] | def stack_images(images, reconstructions, num_imgs_to_visualize=8):
to_reshape = tf.unstack(images)[:num_imgs_to_visualize] + tf.unstack(reconstructions)[:num_imgs_to_visualize]
reshaped_img = tfgan.eval.image_reshaper(to_reshape, num_cols=num_imgs_to_visualize)
return reshaped_img | ['def', 'stack_images(images,', 'reconstructions,', 'num_imgs_to_visualize=8):', 'to_reshape', '=', 'tf.unstack(images)[:num_imgs_to_visualize]', '+', 'tf.unstack(reconstructions)[:num_imgs_to_visualize]', 'reshaped_img', '=', 'tfgan.eval.image_reshaper(to_reshape,', 'num_cols=num_imgs_to_visualize)', 'return', 'reshap... | 48,572 |
scotthuang1989/object_detection_with_tensorflow | util.py | get_frechet_inception_distance | get_frechet_inception_distance | Get Frechet Inception Distance between real and generated images. | [
"Get",
"Frechet",
"Inception",
"Distance",
"between",
"real",
"and",
"generated",
"images."
] | def get_frechet_inception_distance(real_images, generated_images, batch_size, num_inception_images):
real_images.shape[0:1].assert_is_compatible_with([batch_size])
generated_images.shape[0:1].assert_is_compatible_with([batch_size])
size = 299
resized_real_images = tf.image.resize_bilinear(real_images, [... | ['def', 'get_frechet_inception_distance(real_images,', 'generated_images,', 'batch_size,', 'num_inception_images):', 'real_images.shape[0:1].assert_is_compatible_with([batch_size])', 'generated_images.shape[0:1].assert_is_compatible_with([batch_size])', 'size', '=', '299', 'resized_real_images', '=', 'tf.image.resize_b... | 797,118 |
hankcs/HanLP | tf_util.py | hanlp_register | hanlp_register | Registers a class with the Keras serialization framework. | [
"Registers",
"a",
"class",
"with",
"the",
"Keras",
"serialization",
"framework."
] | def hanlp_register(arg):
class_name = arg.__name__
registered_name = 'HanLP' + '>' + class_name
tf.keras.utils.get_custom_objects()[registered_name] = arg
return arg | ['def', 'hanlp_register(arg):', 'class_name', '=', 'arg.__name__', 'registered_name', '=', "'HanLP'", '+', "'>'", '+', 'class_name', 'tf.keras.utils.get_custom_objects()[registered_name]', '=', 'arg', 'return', 'arg'] | 575,898 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | objective.py | Objective.get_optimizer | get_optimizer | Optimizer for gradient descent ops. | [
"Optimizer",
"for",
"gradient",
"descent",
"ops."
] | def get_optimizer(self, learning_rate):
return tf.train.AdamOptimizer(learning_rate=learning_rate, epsilon=0.0002) | ['def', 'get_optimizer(self,', 'learning_rate):', 'return', 'tf.train.AdamOptimizer(learning_rate=learning_rate,', 'epsilon=0.0002)'] | 26,128 |
facebookresearch/deep_bisim4control | point_mass.py | Physics.mass_to_target_dist | mass_to_target_dist | Returns the distance from mass to the target. | [
"Returns",
"the",
"distance",
"from",
"mass",
"to",
"the",
"target."
] | def mass_to_target_dist(self):
return np.linalg.norm(self.mass_to_target()) | ['def', 'mass_to_target_dist(self):', 'return', 'np.linalg.norm(self.mass_to_target())'] | 536,425 |
lebrice/Sequoia | classifier.py | ExampleMethod.from_argparse_args | from_argparse_args | Creates an instance of this Method from the parsed arguments. | [
"Creates",
"an",
"instance",
"of",
"this",
"Method",
"from",
"the",
"parsed",
"arguments."
] | def from_argparse_args(cls, args: Namespace):
hparams: Classifier.HParams = args.hparams
return cls(hparams=hparams) | ['def', 'from_argparse_args(cls,', 'args:', 'Namespace):', 'hparams:', 'Classifier.HParams', '=', 'args.hparams', 'return', 'cls(hparams=hparams)'] | 344,024 |
keyonvafa/career-code | test_noising.py | TestDataNoising.test_noising_dataset_without_eos | test_noising_dataset_without_eos | Similar to test noising dataset with eos except that we have to set *append_eos_to_tgt* to ``True``. | [
"Similar",
"to",
"test",
"noising",
"dataset",
"with",
"eos",
"except",
"that",
"we",
"have",
"to",
"set",
"*append_eos_to_tgt*",
"to",
"``True``."
] | def test_noising_dataset_without_eos(self):
(src_dict, src_tokens, _) = self._get_test_data_with_bpe_cont_marker(append_eos=False)
src_tokens = torch.t(src_tokens)
src_tokens_no_pad = []
for src_sentence in src_tokens:
src_tokens_no_pad.append(utils.strip_pad(tensor=src_sentence, pad=src_dict.pa... | ['def', 'test_noising_dataset_without_eos(self):', '(src_dict,', 'src_tokens,', '_)', '=', 'self._get_test_data_with_bpe_cont_marker(append_eos=False)', 'src_tokens', '=', 'torch.t(src_tokens)', 'src_tokens_no_pad', '=', '[]', 'for', 'src_sentence', 'in', 'src_tokens:', 'src_tokens_no_pad.append(utils.strip_pad(tensor=... | 455,836 |
PaddlePaddle/PaddleSpeech | recog.py | recog_v2 | recog_v2 | Decode with custom models that implements ScorerInterface. | [
"Decode",
"with",
"custom",
"models",
"that",
"implements",
"ScorerInterface."
] | def recog_v2(args):
logger.warning('experimental API for custom LMs is selected by --api v2')
if args.batchsize > 1:
raise NotImplementedError('multi-utt batch decoding is not implemented')
if args.streaming_mode is not None:
raise NotImplementedError('streaming mode is not implemented')
... | ['def', 'recog_v2(args):', "logger.warning('experimental", 'API', 'for', 'custom', 'LMs', 'is', 'selected', 'by', '--api', "v2')", 'if', 'args.batchsize', '>', '1:', 'raise', "NotImplementedError('multi-utt", 'batch', 'decoding', 'is', 'not', "implemented')", 'if', 'args.streaming_mode', 'is', 'not', 'None:', 'raise', ... | 276,578 |
deepmind/dm_control | fruitfly_v2.py | FruitFly.get_action_spec | get_action_spec | Returns a `BoundedArray` spec matching this walker's actuators. | [
"Returns",
"a",
"`BoundedArray`",
"spec",
"matching",
"this",
"walker's",
"actuators."
] | def get_action_spec(self, physics):
minimum = []
maximum = []
indices = []
for (key, _) in self._action_indices.items():
if self._ctrl_indices[key] and self._num_actions[key]:
indices.extend(self._ctrl_indices[key])
(mj_minima, mj_maxima) = physics.model.actuator_ctrlrange[indice... | ['def', 'get_action_spec(self,', 'physics):', 'minimum', '=', '[]', 'maximum', '=', '[]', 'indices', '=', '[]', 'for', '(key,', '_)', 'in', 'self._action_indices.items():', 'if', 'self._ctrl_indices[key]', 'and', 'self._num_actions[key]:', 'indices.extend(self._ctrl_indices[key])', '(mj_minima,', 'mj_maxima)', '=', 'ph... | 166,010 |
rosefun/SemiSupervised | qns3vm.py | DictRBFKernel.getKernelValue | getKernelValue | Returns a single kernel value. | [
"Returns",
"a",
"single",
"kernel",
"value."
] | def getKernelValue(self, xi, xj):
diff = xi.copy()
for key in xj:
if key in diff:
diff[key] -= xj[key]
else:
diff[key] = -xj[key]
diff = diff.values()
val = exp(-self.__sigma_squared_inv * dot(diff, diff))
return val | ['def', 'getKernelValue(self,', 'xi,', 'xj):', 'diff', '=', 'xi.copy()', 'for', 'key', 'in', 'xj:', 'if', 'key', 'in', 'diff:', 'diff[key]', '-=', 'xj[key]', 'else:', 'diff[key]', '=', '-xj[key]', 'diff', '=', 'diff.values()', 'val', '=', 'exp(-self.__sigma_squared_inv', '*', 'dot(diff,', 'diff))', 'return', 'val'] | 343,730 |
tensorflow/agents | ppo_actor_network.py | tanh_and_scale_to_spec | tanh_and_scale_to_spec | Maps inputs with arbitrary range to range defined by spec using `tanh`. | [
"Maps",
"inputs",
"with",
"arbitrary",
"range",
"to",
"range",
"defined",
"by",
"spec",
"using",
"`tanh`."
] | def tanh_and_scale_to_spec(inputs, spec):
means = (spec.maximum + spec.minimum) / 2.0
magnitudes = (spec.maximum - spec.minimum) / 2.0
return means + magnitudes * tf.tanh(inputs) | ['def', 'tanh_and_scale_to_spec(inputs,', 'spec):', 'means', '=', '(spec.maximum', '+', 'spec.minimum)', '/', '2.0', 'magnitudes', '=', '(spec.maximum', '-', 'spec.minimum)', '/', '2.0', 'return', 'means', '+', 'magnitudes', '*', 'tf.tanh(inputs)'] | 23,207 |
rlworkgroup/garage | categorical_mlp_policy.py | categorical_mlp_policy | categorical_mlp_policy | Create Categorical MLP Policy on TF-PPO. | [
"Create",
"Categorical",
"MLP",
"Policy",
"on",
"TF-PPO."
] | def categorical_mlp_policy(ctxt, env_id, seed):
deterministic.set_seed(seed)
with TFTrainer(ctxt) as trainer:
env = normalize(GymEnv(env_id))
policy = CategoricalMLPPolicy(env_spec=env.spec, hidden_nonlinearity=tf.nn.tanh)
baseline = LinearFeatureBaseline(env_spec=env.spec)
sampl... | ['def', 'categorical_mlp_policy(ctxt,', 'env_id,', 'seed):', 'deterministic.set_seed(seed)', 'with', 'TFTrainer(ctxt)', 'as', 'trainer:', 'env', '=', 'normalize(GymEnv(env_id))', 'policy', '=', 'CategoricalMLPPolicy(env_spec=env.spec,', 'hidden_nonlinearity=tf.nn.tanh)', 'baseline', '=', 'LinearFeatureBaseline(env_spec... | 200,110 |
PaccMann/fdsa | loss_setmatching.py | SetMatchLoss.kl_div_loss | kl_div_loss | Computes the KL-Divergence between log softmax of logits and binary matrix of true targets both row and column-wise. | [
"Computes",
"the",
"KL-Divergence",
"between",
"log",
"softmax",
"of",
"logits",
"and",
"binary",
"matrix",
"of",
"true",
"targets",
"both",
"row",
"and",
"column-wise."
] | def kl_div_loss(self, predictions: torch.Tensor, target12: torch.Tensor, target21: torch.Tensor) -> torch.Tensor:
row_constraint = F.log_softmax(predictions, dim=2)
col_constraint = F.log_softmax(predictions, dim=1).permute(0, 2, 1)
one_hot_target12 = F.one_hot(target12).type(torch.float32)
one_hot_targ... | ['def', 'kl_div_loss(self,', 'predictions:', 'torch.Tensor,', 'target12:', 'torch.Tensor,', 'target21:', 'torch.Tensor)', '->', 'torch.Tensor:', 'row_constraint', '=', 'F.log_softmax(predictions,', 'dim=2)', 'col_constraint', '=', 'F.log_softmax(predictions,', 'dim=1).permute(0,', '2,', '1)', 'one_hot_target12', '=', '... | 560,886 |
ivanalberico/Probabilistic-Artificial-Intelligence-ETH | solution.py | BayesNet.log_prior | log_prior | Computes the log prior over all layers. | [
"Computes",
"the",
"log",
"prior",
"over",
"all",
"layers."
] | def log_prior(self):
log_prior = torch.zeros(1)
for i in range(self.num_layers + 1):
log_prior += self.net[i][0].log_prior
log_prior += self.net[self.num_layers + 1].log_prior
return log_prior | ['def', 'log_prior(self):', 'log_prior', '=', 'torch.zeros(1)', 'for', 'i', 'in', 'range(self.num_layers', '+', '1):', 'log_prior', '+=', 'self.net[i][0].log_prior', 'log_prior', '+=', 'self.net[self.num_layers', '+', '1].log_prior', 'return', 'log_prior'] | 295,476 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | deeprotator_factory.py | get | get | Factory function to retrieve a network model. | [
"Factory",
"function",
"to",
"retrieve",
"a",
"network",
"model."
] | def get(params, is_training=False, reuse=False):
def model(inputs):
outputs = {}
encoder_fn = _get_network(params.encoder_name)
with tf.variable_scope('encoder', reuse=reuse):
features = encoder_fn(inputs['images_0'], params, is_training)
outputs['ids'] = features['i... | ['def', 'get(params,', 'is_training=False,', 'reuse=False):', 'def', 'model(inputs):', 'outputs', '=', '{}', 'encoder_fn', '=', '_get_network(params.encoder_name)', 'with', "tf.variable_scope('encoder',", 'reuse=reuse):', 'features', '=', "encoder_fn(inputs['images_0'],", 'params,', 'is_training)', "outputs['ids']", '=... | 109,306 |
tinazhouhui/computer_vision | cpp_lint.py | FileInfo.Extension | Extension | File extension - text following the final period. | [
"File",
"extension",
"-",
"text",
"following",
"the",
"final",
"period."
] | def Extension(self):
return self.Split()[2] | ['def', 'Extension(self):', 'return', 'self.Split()[2]'] | 473,101 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | thinkplot.py | Pmf | Pmf | Plots a Pmf or Hist as a line. | [
"Plots",
"a",
"Pmf",
"or",
"Hist",
"as",
"a",
"line."
] | def Pmf(pmf, **options):
(xs, ys) = pmf.Render()
(low, high) = (min(xs), max(xs))
width = options.pop('width', None)
if width is None:
try:
width = np.diff(xs).min()
except TypeError:
warnings.warn("Pmf: Can't compute bar width automatically.Check for non-numeric ... | ['def', 'Pmf(pmf,', '**options):', '(xs,', 'ys)', '=', 'pmf.Render()', '(low,', 'high)', '=', '(min(xs),', 'max(xs))', 'width', '=', "options.pop('width',", 'None)', 'if', 'width', 'is', 'None:', 'try:', 'width', '=', 'np.diff(xs).min()', 'except', 'TypeError:', 'warnings.warn("Pmf:', "Can't", 'compute', 'bar', 'width'... | 18,806 |
rnsandeep/ObjectDetection | py_nms.py | py_soft_nms | py_soft_nms | Pure python implementation of soft NMS as described in the paper `Improving Object Detection With One Line of Code`_. | [
"Pure",
"python",
"implementation",
"of",
"soft",
"NMS",
"as",
"described",
"in",
"the",
"paper",
"`Improving",
"Object",
"Detection",
"With",
"One",
"Line",
"of",
"Code`_."
] | def py_soft_nms(dets, method='linear', iou_thr=0.3, sigma=0.5, score_thr=0.001):
if method not in ('linear', 'gaussian', 'greedy'):
raise ValueError('method must be linear, gaussian or greedy')
x1 = dets[:, 0]
y1 = dets[:, 1]
x2 = dets[:, 2]
y2 = dets[:, 3]
areas = (x2 - x1 + 1) * (y2 - ... | ['def', 'py_soft_nms(dets,', "method='linear',", 'iou_thr=0.3,', 'sigma=0.5,', 'score_thr=0.001):', 'if', 'method', 'not', 'in', "('linear',", "'gaussian',", "'greedy'):", 'raise', "ValueError('method", 'must', 'be', 'linear,', 'gaussian', 'or', "greedy')", 'x1', '=', 'dets[:,', '0]', 'y1', '=', 'dets[:,', '1]', 'x2', ... | 742,062 |
PacktPublishing/Hands-On-Artificial--for-Banking | test_voting_classifier.py | test_transform | test_transform | Check transform method of VotingClassifier on toy dataset. | [
"Check",
"transform",
"method",
"of",
"VotingClassifier",
"on",
"toy",
"dataset."
] | def test_transform():
clf1 = LogisticRegression(random_state=123)
clf2 = RandomForestClassifier(random_state=123)
clf3 = GaussianNB()
X = np.array([[-1.1, -1.5], [-1.2, -1.4], [-3.4, -2.2], [1.1, 1.2]])
y = np.array([1, 1, 2, 2])
eclf1 = VotingClassifier(estimators=[('lr', clf1), ('rf', clf2), (... | ['def', 'test_transform():', 'clf1', '=', 'LogisticRegression(random_state=123)', 'clf2', '=', 'RandomForestClassifier(random_state=123)', 'clf3', '=', 'GaussianNB()', 'X', '=', 'np.array([[-1.1,', '-1.5],', '[-1.2,', '-1.4],', '[-3.4,', '-2.2],', '[1.1,', '1.2]])', 'y', '=', 'np.array([1,', '1,', '2,', '2])', 'eclf1',... | 204,227 |
Ruturaj123/Flowchart-Detection | split_benchmark.py | build_graph | build_graph | Build a graph containing a sequence of split operations. | [
"Build",
"a",
"graph",
"containing",
"a",
"sequence",
"of",
"split",
"operations."
] | def build_graph(device, input_shape, output_sizes, axis):
with ops.device('/%s:0' % device):
inp = array_ops.zeros(input_shape)
outputs = []
for _ in range(100):
outputs.extend(array_ops.split(inp, output_sizes, axis))
return control_flow_ops.group(*outputs) | ['def', 'build_graph(device,', 'input_shape,', 'output_sizes,', 'axis):', 'with', "ops.device('/%s:0'", '%', 'device):', 'inp', '=', 'array_ops.zeros(input_shape)', 'outputs', '=', '[]', 'for', '_', 'in', 'range(100):', 'outputs.extend(array_ops.split(inp,', 'output_sizes,', 'axis))', 'return', 'control_flow_ops.group(... | 606,130 |
kukuruza/shuffler | backend_db.py | imageField | imageField | Convenience function to access by field name. | [
"Convenience",
"function",
"to",
"access",
"by",
"field",
"name."
] | def imageField(entry, field):
if field == 'imagefile':
return entry[0]
if field == 'width':
return entry[1]
if field == 'height':
return entry[2]
if field == 'maskfile':
return entry[3]
if field == 'timestamp':
return entry[4]
if field == 'name':
r... | ['def', 'imageField(entry,', 'field):', 'if', 'field', '==', "'imagefile':", 'return', 'entry[0]', 'if', 'field', '==', "'width':", 'return', 'entry[1]', 'if', 'field', '==', "'height':", 'return', 'entry[2]', 'if', 'field', '==', "'maskfile':", 'return', 'entry[3]', 'if', 'field', '==', "'timestamp':", 'return', 'entr... | 933,783 |
facebookresearch/minihack | cached_env_test.py | test_speed | test_speed | Tests the speed of an environment for num_steps steps. | [
"Tests",
"the",
"speed",
"of",
"an",
"environment",
"for",
"num_steps",
"steps."
] | def test_speed(env, env_name, num_steps):
start_time = time.time()
env.reset()
for _ in range(num_steps):
(_, _, done, _) = env.step(np.random.randint(8))
if done:
env.reset()
total_time = time.time() - start_time
print('Took {:.4f}s to perform {} steps on {} envs - {:.2f... | ['def', 'test_speed(env,', 'env_name,', 'num_steps):', 'start_time', '=', 'time.time()', 'env.reset()', 'for', '_', 'in', 'range(num_steps):', '(_,', '_,', 'done,', '_)', '=', 'env.step(np.random.randint(8))', 'if', 'done:', 'env.reset()', 'total_time', '=', 'time.time()', '-', 'start_time', "print('Took", '{:.4f}s', '... | 670,761 |
tensorflow/data-validation | natural_language_stats_generator_test.py | NaturalLanguageStatsGeneratorTest.test_nl_generator_string_feature_no_vocab | test_nl_generator_string_feature_no_vocab | Tests generator calculation with a string domain having no vocab. | [
"Tests",
"generator",
"calculation",
"with",
"a",
"string",
"domain",
"having",
"no",
"vocab."
] | def test_nl_generator_string_feature_no_vocab(self):
input_batches = [pa.array([[b'Foo'], None, [b'Baz']])]
generator = nlsg.NLStatsGenerator(self._schema, None, 0, 0, 0)
expected_reported_sequences = [['Baz'], ['Foo']] * 2
self.assertCombinerOutputEqual(input_batches, generator, self._create_expected_f... | ['def', 'test_nl_generator_string_feature_no_vocab(self):', 'input_batches', '=', "[pa.array([[b'Foo'],", 'None,', "[b'Baz']])]", 'generator', '=', 'nlsg.NLStatsGenerator(self._schema,', 'None,', '0,', '0,', '0)', 'expected_reported_sequences', '=', "[['Baz'],", "['Foo']]", '*', '2', 'self.assertCombinerOutputEqual(inp... | 497,510 |
chaitanya100100/Feedforward-Neural-Network | feedforwardneuralnetwork.py | FeedforwardNeuralNetwork.sgd | sgd | Update the weights and biases using backpropagation and Stochastic Gradient Descent. | [
"Update",
"the",
"weights",
"and",
"biases",
"using",
"backpropagation",
"and",
"Stochastic",
"Gradient",
"Descent."
] | def sgd(self, output_data: np.ndarray, learning_rate):
(grad_w, grad_b) = self.backpropagation(output_data)
w_new = []
b_new = []
for i in range(-1, -len(self.layers), -1):
w_old = self.layers[i].get_weights()
b_old = self.layers[i].get_biases()
w_new.append(w_old - learning_rate... | ['def', 'sgd(self,', 'output_data:', 'np.ndarray,', 'learning_rate):', '(grad_w,', 'grad_b)', '=', 'self.backpropagation(output_data)', 'w_new', '=', '[]', 'b_new', '=', '[]', 'for', 'i', 'in', 'range(-1,', '-len(self.layers),', '-1):', 'w_old', '=', 'self.layers[i].get_weights()', 'b_old', '=', 'self.layers[i].get_bia... | 582,187 |
surafelml/adapt-mnmt | ende_client.py | translate | translate | Translates a batch of sentences. | [
"Translates",
"a",
"batch",
"of",
"sentences."
] | def translate(stub, model_name, batch_text, tokenizer, timeout=5.0):
batch_input = [tokenizer.tokenize(text)[0] for text in batch_text]
future = send_request(stub, model_name, batch_input, timeout=timeout)
result = future.result()
batch_output = [tokenizer.detokenize(prediction) for prediction in extrac... | ['def', 'translate(stub,', 'model_name,', 'batch_text,', 'tokenizer,', 'timeout=5.0):', 'batch_input', '=', '[tokenizer.tokenize(text)[0]', 'for', 'text', 'in', 'batch_text]', 'future', '=', 'send_request(stub,', 'model_name,', 'batch_input,', 'timeout=timeout)', 'result', '=', 'future.result()', 'batch_output', '=', '... | 407,907 |
perceptiveshawty/RankCSE | trainers.py | CLTrainer.train | train | Main training entry point. | [
"Main",
"training",
"entry",
"point."
] | def train(self, model_path: Optional[str]=None, trial: Union['optuna.Trial', Dict[str, Any]]=None):
self._hp_search_setup(trial)
if self.model_init is not None:
set_seed(self.args.seed)
model = self.call_model_init(trial)
if not self.is_model_parallel:
model = model.to(self.a... | ['def', 'train(self,', 'model_path:', 'Optional[str]=None,', 'trial:', "Union['optuna.Trial',", 'Dict[str,', 'Any]]=None):', 'self._hp_search_setup(trial)', 'if', 'self.model_init', 'is', 'not', 'None:', 'set_seed(self.args.seed)', 'model', '=', 'self.call_model_init(trial)', 'if', 'not', 'self.is_model_parallel:', 'mo... | 304,294 |
intel/neural-compressor | pruning.py | TfPruningCallback.on_after_compute_loss | on_after_compute_loss | Call the same-name function from hooks. | [
"Call",
"the",
"same-name",
"function",
"from",
"hooks."
] | def on_after_compute_loss(self, input, s_outputs, s_loss, t_outputs=None):
return self.hooks['on_after_compute_loss'](input, s_outputs, s_loss, t_outputs) | ['def', 'on_after_compute_loss(self,', 'input,', 's_outputs,', 's_loss,', 't_outputs=None):', 'return', "self.hooks['on_after_compute_loss'](input,", 's_outputs,', 's_loss,', 't_outputs)'] | 738,386 |
rnsandeep/ObjectDetection | functionalCV.py | pad | pad | Pad the given CV2 Image on all sides with speficified padding mode and fill value. | [
"Pad",
"the",
"given",
"CV2",
"Image",
"on",
"all",
"sides",
"with",
"speficified",
"padding",
"mode",
"and",
"fill",
"value."
] | def pad(img, padding, fill=0, padding_mode='constant'):
if not _is_numpy_image(img):
raise TypeError('img should be nparray Image. Got {}'.format(type(img)))
if not isinstance(padding, (numbers.Number, tuple)):
raise TypeError('Got inappropriate padding arg')
if not isinstance(fill, (numbers... | ['def', 'pad(img,', 'padding,', 'fill=0,', "padding_mode='constant'):", 'if', 'not', '_is_numpy_image(img):', 'raise', "TypeError('img", 'should', 'be', 'nparray', 'Image.', 'Got', "{}'.format(type(img)))", 'if', 'not', 'isinstance(padding,', '(numbers.Number,', 'tuple)):', 'raise', "TypeError('Got", 'inappropriate', '... | 743,447 |
sek788432/Waymo-2D-Object-Detection | yt8m_input.py | TransformBatcher.batch_fn | batch_fn | Add padding when segment_labels is true. | [
"Add",
"padding",
"when",
"segment_labels",
"is",
"true."
] | def batch_fn(self, dataset, input_context):
per_replica_batch_size = input_context.get_per_replica_batch_size(self._global_batch_size) if input_context else self._global_batch_size
if not self._segment_labels:
dataset = dataset.batch(per_replica_batch_size, drop_remainder=True)
else:
pad_sha... | ['def', 'batch_fn(self,', 'dataset,', 'input_context):', 'per_replica_batch_size', '=', 'input_context.get_per_replica_batch_size(self._global_batch_size)', 'if', 'input_context', 'else', 'self._global_batch_size', 'if', 'not', 'self._segment_labels:', 'dataset', '=', 'dataset.batch(per_replica_batch_size,', 'drop_rema... | 973,417 |
weimin17/Object-Detection_HelmetDetection | mst_ops_test.py | MstOpsTest.testLogPartitionFunctionWithVeryHighValues | testLogPartitionFunctionWithVeryHighValues | Tests the overflow protection in the log partition function. | [
"Tests",
"the",
"overflow",
"protection",
"in",
"the",
"log",
"partition",
"function."
] | def testLogPartitionFunctionWithVeryHighValues(self):
with self.test_session():
for forest in [False, True]:
scores = 1000 * tf.ones([10, 10, 10], tf.float64)
num_nodes = tf.range(1, 11, dtype=tf.int32)
log_partition_functions = mst_ops.log_partition_function(num_nodes, s... | ['def', 'testLogPartitionFunctionWithVeryHighValues(self):', 'with', 'self.test_session():', 'for', 'forest', 'in', '[False,', 'True]:', 'scores', '=', '1000', '*', 'tf.ones([10,', '10,', '10],', 'tf.float64)', 'num_nodes', '=', 'tf.range(1,', '11,', 'dtype=tf.int32)', 'log_partition_functions', '=', 'mst_ops.log_parti... | 760,191 |
p-lambda/wilds | camelyon17_dataset.py | Camelyon17Dataset.eval | eval | Computes all evaluation metrics. | [
"Computes",
"all",
"evaluation",
"metrics."
] | def eval(self, y_pred, y_true, metadata, prediction_fn=None):
metric = Accuracy(prediction_fn=prediction_fn)
return self.standard_group_eval(metric, self._eval_grouper, y_pred, y_true, metadata) | ['def', 'eval(self,', 'y_pred,', 'y_true,', 'metadata,', 'prediction_fn=None):', 'metric', '=', 'Accuracy(prediction_fn=prediction_fn)', 'return', 'self.standard_group_eval(metric,', 'self._eval_grouper,', 'y_pred,', 'y_true,', 'metadata)'] | 959,704 |
ddbourgin/numpy-ml | layers.py | DotProductAttention.freeze | freeze | Freeze the layer parameters at their current values so they can no longer be updated. | [
"Freeze",
"the",
"layer",
"parameters",
"at",
"their",
"current",
"values",
"so",
"they",
"can",
"no",
"longer",
"be",
"updated."
] | def freeze(self):
self.trainable = False
self.softmax.freeze() | ['def', 'freeze(self):', 'self.trainable', '=', 'False', 'self.softmax.freeze()'] | 730,130 |
amarack/python-rl | delayed_qlearning.py | delayed_qlearning.getAction | getAction | Get the action under the current policy for the given state. | [
"Get",
"the",
"action",
"under",
"the",
"current",
"policy",
"for",
"the",
"given",
"state."
] | def getAction(self, state, discState):
return numpy.dot(self.weights[discState, :, :].T, self.basis.computeFeatures(state)).argmax() | ['def', 'getAction(self,', 'state,', 'discState):', 'return', 'numpy.dot(self.weights[discState,', ':,', ':].T,', 'self.basis.computeFeatures(state)).argmax()'] | 297,540 |
zomux/deepy | auto_encoder.py | AutoEncoder.stack_encoders | stack_encoders | Stack encoding layers, this must be done before stacking decoding layers. | [
"Stack",
"encoding",
"layers,",
"this",
"must",
"be",
"done",
"before",
"stacking",
"decoding",
"layers."
] | def stack_encoders(self, *layers):
self.stack(*layers)
self.encoding_layes.extend(layers) | ['def', 'stack_encoders(self,', '*layers):', 'self.stack(*layers)', 'self.encoding_layes.extend(layers)'] | 180,971 |
aws/sagemaker-python-sdk | renamed_params.py | S3SessionRenamer.new_param_name | new_param_name | The new name for the SageMaker session argument. | [
"The",
"new",
"name",
"for",
"the",
"SageMaker",
"session",
"argument."
] | def new_param_name(self):
return 'sagemaker_session' | ['def', 'new_param_name(self):', 'return', "'sagemaker_session'"] | 829,864 |
CEA-LIST/SCE | resnet.py | create_resnet | create_resnet | Build ResNet from torchvision for image. | [
"Build",
"ResNet",
"from",
"torchvision",
"for",
"image."
] | def create_resnet(name: str, num_classes: int=1000, progress: bool=True, pretrained: bool=False, small_input: bool=False, **kwargs) -> Module:
assert name in _ResNets, f'ResNet {name} is not supported please add the corresponding entry in _ResNets directory or provide the right name.'
func = _ResNets[name]
... | ['def', 'create_resnet(name:', 'str,', 'num_classes:', 'int=1000,', 'progress:', 'bool=True,', 'pretrained:', 'bool=False,', 'small_input:', 'bool=False,', '**kwargs)', '->', 'Module:', 'assert', 'name', 'in', '_ResNets,', "f'ResNet", '{name}', 'is', 'not', 'supported', 'please', 'add', 'the', 'corresponding', 'entry',... | 329,472 |
williamSYSU/TextGAN-PyTorch | cot_instructor.py | CoTInstructor.train_mediator | train_mediator | Training the mediator on real_data_samples (positive) and generated samples from gen (negative). | [
"Training",
"the",
"mediator",
"on",
"real_data_samples",
"(positive)",
"and",
"generated",
"samples",
"from",
"gen",
"(negative)."
] | def train_mediator(self, cur_epoch, d_step):
d_loss = []
for step in range(d_step):
real = list(self.train_data.loader)[cur_epoch % len(self.train_data.loader)]
(real_inp, real_tar) = (real['input'], real['target'])
(fake_inp, fake_tar) = GenDataIter.prepare(self.gen.sample(cfg.batch_siz... | ['def', 'train_mediator(self,', 'cur_epoch,', 'd_step):', 'd_loss', '=', '[]', 'for', 'step', 'in', 'range(d_step):', 'real', '=', 'list(self.train_data.loader)[cur_epoch', '%', 'len(self.train_data.loader)]', '(real_inp,', 'real_tar)', '=', "(real['input'],", "real['target'])", '(fake_inp,', 'fake_tar)', '=', 'GenData... | 913,853 |
ryu-ed/SpaceInvaders_Ros | math2html.py | ContainerSize.addstyle | addstyle | Add the proper style attribute to the output tag. | [
"Add",
"the",
"proper",
"style",
"attribute",
"to",
"the",
"output",
"tag."
] | def addstyle(self, container):
if not isinstance(container.output, TaggedOutput):
Trace.error('No tag to add style, in ' + unicode(container))
if not self.width and (not self.height) and (not self.maxwidth) and (not self.maxheight):
return
tag = ' style="'
tag += self.styleparameter('wid... | ['def', 'addstyle(self,', 'container):', 'if', 'not', 'isinstance(container.output,', 'TaggedOutput):', "Trace.error('No", 'tag', 'to', 'add', 'style,', 'in', "'", '+', 'unicode(container))', 'if', 'not', 'self.width', 'and', '(not', 'self.height)', 'and', '(not', 'self.maxwidth)', 'and', '(not', 'self.maxheight):', 'r... | 395,260 |
matsu0228/nlp-jp | test_pretty.py | test_sets | test_sets | Test that set and frozenset use Python 3 formatting. | [
"Test",
"that",
"set",
"and",
"frozenset",
"use",
"Python",
"3",
"formatting."
] | def test_sets():
objects = [set(), frozenset(), set([1]), frozenset([1]), set([1, 2]), frozenset([1, 2]), set([-1, -2, -3])]
expected = ['set()', 'frozenset()', '{1}', 'frozenset({1})', '{1, 2}', 'frozenset({1, 2})', '{-3, -2, -1}']
for (obj, expected_output) in zip(objects, expected):
got_output = ... | ['def', 'test_sets():', 'objects', '=', '[set(),', 'frozenset(),', 'set([1]),', 'frozenset([1]),', 'set([1,', '2]),', 'frozenset([1,', '2]),', 'set([-1,', '-2,', '-3])]', 'expected', '=', "['set()',", "'frozenset()',", "'{1}',", "'frozenset({1})',", "'{1,", "2}',", "'frozenset({1,", "2})',", "'{-3,", '-2,', "-1}']", 'f... | 787,268 |
tobegit3hub/deep_image_model | framework.py | BaseDebugWrapperSession.partial_run_setup | partial_run_setup | Sets up the feeds and fetches for partial runs in the session. | [
"Sets",
"up",
"the",
"feeds",
"and",
"fetches",
"for",
"partial",
"runs",
"in",
"the",
"session."
] | def partial_run_setup(self, fetches, feeds=None):
raise NotImplementedError('partial_run_setup is not implemented for debug-wrapper sessions.') | ['def', 'partial_run_setup(self,', 'fetches,', 'feeds=None):', 'raise', "NotImplementedError('partial_run_setup", 'is', 'not', 'implemented', 'for', 'debug-wrapper', "sessions.')"] | 182,422 |
ananthpn/nlp | pipeData.py | Pipe.createDataframe | createDataframe | Creates dataframe class of cleaned descriptions. | [
"Creates",
"dataframe",
"class",
"of",
"cleaned",
"descriptions."
] | def createDataframe(self, description):
return pd.DataFrame({'descriptions': description}) | ['def', 'createDataframe(self,', 'description):', 'return', "pd.DataFrame({'descriptions':", 'description})'] | 808,270 |
mariacer/cl_in_rnns | state_space_plotting.py | plot_supervised_dimension_vs_task | plot_supervised_dimension_vs_task | Plot the loss or accuracy as a function of the number of supervised dimensions. | [
"Plot",
"the",
"loss",
"or",
"accuracy",
"as",
"a",
"function",
"of",
"the",
"number",
"of",
"supervised",
"dimensions."
] | def plot_supervised_dimension_vs_task(results, seed_groups, path='', key='loss', stop_bit=False, for_publication=False):
if for_publication:
fig_size = [1.5 * 1.7, 1.5 * 4.8 * 1.7 / 6.4]
from sequential.plotting_sequential import configure_matplotlib_params
configure_matplotlib_params(fig_si... | ['def', 'plot_supervised_dimension_vs_task(results,', 'seed_groups,', "path='',", "key='loss',", 'stop_bit=False,', 'for_publication=False):', 'if', 'for_publication:', 'fig_size', '=', '[1.5', '*', '1.7,', '1.5', '*', '4.8', '*', '1.7', '/', '6.4]', 'from', 'sequential.plotting_sequential', 'import', 'configure_matplo... | 122,986 |
aws/sagemaker-python-sdk | association.py | Association.create | create | Add an association and return an ``Association`` object representing it. | [
"Add",
"an",
"association",
"and",
"return",
"an",
"``Association``",
"object",
"representing",
"it."
] | def create(cls, source_arn: str, destination_arn: str, association_type: str=None, sagemaker_session=None) -> 'Association':
return super(Association, cls)._construct(cls._boto_create_method, source_arn=source_arn, destination_arn=destination_arn, association_type=association_type, sagemaker_session=sagemaker_sessi... | ['def', 'create(cls,', 'source_arn:', 'str,', 'destination_arn:', 'str,', 'association_type:', 'str=None,', 'sagemaker_session=None)', '->', "'Association':", 'return', 'super(Association,', 'cls)._construct(cls._boto_create_method,', 'source_arn=source_arn,', 'destination_arn=destination_arn,', 'association_type=assoc... | 830,261 |
dickreuter/neuron_poker | helper.py | exception_hook | exception_hook | Catches all unhandled exceptions. | [
"Catches",
"all",
"unhandled",
"exceptions."
] | def exception_hook(*exc_info):
print('--- exception hook ----')
text = ''.join(traceback.format_exception(*exc_info))
log.error('Unhandled exception: %s', text) | ['def', 'exception_hook(*exc_info):', "print('---", 'exception', 'hook', "----')", 'text', '=', "''.join(traceback.format_exception(*exc_info))", "log.error('Unhandled", 'exception:', "%s',", 'text)'] | 723,445 |
TonyLianLong/VAI-ReinforcementLearning | updater.py | Updater.reset | reset | Resets this updater's state. | [
"Resets",
"this",
"updater's",
"state."
] | def reset(self, physics, random_state):
def make_buffers_dict(observables):
out_dict = type(observables)()
for (key, value) in six.iteritems(observables):
if value.enabled:
out_dict[key] = _EnabledObservable(value, physics, random_state, self._strip_singleton_buffer_dim)... | ['def', 'reset(self,', 'physics,', 'random_state):', 'def', 'make_buffers_dict(observables):', 'out_dict', '=', 'type(observables)()', 'for', '(key,', 'value)', 'in', 'six.iteritems(observables):', 'if', 'value.enabled:', 'out_dict[key]', '=', '_EnabledObservable(value,', 'physics,', 'random_state,', 'self._strip_singl... | 439,913 |
rudranil723/mini-main | ddl_references.py | Reference.references_column | references_column | Return whether or not this instance references the specified column. | [
"Return",
"whether",
"or",
"not",
"this",
"instance",
"references",
"the",
"specified",
"column."
] | def references_column(self, table, column):
return False | ['def', 'references_column(self,', 'table,', 'column):', 'return', 'False'] | 315,697 |
shoyo/acoustic-keylogger | hmm.py | test_create_transmat | test_create_transmat | Assert that `create_transmat()` behaves as expected. | [
"Assert",
"that",
"`create_transmat()`",
"behaves",
"as",
"expected."
] | def test_create_transmat():
corpora = [['This', 'is', 'a', 'sentence'], ['contains', '``', 'unrecognized', "''", 'characters'], ['']]
keys = 'abcdefghijklmnopqrstuvwxyz .,'
key_map = id_map(keys)
reverse_map = dict(enumerate(keys))
base_mat = np.zeros((len(keys), len(keys)), dtype=int)
transmats... | ['def', 'test_create_transmat():', 'corpora', '=', "[['This',", "'is',", "'a',", "'sentence'],", "['contains',", "'``',", "'unrecognized',", '"\'\'",', "'characters'],", "['']]", 'keys', '=', "'abcdefghijklmnopqrstuvwxyz", ".,'", 'key_map', '=', 'id_map(keys)', 'reverse_map', '=', 'dict(enumerate(keys))', 'base_mat', '... | 8,644 |
neardws/Game-Theoretic-Deep-Reinforcement-Learning | networks.py | MAD3PGNetwork.make_policy | make_policy | Create a single network which evaluates the policy. | [
"Create",
"a",
"single",
"network",
"which",
"evaluates",
"the",
"policy."
] | def make_policy(self, environment_spec, sigma: float=0.0) -> snt.Module:
stacks = [self.observation_network, self.policy_network]
if sigma > 0.0:
stacks += [network_utils.ClippedGaussian(sigma), network_utils.ClipToSpec(environment_spec.edge_actions)]
return snt.Sequential(stacks) | ['def', 'make_policy(self,', 'environment_spec,', 'sigma:', 'float=0.0)', '->', 'snt.Module:', 'stacks', '=', '[self.observation_network,', 'self.policy_network]', 'if', 'sigma', '>', '0.0:', 'stacks', '+=', '[network_utils.ClippedGaussian(sigma),', 'network_utils.ClipToSpec(environment_spec.edge_actions)]', 'return', ... | 199,706 |
PacktPublishing/Hands-On-Artificial--for-Banking | test_voting_classifier.py | test_predict_on_toy_problem | test_predict_on_toy_problem | Manually check predicted class labels for toy dataset. | [
"Manually",
"check",
"predicted",
"class",
"labels",
"for",
"toy",
"dataset."
] | def test_predict_on_toy_problem():
clf1 = LogisticRegression(random_state=123)
clf2 = RandomForestClassifier(random_state=123)
clf3 = GaussianNB()
X = np.array([[-1.1, -1.5], [-1.2, -1.4], [-3.4, -2.2], [1.1, 1.2], [2.1, 1.4], [3.1, 2.3]])
y = np.array([1, 1, 1, 2, 2, 2])
assert_equal(all(clf1.f... | ['def', 'test_predict_on_toy_problem():', 'clf1', '=', 'LogisticRegression(random_state=123)', 'clf2', '=', 'RandomForestClassifier(random_state=123)', 'clf3', '=', 'GaussianNB()', 'X', '=', 'np.array([[-1.1,', '-1.5],', '[-1.2,', '-1.4],', '[-3.4,', '-2.2],', '[1.1,', '1.2],', '[2.1,', '1.4],', '[3.1,', '2.3]])', 'y',... | 204,219 |
asyml/texar | utils.py | str_join | str_join | Concats :attr:`tokens` along the last dimension with intervening occurrences of :attr:`sep`. | [
"Concats",
":attr:`tokens`",
"along",
"the",
"last",
"dimension",
"with",
"intervening",
"occurrences",
"of",
":attr:`sep`."
] | def str_join(tokens, sep=' ', compat=True):
def _recur_join(s):
if len(s) == 0:
return ''
elif is_str(s[0]):
return sep.join(s)
else:
s_ = [_recur_join(si) for si in s]
return _maybe_list_to_array(s_, s)
if compat:
tokens = compat_... | ['def', 'str_join(tokens,', "sep='", "',", 'compat=True):', 'def', '_recur_join(s):', 'if', 'len(s)', '==', '0:', 'return', "''", 'elif', 'is_str(s[0]):', 'return', 'sep.join(s)', 'else:', 's_', '=', '[_recur_join(si)', 'for', 'si', 'in', 's]', 'return', '_maybe_list_to_array(s_,', 's)', 'if', 'compat:', 'tokens', '=',... | 924,823 |
myothida/Supervised-Machine-Learning | ImageShow.py | Viewer.get_format | get_format | Return format name, or ``None`` to save as PGM/PPM. | [
"Return",
"format",
"name,",
"or",
"``None``",
"to",
"save",
"as",
"PGM/PPM."
] | def get_format(self, image):
return self.format | ['def', 'get_format(self,', 'image):', 'return', 'self.format'] | 443,995 |
Kvatsx/Artificial-Intelligence-Assignments | test_poll.py | TestSelect.test_timeout | test_timeout | make sure select timeout has the right units (seconds). | [
"make",
"sure",
"select",
"timeout",
"has",
"the",
"right",
"units",
"(seconds)."
] | def test_timeout(self):
(s1, s2) = self.create_bound_pair(zmq.PAIR, zmq.PAIR)
tic = time.time()
(r, w, x) = zmq.select([s1, s2], [], [], 0.005)
toc = time.time()
self.assertTrue(toc - tic < 1)
self.assertTrue(toc - tic > 0.001)
tic = time.time()
(r, w, x) = zmq.select([s1, s2], [], [], 0... | ['def', 'test_timeout(self):', '(s1,', 's2)', '=', 'self.create_bound_pair(zmq.PAIR,', 'zmq.PAIR)', 'tic', '=', 'time.time()', '(r,', 'w,', 'x)', '=', 'zmq.select([s1,', 's2],', '[],', '[],', '0.005)', 'toc', '=', 'time.time()', 'self.assertTrue(toc', '-', 'tic', '<', '1)', 'self.assertTrue(toc', '-', 'tic', '>', '0.00... | 79,316 |
Xianpeng919/MonoCon | builder.py | build_shared_head | build_shared_head | Build shared head of detector. | [
"Build",
"shared",
"head",
"of",
"detector."
] | def build_shared_head(cfg):
return build(cfg, SHARED_HEADS) | ['def', 'build_shared_head(cfg):', 'return', 'build(cfg,', 'SHARED_HEADS)'] | 654,511 |
open-mmlab/mmcv | multi_scale_deform_attn.py | MultiScaleDeformableAttention.init_weights | init_weights | Default initialization for Parameters of Module. | [
"Default",
"initialization",
"for",
"Parameters",
"of",
"Module."
] | def init_weights(self) -> None:
constant_init(self.sampling_offsets, 0.0)
device = next(self.parameters()).device
thetas = torch.arange(self.num_heads, dtype=torch.float32, device=device) * (2.0 * math.pi / self.num_heads)
grid_init = torch.stack([thetas.cos(), thetas.sin()], -1)
grid_init = (grid_i... | ['def', 'init_weights(self)', '->', 'None:', 'constant_init(self.sampling_offsets,', '0.0)', 'device', '=', 'next(self.parameters()).device', 'thetas', '=', 'torch.arange(self.num_heads,', 'dtype=torch.float32,', 'device=device)', '*', '(2.0', '*', 'math.pi', '/', 'self.num_heads)', 'grid_init', '=', 'torch.stack([thet... | 631,538 |
scikit-learn/scikit-learn | grower.py | TreeNode.set_children_bounds | set_children_bounds | Set children values bounds to respect monotonic constraints. | [
"Set",
"children",
"values",
"bounds",
"to",
"respect",
"monotonic",
"constraints."
] | def set_children_bounds(self, lower, upper):
self.children_lower_bound = lower
self.children_upper_bound = upper | ['def', 'set_children_bounds(self,', 'lower,', 'upper):', 'self.children_lower_bound', '=', 'lower', 'self.children_upper_bound', '=', 'upper'] | 853,232 |
gilis-rnd/openNMT-arabic-transfer-learning | translation_server.py | TranslationServer.start | start | Read the config file and pre-/load the models. | [
"Read",
"the",
"config",
"file",
"and",
"pre-/load",
"the",
"models."
] | def start(self, config_file):
self.config_file = config_file
with open(self.config_file) as f:
self.confs = json.load(f)
self.models_root = self.confs.get('models_root', './available_models')
for (i, conf) in enumerate(self.confs['models']):
if 'models' not in conf:
if 'model... | ['def', 'start(self,', 'config_file):', 'self.config_file', '=', 'config_file', 'with', 'open(self.config_file)', 'as', 'f:', 'self.confs', '=', 'json.load(f)', 'self.models_root', '=', "self.confs.get('models_root',", "'./available_models')", 'for', '(i,', 'conf)', 'in', "enumerate(self.confs['models']):", 'if', "'mod... | 757,239 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.