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 |
|---|---|---|---|---|---|---|---|---|
matsu0228/nlp-jp | markers.py | Evaluator.get_fragment | get_fragment | Get the part of the source which is causing a problem. | [
"Get",
"the",
"part",
"of",
"the",
"source",
"which",
"is",
"causing",
"a",
"problem."
] | def get_fragment(self, offset):
fragment_len = 10
s = '%r' % self.source[offset:offset + fragment_len]
if offset + fragment_len < len(self.source):
s += '...'
return s | ['def', 'get_fragment(self,', 'offset):', 'fragment_len', '=', '10', 's', '=', "'%r'", '%', 'self.source[offset:offset', '+', 'fragment_len]', 'if', 'offset', '+', 'fragment_len', '<', 'len(self.source):', 's', '+=', "'...'", 'return', 's'] | 803,640 |
43Carrig/recurrent_neural_networks_practice | estimator.py | BaseEstimator.get_variable_value | get_variable_value | Returns value of the variable given by name. | [
"Returns",
"value",
"of",
"the",
"variable",
"given",
"by",
"name."
] | def get_variable_value(self, name):
return load_variable(self.model_dir, name) | ['def', 'get_variable_value(self,', 'name):', 'return', 'load_variable(self.model_dir,', 'name)'] | 313,614 |
Cihsaing/RVSL-rvsl-robust-vehicle-similarity-learning--ECCV22 | _amp_state.py | master_params | master_params | Generator expression that iterates over the params owned by ``optimizer``. | [
"Generator",
"expression",
"that",
"iterates",
"over",
"the",
"params",
"owned",
"by",
"``optimizer``."
] | def master_params(optimizer):
for group in optimizer.param_groups:
for p in group['params']:
yield p | ['def', 'master_params(optimizer):', 'for', 'group', 'in', 'optimizer.param_groups:', 'for', 'p', 'in', "group['params']:", 'yield', 'p'] | 327,059 |
chainer/chainerrl | train_soft_actor_critic.py | concat_obs_and_action | concat_obs_and_action | Concat observation and action to feed the critic. | [
"Concat",
"observation",
"and",
"action",
"to",
"feed",
"the",
"critic."
] | def concat_obs_and_action(obs, action):
return F.concat((obs, action), axis=-1) | ['def', 'concat_obs_and_action(obs,', 'action):', 'return', 'F.concat((obs,', 'action),', 'axis=-1)'] | 104,496 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | dsn.py | add_task_loss | add_task_loss | Adds a classification and/or pose estimation loss to the model. | [
"Adds",
"a",
"classification",
"and/or",
"pose",
"estimation",
"loss",
"to",
"the",
"model."
] | def add_task_loss(source_images, source_labels, basic_tower, params):
with tf.variable_scope('towers'):
(source_logits, source_endpoints) = basic_tower(source_images, weight_decay=params['weight_decay'], prefix='Source')
if 'quaternions' in source_labels:
if 'quaternion_pred' not in source_endpo... | ['def', 'add_task_loss(source_images,', 'source_labels,', 'basic_tower,', 'params):', 'with', "tf.variable_scope('towers'):", '(source_logits,', 'source_endpoints)', '=', 'basic_tower(source_images,', "weight_decay=params['weight_decay'],", "prefix='Source')", 'if', "'quaternions'", 'in', 'source_labels:', 'if', "'quat... | 47,926 |
suarez12138/AI-Reversi_IMP_TextDichotomy | axis.py | Axis.get_ticklabel_extents | get_ticklabel_extents | Get the extents of the tick labels on either side of the axes. | [
"Get",
"the",
"extents",
"of",
"the",
"tick",
"labels",
"on",
"either",
"side",
"of",
"the",
"axes."
] | def get_ticklabel_extents(self, renderer):
ticks_to_draw = self._update_ticks()
(ticklabelBoxes, ticklabelBoxes2) = self._get_tick_bboxes(ticks_to_draw, renderer)
if len(ticklabelBoxes):
bbox = mtransforms.Bbox.union(ticklabelBoxes)
else:
bbox = mtransforms.Bbox.from_extents(0, 0, 0, 0)
... | ['def', 'get_ticklabel_extents(self,', 'renderer):', 'ticks_to_draw', '=', 'self._update_ticks()', '(ticklabelBoxes,', 'ticklabelBoxes2)', '=', 'self._get_tick_bboxes(ticks_to_draw,', 'renderer)', 'if', 'len(ticklabelBoxes):', 'bbox', '=', 'mtransforms.Bbox.union(ticklabelBoxes)', 'else:', 'bbox', '=', 'mtransforms.Bbo... | 96,072 |
ryu-ed/SpaceInvaders_Ros | scrap_test.py | ScrapModuleClipboardNotOwnedTest.test_get_types__not_owned | test_get_types__not_owned | Ensures get_types works when the clipboard is not owned by the pygame application. | [
"Ensures",
"get_types",
"works",
"when",
"the",
"clipboard",
"is",
"not",
"owned",
"by",
"the",
"pygame",
"application."
] | def test_get_types__not_owned(self):
self._skip_if_clipboard_owned()
data_types = scrap.get_types()
self.assertIsInstance(data_types, list) | ['def', 'test_get_types__not_owned(self):', 'self._skip_if_clipboard_owned()', 'data_types', '=', 'scrap.get_types()', 'self.assertIsInstance(data_types,', 'list)'] | 369,153 |
bradfitz/scanningcabinet | model.py | MediaObject.is_image | is_image | Returns True if this media object is an image. | [
"Returns",
"True",
"if",
"this",
"media",
"object",
"is",
"an",
"image."
] | def is_image(self):
image_types = frozenset(['image/png', 'image/jpeg', 'image/tiff', 'image/gif', 'image/bmp'])
return self.guessed_type in image_types | ['def', 'is_image(self):', 'image_types', '=', "frozenset(['image/png',", "'image/jpeg',", "'image/tiff',", "'image/gif',", "'image/bmp'])", 'return', 'self.guessed_type', 'in', 'image_types'] | 329,433 |
arxyzan/data2vec-pytorch | trainer.py | TextTrainer.test_step | test_step | Test a model on one batch of data and return loss. | [
"Test",
"a",
"model",
"on",
"one",
"batch",
"of",
"data",
"and",
"return",
"loss."
] | def test_step(self, batch):
src = batch['input_ids'].to(self.device)
trg = batch['labels'].to(self.device)
mask = batch['masked_indices'].to(self.device)
(x, y) = self.model(src, trg, mask=mask)
loss = self.criterion(x, y)
return loss.item() | ['def', 'test_step(self,', 'batch):', 'src', '=', "batch['input_ids'].to(self.device)", 'trg', '=', "batch['labels'].to(self.device)", 'mask', '=', "batch['masked_indices'].to(self.device)", '(x,', 'y)', '=', 'self.model(src,', 'trg,', 'mask=mask)', 'loss', '=', 'self.criterion(x,', 'y)', 'return', 'loss.item()'] | 126,788 |
clips/pattern | inflect.py | attributive | attributive | For a predicative adjective, returns the attributive form. | [
"For",
"a",
"predicative",
"adjective,",
"returns",
"the",
"attributive",
"form."
] | def attributive(adjective):
raise NotImplementedError | ['def', 'attributive(adjective):', 'raise', 'NotImplementedError'] | 764,937 |
voxel51/fiftyone | cvat.py | CVATAnnotationAPI.download_annotations | download_annotations | Download the annotations from the CVAT server for the given results instance and parses them into the appropriate FiftyOne types. | [
"Download",
"the",
"annotations",
"from",
"the",
"CVAT",
"server",
"for",
"the",
"given",
"results",
"instance",
"and",
"parses",
"them",
"into",
"the",
"appropriate",
"FiftyOne",
"types."
] | def download_annotations(self, results):
label_schema = results.config.label_schema
occluded_attr = results.config.occluded_attr
group_id_attr = results.config.group_id_attr
id_map = results.id_map
server_id_map = results.server_id_map
task_ids = results.task_ids
frame_id_map = results.frame... | ['def', 'download_annotations(self,', 'results):', 'label_schema', '=', 'results.config.label_schema', 'occluded_attr', '=', 'results.config.occluded_attr', 'group_id_attr', '=', 'results.config.group_id_attr', 'id_map', '=', 'results.id_map', 'server_id_map', '=', 'results.server_id_map', 'task_ids', '=', 'results.tas... | 584,014 |
Farama-Foundation/Gymnasium | jax_to_numpy.py | JaxToNumpyV0.step | step | Transforms the action to a jax array . | [
"Transforms",
"the",
"action",
"to",
"a",
"jax",
"array",
"."
] | def step(self, action: WrapperActType) -> tuple[WrapperObsType, SupportsFloat, bool, bool, dict]:
jax_action = numpy_to_jax(action)
(obs, reward, terminated, truncated, info) = self.env.step(jax_action)
return (jax_to_numpy(obs), float(reward), bool(terminated), bool(truncated), jax_to_numpy(info)) | ['def', 'step(self,', 'action:', 'WrapperActType)', '->', 'tuple[WrapperObsType,', 'SupportsFloat,', 'bool,', 'bool,', 'dict]:', 'jax_action', '=', 'numpy_to_jax(action)', '(obs,', 'reward,', 'terminated,', 'truncated,', 'info)', '=', 'self.env.step(jax_action)', 'return', '(jax_to_numpy(obs),', 'float(reward),', 'bool... | 573,163 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | visitor.py | MethodContent.acceptBreak | acceptBreak | Accept and process a break statement. | [
"Accept",
"and",
"process",
"a",
"break",
"statement."
] | def acceptBreak(self, node, memo):
(insert, ok_types) = (True, [tokens.WHILE, tokens.DO, tokens.FOR])
for parent in node.parents():
if parent.type == tokens.SWITCH:
insert = False
break
if parent.type in ok_types:
break
if insert:
if len(node.child... | ['def', 'acceptBreak(self,', 'node,', 'memo):', '(insert,', 'ok_types)', '=', '(True,', '[tokens.WHILE,', 'tokens.DO,', 'tokens.FOR])', 'for', 'parent', 'in', 'node.parents():', 'if', 'parent.type', '==', 'tokens.SWITCH:', 'insert', '=', 'False', 'break', 'if', 'parent.type', 'in', 'ok_types:', 'break', 'if', 'insert:'... | 11,201 |
nicknochnack/RealTimeSignLanguageTFJS | nas_network.py | nas_arg_scope | nas_arg_scope | Default arg scope for the NAS models. | [
"Default",
"arg",
"scope",
"for",
"the",
"NAS",
"models."
] | def nas_arg_scope(weight_decay=4e-05, batch_norm_decay=0.9997, batch_norm_epsilon=0.001, sync_batch_norm_method='None'):
batch_norm_params = {'decay': batch_norm_decay, 'epsilon': batch_norm_epsilon, 'scale': True}
batch_norm = utils.get_batch_norm_fn(sync_batch_norm_method)
weights_regularizer = contrib_la... | ['def', 'nas_arg_scope(weight_decay=4e-05,', 'batch_norm_decay=0.9997,', 'batch_norm_epsilon=0.001,', "sync_batch_norm_method='None'):", 'batch_norm_params', '=', "{'decay':", 'batch_norm_decay,', "'epsilon':", 'batch_norm_epsilon,', "'scale':", 'True}', 'batch_norm', '=', 'utils.get_batch_norm_fn(sync_batch_norm_metho... | 851,531 |
AISIGSJTU/SSVS | base_options.py | BaseOptions.parse | parse | Parse our options, create checkpoints directory suffix, and set up gpu device. | [
"Parse",
"our",
"options,",
"create",
"checkpoints",
"directory",
"suffix,",
"and",
"set",
"up",
"gpu",
"device."
] | def parse(self):
opt = self.gather_options()
opt.isTrain = self.isTrain
if opt.suffix:
suffix = '_' + opt.suffix.format(**vars(opt)) if opt.suffix != '' else ''
opt.name = opt.name + suffix
self.print_options(opt)
str_ids = opt.gpu_ids.split(',')
opt.gpu_ids = []
for str_id i... | ['def', 'parse(self):', 'opt', '=', 'self.gather_options()', 'opt.isTrain', '=', 'self.isTrain', 'if', 'opt.suffix:', 'suffix', '=', "'_'", '+', 'opt.suffix.format(**vars(opt))', 'if', 'opt.suffix', '!=', "''", 'else', "''", 'opt.name', '=', 'opt.name', '+', 'suffix', 'self.print_options(opt)', 'str_ids', '=', "opt.gpu... | 382,959 |
Alexander-Parker/youtube_nlp | action_chains.py | ActionChains.perform | perform | Performs all stored actions. | [
"Performs",
"all",
"stored",
"actions."
] | def perform(self):
if self._driver.w3c:
self.w3c_actions.perform()
else:
for action in self._actions:
action() | ['def', 'perform(self):', 'if', 'self._driver.w3c:', 'self.w3c_actions.perform()', 'else:', 'for', 'action', 'in', 'self._actions:', 'action()'] | 970,786 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | thinkstats2.py | MakeSuiteFromList | MakeSuiteFromList | Makes a suite from an unsorted sequence of values. | [
"Makes",
"a",
"suite",
"from",
"an",
"unsorted",
"sequence",
"of",
"values."
] | def MakeSuiteFromList(t, label=None):
hist = MakeHistFromList(t, label=label)
d = hist.GetDict()
return MakeSuiteFromDict(d) | ['def', 'MakeSuiteFromList(t,', 'label=None):', 'hist', '=', 'MakeHistFromList(t,', 'label=label)', 'd', '=', 'hist.GetDict()', 'return', 'MakeSuiteFromDict(d)'] | 13,190 |
danamyu/hedgehog_detector | translate.py | read_data | read_data | Read data from source and target files and put into buckets. | [
"Read",
"data",
"from",
"source",
"and",
"target",
"files",
"and",
"put",
"into",
"buckets."
] | def read_data(source_path, target_path, max_size=None):
data_set = [[] for _ in _buckets]
with tf.gfile.GFile(source_path, mode='r') as source_file:
with tf.gfile.GFile(target_path, mode='r') as target_file:
(source, target) = (source_file.readline(), target_file.readline())
coun... | ['def', 'read_data(source_path,', 'target_path,', 'max_size=None):', 'data_set', '=', '[[]', 'for', '_', 'in', '_buckets]', 'with', 'tf.gfile.GFile(source_path,', "mode='r')", 'as', 'source_file:', 'with', 'tf.gfile.GFile(target_path,', "mode='r')", 'as', 'target_file:', '(source,', 'target)', '=', '(source_file.readli... | 590,952 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | pyparsing.py | pyparsing_test.TestParseResultsAsserts.assertParseResultsEquals | assertParseResultsEquals | Unit test assertion to compare a ParseResults object with an optional expected_list, and compare any defined results names with an optional expected_dict. | [
"Unit",
"test",
"assertion",
"to",
"compare",
"a",
"ParseResults",
"object",
"with",
"an",
"optional",
"expected_list,",
"and",
"compare",
"any",
"defined",
"results",
"names",
"with",
"an",
"optional",
"expected_dict."
] | def assertParseResultsEquals(self, result, expected_list=None, expected_dict=None, msg=None):
if expected_list is not None:
self.assertEqual(expected_list, result.asList(), msg=msg)
if expected_dict is not None:
self.assertEqual(expected_dict, result.asDict(), msg=msg) | ['def', 'assertParseResultsEquals(self,', 'result,', 'expected_list=None,', 'expected_dict=None,', 'msg=None):', 'if', 'expected_list', 'is', 'not', 'None:', 'self.assertEqual(expected_list,', 'result.asList(),', 'msg=msg)', 'if', 'expected_dict', 'is', 'not', 'None:', 'self.assertEqual(expected_dict,', 'result.asDict(... | 447,580 |
replit-archive/empythoned | numbers.py | Real.conjugate | conjugate | Conjugate is a no-op for Reals. | [
"Conjugate",
"is",
"a",
"no-op",
"for",
"Reals."
] | def conjugate(self):
return +self | ['def', 'conjugate(self):', 'return', '+self'] | 177,332 |
Katja-M/Python_NaturalLanguageProcessing | test_tgrep.py | TestSequenceFunctions.tests_rel_indexed_children | tests_rel_indexed_children | Test matching nodes based on their index in their parent node. | [
"Test",
"matching",
"nodes",
"based",
"on",
"their",
"index",
"in",
"their",
"parent",
"node."
] | def tests_rel_indexed_children(self):
tree = ParentedTree.fromstring('(S (A x) (B x) (C x))')
self.assertEqual(list(tgrep.tgrep_positions('* >, S', [tree])), [[(0,)]])
self.assertEqual(list(tgrep.tgrep_positions('* >1 S', [tree])), [[(0,)]])
self.assertEqual(list(tgrep.tgrep_positions('* >2 S', [tree]))... | ['def', 'tests_rel_indexed_children(self):', 'tree', '=', "ParentedTree.fromstring('(S", '(A', 'x)', '(B', 'x)', '(C', "x))')", "self.assertEqual(list(tgrep.tgrep_positions('*", '>,', "S',", '[tree])),', '[[(0,)]])', "self.assertEqual(list(tgrep.tgrep_positions('*", '>1', "S',", '[tree])),', '[[(0,)]])', "self.assertEq... | 867,098 |
rudranil723/mini-main | universal.py | Definition.dispatch | dispatch | Dispatch a call to an interface method. | [
"Dispatch",
"a",
"call",
"to",
"an",
"interface",
"method."
] | def dispatch(self, ob, index, argPtr, ReadFromInTuple=_univgw.ReadFromInTuple, WriteFromOutTuple=_univgw.WriteFromOutTuple):
meth = self._methods[index]
hr = 0
args = ReadFromInTuple(meth._gw_in_args, argPtr)
ob = getattr(ob, 'policy', ob)
ob._dispid_to_func_[meth.dispid] = meth.name
retVal = ob... | ['def', 'dispatch(self,', 'ob,', 'index,', 'argPtr,', 'ReadFromInTuple=_univgw.ReadFromInTuple,', 'WriteFromOutTuple=_univgw.WriteFromOutTuple):', 'meth', '=', 'self._methods[index]', 'hr', '=', '0', 'args', '=', 'ReadFromInTuple(meth._gw_in_args,', 'argPtr)', 'ob', '=', 'getattr(ob,', "'policy',", 'ob)', 'ob._dispid_t... | 271,168 |
open-mmlab/mmdetection3d | lidar_box3d.py | LiDARInstance3DBoxes.enlarged_box | enlarged_box | Enlarge the length, width and height of boxes. | [
"Enlarge",
"the",
"length,",
"width",
"and",
"height",
"of",
"boxes."
] | def enlarged_box(self, extra_width: Union[float, Tensor]) -> 'LiDARInstance3DBoxes':
enlarged_boxes = self.tensor.clone()
enlarged_boxes[:, 3:6] += extra_width * 2
enlarged_boxes[:, 2] -= extra_width
return self.new_box(enlarged_boxes) | ['def', 'enlarged_box(self,', 'extra_width:', 'Union[float,', 'Tensor])', '->', "'LiDARInstance3DBoxes':", 'enlarged_boxes', '=', 'self.tensor.clone()', 'enlarged_boxes[:,', '3:6]', '+=', 'extra_width', '*', '2', 'enlarged_boxes[:,', '2]', '-=', 'extra_width', 'return', 'self.new_box(enlarged_boxes)'] | 632,284 |
43Carrig/recurrent_neural_networks_practice | implementations.py | secure_channel | secure_channel | Creates a secure Channel to a remote host. | [
"Creates",
"a",
"secure",
"Channel",
"to",
"a",
"remote",
"host."
] | def secure_channel(host, port, channel_credentials):
channel = grpc.secure_channel(host if port is None else '%s:%d' % (host, port), channel_credentials)
return Channel(channel) | ['def', 'secure_channel(host,', 'port,', 'channel_credentials):', 'channel', '=', 'grpc.secure_channel(host', 'if', 'port', 'is', 'None', 'else', "'%s:%d'", '%', '(host,', 'port),', 'channel_credentials)', 'return', 'Channel(channel)'] | 310,115 |
salmanmaq/segmentationNetworks | utils.py | convertToOneHot | convertToOneHot | Converts the network output from softmax to one-hot encoding. | [
"Converts",
"the",
"network",
"output",
"from",
"softmax",
"to",
"one-hot",
"encoding."
] | def convertToOneHot(batch, use_gpu):
if use_gpu:
batch = batch.cpu()
batch = batch.data.numpy()
for i in range(len(batch)):
vec = batch[i, :, :, :]
idxs = np.argmax(vec, axis=0)
single = np.zeros([1, batch.shape[2], batch.shape[3]])
for k in range(batch.shape[1]):
... | ['def', 'convertToOneHot(batch,', 'use_gpu):', 'if', 'use_gpu:', 'batch', '=', 'batch.cpu()', 'batch', '=', 'batch.data.numpy()', 'for', 'i', 'in', 'range(len(batch)):', 'vec', '=', 'batch[i,', ':,', ':,', ':]', 'idxs', '=', 'np.argmax(vec,', 'axis=0)', 'single', '=', 'np.zeros([1,', 'batch.shape[2],', 'batch.shape[3]]... | 842,672 |
tensorflow/privacy | keras_evaluation.py | run_attack_on_keras_model | run_attack_on_keras_model | Performs the attack on a trained model. | [
"Performs",
"the",
"attack",
"on",
"a",
"trained",
"model."
] | def run_attack_on_keras_model(model, in_train, out_train, slicing_spec: SlicingSpec=None, attack_types: Iterable[AttackType]=(AttackType.THRESHOLD_ATTACK,), is_logit: bool=False, batch_size: int=32):
(in_train_data, in_train_labels) = in_train
(out_train_data, out_train_labels) = out_train
(in_train_pred, i... | ['def', 'run_attack_on_keras_model(model,', 'in_train,', 'out_train,', 'slicing_spec:', 'SlicingSpec=None,', 'attack_types:', 'Iterable[AttackType]=(AttackType.THRESHOLD_ATTACK,),', 'is_logit:', 'bool=False,', 'batch_size:', 'int=32):', '(in_train_data,', 'in_train_labels)', '=', 'in_train', '(out_train_data,', 'out_tr... | 824,905 |
unixpickle/anyrl-py | list.py | mean_total_reward | mean_total_reward | Get the mean of the total rewards. | [
"Get",
"the",
"mean",
"of",
"the",
"total",
"rewards."
] | def mean_total_reward(rollouts):
return sum([r.total_reward for r in rollouts]) / len(rollouts) | ['def', 'mean_total_reward(rollouts):', 'return', 'sum([r.total_reward', 'for', 'r', 'in', 'rollouts])', '/', 'len(rollouts)'] | 33,848 |
NoGameNoLife00/mybolg | nodes.py | Node.set_environment | set_environment | Set the environment for all nodes. | [
"Set",
"the",
"environment",
"for",
"all",
"nodes."
] | def set_environment(self, environment):
todo = deque([self])
while todo:
node = todo.popleft()
node.environment = environment
todo.extend(node.iter_child_nodes())
return self | ['def', 'set_environment(self,', 'environment):', 'todo', '=', 'deque([self])', 'while', 'todo:', 'node', '=', 'todo.popleft()', 'node.environment', '=', 'environment', 'todo.extend(node.iter_child_nodes())', 'return', 'self'] | 289,566 |
LLNL/merlin | sample_index.py | SampleIndex.write_multiple_sample_index_files | write_multiple_sample_index_files | Write index files that couple with location in directory hierarchy, contain necessary info to create a new index. | [
"Write",
"index",
"files",
"that",
"couple",
"with",
"location",
"in",
"directory",
"hierarchy,",
"contain",
"necessary",
"info",
"to",
"create",
"a",
"new",
"index."
] | def write_multiple_sample_index_files(self, path='.'):
filepath = self.write_single_sample_index_file(path)
filepaths = []
if filepath is not None:
filepaths.append(filepath)
for child_val in self.children.values():
filepaths += child_val.write_multiple_sample_index_files(os.path.join(pa... | ['def', 'write_multiple_sample_index_files(self,', "path='.'):", 'filepath', '=', 'self.write_single_sample_index_file(path)', 'filepaths', '=', '[]', 'if', 'filepath', 'is', 'not', 'None:', 'filepaths.append(filepath)', 'for', 'child_val', 'in', 'self.children.values():', 'filepaths', '+=', 'child_val.write_multiple_s... | 632,642 |
googleinterns/ddsp-docker | ddsp_run_multiple_vms.py | parse_gin | parse_gin | Parse gin config from --gin_file, --gin_param, and the model directory. | [
"Parse",
"gin",
"config",
"from",
"--gin_file,",
"--gin_param,",
"and",
"the",
"model",
"directory."
] | def parse_gin(restore_dir):
for gin_search_path in [GIN_PATH] + FLAGS.gin_search_path:
gin.add_config_file_search_path(gin_search_path)
with gin.unlock_config():
use_tpu = bool(FLAGS.tpu)
opt_default = 'base.gin' if not use_tpu else 'base_tpu.gin'
gin.parse_config_file(os.path.jo... | ['def', 'parse_gin(restore_dir):', 'for', 'gin_search_path', 'in', '[GIN_PATH]', '+', 'FLAGS.gin_search_path:', 'gin.add_config_file_search_path(gin_search_path)', 'with', 'gin.unlock_config():', 'use_tpu', '=', 'bool(FLAGS.tpu)', 'opt_default', '=', "'base.gin'", 'if', 'not', 'use_tpu', 'else', "'base_tpu.gin'", "gin.... | 516,418 |
coder-mano/Shi-Tomasi-Corner-Detector | _in_process.py | prepare_metadata_for_build_wheel | prepare_metadata_for_build_wheel | Invoke optional prepare_metadata_for_build_wheel Implements a fallback by building a wheel if the hook isn't defined, unless _allow_fallback is False in which case HookMissing is raised. | [
"Invoke",
"optional",
"prepare_metadata_for_build_wheel",
"Implements",
"a",
"fallback",
"by",
"building",
"a",
"wheel",
"if",
"the",
"hook",
"isn't",
"defined,",
"unless",
"_allow_fallback",
"is",
"False",
"in",
"which",
"case",
"HookMissing",
"is",
"raised."
] | def prepare_metadata_for_build_wheel(metadata_directory, config_settings, _allow_fallback):
backend = _build_backend()
try:
hook = backend.prepare_metadata_for_build_wheel
except AttributeError:
if not _allow_fallback:
raise HookMissing()
return _get_wheel_metadata_from_w... | ['def', 'prepare_metadata_for_build_wheel(metadata_directory,', 'config_settings,', '_allow_fallback):', 'backend', '=', '_build_backend()', 'try:', 'hook', '=', 'backend.prepare_metadata_for_build_wheel', 'except', 'AttributeError:', 'if', 'not', '_allow_fallback:', 'raise', 'HookMissing()', 'return', '_get_wheel_meta... | 900,388 |
openvinotoolkit/training_extensions | cls_dataset.py | OTXActionClsDataset.prepare_train_frames | prepare_train_frames | Get training data and annotations after pipeline. | [
"Get",
"training",
"data",
"and",
"annotations",
"after",
"pipeline."
] | def prepare_train_frames(self, idx: int) -> Dict[str, Any]:
item = copy(self.video_infos[idx])
return self.pipeline(item) | ['def', 'prepare_train_frames(self,', 'idx:', 'int)', '->', 'Dict[str,', 'Any]:', 'item', '=', 'copy(self.video_infos[idx])', 'return', 'self.pipeline(item)'] | 903,851 |
inseq-team/inseq | lime.py | Lime.token_similarity_kernel | token_similarity_kernel | Calculates the similarity between original and perturbed input. | [
"Calculates",
"the",
"similarity",
"between",
"original",
"and",
"perturbed",
"input."
] | def token_similarity_kernel(original_input: tuple, perturbed_input: tuple, perturbed_interpretable_input: tuple, **kwargs) -> torch.Tensor:
if len(original_input) == 1:
original_input_tensor = original_input[0][0]
perturbed_input_tensor = perturbed_input[0][0]
elif len(original_input) == 2:
... | ['def', 'token_similarity_kernel(original_input:', 'tuple,', 'perturbed_input:', 'tuple,', 'perturbed_interpretable_input:', 'tuple,', '**kwargs)', '->', 'torch.Tensor:', 'if', 'len(original_input)', '==', '1:', 'original_input_tensor', '=', 'original_input[0][0]', 'perturbed_input_tensor', '=', 'perturbed_input[0][0]'... | 613,925 |
matsu0228/nlp-jp | connection.py | MTurkConnection.get_reviewable_hits | get_reviewable_hits | Retrieve the HITs that have a status of Reviewable, or HITs that have a status of Reviewing, and that belong to the Requester calling the operation. | [
"Retrieve",
"the",
"HITs",
"that",
"have",
"a",
"status",
"of",
"Reviewable,",
"or",
"HITs",
"that",
"have",
"a",
"status",
"of",
"Reviewing,",
"and",
"that",
"belong",
"to",
"the",
"Requester",
"calling",
"the",
"operation."
] | def get_reviewable_hits(self, hit_type=None, status='Reviewable', sort_by='Expiration', sort_direction='Ascending', page_size=10, page_number=1):
params = {'Status': status, 'SortProperty': sort_by, 'SortDirection': sort_direction, 'PageSize': page_size, 'PageNumber': page_number}
if hit_type is not None:
... | ['def', 'get_reviewable_hits(self,', 'hit_type=None,', "status='Reviewable',", "sort_by='Expiration',", "sort_direction='Ascending',", 'page_size=10,', 'page_number=1):', 'params', '=', "{'Status':", 'status,', "'SortProperty':", 'sort_by,', "'SortDirection':", 'sort_direction,', "'PageSize':", 'page_size,', "'PageNumb... | 784,903 |
open-mmlab/mmselfsup | swav.py | SwAV.loss | loss | Forward computation during training. | [
"Forward",
"computation",
"during",
"training."
] | def loss(self, inputs: List[torch.Tensor], data_samples: List[SelfSupDataSample], **kwargs) -> Dict[str, torch.Tensor]:
assert isinstance(inputs, list)
idx_crops = torch.cumsum(torch.unique_consecutive(torch.tensor([input.shape[-1] for input in inputs]), return_counts=True)[1], 0)
start_idx = 0
output =... | ['def', 'loss(self,', 'inputs:', 'List[torch.Tensor],', 'data_samples:', 'List[SelfSupDataSample],', '**kwargs)', '->', 'Dict[str,', 'torch.Tensor]:', 'assert', 'isinstance(inputs,', 'list)', 'idx_crops', '=', 'torch.cumsum(torch.unique_consecutive(torch.tensor([input.shape[-1]', 'for', 'input', 'in', 'inputs]),', 'ret... | 240,399 |
hadikazemi/Machine-Learning | Smooth.py | LaplacianSmoother.add_data | add_data | Adds another sample to the data. | [
"Adds",
"another",
"sample",
"to",
"the",
"data."
] | def add_data(self, data):
if isinstance(data, (str, basestring)):
data_map = dict([(w, []) for w in set(data)])
for i in xrange(len(data) - 1):
data_map[data[i]].append(data[i + 1])
data_map[None] = [data[0]] if data else []
else:
data_map = data
for (key, value) ... | ['def', 'add_data(self,', 'data):', 'if', 'isinstance(data,', '(str,', 'basestring)):', 'data_map', '=', 'dict([(w,', '[])', 'for', 'w', 'in', 'set(data)])', 'for', 'i', 'in', 'xrange(len(data)', '-', '1):', 'data_map[data[i]].append(data[i', '+', '1])', 'data_map[None]', '=', '[data[0]]', 'if', 'data', 'else', '[]', '... | 190,489 |
unixpickle/anyrl-py | test_dists.py | DistributionTester.test_all | test_all | Run all generic tests. | [
"Run",
"all",
"generic",
"tests."
] | def test_all(self):
np.random.seed(1337)
with tf.Graph().as_default():
self.session = tf.Session()
with self.session:
self.test_shapes()
self.test_entropy()
self.test_kl()
self.test_mode() | ['def', 'test_all(self):', 'np.random.seed(1337)', 'with', 'tf.Graph().as_default():', 'self.session', '=', 'tf.Session()', 'with', 'self.session:', 'self.test_shapes()', 'self.test_entropy()', 'self.test_kl()', 'self.test_mode()'] | 33,704 |
KalleHallden/InstaAutomator | config.py | ConfigHandler.parse | parse | Parses configuration file items from one or more related sections. | [
"Parses",
"configuration",
"file",
"items",
"from",
"one",
"or",
"more",
"related",
"sections."
] | def parse(self):
for (section_name, section_options) in self.sections.items():
method_postfix = ''
if section_name:
method_postfix = '_%s' % section_name
section_parser_method = getattr(self, ('parse_section%s' % method_postfix).replace('.', '__'), None)
if section_parser... | ['def', 'parse(self):', 'for', '(section_name,', 'section_options)', 'in', 'self.sections.items():', 'method_postfix', '=', "''", 'if', 'section_name:', 'method_postfix', '=', "'_%s'", '%', 'section_name', 'section_parser_method', '=', 'getattr(self,', "('parse_section%s'", '%', "method_postfix).replace('.',", "'__'),"... | 232,154 |
SamsungLabs/imvoxelnet | points_sampler.py | FFPS_Sampler.forward | forward | Sampling points with F-FPS. | [
"Sampling",
"points",
"with",
"F-FPS."
] | def forward(self, points, features, npoint):
features_for_fps = torch.cat([points, features.transpose(1, 2)], dim=2)
features_dist = calc_square_dist(features_for_fps, features_for_fps, norm=False)
fps_idx = furthest_point_sample_with_dist(features_dist, npoint)
return fps_idx | ['def', 'forward(self,', 'points,', 'features,', 'npoint):', 'features_for_fps', '=', 'torch.cat([points,', 'features.transpose(1,', '2)],', 'dim=2)', 'features_dist', '=', 'calc_square_dist(features_for_fps,', 'features_for_fps,', 'norm=False)', 'fps_idx', '=', 'furthest_point_sample_with_dist(features_dist,', 'npoint... | 612,123 |
irdanish11/Seq2Seq-UrduChatBot | vocabulary.py | Vocabulary.word_exists | word_exists | Check if the given word exists in the vocabulary. | [
"Check",
"if",
"the",
"given",
"word",
"exists",
"in",
"the",
"vocabulary."
] | def word_exists(self, word):
self._validate_compile(True)
return word in self._words2int | ['def', 'word_exists(self,', 'word):', 'self._validate_compile(True)', 'return', 'word', 'in', 'self._words2int'] | 876,476 |
Ixiaohuihuihui/AO2-DETR | re_resnet.py | BasicBlock.norm1 | norm1 | Get normalizion layer's name. | [
"Get",
"normalizion",
"layer's",
"name."
] | def norm1(self):
return getattr(self, self.norm1_name) | ['def', 'norm1(self):', 'return', 'getattr(self,', 'self.norm1_name)'] | 401,460 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | lfads.py | LFADS.get_batch | get_batch | Get a batch of data, either randomly chosen, or specified directly. | [
"Get",
"a",
"batch",
"of",
"data,",
"either",
"randomly",
"chosen,",
"or",
"specified",
"directly."
] | def get_batch(data_extxd, ext_input_extxi=None, batch_size=None, example_idxs=None):
assert batch_size is not None or example_idxs is not None, 'Problems'
(E, T, D) = data_extxd.shape
if example_idxs is None:
example_idxs = np.random.choice(E, batch_size)
ext_input_bxtxi = None
if ext_input_... | ['def', 'get_batch(data_extxd,', 'ext_input_extxi=None,', 'batch_size=None,', 'example_idxs=None):', 'assert', 'batch_size', 'is', 'not', 'None', 'or', 'example_idxs', 'is', 'not', 'None,', "'Problems'", '(E,', 'T,', 'D)', '=', 'data_extxd.shape', 'if', 'example_idxs', 'is', 'None:', 'example_idxs', '=', 'np.random.cho... | 49,676 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | norb_input_record_test.py | NorbInputRecordTest.testDistort | testDistort | Checks the dimmensions of the distorted image. | [
"Checks",
"the",
"dimmensions",
"of",
"the",
"distorted",
"image."
] | def testDistort(self):
with self.test_session(graph=tf.Graph()) as sess:
features = norb_input_record.inputs(data_dir=os.path.join(DATA_DIR), batch_size=1, split='test', height=32, distort=True, batch_capacity=6)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coo... | ['def', 'testDistort(self):', 'with', 'self.test_session(graph=tf.Graph())', 'as', 'sess:', 'features', '=', 'norb_input_record.inputs(data_dir=os.path.join(DATA_DIR),', 'batch_size=1,', "split='test',", 'height=32,', 'distort=True,', 'batch_capacity=6)', 'coord', '=', 'tf.train.Coordinator()', 'threads', '=', 'tf.trai... | 46,965 |
suarez12138/AI-Reversi_IMP_TextDichotomy | mathtext.py | Error | Error | Helper class to raise parser errors. | [
"Helper",
"class",
"to",
"raise",
"parser",
"errors."
] | def Error(msg):
def raise_error(s, loc, toks):
raise ParseFatalException(s, loc, msg)
empty = Empty()
empty.setParseAction(raise_error)
return empty | ['def', 'Error(msg):', 'def', 'raise_error(s,', 'loc,', 'toks):', 'raise', 'ParseFatalException(s,', 'loc,', 'msg)', 'empty', '=', 'Empty()', 'empty.setParseAction(raise_error)', 'return', 'empty'] | 96,579 |
masterkapilkumar/Unsupervised-Learning | data.py | Data.load_batch | load_batch | Load batch of data. | [
"Load",
"batch",
"of",
"data."
] | def load_batch(self):
try:
(x, y) = next(self.iterator)
except StopIteration:
self.iterator = iter(self.dataloader)
(x, y) = next(self.iterator)
return [torch.Tensor(x.float()).to(config.device), torch.Tensor(y.float()).to(config.device)] | ['def', 'load_batch(self):', 'try:', '(x,', 'y)', '=', 'next(self.iterator)', 'except', 'StopIteration:', 'self.iterator', '=', 'iter(self.dataloader)', '(x,', 'y)', '=', 'next(self.iterator)', 'return', '[torch.Tensor(x.float()).to(config.device),', 'torch.Tensor(y.float()).to(config.device)]'] | 353,192 |
aws/sagemaker-python-sdk | _event_bridge_scheduler_helper.py | EventBridgeSchedulerHelper.upsert_schedule | upsert_schedule | Creates or updates a Schedule for the given pipeline_arn and schedule_expression. | [
"Creates",
"or",
"updates",
"a",
"Schedule",
"for",
"the",
"given",
"pipeline_arn",
"and",
"schedule_expression."
] | def upsert_schedule(self, schedule_name: str, pipeline_arn: str, schedule_expression: str, state: str, start_date: datetime, role: str) -> Dict:
pipeline_parameter = dict(PipelineParameterList=[dict(Name=EXECUTION_TIME_PIPELINE_PARAMETER, Value=EVENT_BRIDGE_INVOCATION_TIME)])
create_or_update_schedule_request_d... | ['def', 'upsert_schedule(self,', 'schedule_name:', 'str,', 'pipeline_arn:', 'str,', 'schedule_expression:', 'str,', 'state:', 'str,', 'start_date:', 'datetime,', 'role:', 'str)', '->', 'Dict:', 'pipeline_parameter', '=', 'dict(PipelineParameterList=[dict(Name=EXECUTION_TIME_PIPELINE_PARAMETER,', 'Value=EVENT_BRIDGE_INV... | 830,071 |
openvinotoolkit/datumaro | dataset.py | Dataset.export | export | Saves the dataset in some format. | [
"Saves",
"the",
"dataset",
"in",
"some",
"format."
] | def export(self, save_dir: str, format: Union[str, Type[Exporter]], *, progress_reporter: Optional[ProgressReporter]=None, error_policy: Optional[ExportErrorPolicy]=None, **kwargs) -> None:
if not save_dir:
raise ValueError('Dataset export path is not specified')
inplace = save_dir == self._source_path ... | ['def', 'export(self,', 'save_dir:', 'str,', 'format:', 'Union[str,', 'Type[Exporter]],', '*,', 'progress_reporter:', 'Optional[ProgressReporter]=None,', 'error_policy:', 'Optional[ExportErrorPolicy]=None,', '**kwargs)', '->', 'None:', 'if', 'not', 'save_dir:', 'raise', "ValueError('Dataset", 'export', 'path', 'is', 'n... | 498,071 |
sek788432/Waymo-2D-Object-Detection | preprocess_ops.py | random_horizontal_flip | random_horizontal_flip | Randomly flips input image and bounding boxes. | [
"Randomly",
"flips",
"input",
"image",
"and",
"bounding",
"boxes."
] | def random_horizontal_flip(image, normalized_boxes=None, masks=None, seed=1):
with tf.name_scope('random_horizontal_flip'):
do_flip = tf.greater(tf.random.uniform([], seed=seed), 0.5)
image = tf.cond(do_flip, lambda : horizontal_flip_image(image), lambda : image)
if normalized_boxes is not N... | ['def', 'random_horizontal_flip(image,', 'normalized_boxes=None,', 'masks=None,', 'seed=1):', 'with', "tf.name_scope('random_horizontal_flip'):", 'do_flip', '=', 'tf.greater(tf.random.uniform([],', 'seed=seed),', '0.5)', 'image', '=', 'tf.cond(do_flip,', 'lambda', ':', 'horizontal_flip_image(image),', 'lambda', ':', 'i... | 973,277 |
cassianobecker/tgcn | gcn.py | spmm_batch_2 | spmm_batch_2 | Matrix product of sparse matrix with dense matrix. | [
"Matrix",
"product",
"of",
"sparse",
"matrix",
"with",
"dense",
"matrix."
] | def spmm_batch_2(index, value, m, matrix):
(row, col) = index
matrix = matrix if matrix.dim() > 1 else matrix.unsqueeze(-1)
out = matrix[:, col]
try:
sh = out.shape[2]
except:
out = out.unsqueeze(-1)
sh = 1
temp = value.expand(sh, value.shape[0]).permute(1, 0)
out = t... | ['def', 'spmm_batch_2(index,', 'value,', 'm,', 'matrix):', '(row,', 'col)', '=', 'index', 'matrix', '=', 'matrix', 'if', 'matrix.dim()', '>', '1', 'else', 'matrix.unsqueeze(-1)', 'out', '=', 'matrix[:,', 'col]', 'try:', 'sh', '=', 'out.shape[2]', 'except:', 'out', '=', 'out.unsqueeze(-1)', 'sh', '=', '1', 'temp', '=', ... | 367,270 |
AEProgrammer/object_detection | roidb.py | add_bbox_regression_targets | add_bbox_regression_targets | Add information needed to train bounding-box regressors. | [
"Add",
"information",
"needed",
"to",
"train",
"bounding-box",
"regressors."
] | def add_bbox_regression_targets(roidb):
for entry in roidb:
entry['bbox_targets'] = _compute_targets(entry) | ['def', 'add_bbox_regression_targets(roidb):', 'for', 'entry', 'in', 'roidb:', "entry['bbox_targets']", '=', '_compute_targets(entry)'] | 772,461 |
dibyaghosh/gcsl | group_config.py | TrackerGroupConfig.get_pos | get_pos | Returns the cartesian position of the element. | [
"Returns",
"the",
"cartesian",
"position",
"of",
"the",
"element."
] | def get_pos(self, sim_scene: SimScene) -> np.ndarray:
if self.qpos_indices is not None:
return sim_scene.data.qpos[self.qpos_indices[:3]]
return self.element_attr(sim_scene.data, 'xpos')[self.element_id, :] | ['def', 'get_pos(self,', 'sim_scene:', 'SimScene)', '->', 'np.ndarray:', 'if', 'self.qpos_indices', 'is', 'not', 'None:', 'return', 'sim_scene.data.qpos[self.qpos_indices[:3]]', 'return', 'self.element_attr(sim_scene.data,', "'xpos')[self.element_id,", ':]'] | 201,789 |
RasaHQ/rasa | rest.py | RestInput.blueprint | blueprint | Groups the collection of endpoints used by rest channel. | [
"Groups",
"the",
"collection",
"of",
"endpoints",
"used",
"by",
"rest",
"channel."
] | def blueprint(self, on_new_message: Callable[[UserMessage], Awaitable[None]]) -> Blueprint:
module_type = inspect.getmodule(self)
if module_type is not None:
module_name = module_type.__name__
else:
module_name = None
custom_webhook = Blueprint('custom_webhook_{}'.format(type(self).__nam... | ['def', 'blueprint(self,', 'on_new_message:', 'Callable[[UserMessage],', 'Awaitable[None]])', '->', 'Blueprint:', 'module_type', '=', 'inspect.getmodule(self)', 'if', 'module_type', 'is', 'not', 'None:', 'module_name', '=', 'module_type.__name__', 'else:', 'module_name', '=', 'None', 'custom_webhook', '=', "Blueprint('... | 836,824 |
voxel51/fiftyone | runs.py | RunResults.backend | backend | The :class:`Run` for these results. | [
"The",
":class:`Run`",
"for",
"these",
"results."
] | def backend(self):
return self._backend | ['def', 'backend(self):', 'return', 'self._backend'] | 583,250 |
darrellsilver/norc | schedules.py | CronSchedule.pretty_name | pretty_name | Returns the pretty (predefined) name for this schedule. | [
"Returns",
"the",
"pretty",
"(predefined)",
"name",
"for",
"this",
"schedule."
] | def pretty_name(self):
searchs = {'o\\*d\\*w\\*h\\*m(\\d+),(\\d+)s\\d+': 'HALFHOURLY', 'o\\*d\\*w\\*h\\*m\\d+s\\d+': 'HOURLY', 'o\\*d\\*w\\*h\\d+m\\d+s\\d+': 'DAILY', 'o\\*d\\*w\\d+h\\d+m\\d+s\\d+': 'WEEKLY', 'o\\*d\\d+w\\*h\\d+m\\d+s\\d+': 'MONTHLY'}
for (regex, name) in searchs.items():
m = re.match(r... | ['def', 'pretty_name(self):', 'searchs', '=', "{'o\\\\*d\\\\*w\\\\*h\\\\*m(\\\\d+),(\\\\d+)s\\\\d+':", "'HALFHOURLY',", "'o\\\\*d\\\\*w\\\\*h\\\\*m\\\\d+s\\\\d+':", "'HOURLY',", "'o\\\\*d\\\\*w\\\\*h\\\\d+m\\\\d+s\\\\d+':", "'DAILY',", "'o\\\\*d\\\\*w\\\\d+h\\\\d+m\\\\d+s\\\\d+':", "'WEEKLY',", "'o\\\\*d\\\\d+w\\\\*h\\... | 249,474 |
ryu-ed/SpaceInvaders_Ros | math2html.py | Postprocessor.postprocess | postprocess | Postprocess a container and its contents. | [
"Postprocess",
"a",
"container",
"and",
"its",
"contents."
] | def postprocess(self, next):
self.postrecursive(self.current)
result = self.postcurrent(next)
self.last = self.current
self.current = next
return result | ['def', 'postprocess(self,', 'next):', 'self.postrecursive(self.current)', 'result', '=', 'self.postcurrent(next)', 'self.last', '=', 'self.current', 'self.current', '=', 'next', 'return', 'result'] | 395,274 |
ananthpn/nlp | rc_model.py | RCModel.get_embs | get_embs | Get embeddings of token sequence. | [
"Get",
"embeddings",
"of",
"token",
"sequence."
] | def get_embs(self, input):
embs = layer.embedding(input=input, size=self.emb_dim, param_attr=self.emb_param)
return embs | ['def', 'get_embs(self,', 'input):', 'embs', '=', 'layer.embedding(input=input,', 'size=self.emb_dim,', 'param_attr=self.emb_param)', 'return', 'embs'] | 808,481 |
chenbinghui1/DSL | merge_augs.py | merge_aug_bboxes | merge_aug_bboxes | Merge augmented detection bboxes and scores. | [
"Merge",
"augmented",
"detection",
"bboxes",
"and",
"scores."
] | def merge_aug_bboxes(aug_bboxes, aug_scores, img_metas, rcnn_test_cfg):
recovered_bboxes = []
for (bboxes, img_info) in zip(aug_bboxes, img_metas):
img_shape = img_info[0]['img_shape']
scale_factor = img_info[0]['scale_factor']
flip = img_info[0]['flip']
flip_direction = img_info... | ['def', 'merge_aug_bboxes(aug_bboxes,', 'aug_scores,', 'img_metas,', 'rcnn_test_cfg):', 'recovered_bboxes', '=', '[]', 'for', '(bboxes,', 'img_info)', 'in', 'zip(aug_bboxes,', 'img_metas):', 'img_shape', '=', "img_info[0]['img_shape']", 'scale_factor', '=', "img_info[0]['scale_factor']", 'flip', '=', "img_info[0]['flip... | 167,513 |
danamyu/hedgehog_detector | graph_builder.py | GreedyParser.AddSaver | AddSaver | Adds ops to save and restore model parameters. | [
"Adds",
"ops",
"to",
"save",
"and",
"restore",
"model",
"parameters."
] | def AddSaver(self, slim_model=False):
with tf.name_scope(None):
variables_to_save = self.params.copy()
variables_to_save.update(self.variables)
if slim_model:
for key in variables_to_save.keys():
if not key.endswith('avg_var'):
del variables_to... | ['def', 'AddSaver(self,', 'slim_model=False):', 'with', 'tf.name_scope(None):', 'variables_to_save', '=', 'self.params.copy()', 'variables_to_save.update(self.variables)', 'if', 'slim_model:', 'for', 'key', 'in', 'variables_to_save.keys():', 'if', 'not', "key.endswith('avg_var'):", 'del', 'variables_to_save[key]', 'sel... | 590,679 |
enuguru/artificial_intelligence_and_machine_learning | lexer.py | get_lexer | get_lexer | Return a lexer which is probably cached. | [
"Return",
"a",
"lexer",
"which",
"is",
"probably",
"cached."
] | def get_lexer(environment):
key = (environment.block_start_string, environment.block_end_string, environment.variable_start_string, environment.variable_end_string, environment.comment_start_string, environment.comment_end_string, environment.line_statement_prefix, environment.line_comment_prefix, environment.trim_... | ['def', 'get_lexer(environment):', 'key', '=', '(environment.block_start_string,', 'environment.block_end_string,', 'environment.variable_start_string,', 'environment.variable_end_string,', 'environment.comment_start_string,', 'environment.comment_end_string,', 'environment.line_statement_prefix,', 'environment.line_co... | 158,407 |
Eric3911/OpenAGI | rnnt_wer_bpe.py | RNNTBPEDecoding.decode_ids_to_langs | decode_ids_to_langs | Decode a token id list into language ID (LID) list. | [
"Decode",
"a",
"token",
"id",
"list",
"into",
"language",
"ID",
"(LID)",
"list."
] | def decode_ids_to_langs(self, tokens: List[int]) -> List[str]:
lang_list = self.tokenizer.ids_to_text_and_langs(tokens)
return lang_list | ['def', 'decode_ids_to_langs(self,', 'tokens:', 'List[int])', '->', 'List[str]:', 'lang_list', '=', 'self.tokenizer.ids_to_text_and_langs(tokens)', 'return', 'lang_list'] | 272,365 |
zzndream/ShipRSImageNet | cascade_rpn_head.py | StageCascadeRPNHead.forward_single | forward_single | Forward function of single scale. | [
"Forward",
"function",
"of",
"single",
"scale."
] | def forward_single(self, x, offset):
bridged_x = x
x = self.relu(self.rpn_conv(x, offset))
if self.bridged_feature:
bridged_x = x
cls_score = self.rpn_cls(x) if self.with_cls else None
bbox_pred = self.rpn_reg(x)
return (bridged_x, cls_score, bbox_pred) | ['def', 'forward_single(self,', 'x,', 'offset):', 'bridged_x', '=', 'x', 'x', '=', 'self.relu(self.rpn_conv(x,', 'offset))', 'if', 'self.bridged_feature:', 'bridged_x', '=', 'x', 'cls_score', '=', 'self.rpn_cls(x)', 'if', 'self.with_cls', 'else', 'None', 'bbox_pred', '=', 'self.rpn_reg(x)', 'return', '(bridged_x,', 'cl... | 901,392 |
Eric3911/OpenAGI | language_model.py | Embedding.zero_parameters | zero_parameters | Zero out all parameters in embedding. | [
"Zero",
"out",
"all",
"parameters",
"in",
"embedding."
] | def zero_parameters(self):
self.word_embeddings.weight.data.fill_(0)
self.word_embeddings.weight.shared = True
if self.position_embedding_type == 'learned_absolute':
self.position_embeddings.weight.data.fill_(0)
self.position_embeddings.weight.shared = True
if self.num_tokentypes > 0:
... | ['def', 'zero_parameters(self):', 'self.word_embeddings.weight.data.fill_(0)', 'self.word_embeddings.weight.shared', '=', 'True', 'if', 'self.position_embedding_type', '==', "'learned_absolute':", 'self.position_embeddings.weight.data.fill_(0)', 'self.position_embeddings.weight.shared', '=', 'True', 'if', 'self.num_tok... | 273,755 |
deepmind/ai-safety-gridworlds | pycolab_interface.py | Environment.last_observations | last_observations | Distill and return the last observation. | [
"Distill",
"and",
"return",
"the",
"last",
"observation."
] | def last_observations(self):
if isinstance(self._last_observations, dict):
observation = self._last_observations
else:
observation = {'board': self._last_observations}
return observation | ['def', 'last_observations(self):', 'if', 'isinstance(self._last_observations,', 'dict):', 'observation', '=', 'self._last_observations', 'else:', 'observation', '=', "{'board':", 'self._last_observations}', 'return', 'observation'] | 412,156 |
aivclab/vision | test_video_reader.py | TestVideoReader.test_audio_present_pts | test_audio_present_pts | Test if audio frames are returned with pts unit. | [
"Test",
"if",
"audio",
"frames",
"are",
"returned",
"with",
"pts",
"unit."
] | def test_audio_present_pts(self, test_video, backend, start_offset, end_offset):
full_path = os.path.join(VIDEO_DIR, test_video)
container = av.open(full_path)
if container.streams.audio:
set_video_backend(backend)
(_, audio, _) = io.read_video(full_path, start_offset, end_offset, pts_unit='... | ['def', 'test_audio_present_pts(self,', 'test_video,', 'backend,', 'start_offset,', 'end_offset):', 'full_path', '=', 'os.path.join(VIDEO_DIR,', 'test_video)', 'container', '=', 'av.open(full_path)', 'if', 'container.streams.audio:', 'set_video_backend(backend)', '(_,', 'audio,', '_)', '=', 'io.read_video(full_path,', ... | 958,064 |
matsu0228/nlp-jp | handlers.py | NotebookHandler.get | get | get renders the notebook template if a name is given, or redirects to the '/files/' handler if the name is not given. | [
"get",
"renders",
"the",
"notebook",
"template",
"if",
"a",
"name",
"is",
"given,",
"or",
"redirects",
"to",
"the",
"'/files/'",
"handler",
"if",
"the",
"name",
"is",
"not",
"given."
] | def get(self, path):
path = path.strip('/')
cm = self.contents_manager
try:
model = cm.get(path, content=False)
except web.HTTPError as e:
if e.status_code == 404 and 'files' in path.split('/'):
return FilesRedirectHandler.redirect_to_files(self, path)
else:
... | ['def', 'get(self,', 'path):', 'path', '=', "path.strip('/')", 'cm', '=', 'self.contents_manager', 'try:', 'model', '=', 'cm.get(path,', 'content=False)', 'except', 'web.HTTPError', 'as', 'e:', 'if', 'e.status_code', '==', '404', 'and', "'files'", 'in', "path.split('/'):", 'return', 'FilesRedirectHandler.redirect_to_fi... | 790,620 |
shery322/Lunar-Lander-ANN | cygwinccompiler.py | is_cygwingcc | is_cygwingcc | Try to determine if the gcc that would be used is from cygwin. | [
"Try",
"to",
"determine",
"if",
"the",
"gcc",
"that",
"would",
"be",
"used",
"is",
"from",
"cygwin."
] | def is_cygwingcc():
out_string = check_output(['gcc', '-dumpmachine'])
return out_string.strip().endswith(b'cygwin') | ['def', 'is_cygwingcc():', 'out_string', '=', "check_output(['gcc',", "'-dumpmachine'])", 'return', "out_string.strip().endswith(b'cygwin')"] | 619,570 |
flow-project/flow | lord_of_the_rings.py | gen_policy | gen_policy | Generate a policy in RLlib. | [
"Generate",
"a",
"policy",
"in",
"RLlib."
] | def gen_policy():
return (PPOTFPolicy, obs_space, act_space, {}) | ['def', 'gen_policy():', 'return', '(PPOTFPolicy,', 'obs_space,', 'act_space,', '{})'] | 212,035 |
liuhuiwisdom/object_detection | net.py | average_multi_gpu_blob | average_multi_gpu_blob | Return the average of a scalar blob held on multiple GPUs. | [
"Return",
"the",
"average",
"of",
"a",
"scalar",
"blob",
"held",
"on",
"multiple",
"GPUs."
] | def average_multi_gpu_blob(blob_name):
return sum_multi_gpu_blob(blob_name) / cfg.NUM_GPUS | ['def', 'average_multi_gpu_blob(blob_name):', 'return', 'sum_multi_gpu_blob(blob_name)', '/', 'cfg.NUM_GPUS'] | 773,522 |
dask/dask-ml | conftest.py | X_blobs | X_blobs | X dataset from `Xl_blobs`. | [
"X",
"dataset",
"from",
"`Xl_blobs`."
] | def X_blobs(Xl_blobs):
return Xl_blobs[0] | ['def', 'X_blobs(Xl_blobs):', 'return', 'Xl_blobs[0]'] | 497,264 |
omarmhaimdat/twitter_nlp_native_swift | _collections.py | HTTPHeaderDict.from_httplib | from_httplib | Read headers from a Python 2 httplib message object. | [
"Read",
"headers",
"from",
"a",
"Python",
"2",
"httplib",
"message",
"object."
] | def from_httplib(cls, message):
obs_fold_continued_leaders = (' ', '\t')
headers = []
for line in message.headers:
if line.startswith(obs_fold_continued_leaders):
if not headers:
raise InvalidHeader('Header continuation with no previous header: %s' % line)
els... | ['def', 'from_httplib(cls,', 'message):', 'obs_fold_continued_leaders', '=', "('", "',", "'\\t')", 'headers', '=', '[]', 'for', 'line', 'in', 'message.headers:', 'if', 'line.startswith(obs_fold_continued_leaders):', 'if', 'not', 'headers:', 'raise', "InvalidHeader('Header", 'continuation', 'with', 'no', 'previous', 'he... | 955,239 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | mnist_shift.py | int64_feature | int64_feature | Casts value to a TensorFlow int64 feature list. | [
"Casts",
"value",
"to",
"a",
"TensorFlow",
"int64",
"feature",
"list."
] | def int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) | ['def', 'int64_feature(value):', 'return', 'tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))'] | 53,155 |
dbetm/handwritten-flowchart-with-cnn | roi_helpers.py | ROIHelpers.calc_iou | calc_iou | Calc the best IoUs considering all classes. | [
"Calc",
"the",
"best",
"IoUs",
"considering",
"all",
"classes."
] | def calc_iou(self, R, data, class_mapping):
bboxes = data['bboxes']
(width, height) = (data['width'], data['height'])
(new_width, new_height) = ImageTools.get_new_img_size(width, height, self.config.im_size)
gta = np.zeros((len(bboxes), 4))
for (bbox_num, bbox) in enumerate(bboxes):
rpn_stri... | ['def', 'calc_iou(self,', 'R,', 'data,', 'class_mapping):', 'bboxes', '=', "data['bboxes']", '(width,', 'height)', '=', "(data['width'],", "data['height'])", '(new_width,', 'new_height)', '=', 'ImageTools.get_new_img_size(width,', 'height,', 'self.config.im_size)', 'gta', '=', 'np.zeros((len(bboxes),', '4))', 'for', '(... | 205,479 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | tune.py | compute_tuning_objective | compute_tuning_objective | Compute tuning objective and metrics given results and trial information. | [
"Compute",
"tuning",
"objective",
"and",
"metrics",
"given",
"results",
"and",
"trial",
"information."
] | def compute_tuning_objective(results_list, hparams, trial_name, num_trials):
found_solution = [r['found_solution'] for r in results_list]
successful_program_counts = [r['npe'] for r in results_list if r['found_solution']]
success_rate = sum(found_solution) / float(len(results_list))
max_programs = FLAGS... | ['def', 'compute_tuning_objective(results_list,', 'hparams,', 'trial_name,', 'num_trials):', 'found_solution', '=', "[r['found_solution']", 'for', 'r', 'in', 'results_list]', 'successful_program_counts', '=', "[r['npe']", 'for', 'r', 'in', 'results_list', 'if', "r['found_solution']]", 'success_rate', '=', 'sum(found_so... | 46,774 |
clips/pattern | __init__.py | template | template | Returns the rendered template as a string. | [
"Returns",
"the",
"rendered",
"template",
"as",
"a",
"string."
] | def template(string, *args, **kwargs):
if hasattr(string, 'render'):
return string.render(*args, **kwargs)
(root, cached) = (kwargs.pop('root', None), kwargs.pop('cached', None))
if root is None and len(args) > 0 and isinstance(args[0], str):
root = args[0]
args = args[1:]
return... | ['def', 'template(string,', '*args,', '**kwargs):', 'if', 'hasattr(string,', "'render'):", 'return', 'string.render(*args,', '**kwargs)', '(root,', 'cached)', '=', "(kwargs.pop('root',", 'None),', "kwargs.pop('cached',", 'None))', 'if', 'root', 'is', 'None', 'and', 'len(args)', '>', '0', 'and', 'isinstance(args[0],', '... | 764,697 |
sshleifer/object_detection_kitti | dataset_utils.py | has_labels | has_labels | Specifies whether or not the dataset directory contains a label map file. | [
"Specifies",
"whether",
"or",
"not",
"the",
"dataset",
"directory",
"contains",
"a",
"label",
"map",
"file."
] | def has_labels(dataset_dir, filename=LABELS_FILENAME):
return tf.gfile.Exists(os.path.join(dataset_dir, filename)) | ['def', 'has_labels(dataset_dir,', 'filename=LABELS_FILENAME):', 'return', 'tf.gfile.Exists(os.path.join(dataset_dir,', 'filename))'] | 795,470 |
open-mmlab/mmdetection3d | detr3d_transformer.py | Detr3DTransformer.forward | forward | Forward function for `Detr3DTransformer`. | [
"Forward",
"function",
"for",
"`Detr3DTransformer`."
] | def forward(self, mlvl_feats, query_embed, reg_branches=None, **kwargs):
assert query_embed is not None
bs = mlvl_feats[0].size(0)
(query_pos, query) = torch.split(query_embed, self.embed_dims, dim=1)
query_pos = query_pos.unsqueeze(0).expand(bs, -1, -1)
query = query.unsqueeze(0).expand(bs, -1, -1)... | ['def', 'forward(self,', 'mlvl_feats,', 'query_embed,', 'reg_branches=None,', '**kwargs):', 'assert', 'query_embed', 'is', 'not', 'None', 'bs', '=', 'mlvl_feats[0].size(0)', '(query_pos,', 'query)', '=', 'torch.split(query_embed,', 'self.embed_dims,', 'dim=1)', 'query_pos', '=', 'query_pos.unsqueeze(0).expand(bs,', '-1... | 632,418 |
luojie1024/Computer-vision-Classwork | __init__.py | EntryPoint.resolve | resolve | Resolve the entry point from its module and attrs. | [
"Resolve",
"the",
"entry",
"point",
"from",
"its",
"module",
"and",
"attrs."
] | def resolve(self):
module = __import__(self.module_name, fromlist=['__name__'], level=0)
try:
return functools.reduce(getattr, self.attrs, module)
except AttributeError as exc:
raise ImportError(str(exc)) | ['def', 'resolve(self):', 'module', '=', '__import__(self.module_name,', "fromlist=['__name__'],", 'level=0)', 'try:', 'return', 'functools.reduce(getattr,', 'self.attrs,', 'module)', 'except', 'AttributeError', 'as', 'exc:', 'raise', 'ImportError(str(exc))'] | 468,154 |
octree-nn/ocnn-pytorch | octree.py | Octree.octree_split | octree_split | Sets whether the octree nodes in :attr:`depth` are splitted or not. | [
"Sets",
"whether",
"the",
"octree",
"nodes",
"in",
":attr:`depth`",
"are",
"splitted",
"or",
"not."
] | def octree_split(self, split: torch.Tensor, depth: int):
empty = split == 0
sum = cumsum(split, dim=0, exclusive=True)
(children, nnum_nempty) = torch.split(sum, [split.shape[0], 1])
children[empty] = -1
if nnum_nempty == 0:
nnum_nempty = 1
children[0] = 0
self.children[depth] = ... | ['def', 'octree_split(self,', 'split:', 'torch.Tensor,', 'depth:', 'int):', 'empty', '=', 'split', '==', '0', 'sum', '=', 'cumsum(split,', 'dim=0,', 'exclusive=True)', '(children,', 'nnum_nempty)', '=', 'torch.split(sum,', '[split.shape[0],', '1])', 'children[empty]', '=', '-1', 'if', 'nnum_nempty', '==', '0:', 'nnum_n... | 249,933 |
vbelz/audio_classification | misc.py | make_vcs_requirement_url | make_vcs_requirement_url | Return the URL for a VCS requirement. | [
"Return",
"the",
"URL",
"for",
"a",
"VCS",
"requirement."
] | def make_vcs_requirement_url(repo_url, rev, project_name, subdir=None):
egg_project_name = pkg_resources.to_filename(project_name)
req = '{}@{}#egg={}'.format(repo_url, rev, egg_project_name)
if subdir:
req += '&subdirectory={}'.format(subdir)
return req | ['def', 'make_vcs_requirement_url(repo_url,', 'rev,', 'project_name,', 'subdir=None):', 'egg_project_name', '=', 'pkg_resources.to_filename(project_name)', 'req', '=', "'{}@{}#egg={}'.format(repo_url,", 'rev,', 'egg_project_name)', 'if', 'subdir:', 'req', '+=', "'&subdirectory={}'.format(subdir)", 'return', 'req'] | 403,476 |
enuguru/artificial_intelligence_and_machine_ | dates.py | TimezoneTransition.to_tz | to_tz | The name of the timezone after the transition. | [
"The",
"name",
"of",
"the",
"timezone",
"after",
"the",
"transition."
] | def to_tz(self):
return self.to_tzinfo._tzname | ['def', 'to_tz(self):', 'return', 'self.to_tzinfo._tzname'] | 156,937 |
rishab-sharma/object_detection | detector.py | DetectionModelHelper.DropoutIfTraining | DropoutIfTraining | Add dropout to blob_in if the model is in training mode and dropout_rate is > 0. | [
"Add",
"dropout",
"to",
"blob_in",
"if",
"the",
"model",
"is",
"in",
"training",
"mode",
"and",
"dropout_rate",
"is",
">",
"0."
] | def DropoutIfTraining(self, blob_in, dropout_rate):
blob_out = blob_in
if self.train and dropout_rate > 0:
blob_out = self.Dropout(blob_in, blob_in, ratio=dropout_rate, is_test=False)
return blob_out | ['def', 'DropoutIfTraining(self,', 'blob_in,', 'dropout_rate):', 'blob_out', '=', 'blob_in', 'if', 'self.train', 'and', 'dropout_rate', '>', '0:', 'blob_out', '=', 'self.Dropout(blob_in,', 'blob_in,', 'ratio=dropout_rate,', 'is_test=False)', 'return', 'blob_out'] | 772,553 |
Speedwagon13/CS-3600-Introduction-to-- | feedparser.py | FeedParser.feed | feed | Push more data into the parser. | [
"Push",
"more",
"data",
"into",
"the",
"parser."
] | def feed(self, data):
self._input.push(data)
self._call_parse() | ['def', 'feed(self,', 'data):', 'self._input.push(data)', 'self._call_parse()'] | 140,134 |
MCG-NJU/VideoMAE | video_transforms.py | horizontal_flip | horizontal_flip | Perform horizontal flip on the given images and corresponding boxes. | [
"Perform",
"horizontal",
"flip",
"on",
"the",
"given",
"images",
"and",
"corresponding",
"boxes."
] | def horizontal_flip(prob, images, boxes=None):
if boxes is None:
flipped_boxes = None
else:
flipped_boxes = boxes.copy()
if np.random.uniform() < prob:
images = images.flip(-1)
if len(images.shape) == 3:
width = images.shape[2]
elif len(images.shape) == 4:... | ['def', 'horizontal_flip(prob,', 'images,', 'boxes=None):', 'if', 'boxes', 'is', 'None:', 'flipped_boxes', '=', 'None', 'else:', 'flipped_boxes', '=', 'boxes.copy()', 'if', 'np.random.uniform()', '<', 'prob:', 'images', '=', 'images.flip(-1)', 'if', 'len(images.shape)', '==', '3:', 'width', '=', 'images.shape[2]', 'eli... | 931,672 |
sek788432/Waymo-2D-Object-Detection | augment.py | AutoAugment.policy_test | policy_test | Autoaugment test policy for debugging. | [
"Autoaugment",
"test",
"policy",
"for",
"debugging."
] | def policy_test():
policy = [[('TranslateX', 1.0, 4), ('Equalize', 1.0, 10)]]
return policy | ['def', 'policy_test():', 'policy', '=', "[[('TranslateX',", '1.0,', '4),', "('Equalize',", '1.0,', '10)]]', 'return', 'policy'] | 973,707 |
ryu-ed/SpaceInvaders_Ros | structs.py | DirectedGraph.copy | copy | Return a shallow copy of this graph. | [
"Return",
"a",
"shallow",
"copy",
"of",
"this",
"graph."
] | def copy(self):
other = DirectedGraph()
other._vertices = set(self._vertices)
other._forwards = {k: set(v) for (k, v) in self._forwards.items()}
other._backwards = {k: set(v) for (k, v) in self._backwards.items()}
return other | ['def', 'copy(self):', 'other', '=', 'DirectedGraph()', 'other._vertices', '=', 'set(self._vertices)', 'other._forwards', '=', '{k:', 'set(v)', 'for', '(k,', 'v)', 'in', 'self._forwards.items()}', 'other._backwards', '=', '{k:', 'set(v)', 'for', '(k,', 'v)', 'in', 'self._backwards.items()}', 'return', 'other'] | 368,515 |
sek788432/Waymo-2D-Object-Detection | translate.py | translate_file | translate_file | Translate lines in file, and save to output file if specified. | [
"Translate",
"lines",
"in",
"file,",
"and",
"save",
"to",
"output",
"file",
"if",
"specified."
] | def translate_file(model, params, subtokenizer, input_file, output_file=None, print_all_translations=True, distribution_strategy=None):
batch_size = params['decode_batch_size']
(sorted_inputs, sorted_keys) = _get_sorted_inputs(input_file)
total_samples = len(sorted_inputs)
num_decode_batches = (total_sa... | ['def', 'translate_file(model,', 'params,', 'subtokenizer,', 'input_file,', 'output_file=None,', 'print_all_translations=True,', 'distribution_strategy=None):', 'batch_size', '=', "params['decode_batch_size']", '(sorted_inputs,', 'sorted_keys)', '=', '_get_sorted_inputs(input_file)', 'total_samples', '=', 'len(sorted_i... | 972,874 |
Yuting-Gao/DisCo-pytorch | resnet.py | resnext101_64x4d | resnext101_64x4d | Constructs a ResNeXt101-64x4d model. | [
"Constructs",
"a",
"ResNeXt101-64x4d",
"model."
] | def resnext101_64x4d(pretrained=False, **kwargs):
model_args = dict(block=Bottleneck, layers=[3, 4, 23, 3], cardinality=64, base_width=4, **kwargs)
return _create_resnet('resnext101_64x4d', pretrained, **model_args) | ['def', 'resnext101_64x4d(pretrained=False,', '**kwargs):', 'model_args', '=', 'dict(block=Bottleneck,', 'layers=[3,', '4,', '23,', '3],', 'cardinality=64,', 'base_width=4,', '**kwargs)', 'return', "_create_resnet('resnext101_64x4d',", 'pretrained,', '**model_args)'] | 186,561 |
google-research/scenic | models.py | top_k_hot | top_k_hot | Returns the one-hot mask for k-nearest neighbours. | [
"Returns",
"the",
"one-hot",
"mask",
"for",
"k-nearest",
"neighbours."
] | def top_k_hot(distances, k):
(_, idx) = jax.lax.top_k(-distances, k)
tops = jax.nn.one_hot(idx, distances.shape[-1], dtype=jnp.int32)
return tops.sum(axis=-2) | ['def', 'top_k_hot(distances,', 'k):', '(_,', 'idx)', '=', 'jax.lax.top_k(-distances,', 'k)', 'tops', '=', 'jax.nn.one_hot(idx,', 'distances.shape[-1],', 'dtype=jnp.int32)', 'return', 'tops.sum(axis=-2)'] | 847,259 |
AtmaHou/MetaDialog | context_embedder_base.py | BertContextEmbedder.extract_non_word_piece_reps | extract_non_word_piece_reps | Use the first word piece as entire word representation As we have only one index for each token, we need to expand to the size of reps dim. | [
"Use",
"the",
"first",
"word",
"piece",
"as",
"entire",
"word",
"representation",
"As",
"we",
"have",
"only",
"one",
"index",
"for",
"each",
"token,",
"we",
"need",
"to",
"expand",
"to",
"the",
"size",
"of",
"reps",
"dim."
] | def extract_non_word_piece_reps(self, reps, index):
expand_shape = list(index.shape)
expand_shape[-1] = reps.shape[-1]
index = index.expand(expand_shape)
nwp_reps = torch.gather(input=reps, index=index, dim=-2)
return nwp_reps | ['def', 'extract_non_word_piece_reps(self,', 'reps,', 'index):', 'expand_shape', '=', 'list(index.shape)', 'expand_shape[-1]', '=', 'reps.shape[-1]', 'index', '=', 'index.expand(expand_shape)', 'nwp_reps', '=', 'torch.gather(input=reps,', 'index=index,', 'dim=-2)', 'return', 'nwp_reps'] | 633,578 |
keras-team/keras-nlp | tokenizer.py | Tokenizer.get_vocabulary | get_vocabulary | Get the tokenizer vocabulary as a list of strings terms. | [
"Get",
"the",
"tokenizer",
"vocabulary",
"as",
"a",
"list",
"of",
"strings",
"terms."
] | def get_vocabulary(self) -> List[str]:
raise NotImplementedError(f'No implementation of `get_vocabulary()` was found for {self.__class__.__name__}.') | ['def', 'get_vocabulary(self)', '->', 'List[str]:', 'raise', "NotImplementedError(f'No", 'implementation', 'of', '`get_vocabulary()`', 'was', 'found', 'for', "{self.__class__.__name__}.')"] | 595,694 |
lalwanii26/openscope-barcodingstim | experiment.py | Experiment.remove_item | remove_item | Removes an item by name or reference. | [
"Removes",
"an",
"item",
"by",
"name",
"or",
"reference."
] | def remove_item(self, item=None, name=''):
if item:
for (k, v) in self.items.iteritems():
if item is v:
del self.items[k]
break
else:
del self.items[name] | ['def', 'remove_item(self,', 'item=None,', "name=''):", 'if', 'item:', 'for', '(k,', 'v)', 'in', 'self.items.iteritems():', 'if', 'item', 'is', 'v:', 'del', 'self.items[k]', 'break', 'else:', 'del', 'self.items[name]'] | 757,504 |
BMW-InnovationLab/BMW-Semantic--Inference-API-GPU-CPU | base.py | KeyPointDataset.parent_joints | parent_joints | A dict that defines joint id -> parent_joint_id mapping if applicable, can be empty. | [
"A",
"dict",
"that",
"defines",
"joint",
"id",
"->",
"parent_joint_id",
"mapping",
"if",
"applicable,",
"can",
"be",
"empty."
] | def parent_joints(self):
return {} | ['def', 'parent_joints(self):', 'return', '{}'] | 461,937 |
AlbertPi-Git/Semantic-Recognized-Realtime-Camera-Style-Transfer | gluon_resnet.py | gluon_resnext50_32x4d | gluon_resnext50_32x4d | Constructs a ResNeXt50-32x4d model. | [
"Constructs",
"a",
"ResNeXt50-32x4d",
"model."
] | def gluon_resnext50_32x4d(pretrained=False, num_classes=1000, in_chans=3, **kwargs):
default_cfg = default_cfgs['gluon_resnext50_32x4d']
model = GluonResNet(BottleneckGl, [3, 4, 6, 3], cardinality=32, base_width=4, num_classes=num_classes, in_chans=in_chans, **kwargs)
model.default_cfg = default_cfg
if ... | ['def', 'gluon_resnext50_32x4d(pretrained=False,', 'num_classes=1000,', 'in_chans=3,', '**kwargs):', 'default_cfg', '=', "default_cfgs['gluon_resnext50_32x4d']", 'model', '=', 'GluonResNet(BottleneckGl,', '[3,', '4,', '6,', '3],', 'cardinality=32,', 'base_width=4,', 'num_classes=num_classes,', 'in_chans=in_chans,', '**... | 844,399 |
poodarchu/Det3D | builder.py | children | children | Get children of `m`. | [
"Get",
"children",
"of",
"`m`."
] | def children(m: nn.Module):
return list(m.children()) | ['def', 'children(m:', 'nn.Module):', 'return', 'list(m.children())'] | 538,358 |
feast-dev/feast | offline_store.py | OfflineStore.offline_write_batch | offline_write_batch | Writes the specified arrow table to the data source underlying the specified feature view. | [
"Writes",
"the",
"specified",
"arrow",
"table",
"to",
"the",
"data",
"source",
"underlying",
"the",
"specified",
"feature",
"view."
] | def offline_write_batch(config: RepoConfig, feature_view: FeatureView, table: pyarrow.Table, progress: Optional[Callable[[int], Any]]):
raise NotImplementedError() | ['def', 'offline_write_batch(config:', 'RepoConfig,', 'feature_view:', 'FeatureView,', 'table:', 'pyarrow.Table,', 'progress:', 'Optional[Callable[[int],', 'Any]]):', 'raise', 'NotImplementedError()'] | 544,380 |
Mohamed-94/Alpha-Mine-ChatBot | memorynetwork.py | parse_stories | parse_stories | Parse stories provided in the bAbi tasks format If only_supporting is true, only the sentences that support the answer are kept. | [
"Parse",
"stories",
"provided",
"in",
"the",
"bAbi",
"tasks",
"format",
"If",
"only_supporting",
"is",
"true,",
"only",
"the",
"sentences",
"that",
"support",
"the",
"answer",
"are",
"kept."
] | def parse_stories(lines, only_supporting=False):
data = []
story = []
for line in lines:
line = line.decode('utf-8').strip()
(nid, line) = line.split(' ', 1)
nid = int(nid)
if nid == 1:
story = []
if '\t' in line:
(q, a, supporting) = line.spli... | ['def', 'parse_stories(lines,', 'only_supporting=False):', 'data', '=', '[]', 'story', '=', '[]', 'for', 'line', 'in', 'lines:', 'line', '=', "line.decode('utf-8').strip()", '(nid,', 'line)', '=', "line.split('", "',", '1)', 'nid', '=', 'int(nid)', 'if', 'nid', '==', '1:', 'story', '=', '[]', 'if', "'\\t'", 'in', 'line... | 32,987 |
mushketyk/aima-python | framework.py | Node.get_path_from_root | get_path_from_root | Get nodes that were explored to reach current node :return (list): list of nodes from root node to a current one. | [
"Get",
"nodes",
"that",
"were",
"explored",
"to",
"reach",
"current",
"node",
":return",
"(list):",
"list",
"of",
"nodes",
"from",
"root",
"node",
"to",
"a",
"current",
"one."
] | def get_path_from_root(self):
node = self
path = []
while node is not None:
path.insert(0, node)
node = node.get_parent()
return path | ['def', 'get_path_from_root(self):', 'node', '=', 'self', 'path', '=', '[]', 'while', 'node', 'is', 'not', 'None:', 'path.insert(0,', 'node)', 'node', '=', 'node.get_parent()', 'return', 'path'] | 86,398 |
myothida/Supervised-Machine-Learning | colors.py | LinearSegmentedColormap.set_gamma | set_gamma | Set a new gamma value and regenerate colormap. | [
"Set",
"a",
"new",
"gamma",
"value",
"and",
"regenerate",
"colormap."
] | def set_gamma(self, gamma):
self._gamma = gamma
self._init() | ['def', 'set_gamma(self,', 'gamma):', 'self._gamma', '=', 'gamma', 'self._init()'] | 361,914 |
weimin17/Object-Detection_HelmetDetection | structured_graph_builder.py | AddCrossEntropy | AddCrossEntropy | Adds a cross entropy cost function. | [
"Adds",
"a",
"cross",
"entropy",
"cost",
"function."
] | def AddCrossEntropy(batch_size, n):
cross_entropies = []
def _Pass():
return tf.constant(0, dtype=tf.float32, shape=[1])
for beam_id in range(batch_size):
beam_gold_slot = tf.reshape(tf.strided_slice(n['gold_slot'], [beam_id], [beam_id + 1]), [1])
def _ComputeCrossEntropy():
... | ['def', 'AddCrossEntropy(batch_size,', 'n):', 'cross_entropies', '=', '[]', 'def', '_Pass():', 'return', 'tf.constant(0,', 'dtype=tf.float32,', 'shape=[1])', 'for', 'beam_id', 'in', 'range(batch_size):', 'beam_gold_slot', '=', "tf.reshape(tf.strided_slice(n['gold_slot'],", '[beam_id],', '[beam_id', '+', '1]),', '[1])',... | 753,594 |
bhrnjica/ObjectDetection | dualattention_refinedet.py | RefineDet.forward | forward | Applies network layers and ops on input image(s) x. | [
"Applies",
"network",
"layers",
"and",
"ops",
"on",
"input",
"image(s)",
"x."
] | def forward(self, x):
sources = list()
tcb_source = list()
arm_loc = list()
arm_conf = list()
odm_loc = list()
odm_conf = list()
for k in range(30):
x = self.vgg[k](x)
if 22 == k:
s = self.conv4_3_L2Norm(x)
sources.append(s)
elif 29 == k:
... | ['def', 'forward(self,', 'x):', 'sources', '=', 'list()', 'tcb_source', '=', 'list()', 'arm_loc', '=', 'list()', 'arm_conf', '=', 'list()', 'odm_loc', '=', 'list()', 'odm_conf', '=', 'list()', 'for', 'k', 'in', 'range(30):', 'x', '=', 'self.vgg[k](x)', 'if', '22', '==', 'k:', 's', '=', 'self.conv4_3_L2Norm(x)', 'source... | 742,834 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.