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 |
|---|---|---|---|---|---|---|---|---|
sunishsheth2009/ChatterBot | test_defchararray.py | test_empty_indexing | test_empty_indexing | Regression test for ticket 1948. | [
"Regression",
"test",
"for",
"ticket",
"1948."
] | def test_empty_indexing():
s = np.chararray((4,))
assert_(s[[]].size == 0) | ['def', 'test_empty_indexing():', 's', '=', 'np.chararray((4,))', 'assert_(s[[]].size', '==', '0)'] | 530,795 |
aws-solutions/maintaining-personalized-experiences-with-- | synthesizers.py | CloudFormationTemplate.delete_cdk_helpers | delete_cdk_helpers | Remove the CDK bucket deployment helpers, since solutions don't have a bootstrap bucket. | [
"Remove",
"the",
"CDK",
"bucket",
"deployment",
"helpers,",
"since",
"solutions",
"don't",
"have",
"a",
"bootstrap",
"bucket."
] | def delete_cdk_helpers(self):
to_delete = []
for (resource_name, resource) in self.contents.get('Resources', {}).items():
if 'Custom::CDKBucketDeployment' in resource['Type']:
to_delete.append(resource_name)
if 'CDKBucketDeployment' in resource_name:
to_delete.append(reso... | ['def', 'delete_cdk_helpers(self):', 'to_delete', '=', '[]', 'for', '(resource_name,', 'resource)', 'in', "self.contents.get('Resources',", '{}).items():', 'if', "'Custom::CDKBucketDeployment'", 'in', "resource['Type']:", 'to_delete.append(resource_name)', 'if', "'CDKBucketDeployment'", 'in', 'resource_name:', 'to_dele... | 627,352 |
JunaidMuthukadan/Music-source-seperation-using-recurrent-VAE | utils.py | flatten_maybe_padded_sequences | flatten_maybe_padded_sequences | Flattens the batch of sequences, removing padding (if applicable). | [
"Flattens",
"the",
"batch",
"of",
"sequences,",
"removing",
"padding",
"(if",
"applicable)."
] | def flatten_maybe_padded_sequences(maybe_padded_sequences, lengths=None):
def flatten_unpadded_sequences():
return tf.reshape(maybe_padded_sequences, [-1] + maybe_padded_sequences.shape.as_list()[2:])
if lengths is None:
return flatten_unpadded_sequences()
def flatten_padded_sequences():
... | ['def', 'flatten_maybe_padded_sequences(maybe_padded_sequences,', 'lengths=None):', 'def', 'flatten_unpadded_sequences():', 'return', 'tf.reshape(maybe_padded_sequences,', '[-1]', '+', 'maybe_padded_sequences.shape.as_list()[2:])', 'if', 'lengths', 'is', 'None:', 'return', 'flatten_unpadded_sequences()', 'def', 'flatte... | 644,682 |
deepmind/meltingpot | mocks.py | build_mock_substrate_like | build_mock_substrate_like | Returns a mock of a specific Substrate for use in testing. | [
"Returns",
"a",
"mock",
"of",
"a",
"specific",
"Substrate",
"for",
"use",
"in",
"testing."
] | def build_mock_substrate_like(name: str, *, num_players: Optional[int]=None) -> ...:
factory = meltingpot.substrate.get_factory(name)
if num_players is None:
num_players = len(factory.default_player_roles())
return _build_mock_substrate(spec=substrate.Substrate, num_players=num_players, action_spec=... | ['def', 'build_mock_substrate_like(name:', 'str,', '*,', 'num_players:', 'Optional[int]=None)', '->', '...:', 'factory', '=', 'meltingpot.substrate.get_factory(name)', 'if', 'num_players', 'is', 'None:', 'num_players', '=', 'len(factory.default_player_roles())', 'return', '_build_mock_substrate(spec=substrate.Substrate... | 285,513 |
Speech-Lab-IITM/CCC-wav2vec-2.0 | trainer.py | Trainer.begin_valid_epoch | begin_valid_epoch | Called at the beginning of each validation epoch. | [
"Called",
"at",
"the",
"beginning",
"of",
"each",
"validation",
"epoch."
] | def begin_valid_epoch(self, epoch):
self.task.begin_valid_epoch(epoch, self.get_model()) | ['def', 'begin_valid_epoch(self,', 'epoch):', 'self.task.begin_valid_epoch(epoch,', 'self.get_model())'] | 103,511 |
matsu0228/nlp-jp | oinspect.py | Inspector.noinfo | noinfo | Generic message when no information is found. | [
"Generic",
"message",
"when",
"no",
"information",
"is",
"found."
] | def noinfo(self, msg, oname):
print('No %s found' % msg, end=' ')
if oname:
print('for %s' % oname)
else:
print() | ['def', 'noinfo(self,', 'msg,', 'oname):', "print('No", '%s', "found'", '%', 'msg,', "end='", "')", 'if', 'oname:', "print('for", "%s'", '%', 'oname)', 'else:', 'print()'] | 786,782 |
wfondrie/mokapot | test_parser_pepxml.py | not_pepxml | not_pepxml | Create a file that is not a PepXML. | [
"Create",
"a",
"file",
"that",
"is",
"not",
"a",
"PepXML."
] | def not_pepxml(tmp_path):
out_file = str(tmp_path / 'test.tsv')
with open(out_file, 'w+') as out_ref:
out_ref.write('Blah\\tblah\\blah\\nblah\\tblah\\blah\\n')
return out_file | ['def', 'not_pepxml(tmp_path):', 'out_file', '=', 'str(tmp_path', '/', "'test.tsv')", 'with', 'open(out_file,', "'w+')", 'as', 'out_ref:', "out_ref.write('Blah\\\\tblah\\\\blah\\\\nblah\\\\tblah\\\\blah\\\\n')", 'return', 'out_file'] | 240,828 |
fmassa/vision | image.py | read_file | read_file | Reads and outputs the bytes contents of a file as a uint8 Tensor with one dimension. | [
"Reads",
"and",
"outputs",
"the",
"bytes",
"contents",
"of",
"a",
"file",
"as",
"a",
"uint8",
"Tensor",
"with",
"one",
"dimension."
] | def read_file(path: str) -> torch.Tensor:
if not torch.jit.is_scripting() and (not torch.jit.is_tracing()):
_log_api_usage_once(read_file)
data = torch.ops.image.read_file(path)
return data | ['def', 'read_file(path:', 'str)', '->', 'torch.Tensor:', 'if', 'not', 'torch.jit.is_scripting()', 'and', '(not', 'torch.jit.is_tracing()):', '_log_api_usage_once(read_file)', 'data', '=', 'torch.ops.image.read_file(path)', 'return', 'data'] | 958,346 |
yinyunie/ScenePriors | test_se3.py | TestSE3.test_compare_with_precomputed | test_compare_with_precomputed | Compare the outputs against precomputed results. | [
"Compare",
"the",
"outputs",
"against",
"precomputed",
"results."
] | def test_compare_with_precomputed(self):
self.assertClose(se3_log_map(self.precomputed_transform), self.precomputed_log_transform, atol=0.0001)
self.assertClose(self.precomputed_transform, se3_exp_map(self.precomputed_log_transform), atol=0.0001) | ['def', 'test_compare_with_precomputed(self):', 'self.assertClose(se3_log_map(self.precomputed_transform),', 'self.precomputed_log_transform,', 'atol=0.0001)', 'self.assertClose(self.precomputed_transform,', 'se3_exp_map(self.precomputed_log_transform),', 'atol=0.0001)'] | 330,164 |
rudranil723/mini-main | cache.py | SeparateBodyBaseCache.get_body | get_body | Return the body as file-like object. | [
"Return",
"the",
"body",
"as",
"file-like",
"object."
] | def get_body(self, key):
raise NotImplementedError() | ['def', 'get_body(self,', 'key):', 'raise', 'NotImplementedError()'] | 268,289 |
Megvii-BaseDetection/cvpods | transform.py | AffineTransform.apply_image | apply_image | Apply AffineTransform for the image(s). | [
"Apply",
"AffineTransform",
"for",
"the",
"image(s)."
] | def apply_image(self, img: np.ndarray) -> np.ndarray:
return cv2.warpAffine(img, self.affine, self.output_size, flags=cv2.INTER_LINEAR, borderValue=self.pad_value) | ['def', 'apply_image(self,', 'img:', 'np.ndarray)', '->', 'np.ndarray:', 'return', 'cv2.warpAffine(img,', 'self.affine,', 'self.output_size,', 'flags=cv2.INTER_LINEAR,', 'borderValue=self.pad_value)'] | 510,877 |
Res2Net/Res2Net-maskrcnn | bounding_box.py | BoxList.resize | resize | Returns a resized copy of this bounding box :param size: The requested size in pixels, as a 2-tuple: (width, height). | [
"Returns",
"a",
"resized",
"copy",
"of",
"this",
"bounding",
"box",
":param",
"size:",
"The",
"requested",
"size",
"in",
"pixels,",
"as",
"a",
"2-tuple:",
"(width,",
"height)."
] | def resize(self, size, *args, **kwargs):
ratios = tuple((float(s) / float(s_orig) for (s, s_orig) in zip(size, self.size)))
if ratios[0] == ratios[1]:
ratio = ratios[0]
scaled_box = self.bbox * ratio
bbox = BoxList(scaled_box, size, mode=self.mode)
for (k, v) in self.extra_fields... | ['def', 'resize(self,', 'size,', '*args,', '**kwargs):', 'ratios', '=', 'tuple((float(s)', '/', 'float(s_orig)', 'for', '(s,', 's_orig)', 'in', 'zip(size,', 'self.size)))', 'if', 'ratios[0]', '==', 'ratios[1]:', 'ratio', '=', 'ratios[0]', 'scaled_box', '=', 'self.bbox', '*', 'ratio', 'bbox', '=', 'BoxList(scaled_box,',... | 840,439 |
myothida/Supervised-Machine-Learning | cygwinccompiler.py | is_cygwincc | is_cygwincc | Try to determine if the compiler that would be used is from cygwin. | [
"Try",
"to",
"determine",
"if",
"the",
"compiler",
"that",
"would",
"be",
"used",
"is",
"from",
"cygwin."
] | def is_cygwincc(cc):
out_string = check_output([cc, '-dumpmachine'])
return out_string.strip().endswith(b'cygwin') | ['def', 'is_cygwincc(cc):', 'out_string', '=', 'check_output([cc,', "'-dumpmachine'])", 'return', "out_string.strip().endswith(b'cygwin')"] | 447,064 |
salesforce/CodeRL | trainer_pt_utils.py | log_metrics | log_metrics | Log metrics in a specially formatted way Under distributed environment this is done only for a process with rank 0. | [
"Log",
"metrics",
"in",
"a",
"specially",
"formatted",
"way",
"Under",
"distributed",
"environment",
"this",
"is",
"done",
"only",
"for",
"a",
"process",
"with",
"rank",
"0."
] | def log_metrics(self, split, metrics):
if not self.is_world_process_zero():
return
print(f'***** {split} metrics *****')
metrics_formatted = self.metrics_format(metrics)
k_width = max((len(str(x)) for x in metrics_formatted.keys()))
v_width = max((len(str(x)) for x in metrics_formatted.value... | ['def', 'log_metrics(self,', 'split,', 'metrics):', 'if', 'not', 'self.is_world_process_zero():', 'return', "print(f'*****", '{split}', 'metrics', "*****')", 'metrics_formatted', '=', 'self.metrics_format(metrics)', 'k_width', '=', 'max((len(str(x))', 'for', 'x', 'in', 'metrics_formatted.keys()))', 'v_width', '=', 'max... | 494,178 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | seq2seq_lib.py | sequence_loss_by_example | sequence_loss_by_example | Sampled softmax loss for a sequence of inputs (per example). | [
"Sampled",
"softmax",
"loss",
"for",
"a",
"sequence",
"of",
"inputs",
"(per",
"example)."
] | def sequence_loss_by_example(inputs, targets, weights, loss_function, average_across_timesteps=True, name=None):
if len(targets) != len(inputs) or len(weights) != len(inputs):
raise ValueError('Lengths of logits, weights, and targets must be the same %d, %d, %d.' % (len(inputs), len(weights), len(targets)))... | ['def', 'sequence_loss_by_example(inputs,', 'targets,', 'weights,', 'loss_function,', 'average_across_timesteps=True,', 'name=None):', 'if', 'len(targets)', '!=', 'len(inputs)', 'or', 'len(weights)', '!=', 'len(inputs):', 'raise', "ValueError('Lengths", 'of', 'logits,', 'weights,', 'and', 'targets', 'must', 'be', 'the'... | 29,922 |
ncbi-nlp/DeepRel | utils.py | create_tempfile | create_tempfile | Create a temporary file. | [
"Create",
"a",
"temporary",
"file."
] | def create_tempfile(suffix: str) -> str:
fp = tempfile.NamedTemporaryFile(delete=False, suffix=suffix)
fp.close()
return fp.name | ['def', 'create_tempfile(suffix:', 'str)', '->', 'str:', 'fp', '=', 'tempfile.NamedTemporaryFile(delete=False,', 'suffix=suffix)', 'fp.close()', 'return', 'fp.name'] | 180,748 |
Ruturaj123/Flowchart-Detection | data_flow_ops.py | QueueBase.name | name | The name of the underlying queue. | [
"The",
"name",
"of",
"the",
"underlying",
"queue."
] | def name(self):
return self._queue_ref.op.name | ['def', 'name(self):', 'return', 'self._queue_ref.op.name'] | 605,827 |
rudranil723/mini-main | cells.py | cell_len | cell_len | Get the number of cells required to display text. | [
"Get",
"the",
"number",
"of",
"cells",
"required",
"to",
"display",
"text."
] | def cell_len(text: str, _cell_len: Callable[[str], int]=cached_cell_len) -> int:
if len(text) < 512:
return _cell_len(text)
_get_size = get_character_cell_size
total_size = sum((_get_size(character) for character in text))
return total_size | ['def', 'cell_len(text:', 'str,', '_cell_len:', 'Callable[[str],', 'int]=cached_cell_len)', '->', 'int:', 'if', 'len(text)', '<', '512:', 'return', '_cell_len(text)', '_get_size', '=', 'get_character_cell_size', 'total_size', '=', 'sum((_get_size(character)', 'for', 'character', 'in', 'text))', 'return', 'total_size'] | 268,859 |
googleapis/python-aiplatform | client.py | FeatureOnlineStoreAdminServiceClient.common_folder_path | common_folder_path | Returns a fully-qualified folder string. | [
"Returns",
"a",
"fully-qualified",
"folder",
"string."
] | def common_folder_path(folder: str) -> str:
return 'folders/{folder}'.format(folder=folder) | ['def', 'common_folder_path(folder:', 'str)', '->', 'str:', 'return', "'folders/{folder}'.format(folder=folder)"] | 812,626 |
nicknochnack/RealTimeSignLanguageTFJS | factory.py | build_decoder | build_decoder | Builds decoder from a config. | [
"Builds",
"decoder",
"from",
"a",
"config."
] | def build_decoder(input_specs, model_config, l2_regularizer: tf.keras.regularizers.Regularizer=None):
decoder_type = model_config.decoder.type
decoder_cfg = model_config.decoder.get()
norm_activation_config = model_config.norm_activation
if decoder_type == 'identity':
decoder = None
elif dec... | ['def', 'build_decoder(input_specs,', 'model_config,', 'l2_regularizer:', 'tf.keras.regularizers.Regularizer=None):', 'decoder_type', '=', 'model_config.decoder.type', 'decoder_cfg', '=', 'model_config.decoder.get()', 'norm_activation_config', '=', 'model_config.norm_activation', 'if', 'decoder_type', '==', "'identity'... | 850,839 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | document.py | Document.get_end_of_document_position | get_end_of_document_position | Relative position for the end of the document. | [
"Relative",
"position",
"for",
"the",
"end",
"of",
"the",
"document."
] | def get_end_of_document_position(self) -> int:
return len(self.text) - self.cursor_position | ['def', 'get_end_of_document_position(self)', '->', 'int:', 'return', 'len(self.text)', '-', 'self.cursor_position'] | 435,016 |
sshaoshuai/PointRCNN | fastai_optim.py | OptimWrapper.clear | clear | Reset the state of the inner optimizer. | [
"Reset",
"the",
"state",
"of",
"the",
"inner",
"optimizer."
] | def clear(self):
sd = self.state_dict()
sd['state'] = {}
self.load_state_dict(sd) | ['def', 'clear(self):', 'sd', '=', 'self.state_dict()', "sd['state']", '=', '{}', 'self.load_state_dict(sd)'] | 781,275 |
DevanshuSave/Pacman-and-Ghostbusters | captureAgents.py | AgentFactory.getAgent | getAgent | Returns the agent for the provided index. | [
"Returns",
"the",
"agent",
"for",
"the",
"provided",
"index."
] | def getAgent(self, index):
util.raiseNotDefined() | ['def', 'getAgent(self,', 'index):', 'util.raiseNotDefined()'] | 253,924 |
alteryx/compose | deserialize.py | read_data | read_data | Reads data file from disk. | [
"Reads",
"data",
"file",
"from",
"disk."
] | def read_data(path):
file = ''
for file in os.listdir(path):
if file.startswith('data'):
break
assert file.startswith('data'), 'data not found'
extension = os.path.splitext(file)[1].lstrip('.')
info = 'file extension must be csv, parquet, or pickle'
assert extension in ['csv'... | ['def', 'read_data(path):', 'file', '=', "''", 'for', 'file', 'in', 'os.listdir(path):', 'if', "file.startswith('data'):", 'break', 'assert', "file.startswith('data'),", "'data", 'not', "found'", 'extension', '=', "os.path.splitext(file)[1].lstrip('.')", 'info', '=', "'file", 'extension', 'must', 'be', 'csv,', 'parquet... | 136,041 |
Xianpeng919/MonoCon | gaussian.py | draw_heatmap_gaussian | draw_heatmap_gaussian | Get gaussian masked heatmap. | [
"Get",
"gaussian",
"masked",
"heatmap."
] | def draw_heatmap_gaussian(heatmap, center, radius, k=1):
diameter = 2 * radius + 1
gaussian = gaussian_2d((diameter, diameter), sigma=diameter / 6)
(x, y) = (int(center[0]), int(center[1]))
(height, width) = heatmap.shape[0:2]
(left, right) = (min(x, radius), min(width - x, radius + 1))
(top, bo... | ['def', 'draw_heatmap_gaussian(heatmap,', 'center,', 'radius,', 'k=1):', 'diameter', '=', '2', '*', 'radius', '+', '1', 'gaussian', '=', 'gaussian_2d((diameter,', 'diameter),', 'sigma=diameter', '/', '6)', '(x,', 'y)', '=', '(int(center[0]),', 'int(center[1]))', '(height,', 'width)', '=', 'heatmap.shape[0:2]', '(left,'... | 654,395 |
sek788432/Waymo-2D-Object-Detection | input_pipeline.py | create_squad_dataset | create_squad_dataset | Creates input dataset from (tf)records files for train/eval. | [
"Creates",
"input",
"dataset",
"from",
"(tf)records",
"files",
"for",
"train/eval."
] | def create_squad_dataset(file_path, seq_length, batch_size, is_training=True, input_pipeline_context=None):
name_to_features = {'input_ids': tf.io.FixedLenFeature([seq_length], tf.int64), 'input_mask': tf.io.FixedLenFeature([seq_length], tf.int64), 'segment_ids': tf.io.FixedLenFeature([seq_length], tf.int64)}
i... | ['def', 'create_squad_dataset(file_path,', 'seq_length,', 'batch_size,', 'is_training=True,', 'input_pipeline_context=None):', 'name_to_features', '=', "{'input_ids':", 'tf.io.FixedLenFeature([seq_length],', 'tf.int64),', "'input_mask':", 'tf.io.FixedLenFeature([seq_length],', 'tf.int64),', "'segment_ids':", 'tf.io.Fix... | 972,429 |
amirbar/DETReg | detr.py | SetCriterion.loss_object_embedding | loss_object_embedding | Compute the losses related to the bounding boxes, the L1 regression loss and the GIoU loss targets dicts must contain the key "boxes" containing a tensor of dim [nb_target_boxes, 4] The target boxes are expected in format (center_x, center_y, h, w), normalized by the image size. | [
"Compute",
"the",
"losses",
"related",
"to",
"the",
"bounding",
"boxes,",
"the",
"L1",
"regression",
"loss",
"and",
"the",
"GIoU",
"loss",
"targets",
"dicts",
"must",
"contain",
"the",
"key",
"\"boxes\"",
"containing",
"a",
"tensor",
"of",
"dim",
"[nb_target_b... | def loss_object_embedding(self, outputs, targets, indices, num_boxes):
assert 'pred_boxes' in outputs
idx = self._get_src_permutation_idx(indices)
src_features = outputs['pred_features'][idx]
tgt_idx = self._get_tgt_permutation_idx(indices)
target_features = [t['patches'] for t in targets]
targe... | ['def', 'loss_object_embedding(self,', 'outputs,', 'targets,', 'indices,', 'num_boxes):', 'assert', "'pred_boxes'", 'in', 'outputs', 'idx', '=', 'self._get_src_permutation_idx(indices)', 'src_features', '=', "outputs['pred_features'][idx]", 'tgt_idx', '=', 'self._get_tgt_permutation_idx(indices)', 'target_features', '=... | 549,729 |
rudranil723/mini-main | punkt.py | PunktTrainer.finalize_training | finalize_training | Uses data that has been gathered in training to determine likely collocations and sentence starters. | [
"Uses",
"data",
"that",
"has",
"been",
"gathered",
"in",
"training",
"to",
"determine",
"likely",
"collocations",
"and",
"sentence",
"starters."
] | def finalize_training(self, verbose=False):
self._params.clear_sent_starters()
for (typ, ll) in self._find_sent_starters():
self._params.sent_starters.add(typ)
if verbose:
print(' Sent Starter: [%6.4f] %r' % (ll, typ))
self._params.clear_collocations()
for ((typ1, typ2), ll)... | ['def', 'finalize_training(self,', 'verbose=False):', 'self._params.clear_sent_starters()', 'for', '(typ,', 'll)', 'in', 'self._find_sent_starters():', 'self._params.sent_starters.add(typ)', 'if', 'verbose:', "print('", 'Sent', 'Starter:', '[%6.4f]', "%r'", '%', '(ll,', 'typ))', 'self._params.clear_collocations()', 'fo... | 321,930 |
aralab-unr/ReinforcementLearningWithGA | rollout.py | RolloutWorker.reset_all_rollouts | reset_all_rollouts | Resets all `rollout_batch_size` rollout workers. | [
"Resets",
"all",
"`rollout_batch_size`",
"rollout",
"workers."
] | def reset_all_rollouts(self):
for i in range(self.rollout_batch_size):
self.reset_rollout(i) | ['def', 'reset_all_rollouts(self):', 'for', 'i', 'in', 'range(self.rollout_batch_size):', 'self.reset_rollout(i)'] | 833,916 |
IINemo/isanlp | nlp_service_server.py | NlpServiceServer.serve | serve | Initiates server for listening of incoming connections (blocking). | [
"Initiates",
"server",
"for",
"listening",
"of",
"incoming",
"connections",
"(blocking)."
] | def serve(self):
server = grpc.server(futures.ThreadPoolExecutor(max_workers=self._max_workers))
self._service.add_to_server(server)
server.add_insecure_port('[::]:{}'.format(self._port))
server.start()
try:
while True:
time.sleep(60)
except KeyboardInterrupt:
server.... | ['def', 'serve(self):', 'server', '=', 'grpc.server(futures.ThreadPoolExecutor(max_workers=self._max_workers))', 'self._service.add_to_server(server)', "server.add_insecure_port('[::]:{}'.format(self._port))", 'server.start()', 'try:', 'while', 'True:', 'time.sleep(60)', 'except', 'KeyboardInterrupt:', 'server.stop(0)'... | 577,238 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | layers.py | predictions | predictions | Class prediction from logits. | [
"Class",
"prediction",
"from",
"logits."
] | def predictions(logits):
inner_dim = logits.get_shape().as_list()[-1]
with tf.name_scope('predictions'):
if inner_dim == 1:
pred = tf.cast(tf.greater(tf.squeeze(logits), 0.5), tf.int64)
else:
pred = tf.argmax(logits, 1)
return pred | ['def', 'predictions(logits):', 'inner_dim', '=', 'logits.get_shape().as_list()[-1]', 'with', "tf.name_scope('predictions'):", 'if', 'inner_dim', '==', '1:', 'pred', '=', 'tf.cast(tf.greater(tf.squeeze(logits),', '0.5),', 'tf.int64)', 'else:', 'pred', '=', 'tf.argmax(logits,', '1)', 'return', 'pred'] | 14,270 |
neokarn/computer_vision | config_util_test.py | ConfigUtilTest.testDontOverwriteEmptyLabelMapPath | testDontOverwriteEmptyLabelMapPath | Tests that label map path will not by overwritten with empty string. | [
"Tests",
"that",
"label",
"map",
"path",
"will",
"not",
"by",
"overwritten",
"with",
"empty",
"string."
] | def testDontOverwriteEmptyLabelMapPath(self):
original_label_map_path = 'path/to/original/label_map'
new_label_map_path = ''
pipeline_config_path = os.path.join(self.get_temp_dir(), 'pipeline.config')
pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
train_input_reader = pipeline_config.train... | ['def', 'testDontOverwriteEmptyLabelMapPath(self):', 'original_label_map_path', '=', "'path/to/original/label_map'", 'new_label_map_path', '=', "''", 'pipeline_config_path', '=', 'os.path.join(self.get_temp_dir(),', "'pipeline.config')", 'pipeline_config', '=', 'pipeline_pb2.TrainEvalPipelineConfig()', 'train_input_rea... | 512,212 |
leonnnop/GMMSeg | custom.py | CustomDataset.get_gt_seg_map_by_idx | get_gt_seg_map_by_idx | Get one ground truth segmentation map for evaluation. | [
"Get",
"one",
"ground",
"truth",
"segmentation",
"map",
"for",
"evaluation."
] | def get_gt_seg_map_by_idx(self, index):
ann_info = self.get_ann_info(index)
results = dict(ann_info=ann_info)
self.pre_pipeline(results)
self.gt_seg_map_loader(results)
return results['gt_semantic_seg'] | ['def', 'get_gt_seg_map_by_idx(self,', 'index):', 'ann_info', '=', 'self.get_ann_info(index)', 'results', '=', 'dict(ann_info=ann_info)', 'self.pre_pipeline(results)', 'self.gt_seg_map_loader(results)', 'return', "results['gt_semantic_seg']"] | 578,373 |
suarez12138/AI-Reversi_IMP_TextDichotomy | wheel_legacy.py | get_legacy_build_wheel_path | get_legacy_build_wheel_path | Return the path to the wheel in the temporary build directory. | [
"Return",
"the",
"path",
"to",
"the",
"wheel",
"in",
"the",
"temporary",
"build",
"directory."
] | def get_legacy_build_wheel_path(names, temp_dir, name, command_args, command_output):
names = sorted(names)
if not names:
msg = 'Legacy build of wheel for {!r} created no files.\n'.format(name)
msg += format_command_result(command_args, command_output)
logger.warning(msg)
return ... | ['def', 'get_legacy_build_wheel_path(names,', 'temp_dir,', 'name,', 'command_args,', 'command_output):', 'names', '=', 'sorted(names)', 'if', 'not', 'names:', 'msg', '=', "'Legacy", 'build', 'of', 'wheel', 'for', '{!r}', 'created', 'no', "files.\\n'.format(name)", 'msg', '+=', 'format_command_result(command_args,', 'co... | 98,439 |
Rose-STL-Lab/DIVE | utils.py | get_objects | get_objects | Crop objects from input given the transformer. | [
"Crop",
"objects",
"from",
"input",
"given",
"the",
"transformer."
] | def get_objects(input, transformer, n_components, object_size):
repeated_input = torch.stack([input] * n_components, dim=2)
repeated_input = repeated_input.view(-1, *input.size()[-3:])
transformer = transformer.contiguous().view(-1, transformer.size(-1))
input_obj = image_to_object(repeated_input, trans... | ['def', 'get_objects(input,', 'transformer,', 'n_components,', 'object_size):', 'repeated_input', '=', 'torch.stack([input]', '*', 'n_components,', 'dim=2)', 'repeated_input', '=', 'repeated_input.view(-1,', '*input.size()[-3:])', 'transformer', '=', 'transformer.contiguous().view(-1,', 'transformer.size(-1))', 'input_... | 552,242 |
danamyu/hedgehog_detector | pixelda_losses.py | g_step_loss | g_step_loss | Configures the loss function which runs during the g-step. | [
"Configures",
"the",
"loss",
"function",
"which",
"runs",
"during",
"the",
"g-step."
] | def g_step_loss(source_images, source_labels, end_points, hparams, num_classes):
generator_loss = 0
style_transfer_loss = tf.losses.sigmoid_cross_entropy(logits=end_points['transferred_domain_logits'], multi_class_labels=tf.ones_like(end_points['transferred_domain_logits']), weights=hparams.style_transfer_loss_... | ['def', 'g_step_loss(source_images,', 'source_labels,', 'end_points,', 'hparams,', 'num_classes):', 'generator_loss', '=', '0', 'style_transfer_loss', '=', "tf.losses.sigmoid_cross_entropy(logits=end_points['transferred_domain_logits'],", "multi_class_labels=tf.ones_like(end_points['transferred_domain_logits']),", 'wei... | 589,548 |
mfbx9da4/neuron-astrocyte-networks | gomoku.py | GomokuGame.getKilling | getKilling | return all legal positions for a color that immediately kill the opponent. | [
"return",
"all",
"legal",
"positions",
"for",
"a",
"color",
"that",
"immediately",
"kill",
"the",
"opponent."
] | def getKilling(self, c):
return filter(lambda p: self._fiveRow(c, p), self.getLegals(c)) | ['def', 'getKilling(self,', 'c):', 'return', 'filter(lambda', 'p:', 'self._fiveRow(c,', 'p),', 'self.getLegals(c))'] | 722,601 |
deepmind/dm_alchemy | unity_python_conversion.py | to_unity_chemistry | to_unity_chemistry | Convert from python types to unity Chemistry object. | [
"Convert",
"from",
"python",
"types",
"to",
"unity",
"Chemistry",
"object."
] | def to_unity_chemistry(chemistry: utils.Chemistry) -> Tuple[alchemy_pb2.Chemistry, alchemy_pb2.RotationMapping]:
latent_stones = stones_and_potions.possible_latent_stones()
latent_potions = stones_and_potions.possible_latent_potions()
python_to_unity = PythonToUnityDimMap(chemistry)
python_latent_stones... | ['def', 'to_unity_chemistry(chemistry:', 'utils.Chemistry)', '->', 'Tuple[alchemy_pb2.Chemistry,', 'alchemy_pb2.RotationMapping]:', 'latent_stones', '=', 'stones_and_potions.possible_latent_stones()', 'latent_potions', '=', 'stones_and_potions.possible_latent_potions()', 'python_to_unity', '=', 'PythonToUnityDimMap(che... | 522,288 |
googleinterns/wss | resnet_v1.py | resnet_v1_block | resnet_v1_block | Helper function for creating a resnet_v1 bottleneck block. | [
"Helper",
"function",
"for",
"creating",
"a",
"resnet_v1",
"bottleneck",
"block."
] | def resnet_v1_block(scope, base_depth, num_units, stride):
return resnet_utils.Block(scope, bottleneck, [{'depth': base_depth * 4, 'depth_bottleneck': base_depth, 'stride': 1}] * (num_units - 1) + [{'depth': base_depth * 4, 'depth_bottleneck': base_depth, 'stride': stride}]) | ['def', 'resnet_v1_block(scope,', 'base_depth,', 'num_units,', 'stride):', 'return', 'resnet_utils.Block(scope,', 'bottleneck,', "[{'depth':", 'base_depth', '*', '4,', "'depth_bottleneck':", 'base_depth,', "'stride':", '1}]', '*', '(num_units', '-', '1)', '+', "[{'depth':", 'base_depth', '*', '4,', "'depth_bottleneck':... | 960,915 |
arshpreetsingh/quantopian-machinelearning | vt100.py | Vt100_Output.ask_for_cpr | ask_for_cpr | Asks for a cursor position report (CPR). | [
"Asks",
"for",
"a",
"cursor",
"position",
"report",
"(CPR)."
] | def ask_for_cpr(self):
self.write_raw('\x1b[6n')
self.flush() | ['def', 'ask_for_cpr(self):', "self.write_raw('\\x1b[6n')", 'self.flush()'] | 892,528 |
pytorch/rl | test_transforms.py | TransformBase.test_parallel_trans_env_check | test_parallel_trans_env_check | tests that a parallel transformed env (ParallelEnv(N, lambda: TransformedEnv(env, transform))) passes the check_env_specs test. | [
"tests",
"that",
"a",
"parallel",
"transformed",
"env",
"(ParallelEnv(N,",
"lambda:",
"TransformedEnv(env,",
"transform)))",
"passes",
"the",
"check_env_specs",
"test."
] | def test_parallel_trans_env_check(self):
raise NotImplementedError | ['def', 'test_parallel_trans_env_check(self):', 'raise', 'NotImplementedError'] | 858,417 |
PartnershipOnAI/safelife | safelife_game.py | GameWithGoals.reset_points_table | reset_points_table | Reset the points table to default values. | [
"Reset",
"the",
"points",
"table",
"to",
"default",
"values."
] | def reset_points_table(self):
num_agents = len(self.agent_locs)
self.points_table = np.tile(self.default_points_table, [num_agents, 1, 1]) | ['def', 'reset_points_table(self):', 'num_agents', '=', 'len(self.agent_locs)', 'self.points_table', '=', 'np.tile(self.default_points_table,', '[num_agents,', '1,', '1])'] | 829,256 |
NVIDIA-Omniverse/OmniIsaacGymEnvs | factory_control.py | get_analytic_jacobian | get_analytic_jacobian | Convert geometric Jacobian to analytic Jacobian. | [
"Convert",
"geometric",
"Jacobian",
"to",
"analytic",
"Jacobian."
] | def get_analytic_jacobian(fingertip_quat, fingertip_jacobian, num_envs, device):
batch = num_envs
I = torch.eye(3, device=device)
E_p_inv = I.repeat((batch, 1)).reshape(batch, 3, 3)
E_inv_top = torch.cat((E_p_inv, torch.zeros((batch, 3, 3), device=device)), dim=2)
fingertip_axis_angle = axis_angle_f... | ['def', 'get_analytic_jacobian(fingertip_quat,', 'fingertip_jacobian,', 'num_envs,', 'device):', 'batch', '=', 'num_envs', 'I', '=', 'torch.eye(3,', 'device=device)', 'E_p_inv', '=', 'I.repeat((batch,', '1)).reshape(batch,', '3,', '3)', 'E_inv_top', '=', 'torch.cat((E_p_inv,', 'torch.zeros((batch,', '3,', '3),', 'devic... | 250,383 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | preprocessing.py | cv2resizeminedge | cv2resizeminedge | Resize smallest edge of image to min_edge_size. | [
"Resize",
"smallest",
"edge",
"of",
"image",
"to",
"min_edge_size."
] | def cv2resizeminedge(image, min_edge_size):
assert min_edge_size >= 0
(height, width) = (image.shape[0], image.shape[1])
(new_height, new_width) = (0, 0)
if height > width:
new_width = min_edge_size
new_height = int(height * new_width / float(width))
else:
new_height = min_ed... | ['def', 'cv2resizeminedge(image,', 'min_edge_size):', 'assert', 'min_edge_size', '>=', '0', '(height,', 'width)', '=', '(image.shape[0],', 'image.shape[1])', '(new_height,', 'new_width)', '=', '(0,', '0)', 'if', 'height', '>', 'width:', 'new_width', '=', 'min_edge_size', 'new_height', '=', 'int(height', '*', 'new_width... | 112,216 |
ChandlerBang/awesome-self-supervised-gnn | scholar.py | SearchScholarQuery.set_phrase | set_phrase | Sets phrase that must be found in the result exactly. | [
"Sets",
"phrase",
"that",
"must",
"be",
"found",
"in",
"the",
"result",
"exactly."
] | def set_phrase(self, phrase):
self.phrase = phrase | ['def', 'set_phrase(self,', 'phrase):', 'self.phrase', '=', 'phrase'] | 93,859 |
mayuelala/SimVTP | video_transforms.py | random_short_side_scale_jitter | random_short_side_scale_jitter | Perform a spatial short scale jittering on the given images and corresponding boxes. | [
"Perform",
"a",
"spatial",
"short",
"scale",
"jittering",
"on",
"the",
"given",
"images",
"and",
"corresponding",
"boxes."
] | def random_short_side_scale_jitter(images, min_size, max_size, boxes=None, inverse_uniform_sampling=False):
if inverse_uniform_sampling:
size = int(round(1.0 / np.random.uniform(1.0 / max_size, 1.0 / min_size)))
else:
size = int(round(np.random.uniform(min_size, max_size)))
height = images.s... | ['def', 'random_short_side_scale_jitter(images,', 'min_size,', 'max_size,', 'boxes=None,', 'inverse_uniform_sampling=False):', 'if', 'inverse_uniform_sampling:', 'size', '=', 'int(round(1.0', '/', 'np.random.uniform(1.0', '/', 'max_size,', '1.0', '/', 'min_size)))', 'else:', 'size', '=', 'int(round(np.random.uniform(mi... | 884,289 |
jsyoon0823/VIME | vime_semi.py | vime_semi | vime_semi | Semi-supervied learning part in VIME. | [
"Semi-supervied",
"learning",
"part",
"in",
"VIME."
] | def vime_semi(x_train, y_train, x_unlab, x_test, parameters, p_m, K, beta, file_name):
hidden_dim = parameters['hidden_dim']
act_fn = tf.nn.relu
batch_size = parameters['batch_size']
iterations = parameters['iterations']
data_dim = len(x_train[0, :])
label_dim = len(y_train[0, :])
idx = np.r... | ['def', 'vime_semi(x_train,', 'y_train,', 'x_unlab,', 'x_test,', 'parameters,', 'p_m,', 'K,', 'beta,', 'file_name):', 'hidden_dim', '=', "parameters['hidden_dim']", 'act_fn', '=', 'tf.nn.relu', 'batch_size', '=', "parameters['batch_size']", 'iterations', '=', "parameters['iterations']", 'data_dim', '=', 'len(x_train[0,... | 380,175 |
google-research/s4l | tpu_ops.py | get_norm_modes | get_norm_modes | Returns the currently set NormModes. | [
"Returns",
"the",
"currently",
"set",
"NormModes."
] | def get_norm_modes():
if not _NORM_MODES:
raise ValueError('No norm modes set.')
return _NORM_MODES[-1] | ['def', 'get_norm_modes():', 'if', 'not', '_NORM_MODES:', 'raise', "ValueError('No", 'norm', 'modes', "set.')", 'return', '_NORM_MODES[-1]'] | 328,023 |
enlite-ai/maze | test_wrapper.py | test_assigning_attributes_across_wrapper_stack | test_assigning_attributes_across_wrapper_stack | Attributes should be set on the correct wrappers. | [
"Attributes",
"should",
"be",
"set",
"on",
"the",
"correct",
"wrappers."
] | def test_assigning_attributes_across_wrapper_stack():
env = build_dummy_maze_env()
env = _NestedWrapper.wrap(env)
env = LogStatsWrapper.wrap(env)
assert env.custom_attribute == 0
assert env.env.custom_attribute == 0
assert not hasattr(env.env.env, 'custom_attribute')
env.custom_attribute = 1... | ['def', 'test_assigning_attributes_across_wrapper_stack():', 'env', '=', 'build_dummy_maze_env()', 'env', '=', '_NestedWrapper.wrap(env)', 'env', '=', 'LogStatsWrapper.wrap(env)', 'assert', 'env.custom_attribute', '==', '0', 'assert', 'env.env.custom_attribute', '==', '0', 'assert', 'not', 'hasattr(env.env.env,', "'cus... | 647,217 |
chaiso-krit/autoencoder | train-autoencoder.py | show_parameter_count | show_parameter_count | Count and print how many parameters there are. | [
"Count",
"and",
"print",
"how",
"many",
"parameters",
"there",
"are."
] | def show_parameter_count(variables):
total_parameters = 0
for variable in variables:
name = variable.name
shape = variable.get_shape()
variable_parametes = 1
for dim in shape:
variable_parametes *= dim.value
print('{}: {} ({} parameters)'.format(name, shape, v... | ['def', 'show_parameter_count(variables):', 'total_parameters', '=', '0', 'for', 'variable', 'in', 'variables:', 'name', '=', 'variable.name', 'shape', '=', 'variable.get_shape()', 'variable_parametes', '=', '1', 'for', 'dim', 'in', 'shape:', 'variable_parametes', '*=', 'dim.value', "print('{}:", '{}', '({}', "paramete... | 419,331 |
zhang614/MicroGrid | __init__.py | FCompiler.can_ccompiler_link | can_ccompiler_link | Check if the given C compiler can link objects produced by this compiler. | [
"Check",
"if",
"the",
"given",
"C",
"compiler",
"can",
"link",
"objects",
"produced",
"by",
"this",
"compiler."
] | def can_ccompiler_link(self, ccompiler):
return True | ['def', 'can_ccompiler_link(self,', 'ccompiler):', 'return', 'True'] | 667,365 |
RonMcKay/OODRetrieval | a2d2.py | fulltotrain | fulltotrain | Transforms labels from full A2D2 labelset to training label set. | [
"Transforms",
"labels",
"from",
"full",
"A2D2",
"labelset",
"to",
"training",
"label",
"set."
] | def fulltotrain(target):
remapped_target = target.clone()
for (k, v) in id_to_trainid.items():
remapped_target[target == k] = v
return remapped_target | ['def', 'fulltotrain(target):', 'remapped_target', '=', 'target.clone()', 'for', '(k,', 'v)', 'in', 'id_to_trainid.items():', 'remapped_target[target', '==', 'k]', '=', 'v', 'return', 'remapped_target'] | 756,675 |
atulkum/object_detection | box_list_ops.py | scale | scale | scale box coordinates in x and y dimensions. | [
"scale",
"box",
"coordinates",
"in",
"x",
"and",
"y",
"dimensions."
] | def scale(boxlist, y_scale, x_scale, scope=None):
with tf.name_scope(scope, 'Scale'):
y_scale = tf.cast(y_scale, tf.float32)
x_scale = tf.cast(x_scale, tf.float32)
(y_min, x_min, y_max, x_max) = tf.split(value=boxlist.get(), num_or_size_splits=4, axis=1)
y_min = y_scale * y_min
... | ['def', 'scale(boxlist,', 'y_scale,', 'x_scale,', 'scope=None):', 'with', 'tf.name_scope(scope,', "'Scale'):", 'y_scale', '=', 'tf.cast(y_scale,', 'tf.float32)', 'x_scale', '=', 'tf.cast(x_scale,', 'tf.float32)', '(y_min,', 'x_min,', 'y_max,', 'x_max)', '=', 'tf.split(value=boxlist.get(),', 'num_or_size_splits=4,', 'ax... | 771,199 |
enuguru/artificial_intelligence_and_machine_learning | datastructures.py | MultiDict.copy | copy | Return a shallow copy of this object. | [
"Return",
"a",
"shallow",
"copy",
"of",
"this",
"object."
] | def copy(self):
return self.__class__(self) | ['def', 'copy(self):', 'return', 'self.__class__(self)'] | 161,108 |
triaquae/triaquae | aggregates.py | Aggregate.as_sql | as_sql | Return the aggregate, rendered as SQL. | [
"Return",
"the",
"aggregate,",
"rendered",
"as",
"SQL."
] | def as_sql(self, qn, connection):
if hasattr(self.col, 'as_sql'):
field_name = self.col.as_sql(qn, connection)
elif isinstance(self.col, (list, tuple)):
field_name = '.'.join([qn(c) for c in self.col])
else:
field_name = self.col
params = {'function': self.sql_function, 'field': ... | ['def', 'as_sql(self,', 'qn,', 'connection):', 'if', 'hasattr(self.col,', "'as_sql'):", 'field_name', '=', 'self.col.as_sql(qn,', 'connection)', 'elif', 'isinstance(self.col,', '(list,', 'tuple)):', 'field_name', '=', "'.'.join([qn(c)", 'for', 'c', 'in', 'self.col])', 'else:', 'field_name', '=', 'self.col', 'params', '... | 423,540 |
wutong8023/CoLL | training_args.py | TrainingArguments.device | device | The device used by this process. | [
"The",
"device",
"used",
"by",
"this",
"process."
] | def device(self) -> 'torch.device':
return self._setup_devices | ['def', 'device(self)', '->', "'torch.device':", 'return', 'self._setup_devices'] | 496,515 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | prediction_model.py | construct_model | construct_model | Build convolutional lstm video predictor using STP, CDNA, or DNA. | [
"Build",
"convolutional",
"lstm",
"video",
"predictor",
"using",
"STP,",
"CDNA,",
"or",
"DNA."
] | def construct_model(images, actions=None, states=None, iter_num=-1.0, k=-1, use_state=True, num_masks=10, stp=False, cdna=True, dna=False, context_frames=2):
if stp + cdna + dna != 1:
raise ValueError('More than one, or no network option specified.')
(batch_size, img_height, img_width, color_channels) =... | ['def', 'construct_model(images,', 'actions=None,', 'states=None,', 'iter_num=-1.0,', 'k=-1,', 'use_state=True,', 'num_masks=10,', 'stp=False,', 'cdna=True,', 'dna=False,', 'context_frames=2):', 'if', 'stp', '+', 'cdna', '+', 'dna', '!=', '1:', 'raise', "ValueError('More", 'than', 'one,', 'or', 'no', 'network', 'option... | 30,001 |
Mahesh-Shirsath/Natural-Language- | predict.py | predict | predict | Makes predictions using model on instances and saves them in save_to_file. | [
"Makes",
"predictions",
"using",
"model",
"on",
"instances",
"and",
"saves",
"them",
"in",
"save_to_file."
] | def predict(model: models.Model, instances: List[Dict], batch_size: int, save_to_file: str=None) -> List[int]:
batches = generate_batches(instances, batch_size)
predicted_labels = []
all_predicted_labels = []
print('Making predictions')
for batch_inputs in tqdm(batches):
batch_inputs.pop('la... | ['def', 'predict(model:', 'models.Model,', 'instances:', 'List[Dict],', 'batch_size:', 'int,', 'save_to_file:', 'str=None)', '->', 'List[int]:', 'batches', '=', 'generate_batches(instances,', 'batch_size)', 'predicted_labels', '=', '[]', 'all_predicted_labels', '=', '[]', "print('Making", "predictions')", 'for', 'batch... | 685,653 |
sunishsheth2009/ChatterBot | scoring.py | BaseScorer.supports_block_quality | supports_block_quality | Returns True if this class supports quality optimizations. | [
"Returns",
"True",
"if",
"this",
"class",
"supports",
"quality",
"optimizations."
] | def supports_block_quality(self):
return False | ['def', 'supports_block_quality(self):', 'return', 'False'] | 484,098 |
jpmorganchase/Phantom | env.py | PhantomEnv.strategic_agents | strategic_agents | Return a list of agents that take actions. | [
"Return",
"a",
"list",
"of",
"agents",
"that",
"take",
"actions."
] | def strategic_agents(self) -> List[StrategicAgent]:
return [a for a in self.agents.values() if isinstance(a, StrategicAgent)] | ['def', 'strategic_agents(self)', '->', 'List[StrategicAgent]:', 'return', '[a', 'for', 'a', 'in', 'self.agents.values()', 'if', 'isinstance(a,', 'StrategicAgent)]'] | 768,676 |
Yuting-Gao/DisCo-pytorch | create_act.py | get_act_fn | get_act_fn | Activation Function Factory Fetching activation fns by name with this function allows export or torch script friendly functions to be returned dynamically based on current config. | [
"Activation",
"Function",
"Factory",
"Fetching",
"activation",
"fns",
"by",
"name",
"with",
"this",
"function",
"allows",
"export",
"or",
"torch",
"script",
"friendly",
"functions",
"to",
"be",
"returned",
"dynamically",
"based",
"on",
"current",
"config."
] | def get_act_fn(name='relu'):
if not name:
return None
if not (is_no_jit() or is_exportable() or is_scriptable()):
if name in _ACT_FN_ME:
return _ACT_FN_ME[name]
if is_exportable() and name in ('silu', 'swish'):
return swish
if not (is_no_jit() or is_exportable()):
... | ['def', "get_act_fn(name='relu'):", 'if', 'not', 'name:', 'return', 'None', 'if', 'not', '(is_no_jit()', 'or', 'is_exportable()', 'or', 'is_scriptable()):', 'if', 'name', 'in', '_ACT_FN_ME:', 'return', '_ACT_FN_ME[name]', 'if', 'is_exportable()', 'and', 'name', 'in', "('silu',", "'swish'):", 'return', 'swish', 'if', 'n... | 186,389 |
lancopku/Graph-to-seq-comment-generation | bert.py | EncoderLayer.forward | forward | Follow Figure 1 (left) for connections. | [
"Follow",
"Figure",
"1",
"(left)",
"for",
"connections."
] | def forward(self, x, mask):
x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, mask))
attn = self.self_attn.get_attn(x, x, x, mask)
return (self.sublayer[1](x, self.feed_forward), attn) | ['def', 'forward(self,', 'x,', 'mask):', 'x', '=', 'self.sublayer[0](x,', 'lambda', 'x:', 'self.self_attn(x,', 'x,', 'x,', 'mask))', 'attn', '=', 'self.self_attn.get_attn(x,', 'x,', 'x,', 'mask)', 'return', '(self.sublayer[1](x,', 'self.feed_forward),', 'attn)'] | 580,388 |
yan86471/DMT-implementation | converter.py | Converter.readImage | readImage | Read a image from the path. | [
"Read",
"a",
"image",
"from",
"the",
"path."
] | def readImage(self, path, mode):
try:
skimage.io.imread(path)
except Exception as e:
print('[Converter] {} : {}'.format(path, e))
image = []
else:
image = cv2.imread(path, mode)
return image | ['def', 'readImage(self,', 'path,', 'mode):', 'try:', 'skimage.io.imread(path)', 'except', 'Exception', 'as', 'e:', "print('[Converter]", '{}', ':', "{}'.format(path,", 'e))', 'image', '=', '[]', 'else:', 'image', '=', 'cv2.imread(path,', 'mode)', 'return', 'image'] | 522,131 |
QData/deepWordBug | test_length_sequence.py | test_sequence_is_movement_false | test_sequence_is_movement_false | Test parser about sequences that do not move the cursor. | [
"Test",
"parser",
"about",
"sequences",
"that",
"do",
"not",
"move",
"the",
"cursor."
] | def test_sequence_is_movement_false(all_terms):
@as_subprocess
def child(kind):
from blessed.sequences import measure_length
term = TestTerminal(kind=kind)
assert 0 == measure_length(u'', term)
assert 0 == measure_length(u'xyzzy', term)
assert 0 == measure_length(term.cu... | ['def', 'test_sequence_is_movement_false(all_terms):', '@as_subprocess', 'def', 'child(kind):', 'from', 'blessed.sequences', 'import', 'measure_length', 'term', '=', 'TestTerminal(kind=kind)', 'assert', '0', '==', "measure_length(u'',", 'term)', 'assert', '0', '==', "measure_length(u'xyzzy',", 'term)', 'assert', '0', '... | 541,163 |
blavad/marl | agent.py | TrainableAgent.store_experience | store_experience | Store a transition in the experience buffer. | [
"Store",
"a",
"transition",
"in",
"the",
"experience",
"buffer."
] | def store_experience(self, *args):
if isinstance(self.experience, ReplayMemory):
self.experience.push(*args)
elif isinstance(self.experience, PrioritizedReplayMemory):
self.experience.push_transition(*args) | ['def', 'store_experience(self,', '*args):', 'if', 'isinstance(self.experience,', 'ReplayMemory):', 'self.experience.push(*args)', 'elif', 'isinstance(self.experience,', 'PrioritizedReplayMemory):', 'self.experience.push_transition(*args)'] | 627,884 |
deepmind/bsuite | agent.py | DQN.update | update | Adds transition to replay and periodically does SGD. | [
"Adds",
"transition",
"to",
"replay",
"and",
"periodically",
"does",
"SGD."
] | def update(self, timestep: dm_env.TimeStep, action: base.Action, new_timestep: dm_env.TimeStep):
self._replay.add([timestep.observation, action, new_timestep.reward, new_timestep.discount, new_timestep.observation])
self._total_steps += 1
if self._total_steps % self._sgd_period != 0:
return
if s... | ['def', 'update(self,', 'timestep:', 'dm_env.TimeStep,', 'action:', 'base.Action,', 'new_timestep:', 'dm_env.TimeStep):', 'self._replay.add([timestep.observation,', 'action,', 'new_timestep.reward,', 'new_timestep.discount,', 'new_timestep.observation])', 'self._total_steps', '+=', '1', 'if', 'self._total_steps', '%', ... | 410,120 |
RashadGarayev/FireDetection | feature_map_generators.py | create_conv_block | create_conv_block | Create Keras layers for depthwise & non-depthwise convolutions. | [
"Create",
"Keras",
"layers",
"for",
"depthwise",
"&",
"non-depthwise",
"convolutions."
] | def create_conv_block(use_depthwise, kernel_size, padding, stride, layer_name, conv_hyperparams, is_training, freeze_batchnorm, depth):
layers = []
if use_depthwise:
kwargs = conv_hyperparams.params()
kwargs['depthwise_regularizer'] = kwargs['kernel_regularizer']
kwargs['depthwise_initia... | ['def', 'create_conv_block(use_depthwise,', 'kernel_size,', 'padding,', 'stride,', 'layer_name,', 'conv_hyperparams,', 'is_training,', 'freeze_batchnorm,', 'depth):', 'layers', '=', '[]', 'if', 'use_depthwise:', 'kwargs', '=', 'conv_hyperparams.params()', "kwargs['depthwise_regularizer']", '=', "kwargs['kernel_regulari... | 210,637 |
scorpiocodes/NaturalLanguageProcessing | trigram_model.py | TrigramModel.perplexity | perplexity | COMPLETE THIS METHOD (PART 6) Returns the log probability of an entire sequence. | [
"COMPLETE",
"THIS",
"METHOD",
"(PART",
"6)",
"Returns",
"the",
"log",
"probability",
"of",
"an",
"entire",
"sequence."
] | def perplexity(self, corpus):
l = 0
M = 0
for sentence in corpus:
M += len(sentence)
l += self.sentence_logprob(sentence)
l = l * (1 / M)
perplexity = 2 ** (-l)
return perplexity | ['def', 'perplexity(self,', 'corpus):', 'l', '=', '0', 'M', '=', '0', 'for', 'sentence', 'in', 'corpus:', 'M', '+=', 'len(sentence)', 'l', '+=', 'self.sentence_logprob(sentence)', 'l', '=', 'l', '*', '(1', '/', 'M)', 'perplexity', '=', '2', '**', '(-l)', 'return', 'perplexity'] | 677,541 |
Xianpeng919/MonoCon | kitti_converter.py | get_2d_boxes | get_2d_boxes | Get the 2D annotation records for a given info. | [
"Get",
"the",
"2D",
"annotation",
"records",
"for",
"a",
"given",
"info."
] | def get_2d_boxes(info, occluded, mono3d=True):
P2 = info['calib']['P2']
repro_recs = []
if 'annos' not in info:
return repro_recs
ann_dicts = info['annos']
mask = [ocld in occluded for ocld in ann_dicts['occluded']]
for k in ann_dicts.keys():
ann_dicts[k] = ann_dicts[k][mask]
... | ['def', 'get_2d_boxes(info,', 'occluded,', 'mono3d=True):', 'P2', '=', "info['calib']['P2']", 'repro_recs', '=', '[]', 'if', "'annos'", 'not', 'in', 'info:', 'return', 'repro_recs', 'ann_dicts', '=', "info['annos']", 'mask', '=', '[ocld', 'in', 'occluded', 'for', 'ocld', 'in', "ann_dicts['occluded']]", 'for', 'k', 'in'... | 654,752 |
suarez12138/AI-Reversi_IMP_TextDichotomy | test_arraypad.py | test_kwargs | test_kwargs | Test behavior of pad's kwargs for the given mode. | [
"Test",
"behavior",
"of",
"pad's",
"kwargs",
"for",
"the",
"given",
"mode."
] | def test_kwargs(mode):
allowed = _all_modes[mode]
not_allowed = {}
for kwargs in _all_modes.values():
if kwargs != allowed:
not_allowed.update(kwargs)
np.pad([1, 2, 3], 1, mode, **allowed)
for (key, value) in not_allowed.items():
match = "unsupported keyword arguments for... | ['def', 'test_kwargs(mode):', 'allowed', '=', '_all_modes[mode]', 'not_allowed', '=', '{}', 'for', 'kwargs', 'in', '_all_modes.values():', 'if', 'kwargs', '!=', 'allowed:', 'not_allowed.update(kwargs)', 'np.pad([1,', '2,', '3],', '1,', 'mode,', '**allowed)', 'for', '(key,', 'value)', 'in', 'not_allowed.items():', 'matc... | 98,005 |
ldfaiztt/CSE473 | inference.py | MarginalInference.initializeUniformly | initializeUniformly | Set the belief state to an initial, prior value. | [
"Set",
"the",
"belief",
"state",
"to",
"an",
"initial,",
"prior",
"value."
] | def initializeUniformly(self, gameState):
if self.index == 1:
jointInference.initialize(gameState, self.legalPositions)
jointInference.addGhostAgent(self.ghostAgent) | ['def', 'initializeUniformly(self,', 'gameState):', 'if', 'self.index', '==', '1:', 'jointInference.initialize(gameState,', 'self.legalPositions)', 'jointInference.addGhostAgent(self.ghostAgent)'] | 193,237 |
aalgirdas/Artificial-Intelligence-Course | csp.py | NQueensCSP.display | display | Print the queens and the nconflicts values (for debugging). | [
"Print",
"the",
"queens",
"and",
"the",
"nconflicts",
"values",
"(for",
"debugging)."
] | def display(self, assignment):
n = len(self.variables)
for val in range(n):
for var in range(n):
if assignment.get(var, '') == val:
ch = 'Q'
elif (var + val) % 2 == 0:
ch = '.'
else:
ch = '-'
print(ch, end=' ... | ['def', 'display(self,', 'assignment):', 'n', '=', 'len(self.variables)', 'for', 'val', 'in', 'range(n):', 'for', 'var', 'in', 'range(n):', 'if', 'assignment.get(var,', "'')", '==', 'val:', 'ch', '=', "'Q'", 'elif', '(var', '+', 'val)', '%', '2', '==', '0:', 'ch', '=', "'.'", 'else:', 'ch', '=', "'-'", 'print(ch,', "en... | 79,622 |
tobegit3hub/deep_image_model | ops.py | get_collection_proto_type | get_collection_proto_type | Returns the proto_type for collection_name. | [
"Returns",
"the",
"proto_type",
"for",
"collection_name."
] | def get_collection_proto_type(collection_name):
try:
return _proto_function_registry.lookup(collection_name)[0]
except LookupError:
return None | ['def', 'get_collection_proto_type(collection_name):', 'try:', 'return', '_proto_function_registry.lookup(collection_name)[0]', 'except', 'LookupError:', 'return', 'None'] | 182,549 |
ForrestPi/ObjectDetection | comm.py | SyncMaster.register_slave | register_slave | Register an slave device. | [
"Register",
"an",
"slave",
"device."
] | def register_slave(self, identifier):
if self._activated:
assert self._queue.empty(), 'Queue is not clean before next initialization.'
self._activated = False
self._registry.clear()
future = FutureResult()
self._registry[identifier] = _MasterRegistry(future)
return SlavePipe(iden... | ['def', 'register_slave(self,', 'identifier):', 'if', 'self._activated:', 'assert', 'self._queue.empty(),', "'Queue", 'is', 'not', 'clean', 'before', 'next', "initialization.'", 'self._activated', '=', 'False', 'self._registry.clear()', 'future', '=', 'FutureResult()', 'self._registry[identifier]', '=', '_MasterRegistr... | 742,965 |
rudranil723/mini-main | colors.py | Colormap.get_bad | get_bad | Get the color for masked values. | [
"Get",
"the",
"color",
"for",
"masked",
"values."
] | def get_bad(self):
if not self._isinit:
self._init()
return np.array(self._lut[self._i_bad]) | ['def', 'get_bad(self):', 'if', 'not', 'self._isinit:', 'self._init()', 'return', 'np.array(self._lut[self._i_bad])'] | 319,298 |
bhateharsh/computer_vision | preprocessor.py | rgb_to_gray | rgb_to_gray | Converts a 3 channel RGB image to a 1 channel grayscale image. | [
"Converts",
"a",
"3",
"channel",
"RGB",
"image",
"to",
"a",
"1",
"channel",
"grayscale",
"image."
] | def rgb_to_gray(image):
return _rgb_to_grayscale(image) | ['def', 'rgb_to_gray(image):', 'return', '_rgb_to_grayscale(image)'] | 505,448 |
dawdleryang/object_detection | fast_rcnn.py | add_fast_rcnn_blobs | add_fast_rcnn_blobs | Add blobs needed for training Fast R-CNN style models. | [
"Add",
"blobs",
"needed",
"for",
"training",
"Fast",
"R-CNN",
"style",
"models."
] | def add_fast_rcnn_blobs(blobs, im_scales, roidb):
for (im_i, entry) in enumerate(roidb):
frcn_blobs = _sample_rois(entry, im_scales[im_i], im_i)
for (k, v) in frcn_blobs.items():
blobs[k].append(v)
for (k, v) in blobs.items():
if isinstance(v, list) and len(v) > 0:
... | ['def', 'add_fast_rcnn_blobs(blobs,', 'im_scales,', 'roidb):', 'for', '(im_i,', 'entry)', 'in', 'enumerate(roidb):', 'frcn_blobs', '=', '_sample_rois(entry,', 'im_scales[im_i],', 'im_i)', 'for', '(k,', 'v)', 'in', 'frcn_blobs.items():', 'blobs[k].append(v)', 'for', '(k,', 'v)', 'in', 'blobs.items():', 'if', 'isinstance... | 772,951 |
weimin17/Object-Detection_HelmetDetection | ptn_encoder.py | model | model | Model encoding the images into view-invariant embedding. | [
"Model",
"encoding",
"the",
"images",
"into",
"view-invariant",
"embedding."
] | def model(images, params, is_training):
del is_training
image_size = images.get_shape().as_list()[1]
f_dim = params.f_dim
fc_dim = params.fc_dim
z_dim = params.z_dim
outputs = dict()
images = _preprocess(images)
with slim.arg_scope([slim.conv2d, slim.fully_connected], weights_initializer... | ['def', 'model(images,', 'params,', 'is_training):', 'del', 'is_training', 'image_size', '=', 'images.get_shape().as_list()[1]', 'f_dim', '=', 'params.f_dim', 'fc_dim', '=', 'params.fc_dim', 'z_dim', '=', 'params.z_dim', 'outputs', '=', 'dict()', 'images', '=', '_preprocess(images)', 'with', 'slim.arg_scope([slim.conv2... | 759,499 |
openai/gym | async_vector_env.py | AsyncVectorEnv.set_attr | set_attr | Sets an attribute of the sub-environments. | [
"Sets",
"an",
"attribute",
"of",
"the",
"sub-environments."
] | def set_attr(self, name: str, values: Union[list, tuple, object]):
self._assert_is_running()
if not isinstance(values, (list, tuple)):
values = [values for _ in range(self.num_envs)]
if len(values) != self.num_envs:
raise ValueError(f'Values must be a list or tuple with length equal to the n... | ['def', 'set_attr(self,', 'name:', 'str,', 'values:', 'Union[list,', 'tuple,', 'object]):', 'self._assert_is_running()', 'if', 'not', 'isinstance(values,', '(list,', 'tuple)):', 'values', '=', '[values', 'for', '_', 'in', 'range(self.num_envs)]', 'if', 'len(values)', '!=', 'self.num_envs:', 'raise', "ValueError(f'Value... | 234,252 |
shanest/quantifier-rnn-learning | quantifiers.py | last_n_ver | last_n_ver | Verifies whether the last n As are also Bs. | [
"Verifies",
"whether",
"the",
"last",
"n",
"As",
"are",
"also",
"Bs."
] | def last_n_ver(seq, n):
return first_n_ver(list(reversed(seq)), n) | ['def', 'last_n_ver(seq,', 'n):', 'return', 'first_n_ver(list(reversed(seq)),', 'n)'] | 304,026 |
lishunyao97/Pun-GAN | nmt_utils.py | get_translation | get_translation | Given batch decoding outputs, select a sentence and turn to text. | [
"Given",
"batch",
"decoding",
"outputs,",
"select",
"a",
"sentence",
"and",
"turn",
"to",
"text."
] | def get_translation(nmt_outputs, infer_logits, sent_id, tgt_eos, subword_option):
if tgt_eos:
tgt_eos = tgt_eos.encode('utf-8')
output = nmt_outputs[sent_id, :].tolist()
scores = infer_logits[sent_id]
if tgt_eos and tgt_eos in output:
output = output[:output.index(tgt_eos)]
if subwor... | ['def', 'get_translation(nmt_outputs,', 'infer_logits,', 'sent_id,', 'tgt_eos,', 'subword_option):', 'if', 'tgt_eos:', 'tgt_eos', '=', "tgt_eos.encode('utf-8')", 'output', '=', 'nmt_outputs[sent_id,', ':].tolist()', 'scores', '=', 'infer_logits[sent_id]', 'if', 'tgt_eos', 'and', 'tgt_eos', 'in', 'output:', 'output', '=... | 818,823 |
ZumoLabs/zpy | render.py | hsv_node | hsv_node | Adds a Hue-Saturation-Value Node. | [
"Adds",
"a",
"Hue-Saturation-Value",
"Node."
] | def hsv_node(node_tree: bpy.types.NodeTree, input_node: bpy.types.Node) -> bpy.types.Node:
hsv_node = zpy.nodes.get_or_make('HSV', 'CompositorNodeHueSat', node_tree)
node_tree.links.new(input_node.outputs['Image'], hsv_node.inputs['Image'])
return hsv_node | ['def', 'hsv_node(node_tree:', 'bpy.types.NodeTree,', 'input_node:', 'bpy.types.Node)', '->', 'bpy.types.Node:', 'hsv_node', '=', "zpy.nodes.get_or_make('HSV',", "'CompositorNodeHueSat',", 'node_tree)', "node_tree.links.new(input_node.outputs['Image'],", "hsv_node.inputs['Image'])", 'return', 'hsv_node'] | 972,100 |
dlshriver/dnnv | abstract_mapping.py | AbstractMapping.out_shape | out_shape | Returns the output-shape of the data as seen in the original network. | [
"Returns",
"the",
"output-shape",
"of",
"the",
"data",
"as",
"seen",
"in",
"the",
"original",
"network."
] | def out_shape(self, in_shape: np.array) -> np.array:
return in_shape | ['def', 'out_shape(self,', 'in_shape:', 'np.array)', '->', 'np.array:', 'return', 'in_shape'] | 522,597 |
devashish-patel/webcam-motion-detector | prefilter.py | PrefilterManager.init_transformers | init_transformers | Create the default transformers. | [
"Create",
"the",
"default",
"transformers."
] | def init_transformers(self):
self._transformers = []
for transformer_cls in _default_transformers:
transformer_cls(shell=self.shell, prefilter_manager=self, parent=self) | ['def', 'init_transformers(self):', 'self._transformers', '=', '[]', 'for', 'transformer_cls', 'in', '_default_transformers:', 'transformer_cls(shell=self.shell,', 'prefilter_manager=self,', 'parent=self)'] | 978,792 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | test_stdout.py | TestStdout.test_output | test_output | Test stdout writer output. | [
"Test",
"stdout",
"writer",
"output."
] | def test_output(self):
stdout = sys.stdout
stream = StringIO()
sys.stdout = stream
writer = StdoutWriter()
writer.write(u'aÃ\x83Â\x97', {'b': 'c'})
output = stream.getvalue()
self.fuzzy_compare(output, u'aÃ\x83Â\x97')
sys.stdout = stdout | ['def', 'test_output(self):', 'stdout', '=', 'sys.stdout', 'stream', '=', 'StringIO()', 'sys.stdout', '=', 'stream', 'writer', '=', 'StdoutWriter()', "writer.write(u'aÃ\\x83Â\\x97',", "{'b':", "'c'})", 'output', '=', 'stream.getvalue()', 'self.fuzzy_compare(output,', "u'aÃ\\x83Â\\x97')", 'sys.stdout', '=', 'stdout'] | 451,882 |
weimin17/Object-Detection_HelmetDetection | test_flags.py | temp_dir | temp_dir | Returns a temporary directory for tests. | [
"Returns",
"a",
"temporary",
"directory",
"for",
"tests."
] | def temp_dir():
return getattr(FLAGS, 'test_tmpdir', tf.test.get_temp_dir()) | ['def', 'temp_dir():', 'return', 'getattr(FLAGS,', "'test_tmpdir',", 'tf.test.get_temp_dir())'] | 760,437 |
mlwithtf/mlwithtf | prediction_service_pb2.py | BetaPredictionServiceStub.GetModelMetadata | GetModelMetadata | GetModelMetadata - provides access to metadata for loaded models. | [
"GetModelMetadata",
"-",
"provides",
"access",
"to",
"metadata",
"for",
"loaded",
"models."
] | def GetModelMetadata(self, request, timeout, metadata=None, with_call=False, protocol_options=None):
raise NotImplementedError() | ['def', 'GetModelMetadata(self,', 'request,', 'timeout,', 'metadata=None,', 'with_call=False,', 'protocol_options=None):', 'raise', 'NotImplementedError()'] | 631,166 |
idptools/parrot | _version.py | git_get_keywords | git_get_keywords | Extract version information from the given file. | [
"Extract",
"version",
"information",
"from",
"the",
"given",
"file."
] | def git_get_keywords(versionfile_abs):
keywords = {}
try:
f = open(versionfile_abs, 'r')
for line in f.readlines():
if line.strip().startswith('git_refnames ='):
mo = re.search('=\\s*"(.*)"', line)
if mo:
keywords['refnames'] = mo.g... | ['def', 'git_get_keywords(versionfile_abs):', 'keywords', '=', '{}', 'try:', 'f', '=', 'open(versionfile_abs,', "'r')", 'for', 'line', 'in', 'f.readlines():', 'if', "line.strip().startswith('git_refnames", "='):", 'mo', '=', 're.search(\'=\\\\s*"(.*)"\',', 'line)', 'if', 'mo:', "keywords['refnames']", '=', 'mo.group(1)... | 278,278 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | gaussian_moments.py | get_privacy_spent | get_privacy_spent | Compute delta (or eps) for given eps (or delta) from log moments. | [
"Compute",
"delta",
"(or",
"eps)",
"for",
"given",
"eps",
"(or",
"delta)",
"from",
"log",
"moments."
] | def get_privacy_spent(log_moments, target_eps=None, target_delta=None):
assert (target_eps is None) ^ (target_delta is None)
assert not (target_eps is None and target_delta is None)
if target_eps is not None:
return (target_eps, _compute_delta(log_moments, target_eps))
else:
return (_com... | ['def', 'get_privacy_spent(log_moments,', 'target_eps=None,', 'target_delta=None):', 'assert', '(target_eps', 'is', 'None)', '^', '(target_delta', 'is', 'None)', 'assert', 'not', '(target_eps', 'is', 'None', 'and', 'target_delta', 'is', 'None)', 'if', 'target_eps', 'is', 'not', 'None:', 'return', '(target_eps,', '_comp... | 47,854 |
intelligent-environments-lab/CityLearn | wrappers.py | StableBaselines3ActionWrapper.action | action | Returns actions as 1-dimensional numpy array. | [
"Returns",
"actions",
"as",
"1-dimensional",
"numpy",
"array."
] | def action(self, actions: List[float]) -> List[List[float]]:
return [actions] | ['def', 'action(self,', 'actions:', 'List[float])', '->', 'List[List[float]]:', 'return', '[actions]'] | 105,500 |
Sandbergo/branch2learn | 01_generate_data.py | ExploreThenStrongBranch.before_reset | before_reset | This function will be called at initialization of the environment (before dynamics are reset). | [
"This",
"function",
"will",
"be",
"called",
"at",
"initialization",
"of",
"the",
"environment",
"(before",
"dynamics",
"are",
"reset)."
] | def before_reset(self, model):
self.pseudocosts_function.before_reset(model)
self.strong_branching_function.before_reset(model) | ['def', 'before_reset(self,', 'model):', 'self.pseudocosts_function.before_reset(model)', 'self.strong_branching_function.before_reset(model)'] | 108,273 |
rlworkgroup/garage | cma_es_cartpole.py | cma_es_cartpole | cma_es_cartpole | Train CMA_ES with Cartpole-v1 environment. | [
"Train",
"CMA_ES",
"with",
"Cartpole-v1",
"environment."
] | def cma_es_cartpole(ctxt=None, seed=1):
set_seed(seed)
with TFTrainer(ctxt) as trainer:
env = GymEnv('CartPole-v1')
policy = CategoricalMLPPolicy(name='policy', env_spec=env.spec, hidden_sizes=(32, 32))
n_samples = 20
sampler = LocalSampler(agents=policy, envs=env, max_episode_le... | ['def', 'cma_es_cartpole(ctxt=None,', 'seed=1):', 'set_seed(seed)', 'with', 'TFTrainer(ctxt)', 'as', 'trainer:', 'env', '=', "GymEnv('CartPole-v1')", 'policy', '=', "CategoricalMLPPolicy(name='policy',", 'env_spec=env.spec,', 'hidden_sizes=(32,', '32))', 'n_samples', '=', '20', 'sampler', '=', 'LocalSampler(agents=poli... | 200,265 |
greydanus/mr_london | locations.py | virtualenv_no_global | virtualenv_no_global | Return True if in a venv and no system site packages. | [
"Return",
"True",
"if",
"in",
"a",
"venv",
"and",
"no",
"system",
"site",
"packages."
] | def virtualenv_no_global():
site_mod_dir = os.path.dirname(os.path.abspath(site.__file__))
no_global_file = os.path.join(site_mod_dir, 'no-global-site-packages.txt')
if running_under_virtualenv() and os.path.isfile(no_global_file):
return True | ['def', 'virtualenv_no_global():', 'site_mod_dir', '=', 'os.path.dirname(os.path.abspath(site.__file__))', 'no_global_file', '=', 'os.path.join(site_mod_dir,', "'no-global-site-packages.txt')", 'if', 'running_under_virtualenv()', 'and', 'os.path.isfile(no_global_file):', 'return', 'True'] | 263,340 |
ayushbhardwaj10/Natural-Language- | evaluate.py | evaluate | evaluate | Evaluates accuracy of label predictions in ``prediction_data_path`` based on gold labels in ``gold_data_path``. | [
"Evaluates",
"accuracy",
"of",
"label",
"predictions",
"in",
"``prediction_data_path``",
"based",
"on",
"gold",
"labels",
"in",
"``gold_data_path``."
] | def evaluate(gold_data_path: str, prediction_data_path: str) -> float:
with open(gold_data_path) as file:
gold_labels = [int(json.loads(line.strip())['label']) for line in file.readlines() if line.strip()]
with open(prediction_data_path) as file:
predicted_labels = [int(line.strip()) for line in... | ['def', 'evaluate(gold_data_path:', 'str,', 'prediction_data_path:', 'str)', '->', 'float:', 'with', 'open(gold_data_path)', 'as', 'file:', 'gold_labels', '=', "[int(json.loads(line.strip())['label'])", 'for', 'line', 'in', 'file.readlines()', 'if', 'line.strip()]', 'with', 'open(prediction_data_path)', 'as', 'file:', ... | 685,473 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | word2vec.py | Word2Vec.build_eval_graph | build_eval_graph | Build the eval graph. | [
"Build",
"the",
"eval",
"graph."
] | def build_eval_graph(self):
analogy_a = tf.placeholder(dtype=tf.int32)
analogy_b = tf.placeholder(dtype=tf.int32)
analogy_c = tf.placeholder(dtype=tf.int32)
nemb = tf.nn.l2_normalize(self._emb, 1)
a_emb = tf.gather(nemb, analogy_a)
b_emb = tf.gather(nemb, analogy_b)
c_emb = tf.gather(nemb, a... | ['def', 'build_eval_graph(self):', 'analogy_a', '=', 'tf.placeholder(dtype=tf.int32)', 'analogy_b', '=', 'tf.placeholder(dtype=tf.int32)', 'analogy_c', '=', 'tf.placeholder(dtype=tf.int32)', 'nemb', '=', 'tf.nn.l2_normalize(self._emb,', '1)', 'a_emb', '=', 'tf.gather(nemb,', 'analogy_a)', 'b_emb', '=', 'tf.gather(nemb,... | 30,137 |
PyRetri/PyRetri | misc.py | load_state_dict | load_state_dict | Load parameters regardless the shape of parameters with the same name need to match, which is a slight modification to load_state_dict of pytorch. | [
"Load",
"parameters",
"regardless",
"the",
"shape",
"of",
"parameters",
"with",
"the",
"same",
"name",
"need",
"to",
"match,",
"which",
"is",
"a",
"slight",
"modification",
"to",
"load_state_dict",
"of",
"pytorch."
] | def load_state_dict(model: nn.Module, state_dict: Dict) -> None:
own_state = model.state_dict()
success_keys = list()
for (name, param) in state_dict.items():
if name in own_state:
if isinstance(param, Parameter):
param = param.data
try:
own_st... | ['def', 'load_state_dict(model:', 'nn.Module,', 'state_dict:', 'Dict)', '->', 'None:', 'own_state', '=', 'model.state_dict()', 'success_keys', '=', 'list()', 'for', '(name,', 'param)', 'in', 'state_dict.items():', 'if', 'name', 'in', 'own_state:', 'if', 'isinstance(param,', 'Parameter):', 'param', '=', 'param.data', 't... | 297,230 |
TonyLianLong/VAI-ReinforcementLearning | wrappers.py | MjModelWrapper.dof_Madr | dof_Madr | dof address in M-diagonal (nv x 1). | [
"dof",
"address",
"in",
"M-diagonal",
"(nv",
"x",
"1)."
] | def dof_Madr(self):
return util.buf_to_npy(self._ptr.contents.dof_Madr, (self.nv,)) | ['def', 'dof_Madr(self):', 'return', 'util.buf_to_npy(self._ptr.contents.dof_Madr,', '(self.nv,))'] | 440,273 |
jymChen/Diaformer | modeling_utils.py | PreTrainedModel.save_pretrained | save_pretrained | Save a model with its configuration file to a directory, so that it can be re-loaded using the `from_pretrained(save_directory)` class method. | [
"Save",
"a",
"model",
"with",
"its",
"configuration",
"file",
"to",
"a",
"directory,",
"so",
"that",
"it",
"can",
"be",
"re-loaded",
"using",
"the",
"`from_pretrained(save_directory)`",
"class",
"method."
] | def save_pretrained(self, save_directory):
assert os.path.isdir(save_directory), 'Saving path should be a directory where the model and configuration can be saved'
model_to_save = self.module if hasattr(self, 'module') else self
model_to_save.config.save_pretrained(save_directory)
output_model_file = os... | ['def', 'save_pretrained(self,', 'save_directory):', 'assert', 'os.path.isdir(save_directory),', "'Saving", 'path', 'should', 'be', 'a', 'directory', 'where', 'the', 'model', 'and', 'configuration', 'can', 'be', "saved'", 'model_to_save', '=', 'self.module', 'if', 'hasattr(self,', "'module')", 'else', 'self', 'model_to... | 550,121 |
tensorly/quantum | circuit_execution_ops_test.py | ExecutionOpsConsistentyTest.test_sampling | test_sampling | Compare sampling with tfq ops and Cirq. | [
"Compare",
"sampling",
"with",
"tfq",
"ops",
"and",
"Cirq."
] | def test_sampling(self, op_and_sim, n_qubits, symbol_names):
op = op_and_sim[0]
sim = op_and_sim[1]
qubits = cirq.GridQubit.rect(1, n_qubits)
n_samples = int(2 ** n_qubits * 1000)
(circuit_batch, resolver_batch) = util.random_symbol_circuit_resolver_batch(qubits, symbol_names, BATCH_SIZE, n_moments=... | ['def', 'test_sampling(self,', 'op_and_sim,', 'n_qubits,', 'symbol_names):', 'op', '=', 'op_and_sim[0]', 'sim', '=', 'op_and_sim[1]', 'qubits', '=', 'cirq.GridQubit.rect(1,', 'n_qubits)', 'n_samples', '=', 'int(2', '**', 'n_qubits', '*', '1000)', '(circuit_batch,', 'resolver_batch)', '=', 'util.random_symbol_circuit_re... | 834,614 |
vasgaowei/pytorch_MELM | train_val.py | get_training_roidb | get_training_roidb | Returns a roidb (Region of Interest database) for use in training. | [
"Returns",
"a",
"roidb",
"(Region",
"of",
"Interest",
"database)",
"for",
"use",
"in",
"training."
] | def get_training_roidb(imdb):
if cfg.TRAIN.USE_FLIPPED:
print('Appending horizontally-flipped training examples...')
imdb.append_flipped_images()
print('done')
print('Preparing training data...')
rdl_roidb.prepare_roidb(imdb)
print('done')
return imdb.roidb | ['def', 'get_training_roidb(imdb):', 'if', 'cfg.TRAIN.USE_FLIPPED:', "print('Appending", 'horizontally-flipped', 'training', "examples...')", 'imdb.append_flipped_images()', "print('done')", "print('Preparing", 'training', "data...')", 'rdl_roidb.prepare_roidb(imdb)', "print('done')", 'return', 'imdb.roidb'] | 815,522 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.