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 |
|---|---|---|---|---|---|---|---|---|
akandykeller/NeuralWaveMachines | dynamics.py | PhysicsSimulationNetwork.sum_per_dim_energy | sum_per_dim_energy | Sums the per dimension energy. | [
"Sums",
"the",
"per",
"dimension",
"energy."
] | def sum_per_dim_energy(self, energy: jnp.ndarray) -> jnp.ndarray:
axis = [-i - 1 for i in range(self.features_extra_dims + 1)]
return jnp.sum(energy, axis=axis) | ['def', 'sum_per_dim_energy(self,', 'energy:', 'jnp.ndarray)', '->', 'jnp.ndarray:', 'axis', '=', '[-i', '-', '1', 'for', 'i', 'in', 'range(self.features_extra_dims', '+', '1)]', 'return', 'jnp.sum(energy,', 'axis=axis)'] | 293,671 |
EarthNets/RSI-Segmentation | point_head.py | PointHead.cls_seg | cls_seg | Classify each pixel with fc. | [
"Classify",
"each",
"pixel",
"with",
"fc."
] | def cls_seg(self, feat):
if self.dropout is not None:
feat = self.dropout(feat)
output = self.fc_seg(feat)
return output | ['def', 'cls_seg(self,', 'feat):', 'if', 'self.dropout', 'is', 'not', 'None:', 'feat', '=', 'self.dropout(feat)', 'output', '=', 'self.fc_seg(feat)', 'return', 'output'] | 828,089 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | labeled_eval.py | evaluate_once | evaluate_once | Compute the recall@k for a given checkpoint path. | [
"Compute",
"the",
"recall@k",
"for",
"a",
"given",
"checkpoint",
"path."
] | def evaluate_once(estimator, input_fn_by_view, batch_size, checkpoint_path, label_attr_keys, embedding_size, num_views, k_list):
feat_matrix = np.zeros((0, embedding_size))
label_vect = np.zeros((0, len(label_attr_keys)))
tasks = []
eval_tensor_keys = ['embeddings', 'tasks', 'classification_labels']
... | ['def', 'evaluate_once(estimator,', 'input_fn_by_view,', 'batch_size,', 'checkpoint_path,', 'label_attr_keys,', 'embedding_size,', 'num_views,', 'k_list):', 'feat_matrix', '=', 'np.zeros((0,', 'embedding_size))', 'label_vect', '=', 'np.zeros((0,', 'len(label_attr_keys)))', 'tasks', '=', '[]', 'eval_tensor_keys', '=', "... | 29,284 |
OctoConsulting/octobot | create_lex_response_table.py | create_dynamodb_table | create_dynamodb_table | Create a DynamoDB table for intents, with primary keys of intent and the version. | [
"Create",
"a",
"DynamoDB",
"table",
"for",
"intents,",
"with",
"primary",
"keys",
"of",
"intent",
"and",
"the",
"version."
] | def create_dynamodb_table(table_name: str) -> str:
create_table_response = ddb_client.create_table(TableName=table_name, KeySchema=[{'AttributeName': 'intent', 'KeyType': 'HASH'}, {'AttributeName': 'version', 'KeyType': 'RANGE'}], AttributeDefinitions=[{'AttributeName': 'intent', 'AttributeType': 'S'}, {'AttributeN... | ['def', 'create_dynamodb_table(table_name:', 'str)', '->', 'str:', 'create_table_response', '=', 'ddb_client.create_table(TableName=table_name,', "KeySchema=[{'AttributeName':", "'intent',", "'KeyType':", "'HASH'},", "{'AttributeName':", "'version',", "'KeyType':", "'RANGE'}],", "AttributeDefinitions=[{'AttributeName':... | 249,988 |
weimin17/Object-Detection_HelmetDetection | model_voxel_generation.py | Im2Vox.get_train_op_for_scope | get_train_op_for_scope | Train operation function for the given scope used file training. | [
"Train",
"operation",
"function",
"for",
"the",
"given",
"scope",
"used",
"file",
"training."
] | def get_train_op_for_scope(self, loss, optimizer, scopes):
is_trainable = lambda x: x in tf.trainable_variables()
var_list = []
update_ops = []
for scope in scopes:
var_list.extend(filter(is_trainable, tf.contrib.framework.get_model_variables(scope)))
update_ops.extend(tf.get_collection(... | ['def', 'get_train_op_for_scope(self,', 'loss,', 'optimizer,', 'scopes):', 'is_trainable', '=', 'lambda', 'x:', 'x', 'in', 'tf.trainable_variables()', 'var_list', '=', '[]', 'update_ops', '=', '[]', 'for', 'scope', 'in', 'scopes:', 'var_list.extend(filter(is_trainable,', 'tf.contrib.framework.get_model_variables(scope)... | 759,479 |
enuguru/artificial_intelligence_and_machine_learning | scoring.py | BaseScorer.score | score | Returns a score for the current document of the matcher. | [
"Returns",
"a",
"score",
"for",
"the",
"current",
"document",
"of",
"the",
"matcher."
] | def score(self, matcher):
raise NotImplementedError(self.__class__.__name__) | ['def', 'score(self,', 'matcher):', 'raise', 'NotImplementedError(self.__class__.__name__)'] | 133,072 |
sunishsheth2009/ChatterBot | _import_tools.py | PackageLoader.get_pkgdocs | get_pkgdocs | Return documentation summary of subpackages. | [
"Return",
"documentation",
"summary",
"of",
"subpackages."
] | def get_pkgdocs(self):
import sys
self.info_modules = {}
self._init_info_modules(None)
titles = []
symbols = []
for (package_name, info_module) in self.info_modules.items():
global_symbols = getattr(info_module, 'global_symbols', [])
fullname = self.parent_name + '.' + package_na... | ['def', 'get_pkgdocs(self):', 'import', 'sys', 'self.info_modules', '=', '{}', 'self._init_info_modules(None)', 'titles', '=', '[]', 'symbols', '=', '[]', 'for', '(package_name,', 'info_module)', 'in', 'self.info_modules.items():', 'global_symbols', '=', 'getattr(info_module,', "'global_symbols',", '[])', 'fullname', '... | 530,551 |
aisingapore/PeekingDuck | test_instance_mask.py | draw_mask_inputs | draw_mask_inputs | Returns dictionary of masks, bbox_labels, bbox_scores. | [
"Returns",
"dictionary",
"of",
"masks,",
"bbox_labels,",
"bbox_scores."
] | def draw_mask_inputs():
inputs = dict(np.load(TEST_DATA_DIR / TEST_DATA_SUBDIR / INPUTS_NPZ))
return inputs | ['def', 'draw_mask_inputs():', 'inputs', '=', 'dict(np.load(TEST_DATA_DIR', '/', 'TEST_DATA_SUBDIR', '/', 'INPUTS_NPZ))', 'return', 'inputs'] | 767,220 |
arijit7978/arijit7978-Artificial-Intelligence-CSE-471--PacMan | gridworld.py | Gridworld.getTransitionStatesAndProbs | getTransitionStatesAndProbs | Returns list of (nextState, prob) pairs representing the states reachable from 'state' by taking 'action' along with their transition probabilities. | [
"Returns",
"list",
"of",
"(nextState,",
"prob)",
"pairs",
"representing",
"the",
"states",
"reachable",
"from",
"'state'",
"by",
"taking",
"'action'",
"along",
"with",
"their",
"transition",
"probabilities."
] | def getTransitionStatesAndProbs(self, state, action):
if action not in self.getPossibleActions(state):
raise Exception('Illegal action!')
if self.isTerminal(state):
return []
(x, y) = state
if type(self.grid[x][y]) == int or type(self.grid[x][y]) == float:
termState = self.grid.t... | ['def', 'getTransitionStatesAndProbs(self,', 'state,', 'action):', 'if', 'action', 'not', 'in', 'self.getPossibleActions(state):', 'raise', "Exception('Illegal", "action!')", 'if', 'self.isTerminal(state):', 'return', '[]', '(x,', 'y)', '=', 'state', 'if', 'type(self.grid[x][y])', '==', 'int', 'or', 'type(self.grid[x][... | 34,610 |
matsu0228/nlp-jp | _fortran.py | needs_g77_abi_wrapper | needs_g77_abi_wrapper | Returns True if g77 ABI wrapper must be used. | [
"Returns",
"True",
"if",
"g77",
"ABI",
"wrapper",
"must",
"be",
"used."
] | def needs_g77_abi_wrapper(info):
if uses_accelerate(info) or uses_veclib(info):
return True
elif uses_mkl(info):
return True
else:
return False | ['def', 'needs_g77_abi_wrapper(info):', 'if', 'uses_accelerate(info)', 'or', 'uses_veclib(info):', 'return', 'True', 'elif', 'uses_mkl(info):', 'return', 'True', 'else:', 'return', 'False'] | 806,020 |
ucas-vg/PointTinyBenchmark | merge_augs.py | merge_aug_scores | merge_aug_scores | Merge augmented bbox scores. | [
"Merge",
"augmented",
"bbox",
"scores."
] | def merge_aug_scores(aug_scores):
if isinstance(aug_scores[0], torch.Tensor):
return torch.mean(torch.stack(aug_scores), dim=0)
else:
return np.mean(aug_scores, axis=0) | ['def', 'merge_aug_scores(aug_scores):', 'if', 'isinstance(aug_scores[0],', 'torch.Tensor):', 'return', 'torch.mean(torch.stack(aug_scores),', 'dim=0)', 'else:', 'return', 'np.mean(aug_scores,', 'axis=0)'] | 781,466 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | beam_search.py | Beam.get_best | get_best | Get the most likely candidate. | [
"Get",
"the",
"most",
"likely",
"candidate."
] | def get_best(self):
(scores, ids) = self.sort_best()
return (scores[1], ids[1]) | ['def', 'get_best(self):', '(scores,', 'ids)', '=', 'self.sort_best()', 'return', '(scores[1],', 'ids[1])'] | 8,867 |
ilya16/MultINN | dbn.py | DBN.num_dims | num_dims | int: The number of input/output dimensions of the DBN. | [
"int:",
"The",
"number",
"of",
"input/output",
"dimensions",
"of",
"the",
"DBN."
] | def num_dims(self):
return self._num_dims | ['def', 'num_dims(self):', 'return', 'self._num_dims'] | 644,160 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | word2vec_optimized.py | Word2Vec.analogy | analogy | Predict word w3 as in w0:w1 vs w2:w3. | [
"Predict",
"word",
"w3",
"as",
"in",
"w0:w1",
"vs",
"w2:w3."
] | def analogy(self, w0, w1, w2):
wid = np.array([[self._word2id.get(w, 0) for w in [w0, w1, w2]]])
idx = self._predict(wid)
for c in [self._id2word[i] for i in idx[0, :]]:
if c not in [w0, w1, w2]:
print(c)
break
print('unknown') | ['def', 'analogy(self,', 'w0,', 'w1,', 'w2):', 'wid', '=', 'np.array([[self._word2id.get(w,', '0)', 'for', 'w', 'in', '[w0,', 'w1,', 'w2]]])', 'idx', '=', 'self._predict(wid)', 'for', 'c', 'in', '[self._id2word[i]', 'for', 'i', 'in', 'idx[0,', ':]]:', 'if', 'c', 'not', 'in', '[w0,', 'w1,', 'w2]:', 'print(c)', 'break', ... | 113,007 |
scikit-learn/scikit-learn | test_common_curve_display.py | test_display_curve_estimator_name_multiple_calls | test_display_curve_estimator_name_multiple_calls | Check that passing `name` when calling `plot` will overwrite the original name in the legend. | [
"Check",
"that",
"passing",
"`name`",
"when",
"calling",
"`plot`",
"will",
"overwrite",
"the",
"original",
"name",
"in",
"the",
"legend."
] | def test_display_curve_estimator_name_multiple_calls(pyplot, data_binary, Display, constructor_name):
(X, y) = data_binary
clf_name = 'my hand-crafted name'
clf = LogisticRegression().fit(X, y)
y_pred = clf.predict_proba(X)[:, 1]
assert constructor_name in ('from_estimator', 'from_predictions')
... | ['def', 'test_display_curve_estimator_name_multiple_calls(pyplot,', 'data_binary,', 'Display,', 'constructor_name):', '(X,', 'y)', '=', 'data_binary', 'clf_name', '=', "'my", 'hand-crafted', "name'", 'clf', '=', 'LogisticRegression().fit(X,', 'y)', 'y_pred', '=', 'clf.predict_proba(X)[:,', '1]', 'assert', 'constructor_... | 853,722 |
bytedance/DeepSolid | utils.py | solve_maybe_small | solve_maybe_small | Computes a^-1 b more efficiently for small matrices. | [
"Computes",
"a^-1",
"b",
"more",
"efficiently",
"for",
"small",
"matrices."
] | def solve_maybe_small(a: jnp.ndarray, b: jnp.ndarray) -> jnp.ndarray:
assert a.shape[-1] == a.shape[-2] == b.shape[-1]
d = a.shape[-1]
if d == 0:
return a
elif d == 1:
return b / a[..., 0]
elif d == 2:
det = a[..., 0, 0] * a[..., 1, 1] - a[..., 0, 1] * a[..., 1, 0]
b_... | ['def', 'solve_maybe_small(a:', 'jnp.ndarray,', 'b:', 'jnp.ndarray)', '->', 'jnp.ndarray:', 'assert', 'a.shape[-1]', '==', 'a.shape[-2]', '==', 'b.shape[-1]', 'd', '=', 'a.shape[-1]', 'if', 'd', '==', '0:', 'return', 'a', 'elif', 'd', '==', '1:', 'return', 'b', '/', 'a[...,', '0]', 'elif', 'd', '==', '2:', 'det', '=', ... | 539,978 |
mlcommons/medperf | views.py | DatasetDetail.delete | delete | Delete a dataset instance. | [
"Delete",
"a",
"dataset",
"instance."
] | def delete(self, request, pk, format=None):
dataset = self.get_object(pk)
dataset.delete()
return Response(status=status.HTTP_204_NO_CONTENT) | ['def', 'delete(self,', 'request,', 'pk,', 'format=None):', 'dataset', '=', 'self.get_object(pk)', 'dataset.delete()', 'return', 'Response(status=status.HTTP_204_NO_CONTENT)'] | 285,193 |
enlite-ai/maze | torch_policy.py | TorchPolicy.needs_state | needs_state | This policy does not require the state() object to compute the action. | [
"This",
"policy",
"does",
"not",
"require",
"the",
"state()",
"object",
"to",
"compute",
"the",
"action."
] | def needs_state(self) -> bool:
return False | ['def', 'needs_state(self)', '->', 'bool:', 'return', 'False'] | 646,534 |
noambassat/SpeechTrainer | dist.py | DistributionMetadata.write_pkg_file | write_pkg_file | Write the PKG-INFO format data to a file object. | [
"Write",
"the",
"PKG-INFO",
"format",
"data",
"to",
"a",
"file",
"object."
] | def write_pkg_file(self, file):
version = '1.0'
if self.provides or self.requires or self.obsoletes or self.classifiers or self.download_url:
version = '1.1'
file.write('Metadata-Version: %s\n' % version)
file.write('Name: %s\n' % self.get_name())
file.write('Version: %s\n' % self.get_versio... | ['def', 'write_pkg_file(self,', 'file):', 'version', '=', "'1.0'", 'if', 'self.provides', 'or', 'self.requires', 'or', 'self.obsoletes', 'or', 'self.classifiers', 'or', 'self.download_url:', 'version', '=', "'1.1'", "file.write('Metadata-Version:", "%s\\n'", '%', 'version)', "file.write('Name:", "%s\\n'", '%', 'self.ge... | 896,239 |
eddylau328/fyp-artificial-intelligence-ac-control-device | req_uninstall.py | StashedUninstallPathSet.rollback | rollback | Undoes the uninstall by moving stashed files back. | [
"Undoes",
"the",
"uninstall",
"by",
"moving",
"stashed",
"files",
"back."
] | def rollback(self):
for p in self._moves:
logging.info('Moving to %s\n from %s', *p)
for (new_path, path) in self._moves:
try:
logger.debug('Replacing %s from %s', new_path, path)
if os.path.isfile(new_path) or os.path.islink(new_path):
os.unlink(new_path)... | ['def', 'rollback(self):', 'for', 'p', 'in', 'self._moves:', "logging.info('Moving", 'to', '%s\\n', 'from', "%s',", '*p)', 'for', '(new_path,', 'path)', 'in', 'self._moves:', 'try:', "logger.debug('Replacing", '%s', 'from', "%s',", 'new_path,', 'path)', 'if', 'os.path.isfile(new_path)', 'or', 'os.path.islink(new_path):... | 215,910 |
BaderLab/Transfer-Learning-BNER-Bioinformatics-2018 | brat_standoff_corpus_proccessing.py | get_top_n_intersection | get_top_n_intersection | Returns a list containing the n most common elements in A intersection B. | [
"Returns",
"a",
"list",
"containing",
"the",
"n",
"most",
"common",
"elements",
"in",
"A",
"intersection",
"B."
] | def get_top_n_intersection(A, B, n=10):
A_intersection_B = Counter([x.split('\t')[1] for x in A.intersection(B)]).most_common(n)
return A_intersection_B | ['def', 'get_top_n_intersection(A,', 'B,', 'n=10):', 'A_intersection_B', '=', "Counter([x.split('\\t')[1]", 'for', 'x', 'in', 'A.intersection(B)]).most_common(n)', 'return', 'A_intersection_B'] | 920,808 |
weimin17/Object-Detection_HelmetDetection | data_download.py | download_report_hook | download_report_hook | Report hook for download progress. | [
"Report",
"hook",
"for",
"download",
"progress."
] | def download_report_hook(count, block_size, total_size):
percent = int(count * block_size * 100 / total_size)
print('\r%d%%' % percent + ' completed', end='\r') | ['def', 'download_report_hook(count,', 'block_size,', 'total_size):', 'percent', '=', 'int(count', '*', 'block_size', '*', '100', '/', 'total_size)', "print('\\r%d%%'", '%', 'percent', '+', "'", "completed',", "end='\\r')"] | 748,674 |
santhoshkolloju/Abstractive-Summarization-With-Transfer- | data_decoders.py | TextDataDecoder.length_tensor_name | length_tensor_name | The name of length tensor. | [
"The",
"name",
"of",
"length",
"tensor."
] | def length_tensor_name(self):
return self._length_tensor_name | ['def', 'length_tensor_name(self):', 'return', 'self._length_tensor_name'] | 406,006 |
Guanyuansheng/TFGAN-PLC | discriminator.py | Discriminator.forward | forward | Forward pass of discriminator. | [
"Forward",
"pass",
"of",
"discriminator."
] | def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
x = self.conv4(x)
x = self.conv5(x)
x = self.conv6(x)
x = self.conv7(x)
x = x.view(-1, 2560)
x = self.fully_connected(x)
return x | ['def', 'forward(self,', 'x):', 'x', '=', 'self.conv1(x)', 'x', '=', 'self.conv2(x)', 'x', '=', 'self.conv3(x)', 'x', '=', 'self.conv4(x)', 'x', '=', 'self.conv5(x)', 'x', '=', 'self.conv6(x)', 'x', '=', 'self.conv7(x)', 'x', '=', 'x.view(-1,', '2560)', 'x', '=', 'self.fully_connected(x)', 'return', 'x'] | 915,771 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | management.py | TermManagerBase.pty_read | pty_read | Called by the event loop when there is pty data ready to read. | [
"Called",
"by",
"the",
"event",
"loop",
"when",
"there",
"is",
"pty",
"data",
"ready",
"to",
"read."
] | def pty_read(self, fd, events=None):
ptywclients = self.ptys_by_fd[fd]
try:
s = ptywclients.ptyproc.read(65536)
client_list = ptywclients.clients
ptywclients.read_buffer.append(s)
if not client_list:
ptywclients.preopen_buffer.append(s)
return
for ... | ['def', 'pty_read(self,', 'fd,', 'events=None):', 'ptywclients', '=', 'self.ptys_by_fd[fd]', 'try:', 's', '=', 'ptywclients.ptyproc.read(65536)', 'client_list', '=', 'ptywclients.clients', 'ptywclients.read_buffer.append(s)', 'if', 'not', 'client_list:', 'ptywclients.preopen_buffer.append(s)', 'return', 'for', 'client'... | 437,433 |
replit-archive/empythoned | macosxSupport.py | setupApp | setupApp | Perform setup for the OSX application bundle. | [
"Perform",
"setup",
"for",
"the",
"OSX",
"application",
"bundle."
] | def setupApp(root, flist):
if not runningAsOSXApp():
return
hideTkConsole(root)
overrideRootMenu(root, flist)
addOpenEventSupport(root, flist) | ['def', 'setupApp(root,', 'flist):', 'if', 'not', 'runningAsOSXApp():', 'return', 'hideTkConsole(root)', 'overrideRootMenu(root,', 'flist)', 'addOpenEventSupport(root,', 'flist)'] | 176,708 |
weimin17/Object-Detection_HelmetDetection | nav_env.py | GridWorld.get_feasible_actions | get_feasible_actions | Returns the feasible set of actions from the current node. | [
"Returns",
"the",
"feasible",
"set",
"of",
"actions",
"from",
"the",
"current",
"node."
] | def get_feasible_actions(self, node_ids):
a = np.zeros((len(node_ids), self.task_params.num_actions), dtype=np.int32)
gtG = self.task.gtG
next_node = []
for (i, c) in enumerate(node_ids):
neigh = gtG.vertex(c).out_neighbours()
neigh_edge = gtG.vertex(c).out_edges()
nn = {}
... | ['def', 'get_feasible_actions(self,', 'node_ids):', 'a', '=', 'np.zeros((len(node_ids),', 'self.task_params.num_actions),', 'dtype=np.int32)', 'gtG', '=', 'self.task.gtG', 'next_node', '=', '[]', 'for', '(i,', 'c)', 'in', 'enumerate(node_ids):', 'neigh', '=', 'gtG.vertex(c).out_neighbours()', 'neigh_edge', '=', 'gtG.ve... | 762,030 |
open-mmlab/mmselfsup | layer_decay_optim_wrapper_constructor.py | get_layer_id_for_vit | get_layer_id_for_vit | Get the layer id to set the different learning rates for ViT. | [
"Get",
"the",
"layer",
"id",
"to",
"set",
"the",
"different",
"learning",
"rates",
"for",
"ViT."
] | def get_layer_id_for_vit(var_name: str, max_layer_id: int) -> int:
if var_name in ('backbone.cls_token', 'backbone.mask_token', 'backbone.pos_embed'):
return 0
elif var_name.startswith('backbone.patch_embed'):
return 0
elif var_name.startswith('backbone.layers'):
layer_id = int(var_n... | ['def', 'get_layer_id_for_vit(var_name:', 'str,', 'max_layer_id:', 'int)', '->', 'int:', 'if', 'var_name', 'in', "('backbone.cls_token',", "'backbone.mask_token',", "'backbone.pos_embed'):", 'return', '0', 'elif', "var_name.startswith('backbone.patch_embed'):", 'return', '0', 'elif', "var_name.startswith('backbone.laye... | 240,337 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | locale.py | str | str | Convert float to string, taking the locale into account. | [
"Convert",
"float",
"to",
"string,",
"taking",
"the",
"locale",
"into",
"account."
] | def str(val):
return format('%.12g', val) | ['def', 'str(val):', 'return', "format('%.12g',", 'val)'] | 428,762 |
simpleai-team/simpleai | models.py | Attribute.reason | reason | Returns a string with an explanation of why the attribute is being applied. | [
"Returns",
"a",
"string",
"with",
"an",
"explanation",
"of",
"why",
"the",
"attribute",
"is",
"being",
"applied."
] | def reason(self, example):
raise NotImplementedError() | ['def', 'reason(self,', 'example):', 'raise', 'NotImplementedError()'] | 350,621 |
famura/SimuRLacra | sbi_rollout_sampler.py | RecRolloutSamplerForSBI.num_rollouts | num_rollouts | Get the number of stored rollouts. | [
"Get",
"the",
"number",
"of",
"stored",
"rollouts."
] | def num_rollouts(self) -> int:
return len(self.rollouts_rec) | ['def', 'num_rollouts(self)', '->', 'int:', 'return', 'len(self.rollouts_rec)'] | 883,938 |
rishikksh20/HiFi-GAN | stft_loss.py | stft | stft | Perform STFT and convert to magnitude spectrogram. | [
"Perform",
"STFT",
"and",
"convert",
"to",
"magnitude",
"spectrogram."
] | def stft(x, fft_size, hop_size, win_length, window):
x_stft = torch.stft(x, fft_size, hop_size, win_length, window)
real = x_stft[..., 0]
imag = x_stft[..., 1]
return torch.sqrt(torch.clamp(real ** 2 + imag ** 2, min=1e-07)).transpose(2, 1) | ['def', 'stft(x,', 'fft_size,', 'hop_size,', 'win_length,', 'window):', 'x_stft', '=', 'torch.stft(x,', 'fft_size,', 'hop_size,', 'win_length,', 'window)', 'real', '=', 'x_stft[...,', '0]', 'imag', '=', 'x_stft[...,', '1]', 'return', 'torch.sqrt(torch.clamp(real', '**', '2', '+', 'imag', '**', '2,', 'min=1e-07)).transp... | 593,209 |
Hughes-Genome-Group/deepHaem | deepHaemWindow.py | evaluation | evaluation | Evaluate the quality of the logits at predicting the label. | [
"Evaluate",
"the",
"quality",
"of",
"the",
"logits",
"at",
"predicting",
"the",
"label."
] | def evaluation(logits, labels):
labels = tf.to_float(labels)
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1))
mean_correct = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
return mean_correct | ['def', 'evaluation(logits,', 'labels):', 'labels', '=', 'tf.to_float(labels)', 'correct_prediction', '=', 'tf.equal(tf.argmax(logits,', '1),', 'tf.argmax(labels,', '1))', 'mean_correct', '=', 'tf.reduce_mean(tf.cast(correct_prediction,', 'tf.float32))', 'return', 'mean_correct'] | 128,695 |
greydanus/mr_london | serving.py | WSGIRequestHandler.handle_one_request | handle_one_request | Handle a single HTTP request. | [
"Handle",
"a",
"single",
"HTTP",
"request."
] | def handle_one_request(self):
self.raw_requestline = self.rfile.readline()
if not self.raw_requestline:
self.close_connection = 1
elif self.parse_request():
return self.run_wsgi() | ['def', 'handle_one_request(self):', 'self.raw_requestline', '=', 'self.rfile.readline()', 'if', 'not', 'self.raw_requestline:', 'self.close_connection', '=', '1', 'elif', 'self.parse_request():', 'return', 'self.run_wsgi()'] | 264,160 |
chribsen/simple-machine-learning-examples | __init__.py | parse_requirements | parse_requirements | Yield ``Requirement`` objects for each specification in `strs` `strs` must be a string, or a (possibly-nested) iterable thereof. | [
"Yield",
"``Requirement``",
"objects",
"for",
"each",
"specification",
"in",
"`strs`",
"`strs`",
"must",
"be",
"a",
"string,",
"or",
"a",
"(possibly-nested)",
"iterable",
"thereof."
] | def parse_requirements(strs):
lines = iter(yield_lines(strs))
for line in lines:
if ' #' in line:
line = line[:line.find(' #')]
if line.endswith('\\'):
line = line[:-2].strip()
line += next(lines)
yield Requirement(line) | ['def', 'parse_requirements(strs):', 'lines', '=', 'iter(yield_lines(strs))', 'for', 'line', 'in', 'lines:', 'if', "'", "#'", 'in', 'line:', 'line', '=', "line[:line.find('", "#')]", 'if', "line.endswith('\\\\'):", 'line', '=', 'line[:-2].strip()', 'line', '+=', 'next(lines)', 'yield', 'Requirement(line)'] | 937,635 |
GHOST5454/Natural-Language-Processing | yake.py | YAKE.candidate_weighting | candidate_weighting | Candidate weight calculation as described in the YAKE paper. | [
"Candidate",
"weight",
"calculation",
"as",
"described",
"in",
"the",
"YAKE",
"paper."
] | def candidate_weighting(self, window=2, stoplist=None, use_stems=False):
if not self.candidates:
return
self._vocabulary_building(use_stems=use_stems)
self._contexts_building(use_stems=use_stems, window=window)
self._feature_extraction(stoplist=stoplist)
for (k, v) in self.candidates.items()... | ['def', 'candidate_weighting(self,', 'window=2,', 'stoplist=None,', 'use_stems=False):', 'if', 'not', 'self.candidates:', 'return', 'self._vocabulary_building(use_stems=use_stems)', 'self._contexts_building(use_stems=use_stems,', 'window=window)', 'self._feature_extraction(stoplist=stoplist)', 'for', '(k,', 'v)', 'in',... | 662,653 |
tobegit3hub/deep_image_model | util.py | placeholder_name | placeholder_name | Create placeholder name for the graph editor. | [
"Create",
"placeholder",
"name",
"for",
"the",
"graph",
"editor."
] | def placeholder_name(t=None, scope=None):
if scope is not None:
scope = scope_finalize(scope)
if t is not None:
if not isinstance(t, tf_ops.Tensor):
raise TypeError('Expected a tf.Tenfor, got: {}'.format(type(t)))
op_dirname = scope_dirname(t.op.name)
op_basename = sc... | ['def', 'placeholder_name(t=None,', 'scope=None):', 'if', 'scope', 'is', 'not', 'None:', 'scope', '=', 'scope_finalize(scope)', 'if', 't', 'is', 'not', 'None:', 'if', 'not', 'isinstance(t,', 'tf_ops.Tensor):', 'raise', "TypeError('Expected", 'a', 'tf.Tenfor,', 'got:', "{}'.format(type(t)))", 'op_dirname', '=', 'scope_d... | 181,409 |
MegEngine/Transfer-Learning-Library | ibn.py | resnet34_ibn_b | resnet34_ibn_b | Constructs a ResNet-34-IBN-b model. | [
"Constructs",
"a",
"ResNet-34-IBN-b",
"model."
] | def resnet34_ibn_b(pretrained=False):
model = IBNNet(block=BasicBlock, layers=[3, 4, 6, 3], ibn_cfg=('b', 'b', None, None))
if pretrained:
model.load_state_dict(torch.hub.load_state_dict_from_url(model_urls['resnet34_ibn_b']), strict=False)
return model | ['def', 'resnet34_ibn_b(pretrained=False):', 'model', '=', 'IBNNet(block=BasicBlock,', 'layers=[3,', '4,', '6,', '3],', "ibn_cfg=('b',", "'b',", 'None,', 'None))', 'if', 'pretrained:', "model.load_state_dict(torch.hub.load_state_dict_from_url(model_urls['resnet34_ibn_b']),", 'strict=False)', 'return', 'model'] | 921,173 |
jiacheng-xu/vmf_vae_nlp | main.py | repackage_hidden | repackage_hidden | Wraps hidden states in new Variables, to detach them from their history. | [
"Wraps",
"hidden",
"states",
"in",
"new",
"Variables,",
"to",
"detach",
"them",
"from",
"their",
"history."
] | def repackage_hidden(h):
if type(h) == Variable:
return Variable(h.data)
else:
return tuple((repackage_hidden(v) for v in h)) | ['def', 'repackage_hidden(h):', 'if', 'type(h)', '==', 'Variable:', 'return', 'Variable(h.data)', 'else:', 'return', 'tuple((repackage_hidden(v)', 'for', 'v', 'in', 'h))'] | 946,122 |
nicknochnack/RealTimeSignLanguageTFJS | mnist_main.py | run | run | Run MNIST model training and eval loop using native Keras APIs. | [
"Run",
"MNIST",
"model",
"training",
"and",
"eval",
"loop",
"using",
"native",
"Keras",
"APIs."
] | def run(flags_obj, datasets_override=None, strategy_override=None):
strategy = strategy_override or distribute_utils.get_distribution_strategy(distribution_strategy=flags_obj.distribution_strategy, num_gpus=flags_obj.num_gpus, tpu_address=flags_obj.tpu)
strategy_scope = distribute_utils.get_strategy_scope(strat... | ['def', 'run(flags_obj,', 'datasets_override=None,', 'strategy_override=None):', 'strategy', '=', 'strategy_override', 'or', 'distribute_utils.get_distribution_strategy(distribution_strategy=flags_obj.distribution_strategy,', 'num_gpus=flags_obj.num_gpus,', 'tpu_address=flags_obj.tpu)', 'strategy_scope', '=', 'distribu... | 851,190 |
eora-ai/torchok | detection.py | SingleStageDetectionTask.forward_with_gt | forward_with_gt | Forward with ground truth labels. | [
"Forward",
"with",
"ground",
"truth",
"labels."
] | def forward_with_gt(self, batch: Dict[str, torch.Tensor]) -> Dict[str, Any]:
input_data = batch.get('image')
img_shape = (*input_data.shape[-2:], input_data.shape[-3])
img_metas = [dict(orig_img_shape=orig_shape, img_shape=img_shape) for orig_shape in batch.get('orig_img_shape')]
features = self.backbon... | ['def', 'forward_with_gt(self,', 'batch:', 'Dict[str,', 'torch.Tensor])', '->', 'Dict[str,', 'Any]:', 'input_data', '=', "batch.get('image')", 'img_shape', '=', '(*input_data.shape[-2:],', 'input_data.shape[-3])', 'img_metas', '=', '[dict(orig_img_shape=orig_shape,', 'img_shape=img_shape)', 'for', 'orig_shape', 'in', "... | 903,318 |
kornia/kornia | test_zca.py | TestZCA.test_identity | test_identity | Assert that data can be recovered by the inverse transform. | [
"Assert",
"that",
"data",
"can",
"be",
"recovered",
"by",
"the",
"inverse",
"transform."
] | def test_identity(self, input_shape, eps, device, dtype):
data = torch.randn(*input_shape, device=device, dtype=dtype)
zca = kornia.enhance.ZCAWhitening(compute_inv=True, eps=eps).fit(data)
data_w = zca(data)
data_hat = zca.inverse_transform(data_w)
self.assert_close(data, data_hat, low_tolerance=Tr... | ['def', 'test_identity(self,', 'input_shape,', 'eps,', 'device,', 'dtype):', 'data', '=', 'torch.randn(*input_shape,', 'device=device,', 'dtype=dtype)', 'zca', '=', 'kornia.enhance.ZCAWhitening(compute_inv=True,', 'eps=eps).fit(data)', 'data_w', '=', 'zca(data)', 'data_hat', '=', 'zca.inverse_transform(data_w)', 'self.... | 622,327 |
facebookresearch/deep_bisim4control | cartpole.py | get_model_and_assets | get_model_and_assets | Returns a tuple containing the model XML string and a dict of assets. | [
"Returns",
"a",
"tuple",
"containing",
"the",
"model",
"XML",
"string",
"and",
"a",
"dict",
"of",
"assets."
] | def get_model_and_assets(num_poles=1):
return (_make_model(num_poles), common.ASSETS) | ['def', 'get_model_and_assets(num_poles=1):', 'return', '(_make_model(num_poles),', 'common.ASSETS)'] | 536,308 |
Erfanafshar/Principles-and-Applications-of---graph-coloring | colors.py | is_color_like | is_color_like | Return whether *c* can be interpreted as an RGB(A) color. | [
"Return",
"whether",
"*c*",
"can",
"be",
"interpreted",
"as",
"an",
"RGB(A)",
"color."
] | def is_color_like(c):
if _is_nth_color(c):
return True
try:
to_rgba(c)
except ValueError:
return False
else:
return True | ['def', 'is_color_like(c):', 'if', '_is_nth_color(c):', 'return', 'True', 'try:', 'to_rgba(c)', 'except', 'ValueError:', 'return', 'False', 'else:', 'return', 'True'] | 306,582 |
wangqiangneu/dlcl | learned_positional_embedding.py | LearnedPositionalEmbedding.max_positions | max_positions | Maximum number of supported positions. | [
"Maximum",
"number",
"of",
"supported",
"positions."
] | def max_positions(self):
return self.num_embeddings - self.padding_idx - 1 | ['def', 'max_positions(self):', 'return', 'self.num_embeddings', '-', 'self.padding_idx', '-', '1'] | 521,817 |
Kvatsx/Artificial-Intelligence-Assignments | sputils.py | upcast_scalar | upcast_scalar | Determine data type for binary operation between an array of type `dtype` and a scalar. | [
"Determine",
"data",
"type",
"for",
"binary",
"operation",
"between",
"an",
"array",
"of",
"type",
"`dtype`",
"and",
"a",
"scalar."
] | def upcast_scalar(dtype, scalar):
return (np.array([0], dtype=dtype) * scalar).dtype | ['def', 'upcast_scalar(dtype,', 'scalar):', 'return', '(np.array([0],', 'dtype=dtype)', '*', 'scalar).dtype'] | 78,005 |
wandb/wandb | test_gcp_artifact_registry.py | test_from_config | test_from_config | Test that we construct a GoogleArtifactRegistry from a config dict. | [
"Test",
"that",
"we",
"construct",
"a",
"GoogleArtifactRegistry",
"from",
"a",
"config",
"dict."
] | def test_from_config():
environment = MagicMock()
environment.project = 'myproject-12345'
environment.region = 'region'
config = {'type': 'gcr', 'repository': 'test-repository', 'image-name': 'test-image'}
registry = GoogleArtifactRegistry.from_config(config, environment, verify=False)
assert re... | ['def', 'test_from_config():', 'environment', '=', 'MagicMock()', 'environment.project', '=', "'myproject-12345'", 'environment.region', '=', "'region'", 'config', '=', "{'type':", "'gcr',", "'repository':", "'test-repository',", "'image-name':", "'test-image'}", 'registry', '=', 'GoogleArtifactRegistry.from_config(con... | 941,280 |
ryu-ed/SpaceInvaders_Ros | mixer_test.py | SoundTypeTest.test_sound__from_sound_object | test_sound__from_sound_object | Ensure Sound() creation with a Sound() object works. | [
"Ensure",
"Sound()",
"creation",
"with",
"a",
"Sound()",
"object",
"works."
] | def test_sound__from_sound_object(self):
filename = example_path(os.path.join('data', 'house_lo.wav'))
sound_obj = mixer.Sound(file=filename)
sound = mixer.Sound(sound_obj)
self.assertIsInstance(sound, mixer.Sound) | ['def', 'test_sound__from_sound_object(self):', 'filename', '=', "example_path(os.path.join('data',", "'house_lo.wav'))", 'sound_obj', '=', 'mixer.Sound(file=filename)', 'sound', '=', 'mixer.Sound(sound_obj)', 'self.assertIsInstance(sound,', 'mixer.Sound)'] | 369,097 |
Rituraj-commits/Semantic-Segmentation | helpers.py | random_crop_and_pad_image_and_labels | random_crop_and_pad_image_and_labels | Randomly crops `image` together with `labels`. | [
"Randomly",
"crops",
"`image`",
"together",
"with",
"`labels`."
] | def random_crop_and_pad_image_and_labels(image, labels, size):
combined = tf.concat([image, labels], axis=2)
image_shape = tf.shape(image)
combined_pad = tf.image.pad_to_bounding_box(combined, 0, 0, tf.maximum(size[0], image_shape[0]), tf.maximum(size[1], image_shape[1]))
last_label_dim = tf.shape(label... | ['def', 'random_crop_and_pad_image_and_labels(image,', 'labels,', 'size):', 'combined', '=', 'tf.concat([image,', 'labels],', 'axis=2)', 'image_shape', '=', 'tf.shape(image)', 'combined_pad', '=', 'tf.image.pad_to_bounding_box(combined,', '0,', '0,', 'tf.maximum(size[0],', 'image_shape[0]),', 'tf.maximum(size[1],', 'im... | 870,264 |
facebookresearch/HRViT | checkpoint.py | load_fileclient_dist | load_fileclient_dist | In distributed setting, this function only download checkpoint at local rank 0. | [
"In",
"distributed",
"setting,",
"this",
"function",
"only",
"download",
"checkpoint",
"at",
"local",
"rank",
"0."
] | def load_fileclient_dist(filename, backend, map_location):
(rank, world_size) = get_dist_info()
rank = int(os.environ.get('LOCAL_RANK', rank))
allowed_backends = ['ceph']
if backend not in allowed_backends:
raise ValueError(f'Load from Backend {backend} is not supported.')
if rank == 0:
... | ['def', 'load_fileclient_dist(filename,', 'backend,', 'map_location):', '(rank,', 'world_size)', '=', 'get_dist_info()', 'rank', '=', "int(os.environ.get('LOCAL_RANK',", 'rank))', 'allowed_backends', '=', "['ceph']", 'if', 'backend', 'not', 'in', 'allowed_backends:', 'raise', "ValueError(f'Load", 'from', 'Backend', '{b... | 570,614 |
marcsto/rl | utils.py | roll_by_gather | roll_by_gather | Rolls a batched matrix along the last or last but one dimension. | [
"Rolls",
"a",
"batched",
"matrix",
"along",
"the",
"last",
"or",
"last",
"but",
"one",
"dimension."
] | def roll_by_gather(mat: torch.Tensor, dim: int, shifts: torch.LongTensor):
(*batch, n_rows, n_cols) = mat.shape
device = mat.device
if dim in (0, -2):
arange1 = torch.arange(n_rows, device=device).unsqueeze(-1).expand((n_rows, n_cols))
arange2 = (arange1 - shifts) % n_rows
return tor... | ['def', 'roll_by_gather(mat:', 'torch.Tensor,', 'dim:', 'int,', 'shifts:', 'torch.LongTensor):', '(*batch,', 'n_rows,', 'n_cols)', '=', 'mat.shape', 'device', '=', 'mat.device', 'if', 'dim', 'in', '(0,', '-2):', 'arange1', '=', 'torch.arange(n_rows,', 'device=device).unsqueeze(-1).expand((n_rows,', 'n_cols))', 'arange2... | 859,431 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | pixelda_utils.py | summarize_transferred_grid | summarize_transferred_grid | Produces a visual grid summarization of the image transferrence. | [
"Produces",
"a",
"visual",
"grid",
"summarization",
"of",
"the",
"image",
"transferrence."
] | def summarize_transferred_grid(transferred_images, source_images=None, name='Transferred'):
if source_images is not None:
grid = source_and_output_image_grid(transferred_images, source_images)
else:
grid = image_grid(transferred_images)
tf.summary.image('%s_Images_Grid' % name, grid, max_out... | ['def', 'summarize_transferred_grid(transferred_images,', 'source_images=None,', "name='Transferred'):", 'if', 'source_images', 'is', 'not', 'None:', 'grid', '=', 'source_and_output_image_grid(transferred_images,', 'source_images)', 'else:', 'grid', '=', 'image_grid(transferred_images)', "tf.summary.image('%s_Images_Gr... | 48,325 |
michellesri/cs188 | autograder.py | GameState.getAgentPosition | getAgentPosition | Returns a location tuple if the agent with the given index is observable; if the agent is unobservable, returns None. | [
"Returns",
"a",
"location",
"tuple",
"if",
"the",
"agent",
"with",
"the",
"given",
"index",
"is",
"observable;",
"if",
"the",
"agent",
"is",
"unobservable,",
"returns",
"None."
] | def getAgentPosition(self, index):
agentState = self.data.agentStates[index]
ret = agentState.getPosition()
if ret:
return tuple((int(x) for x in ret))
return ret | ['def', 'getAgentPosition(self,', 'index):', 'agentState', '=', 'self.data.agentStates[index]', 'ret', '=', 'agentState.getPosition()', 'if', 'ret:', 'return', 'tuple((int(x)', 'for', 'x', 'in', 'ret))', 'return', 'ret'] | 223,956 |
jshilong/DDQ | openimages.py | OpenImagesDataset.get_meta_from_file | get_meta_from_file | Get image metas from pkl file. | [
"Get",
"image",
"metas",
"from",
"pkl",
"file."
] | def get_meta_from_file(self, meta_file=''):
assert meta_file.endswith('pkl'), 'File name must be pkl suffix'
metas = mmcv.load(meta_file)
assert len(metas) == len(self)
for i in range(len(metas)):
file_name = osp.split(metas[i]['filename'])[-1]
img_info = self.data_infos[i].get('img_info... | ['def', 'get_meta_from_file(self,', "meta_file=''):", 'assert', "meta_file.endswith('pkl'),", "'File", 'name', 'must', 'be', 'pkl', "suffix'", 'metas', '=', 'mmcv.load(meta_file)', 'assert', 'len(metas)', '==', 'len(self)', 'for', 'i', 'in', 'range(len(metas)):', 'file_name', '=', "osp.split(metas[i]['filename'])[-1]",... | 515,842 |
scikit-learn/scikit-learn | test_response.py | test_get_response_values_regressor_error | test_get_response_values_regressor_error | Check the error message with regressor an not supported response method. | [
"Check",
"the",
"error",
"message",
"with",
"regressor",
"an",
"not",
"supported",
"response",
"method."
] | def test_get_response_values_regressor_error(response_method):
my_estimator = _MockEstimatorOnOffPrediction(response_methods=[response_method])
X = ('mocking_data', 'mocking_target')
err_msg = f'{my_estimator.__class__.__name__} should either be a classifier'
with pytest.raises(ValueError, match=err_msg... | ['def', 'test_get_response_values_regressor_error(response_method):', 'my_estimator', '=', '_MockEstimatorOnOffPrediction(response_methods=[response_method])', 'X', '=', "('mocking_data',", "'mocking_target')", 'err_msg', '=', "f'{my_estimator.__class__.__name__}", 'should', 'either', 'be', 'a', "classifier'", 'with', ... | 854,354 |
IordachescuAnca/Artificial-Intelligence | csp.py | min_conflicts | min_conflicts | Solve a CSP by stochastic Hill Climbing on the number of conflicts. | [
"Solve",
"a",
"CSP",
"by",
"stochastic",
"Hill",
"Climbing",
"on",
"the",
"number",
"of",
"conflicts."
] | def min_conflicts(csp, max_steps=100000):
csp.current = current = {}
for var in csp.variables:
val = min_conflicts_value(csp, var, current)
csp.assign(var, val, current)
for i in range(max_steps):
conflicted = csp.conflicted_vars(current)
if not conflicted:
return... | ['def', 'min_conflicts(csp,', 'max_steps=100000):', 'csp.current', '=', 'current', '=', '{}', 'for', 'var', 'in', 'csp.variables:', 'val', '=', 'min_conflicts_value(csp,', 'var,', 'current)', 'csp.assign(var,', 'val,', 'current)', 'for', 'i', 'in', 'range(max_steps):', 'conflicted', '=', 'csp.conflicted_vars(current)',... | 115,539 |
cristianpb/object-detection | ops.py | filter_groundtruth_with_crowd_boxes | filter_groundtruth_with_crowd_boxes | Filters out groundtruth with boxes corresponding to crowd. | [
"Filters",
"out",
"groundtruth",
"with",
"boxes",
"corresponding",
"to",
"crowd."
] | def filter_groundtruth_with_crowd_boxes(tensor_dict):
if fields.InputDataFields.groundtruth_is_crowd in tensor_dict:
is_crowd = tensor_dict[fields.InputDataFields.groundtruth_is_crowd]
is_not_crowd = tf.logical_not(is_crowd)
is_not_crowd_indices = tf.where(is_not_crowd)
tensor_dict =... | ['def', 'filter_groundtruth_with_crowd_boxes(tensor_dict):', 'if', 'fields.InputDataFields.groundtruth_is_crowd', 'in', 'tensor_dict:', 'is_crowd', '=', 'tensor_dict[fields.InputDataFields.groundtruth_is_crowd]', 'is_not_crowd', '=', 'tf.logical_not(is_crowd)', 'is_not_crowd_indices', '=', 'tf.where(is_not_crowd)', 'te... | 747,378 |
googleapis/python-aiplatform | grpc_asyncio.py | PipelineServiceGrpcAsyncIOTransport.list_locations | list_locations | Return a callable for the list locations method over gRPC. | [
"Return",
"a",
"callable",
"for",
"the",
"list",
"locations",
"method",
"over",
"gRPC."
] | def list_locations(self) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]:
if 'list_locations' not in self._stubs:
self._stubs['list_locations'] = self.grpc_channel.unary_unary('/google.cloud.location.Locations/ListLocations', request_serializer=locations_pb2.ListLocati... | ['def', 'list_locations(self)', '->', 'Callable[[locations_pb2.ListLocationsRequest],', 'locations_pb2.ListLocationsResponse]:', 'if', "'list_locations'", 'not', 'in', 'self._stubs:', "self._stubs['list_locations']", '=', "self.grpc_channel.unary_unary('/google.cloud.location.Locations/ListLocations',", 'request_serial... | 813,873 |
yinyunie/ScenePriors | test_sample_points_from_meshes.py | TestSamplePoints.test_all_empty_meshes | test_all_empty_meshes | Check sample_points_from_meshes raises an exception if all meshes are invalid. | [
"Check",
"sample_points_from_meshes",
"raises",
"an",
"exception",
"if",
"all",
"meshes",
"are",
"invalid."
] | def test_all_empty_meshes(self):
device = get_random_cuda_device()
verts1 = torch.tensor([], dtype=torch.float32, device=device)
faces1 = torch.tensor([], dtype=torch.int64, device=device)
meshes = Meshes(verts=[verts1, verts1, verts1], faces=[faces1, faces1, faces1])
with self.assertRaises(ValueErr... | ['def', 'test_all_empty_meshes(self):', 'device', '=', 'get_random_cuda_device()', 'verts1', '=', 'torch.tensor([],', 'dtype=torch.float32,', 'device=device)', 'faces1', '=', 'torch.tensor([],', 'dtype=torch.int64,', 'device=device)', 'meshes', '=', 'Meshes(verts=[verts1,', 'verts1,', 'verts1],', 'faces=[faces1,', 'fac... | 330,157 |
ldkong1205/LaserMix | ssd_3d_head.py | SSD3DHead.get_targets | get_targets | Generate targets of 3DSSD head. | [
"Generate",
"targets",
"of",
"3DSSD",
"head."
] | def get_targets(self, points: List[Tensor], bbox_preds_dict: dict=None, batch_gt_instances_3d: List[InstanceData]=None, batch_pts_semantic_mask: List[torch.Tensor]=None, batch_pts_instance_mask: List[torch.Tensor]=None) -> Tuple[Tensor]:
batch_gt_labels_3d = [gt_instances_3d.labels_3d for gt_instances_3d in batch_g... | ['def', 'get_targets(self,', 'points:', 'List[Tensor],', 'bbox_preds_dict:', 'dict=None,', 'batch_gt_instances_3d:', 'List[InstanceData]=None,', 'batch_pts_semantic_mask:', 'List[torch.Tensor]=None,', 'batch_pts_instance_mask:', 'List[torch.Tensor]=None)', '->', 'Tuple[Tensor]:', 'batch_gt_labels_3d', '=', '[gt_instanc... | 624,039 |
MolecularAI/Siamese-RNN-Self-Attention | fingerprints.py | Fingerprint.smiles_convert | smiles_convert | Converts SMILES strings into RDKit molecules suitable for fingerprint calculation. | [
"Converts",
"SMILES",
"strings",
"into",
"RDKit",
"molecules",
"suitable",
"for",
"fingerprint",
"calculation."
] | def smiles_convert(self):
smiles_convert = [Chem.MolFromSmiles(smiles) for smiles in self.smiles]
return smiles_convert | ['def', 'smiles_convert(self):', 'smiles_convert', '=', '[Chem.MolFromSmiles(smiles)', 'for', 'smiles', 'in', 'self.smiles]', 'return', 'smiles_convert'] | 350,336 |
bm777/object_detection | nn.py | convolution_no_bias | convolution_no_bias | Apply a convolutional layer (without bias). | [
"Apply",
"a",
"convolutional",
"layer",
"(without",
"bias)."
] | def convolution_no_bias(x, k_h, k_w, c_o, s_h, s_w, name, init_w='normal', stddev=0.001, padding='SAME', group_id=0):
c_i = _get_shape(x)[-1]
convolve = lambda i, k: tf.nn.conv2d(i, k, [1, s_h, s_w, 1], padding=padding)
with tf.variable_scope(name) as scope:
w = weight('weights', [k_h, k_w, c_i, c_o... | ['def', 'convolution_no_bias(x,', 'k_h,', 'k_w,', 'c_o,', 's_h,', 's_w,', 'name,', "init_w='normal',", 'stddev=0.001,', "padding='SAME',", 'group_id=0):', 'c_i', '=', '_get_shape(x)[-1]', 'convolve', '=', 'lambda', 'i,', 'k:', 'tf.nn.conv2d(i,', 'k,', '[1,', 's_h,', 's_w,', '1],', 'padding=padding)', 'with', 'tf.variab... | 793,195 |
cszhilu1998/SelfDZSR | unprocess.py | random_gains | random_gains | Generates random gains for brightening and white balance. | [
"Generates",
"random",
"gains",
"for",
"brightening",
"and",
"white",
"balance."
] | def random_gains():
n = tdist.Normal(loc=torch.tensor([0.8]), scale=torch.tensor([0.1]))
rgb_gain = 1.0 / n.sample()
red_gain = torch.FloatTensor(1).uniform_(1.9, 2.4)
blue_gain = torch.FloatTensor(1).uniform_(1.5, 1.9)
return (rgb_gain, red_gain, blue_gain) | ['def', 'random_gains():', 'n', '=', 'tdist.Normal(loc=torch.tensor([0.8]),', 'scale=torch.tensor([0.1]))', 'rgb_gain', '=', '1.0', '/', 'n.sample()', 'red_gain', '=', 'torch.FloatTensor(1).uniform_(1.9,', '2.4)', 'blue_gain', '=', 'torch.FloatTensor(1).uniform_(1.5,', '1.9)', 'return', '(rgb_gain,', 'red_gain,', 'blue... | 342,307 |
deepmind/dm_control | camera.py | MultiplayerTrackingCamera.initialize_episode | initialize_episode | Begin the episode with the camera set to its target pose. | [
"Begin",
"the",
"episode",
"with",
"the",
"camera",
"set",
"to",
"its",
"target",
"pose."
] | def initialize_episode(self, entity_positions):
target_pose = self._get_target_camera_pose(entity_positions)
self._camera.set_pose(*target_pose) | ['def', 'initialize_episode(self,', 'entity_positions):', 'target_pose', '=', 'self._get_target_camera_pose(entity_positions)', 'self._camera.set_pose(*target_pose)'] | 165,074 |
tudelft3d/SUMS-Semantic-Urban-Mesh--public | pep425tags.py | get_abbr_impl | get_abbr_impl | Return abbreviated implementation name. | [
"Return",
"abbreviated",
"implementation",
"name."
] | def get_abbr_impl():
if hasattr(sys, 'pypy_version_info'):
pyimpl = 'pp'
elif sys.platform.startswith('java'):
pyimpl = 'jy'
elif sys.platform == 'cli':
pyimpl = 'ip'
else:
pyimpl = 'cp'
return pyimpl | ['def', 'get_abbr_impl():', 'if', 'hasattr(sys,', "'pypy_version_info'):", 'pyimpl', '=', "'pp'", 'elif', "sys.platform.startswith('java'):", 'pyimpl', '=', "'jy'", 'elif', 'sys.platform', '==', "'cli':", 'pyimpl', '=', "'ip'", 'else:', 'pyimpl', '=', "'cp'", 'return', 'pyimpl'] | 910,902 |
amartya-k/vision | phototour.py | read_info_file | read_info_file | Return a Tensor containing the list of labels Read the file and keep only the ID of the 3D point. | [
"Return",
"a",
"Tensor",
"containing",
"the",
"list",
"of",
"labels",
"Read",
"the",
"file",
"and",
"keep",
"only",
"the",
"ID",
"of",
"the",
"3D",
"point."
] | def read_info_file(data_dir: str, info_file: str) -> flow.Tensor:
with open(os.path.join(data_dir, info_file), 'r') as f:
labels = [int(line.split()[0]) for line in f]
return flow.Tensor(labels, dtype=flow.int64) | ['def', 'read_info_file(data_dir:', 'str,', 'info_file:', 'str)', '->', 'flow.Tensor:', 'with', 'open(os.path.join(data_dir,', 'info_file),', "'r')", 'as', 'f:', 'labels', '=', '[int(line.split()[0])', 'for', 'line', 'in', 'f]', 'return', 'flow.Tensor(labels,', 'dtype=flow.int64)'] | 955,885 |
deepmind/xmanager | executables.py | name_from_path | name_from_path | Returns a safe to use executable name based on a filesystem path. | [
"Returns",
"a",
"safe",
"to",
"use",
"executable",
"name",
"based",
"on",
"a",
"filesystem",
"path."
] | def name_from_path(path: str) -> str:
return re.sub('\\W', '_', os.path.basename(path.rstrip(os.sep))) | ['def', 'name_from_path(path:', 'str)', '->', 'str:', 'return', "re.sub('\\\\W',", "'_',", 'os.path.basename(path.rstrip(os.sep)))'] | 968,757 |
liqd/adhocracy | sources.py | delegation_source | delegation_source | Notify users of gained and lost delegations. | [
"Notify",
"users",
"of",
"gained",
"and",
"lost",
"delegations."
] | def delegation_source(event):
if event.event == T_DELEGATION_CREATE:
yield Notification(event, event.agent, type=N_DELEGATION_RECEIVED)
elif event.event == T_DELEGATION_REVOKE:
yield Notification(event, event.agent, type=N_DELEGATION_LOST) | ['def', 'delegation_source(event):', 'if', 'event.event', '==', 'T_DELEGATION_CREATE:', 'yield', 'Notification(event,', 'event.agent,', 'type=N_DELEGATION_RECEIVED)', 'elif', 'event.event', '==', 'T_DELEGATION_REVOKE:', 'yield', 'Notification(event,', 'event.agent,', 'type=N_DELEGATION_LOST)'] | 39,983 |
dibyaghosh/gcsl | manual_reset.py | ManualAutoDKittyResetProcedure.finish | finish | Called when the reset is complete. | [
"Called",
"when",
"the",
"reset",
"is",
"complete."
] | def finish(self):
self._wait_until_upright() | ['def', 'finish(self):', 'self._wait_until_upright()'] | 201,953 |
weimin17/Object-Detection_HelmetDetection | component.py | ComponentBuilderBase.add_regularizer | add_regularizer | Adds L2 regularization for parameters which have it turned on. | [
"Adds",
"L2",
"regularization",
"for",
"parameters",
"which",
"have",
"it",
"turned",
"on."
] | def add_regularizer(self, cost):
if self.network is None:
return cost
regularized_weights = self.network.get_l2_regularized_weights()
if not regularized_weights:
return cost
l2_coeff = self.master.hyperparams.l2_regularization_coefficient
if l2_coeff == 0.0:
return cost
t... | ['def', 'add_regularizer(self,', 'cost):', 'if', 'self.network', 'is', 'None:', 'return', 'cost', 'regularized_weights', '=', 'self.network.get_l2_regularized_weights()', 'if', 'not', 'regularized_weights:', 'return', 'cost', 'l2_coeff', '=', 'self.master.hyperparams.l2_regularization_coefficient', 'if', 'l2_coeff', '=... | 753,262 |
weimin17/Object-Detection_HelmetDetection | run_lfads.py | clean_data_dict | clean_data_dict | Add some key/value pairs to the data dict, if they are missing. | [
"Add",
"some",
"key/value",
"pairs",
"to",
"the",
"data",
"dict,",
"if",
"they",
"are",
"missing."
] | def clean_data_dict(data_dict):
keys = ['train_truth', 'train_ext_input', 'valid_data', 'valid_truth', 'valid_ext_input', 'valid_train']
for k in keys:
if k not in data_dict:
data_dict[k] = None
return data_dict | ['def', 'clean_data_dict(data_dict):', 'keys', '=', "['train_truth',", "'train_ext_input',", "'valid_data',", "'valid_truth',", "'valid_ext_input',", "'valid_train']", 'for', 'k', 'in', 'keys:', 'if', 'k', 'not', 'in', 'data_dict:', 'data_dict[k]', '=', 'None', 'return', 'data_dict'] | 757,833 |
danamyu/hedgehog_detector | train_eval.py | batch_of_random_bools | batch_of_random_bools | Return a batch of random "boolean" numbers. | [
"Return",
"a",
"batch",
"of",
"random",
"\"boolean\"",
"numbers."
] | def batch_of_random_bools(batch_size, n):
as_int = tf.random_uniform([batch_size, n], minval=0, maxval=2, dtype=tf.int32)
expanded_range = as_int * 2 - 1
return tf.cast(expanded_range, tf.float32) | ['def', 'batch_of_random_bools(batch_size,', 'n):', 'as_int', '=', 'tf.random_uniform([batch_size,', 'n],', 'minval=0,', 'maxval=2,', 'dtype=tf.int32)', 'expanded_range', '=', 'as_int', '*', '2', '-', '1', 'return', 'tf.cast(expanded_range,', 'tf.float32)'] | 589,174 |
suarez12138/AI-Reversi_IMP_TextDichotomy | transforms.py | Bbox.set | set | Set this bounding box from the "frozen" bounds of another `Bbox`. | [
"Set",
"this",
"bounding",
"box",
"from",
"the",
"\"frozen\"",
"bounds",
"of",
"another",
"`Bbox`."
] | def set(self, other):
if np.any(self._points != other.get_points()):
self._points = other.get_points()
self.invalidate() | ['def', 'set(self,', 'other):', 'if', 'np.any(self._points', '!=', 'other.get_points()):', 'self._points', '=', 'other.get_points()', 'self.invalidate()'] | 96,900 |
BMW-InnovationLab/BMW-Semantic--Training-GUI | monodepth2.py | get_monodepth2_resnet18_kitti_mono_stereo_640x192 | get_monodepth2_resnet18_kitti_mono_stereo_640x192 | Monodepth2 Parameters ---------- backbone : string Pre-trained dilated backbone network type (default:'resnet18'). | [
"Monodepth2",
"Parameters",
"----------",
"backbone",
":",
"string",
"Pre-trained",
"dilated",
"backbone",
"network",
"type",
"(default:'resnet18')."
] | def get_monodepth2_resnet18_kitti_mono_stereo_640x192(**kwargs):
return get_monodepth2(backbone='resnet18', pretrained_model='kitti_mono_stereo_640x192', **kwargs) | ['def', 'get_monodepth2_resnet18_kitti_mono_stereo_640x192(**kwargs):', 'return', "get_monodepth2(backbone='resnet18',", "pretrained_model='kitti_mono_stereo_640x192',", '**kwargs)'] | 462,739 |
zhang614/MicroGrid | test_peak_finding.py | TestFindPeaks.test_plateau_size | test_plateau_size | Test plateau size condition for peaks. | [
"Test",
"plateau",
"size",
"condition",
"for",
"peaks."
] | def test_plateau_size(self):
plateau_sizes = np.array([1, 2, 3, 4, 8, 20, 111])
x = np.zeros(plateau_sizes.size * 2 + 1)
x[1::2] = plateau_sizes
repeats = np.ones(x.size, dtype=int)
repeats[1::2] = x[1::2]
x = np.repeat(x, repeats)
(peaks, props) = find_peaks(x, plateau_size=(None, None))
... | ['def', 'test_plateau_size(self):', 'plateau_sizes', '=', 'np.array([1,', '2,', '3,', '4,', '8,', '20,', '111])', 'x', '=', 'np.zeros(plateau_sizes.size', '*', '2', '+', '1)', 'x[1::2]', '=', 'plateau_sizes', 'repeats', '=', 'np.ones(x.size,', 'dtype=int)', 'repeats[1::2]', '=', 'x[1::2]', 'x', '=', 'np.repeat(x,', 're... | 669,713 |
Katja-M/Python_NaturalLanguageProcessing | testing.py | HTMLTreeBuilderSmokeTest.test_normal_doctypes | test_normal_doctypes | Make sure normal, everyday HTML doctypes are handled correctly. | [
"Make",
"sure",
"normal,",
"everyday",
"HTML",
"doctypes",
"are",
"handled",
"correctly."
] | def test_normal_doctypes(self):
self.assertDoctypeHandled('html')
self.assertDoctypeHandled('html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"') | ['def', 'test_normal_doctypes(self):', "self.assertDoctypeHandled('html')", "self.assertDoctypeHandled('html", 'PUBLIC', '"-//W3C//DTD', 'XHTML', '1.0', 'Transitional//EN"\')'] | 863,954 |
tomcatmanager/tomcatmanager | mock_server_ssl.py | MockRequestHandlerSSL.authorized | authorized | Check authorization and return True or False. | [
"Check",
"authorization",
"and",
"return",
"True",
"or",
"False."
] | def authorized(self):
if self.headers.get('Authorization') == 'Basic ' + self.AUTH_KEY:
return True
self.send_response(requests.codes.unauthorized)
self.send_header('WWW-Authenticate', 'Basic realm="tomcatmanager"')
self.send_header('Content-type', 'text/html')
self.end_headers()
msg = '... | ['def', 'authorized(self):', 'if', "self.headers.get('Authorization')", '==', "'Basic", "'", '+', 'self.AUTH_KEY:', 'return', 'True', 'self.send_response(requests.codes.unauthorized)', "self.send_header('WWW-Authenticate',", "'Basic", 'realm="tomcatmanager"\')', "self.send_header('Content-type',", "'text/html')", 'self... | 355,656 |
wandb/wandb | utils.py | construct_launch_spec | construct_launch_spec | Construct the launch specification from CLI arguments. | [
"Construct",
"the",
"launch",
"specification",
"from",
"CLI",
"arguments."
] | def construct_launch_spec(uri: Optional[str], job: Optional[str], api: Api, name: Optional[str], project: Optional[str], entity: Optional[str], docker_image: Optional[str], resource: Optional[str], entry_point: Optional[List[str]], version: Optional[str], resource_args: Optional[Dict[str, Any]], launch_config: Optional... | ['def', 'construct_launch_spec(uri:', 'Optional[str],', 'job:', 'Optional[str],', 'api:', 'Api,', 'name:', 'Optional[str],', 'project:', 'Optional[str],', 'entity:', 'Optional[str],', 'docker_image:', 'Optional[str],', 'resource:', 'Optional[str],', 'entry_point:', 'Optional[List[str]],', 'version:', 'Optional[str],', ... | 941,752 |
Jamie725/Multimodal-Object-Detection-via-Probabilistic-Ensembling | visualizer.py | Visualizer.draw_panoptic_seg_predictions | draw_panoptic_seg_predictions | Draw panoptic prediction results on an image. | [
"Draw",
"panoptic",
"prediction",
"results",
"on",
"an",
"image."
] | def draw_panoptic_seg_predictions(self, panoptic_seg, segments_info, area_threshold=None, alpha=0.7):
pred = _PanopticPrediction(panoptic_seg, segments_info)
if self._instance_mode == ColorMode.IMAGE_BW:
self.output.img = self._create_grayscale_image(pred.non_empty_mask())
for (mask, sinfo) in pred.... | ['def', 'draw_panoptic_seg_predictions(self,', 'panoptic_seg,', 'segments_info,', 'area_threshold=None,', 'alpha=0.7):', 'pred', '=', '_PanopticPrediction(panoptic_seg,', 'segments_info)', 'if', 'self._instance_mode', '==', 'ColorMode.IMAGE_BW:', 'self.output.img', '=', 'self._create_grayscale_image(pred.non_empty_mask... | 644,005 |
HCIILAB/DeRPN | cpp_lint.py | CheckForCopyright | CheckForCopyright | Logs an error if a Copyright message appears at the top of the file. | [
"Logs",
"an",
"error",
"if",
"a",
"Copyright",
"message",
"appears",
"at",
"the",
"top",
"of",
"the",
"file."
] | def CheckForCopyright(filename, lines, error):
for line in xrange(1, min(len(lines), 11)):
if _RE_COPYRIGHT.search(lines[line], re.I):
error(filename, 0, 'legal/copyright', 5, 'Copyright message found. You should not include a copyright line.') | ['def', 'CheckForCopyright(filename,', 'lines,', 'error):', 'for', 'line', 'in', 'xrange(1,', 'min(len(lines),', '11)):', 'if', '_RE_COPYRIGHT.search(lines[line],', 're.I):', 'error(filename,', '0,', "'legal/copyright',", '5,', "'Copyright", 'message', 'found.', 'You', 'should', 'not', 'include', 'a', 'copyright', "lin... | 184,081 |
tychovdo/PacmanDQN | pacman.py | PacmanRules.getLegalActions | getLegalActions | Returns a list of possible actions. | [
"Returns",
"a",
"list",
"of",
"possible",
"actions."
] | def getLegalActions(state):
return Actions.getPossibleActions(state.getPacmanState().configuration, state.data.layout.walls) | ['def', 'getLegalActions(state):', 'return', 'Actions.getPossibleActions(state.getPacmanState().configuration,', 'state.data.layout.walls)'] | 255,781 |
cjrd/self-supervised-pretraining | events.py | EventStorage.put_histogram | put_histogram | Create a histogram from a tensor. | [
"Create",
"a",
"histogram",
"from",
"a",
"tensor."
] | def put_histogram(self, hist_name, hist_tensor, bins=1000):
(ht_min, ht_max) = (hist_tensor.min().item(), hist_tensor.max().item())
hist_counts = torch.histc(hist_tensor, bins=bins)
hist_edges = torch.linspace(start=ht_min, end=ht_max, steps=bins + 1, dtype=torch.float32)
hist_params = dict(tag=hist_nam... | ['def', 'put_histogram(self,', 'hist_name,', 'hist_tensor,', 'bins=1000):', '(ht_min,', 'ht_max)', '=', '(hist_tensor.min().item(),', 'hist_tensor.max().item())', 'hist_counts', '=', 'torch.histc(hist_tensor,', 'bins=bins)', 'hist_edges', '=', 'torch.linspace(start=ht_min,', 'end=ht_max,', 'steps=bins', '+', '1,', 'dty... | 843,651 |
RasaHQ/rasa | test.py | pick_best_entity_fit | pick_best_entity_fit | Determines the best fitting entity given intersecting entities. | [
"Determines",
"the",
"best",
"fitting",
"entity",
"given",
"intersecting",
"entities."
] | def pick_best_entity_fit(token: Token, candidates: List[Dict[Text, Any]]) -> Optional[Dict[Text, Any]]:
if len(candidates) == 0:
return None
elif len(candidates) == 1:
return candidates[0]
else:
best_fit = np.argmax([determine_intersection(token, c) for c in candidates])
retu... | ['def', 'pick_best_entity_fit(token:', 'Token,', 'candidates:', 'List[Dict[Text,', 'Any]])', '->', 'Optional[Dict[Text,', 'Any]]:', 'if', 'len(candidates)', '==', '0:', 'return', 'None', 'elif', 'len(candidates)', '==', '1:', 'return', 'candidates[0]', 'else:', 'best_fit', '=', 'np.argmax([determine_intersection(token,... | 837,121 |
nemanja-rakicevic/informed_search | modelling.py | InformedSearch.update_model | update_model | Select successful trials to estimate the GPR model's mean and variance, and the failed ones to update the penalisation IDF. | [
"Select",
"successful",
"trials",
"to",
"estimate",
"the",
"GPR",
"model's",
"mean",
"and",
"variance,",
"and",
"the",
"failed",
"ones",
"to",
"update",
"the",
"penalisation",
"IDF."
] | def update_model(self, info_list, save_model_progress=False, **kwargs):
if len(info_list):
if info_list[-1]['fail_status'] == 0:
good_params = np.vstack([tr['parameters'] for tr in info_list if tr['fail_status'] == 0])
good_fevals = np.vstack([tr['ball_polar'] for tr in info_list if ... | ['def', 'update_model(self,', 'info_list,', 'save_model_progress=False,', '**kwargs):', 'if', 'len(info_list):', 'if', "info_list[-1]['fail_status']", '==', '0:', 'good_params', '=', "np.vstack([tr['parameters']", 'for', 'tr', 'in', 'info_list', 'if', "tr['fail_status']", '==', '0])', 'good_fevals', '=', "np.vstack([tr... | 612,614 |
jelgun/Artificial-Intelligence | csp.py | CSP.goal_test | goal_test | The goal is to assign all variables, with all constraints satisfied. | [
"The",
"goal",
"is",
"to",
"assign",
"all",
"variables,",
"with",
"all",
"constraints",
"satisfied."
] | def goal_test(self, state):
assignment = dict(state)
return len(assignment) == len(self.variables) and all((self.nconflicts(variables, assignment[variables], assignment) == 0 for variables in self.variables)) | ['def', 'goal_test(self,', 'state):', 'assignment', '=', 'dict(state)', 'return', 'len(assignment)', '==', 'len(self.variables)', 'and', 'all((self.nconflicts(variables,', 'assignment[variables],', 'assignment)', '==', '0', 'for', 'variables', 'in', 'self.variables))'] | 116,079 |
arshpreetsingh/quantopian-machinelearning | markers.py | Evaluator.evaluate | evaluate | Evaluate a marker expression returned by the :func:`parse_requirement` function in the specified context. | [
"Evaluate",
"a",
"marker",
"expression",
"returned",
"by",
"the",
":func:`parse_requirement`",
"function",
"in",
"the",
"specified",
"context."
] | def evaluate(self, expr, context):
if isinstance(expr, string_types):
if expr[0] in '\'"':
result = expr[1:-1]
else:
if expr not in context:
raise SyntaxError('unknown variable: %s' % expr)
result = context[expr]
else:
assert isinstance... | ['def', 'evaluate(self,', 'expr,', 'context):', 'if', 'isinstance(expr,', 'string_types):', 'if', 'expr[0]', 'in', '\'\\\'"\':', 'result', '=', 'expr[1:-1]', 'else:', 'if', 'expr', 'not', 'in', 'context:', 'raise', "SyntaxError('unknown", 'variable:', "%s'", '%', 'expr)', 'result', '=', 'context[expr]', 'else:', 'asser... | 891,517 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | thinkstats2.py | Interpolator.Lookup | Lookup | Looks up x and returns the corresponding value of y. | [
"Looks",
"up",
"x",
"and",
"returns",
"the",
"corresponding",
"value",
"of",
"y."
] | def Lookup(self, x):
return self._Bisect(x, self.xs, self.ys) | ['def', 'Lookup(self,', 'x):', 'return', 'self._Bisect(x,', 'self.xs,', 'self.ys)'] | 19,739 |
Showmax/conveiro | utils.py | bgr_to_rgb | bgr_to_rgb | Swap blue and red channel in an image. | [
"Swap",
"blue",
"and",
"red",
"channel",
"in",
"an",
"image."
] | def bgr_to_rgb(image):
image = image.copy()
tmp = image[..., 0].copy()
image[..., 0] = image[..., 2]
image[..., 2] = tmp
return image | ['def', 'bgr_to_rgb(image):', 'image', '=', 'image.copy()', 'tmp', '=', 'image[...,', '0].copy()', 'image[...,', '0]', '=', 'image[...,', '2]', 'image[...,', '2]', '=', 'tmp', 'return', 'image'] | 136,812 |
jbalogh/jingo | __init__.py | get_env | get_env | Configure and return a jinja2 Environment. | [
"Configure",
"and",
"return",
"a",
"jinja2",
"Environment."
] | def get_env():
global _env
if _env:
return _env
loaders = [jinja2.FileSystemLoader(d) for d in settings.TEMPLATE_DIRS]
loaders += [jinja2.PackageLoader(c.name) for c in apps.get_app_configs()]
opts = {'trim_blocks': True, 'extensions': ['jinja2.ext.i18n', 'jingo.ext.JingoExtension'], 'autoes... | ['def', 'get_env():', 'global', '_env', 'if', '_env:', 'return', '_env', 'loaders', '=', '[jinja2.FileSystemLoader(d)', 'for', 'd', 'in', 'settings.TEMPLATE_DIRS]', 'loaders', '+=', '[jinja2.PackageLoader(c.name)', 'for', 'c', 'in', 'apps.get_app_configs()]', 'opts', '=', "{'trim_blocks':", 'True,', "'extensions':", "[... | 247,128 |
gunthercox/ChatterBot | extract.py | extract_nothing | extract_nothing | Pseudo extractor that does not actually extract anything, but simply returns an empty list. | [
"Pseudo",
"extractor",
"that",
"does",
"not",
"actually",
"extract",
"anything,",
"but",
"simply",
"returns",
"an",
"empty",
"list."
] | def extract_nothing(fileobj, keywords, comment_tags, options):
return [] | ['def', 'extract_nothing(fileobj,', 'keywords,', 'comment_tags,', 'options):', 'return', '[]'] | 528,700 |
hyz-xmaster/swa_object_detection | yolact.py | YOLACT.simple_test | simple_test | Test function without test time augmentation. | [
"Test",
"function",
"without",
"test",
"time",
"augmentation."
] | def simple_test(self, img, img_metas, rescale=False):
x = self.extract_feat(img)
(cls_score, bbox_pred, coeff_pred) = self.bbox_head(x)
bbox_inputs = (cls_score, bbox_pred, coeff_pred) + (img_metas, self.test_cfg, rescale)
(det_bboxes, det_labels, det_coeffs) = self.bbox_head.get_bboxes(*bbox_inputs)
... | ['def', 'simple_test(self,', 'img,', 'img_metas,', 'rescale=False):', 'x', '=', 'self.extract_feat(img)', '(cls_score,', 'bbox_pred,', 'coeff_pred)', '=', 'self.bbox_head(x)', 'bbox_inputs', '=', '(cls_score,', 'bbox_pred,', 'coeff_pred)', '+', '(img_metas,', 'self.test_cfg,', 'rescale)', '(det_bboxes,', 'det_labels,',... | 882,635 |
Cheng-Lin-Li/AI | inference.py | DiscreteDistribution.total | total | Return the sum of values for all keys. | [
"Return",
"the",
"sum",
"of",
"values",
"for",
"all",
"keys."
] | def total(self):
return float(sum(self.values())) | ['def', 'total(self):', 'return', 'float(sum(self.values()))'] | 67,349 |
bnpy/bnpy | BernObsModel.py | calcSummaryStats | calcSummaryStats | Calculate summary statistics for given dataset and local parameters Returns -------- SS : SuffStatBag object, with K components. | [
"Calculate",
"summary",
"statistics",
"for",
"given",
"dataset",
"and",
"local",
"parameters",
"Returns",
"--------",
"SS",
":",
"SuffStatBag",
"object,",
"with",
"K",
"components."
] | def calcSummaryStats(Dslice, SS, LP, DataAtomType='doc', **kwargs):
if 'resp' in LP:
N = LP['resp'].shape[0]
K = LP['resp'].shape[1]
if LP['resp'].ndim == 2:
CompDims = ('K',)
else:
assert LP['resp'].ndim == 3
CompDims = ('K', 'K')
else:
... | ['def', 'calcSummaryStats(Dslice,', 'SS,', 'LP,', "DataAtomType='doc',", '**kwargs):', 'if', "'resp'", 'in', 'LP:', 'N', '=', "LP['resp'].shape[0]", 'K', '=', "LP['resp'].shape[1]", 'if', "LP['resp'].ndim", '==', '2:', 'CompDims', '=', "('K',)", 'else:', 'assert', "LP['resp'].ndim", '==', '3', 'CompDims', '=', "('K',",... | 464,919 |
zhangyp15/MonoFlex | comm.py | reduce_dict | reduce_dict | Reduce the values in the dictionary from all processes so that process with rank 0 has the reduced results. | [
"Reduce",
"the",
"values",
"in",
"the",
"dictionary",
"from",
"all",
"processes",
"so",
"that",
"process",
"with",
"rank",
"0",
"has",
"the",
"reduced",
"results."
] | def reduce_dict(input_dict, average=True):
world_size = get_world_size()
if world_size < 2:
return input_dict
with torch.no_grad():
names = []
values = []
for k in sorted(input_dict.keys()):
names.append(k)
values.append(input_dict[k])
values =... | ['def', 'reduce_dict(input_dict,', 'average=True):', 'world_size', '=', 'get_world_size()', 'if', 'world_size', '<', '2:', 'return', 'input_dict', 'with', 'torch.no_grad():', 'names', '=', '[]', 'values', '=', '[]', 'for', 'k', 'in', 'sorted(input_dict.keys()):', 'names.append(k)', 'values.append(input_dict[k])', 'valu... | 655,196 |
meidachen/STPLS3D | cindex.py | TypeKind.spelling | spelling | Retrieve the spelling of this TypeKind. | [
"Retrieve",
"the",
"spelling",
"of",
"this",
"TypeKind."
] | def spelling(self):
return conf.lib.clang_getTypeKindSpelling(self.value) | ['def', 'spelling(self):', 'return', 'conf.lib.clang_getTypeKindSpelling(self.value)'] | 909,171 |
suarez12138/AI-Reversi_IMP_TextDichotomy | backend_bases.py | RendererBase.option_scale_image | option_scale_image | Return whether arbitrary affine transformations in :meth:`draw_image` are supported (True for most vector backends). | [
"Return",
"whether",
"arbitrary",
"affine",
"transformations",
"in",
":meth:`draw_image`",
"are",
"supported",
"(True",
"for",
"most",
"vector",
"backends)."
] | def option_scale_image(self):
return False | ['def', 'option_scale_image(self):', 'return', 'False'] | 96,141 |
gopinath-balu/computer_vision | config_util_test.py | ConfigUtilTest.testNewTrainInputPathList | testNewTrainInputPathList | Tests that train input path can be overwritten with multiple files. | [
"Tests",
"that",
"train",
"input",
"path",
"can",
"be",
"overwritten",
"with",
"multiple",
"files."
] | def testNewTrainInputPathList(self):
original_train_path = ['path/to/data']
new_train_path = ['another/path/to/data', 'yet/another/path/to/data']
pipeline_config_path = os.path.join(self.get_temp_dir(), 'pipeline.config')
pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
reader_config = pipel... | ['def', 'testNewTrainInputPathList(self):', 'original_train_path', '=', "['path/to/data']", 'new_train_path', '=', "['another/path/to/data',", "'yet/another/path/to/data']", 'pipeline_config_path', '=', 'os.path.join(self.get_temp_dir(),', "'pipeline.config')", 'pipeline_config', '=', 'pipeline_pb2.TrainEvalPipelineCon... | 512,294 |
myothida/Supervised-Machine-Learning | rcsetup.py | validate_fonttype | validate_fonttype | Confirm that this is a Postscript or PDF font type that we know how to convert to. | [
"Confirm",
"that",
"this",
"is",
"a",
"Postscript",
"or",
"PDF",
"font",
"type",
"that",
"we",
"know",
"how",
"to",
"convert",
"to."
] | def validate_fonttype(s):
fonttypes = {'type3': 3, 'truetype': 42}
try:
fonttype = validate_int(s)
except ValueError:
try:
return fonttypes[s.lower()]
except KeyError as e:
raise ValueError('Supported Postscript/PDF font types are %s' % list(fonttypes)) from e... | ['def', 'validate_fonttype(s):', 'fonttypes', '=', "{'type3':", '3,', "'truetype':", '42}', 'try:', 'fonttype', '=', 'validate_int(s)', 'except', 'ValueError:', 'try:', 'return', 'fonttypes[s.lower()]', 'except', 'KeyError', 'as', 'e:', 'raise', "ValueError('Supported", 'Postscript/PDF', 'font', 'types', 'are', "%s'", ... | 362,228 |
yahyaizala/Natural-Language-Processing | base.py | LoadFile.unescape_punctuation_marks | unescape_punctuation_marks | Replaces the special punctuation marks produced by CoreNLP. | [
"Replaces",
"the",
"special",
"punctuation",
"marks",
"produced",
"by",
"CoreNLP."
] | def unescape_punctuation_marks(self):
for (i, sentence) in enumerate(self.sentences):
for (j, word) in enumerate(sentence.words):
l_word = word.lower()
self.sentences[i].words[j] = escaped_punctuation.get(l_word, word) | ['def', 'unescape_punctuation_marks(self):', 'for', '(i,', 'sentence)', 'in', 'enumerate(self.sentences):', 'for', '(j,', 'word)', 'in', 'enumerate(sentence.words):', 'l_word', '=', 'word.lower()', 'self.sentences[i].words[j]', '=', 'escaped_punctuation.get(l_word,', 'word)'] | 637,333 |
supernlogn/squeezeDetTL | hyperparam_tuner.py | parse_mc | parse_mc | Parses all mc to find hopt vars to hyperoptimize and to edit in every hyperoptimization iteration. | [
"Parses",
"all",
"mc",
"to",
"find",
"hopt",
"vars",
"to",
"hyperoptimize",
"and",
"to",
"edit",
"in",
"every",
"hyperoptimization",
"iteration."
] | def parse_mc(mc):
hopt_vars = []
for x in mc.keys():
(val_ar, r) = parse_mc_option(mc[x], hfuncs)
if r != None:
hopt_vars.append((x, val_ar, r))
else:
mc[x] = val_ar
new_mc = edict(mc.copy())
return (new_mc, hopt_vars) | ['def', 'parse_mc(mc):', 'hopt_vars', '=', '[]', 'for', 'x', 'in', 'mc.keys():', '(val_ar,', 'r)', '=', 'parse_mc_option(mc[x],', 'hfuncs)', 'if', 'r', '!=', 'None:', 'hopt_vars.append((x,', 'val_ar,', 'r))', 'else:', 'mc[x]', '=', 'val_ar', 'new_mc', '=', 'edict(mc.copy())', 'return', '(new_mc,', 'hopt_vars)'] | 897,332 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.