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
jimtin/Stock_Comparison
inputsplitter.py
InputSplitter.source_reset
source_reset
Return the input source and perform a full reset.
[ "Return", "the", "input", "source", "and", "perform", "a", "full", "reset." ]
def source_reset(self): out = self.source self.reset() return out
['def', 'source_reset(self):', 'out', '=', 'self.source', 'self.reset()', 'return', 'out']
384,702
drprojects/superpoint_transformer
base.py
BaseDataModule.dataset_class
dataset_class
Return the LightningDataModule's Dataset class.
[ "Return", "the", "LightningDataModule's", "Dataset", "class." ]
def dataset_class(self): if self.hparams.mini: return self._MINIDATASET_CLASS return self._DATASET_CLASS
['def', 'dataset_class(self):', 'if', 'self.hparams.mini:', 'return', 'self._MINIDATASET_CLASS', 'return', 'self._DATASET_CLASS']
880,800
openvinotoolkit/training_extensions
sam_prompt_encoder.py
PositionEmbeddingRandom.forward
forward
Generate positional encoding for a grid of the specified size.
[ "Generate", "positional", "encoding", "for", "a", "grid", "of", "the", "specified", "size." ]
def forward(self, size: Tuple[int, int]) -> Tensor: (h, w) = size device: Any = self.positional_encoding_gaussian_matrix.device grid = torch.ones((h, w), device=device, dtype=torch.float32) y_embed = grid.cumsum(dim=0) - 0.5 x_embed = grid.cumsum(dim=1) - 0.5 y_embed = y_embed / h x_embed = ...
['def', 'forward(self,', 'size:', 'Tuple[int,', 'int])', '->', 'Tensor:', '(h,', 'w)', '=', 'size', 'device:', 'Any', '=', 'self.positional_encoding_gaussian_matrix.device', 'grid', '=', 'torch.ones((h,', 'w),', 'device=device,', 'dtype=torch.float32)', 'y_embed', '=', 'grid.cumsum(dim=0)', '-', '0.5', 'x_embed', '=', ...
918,356
enuguru/artificial_intelligence_and_machine_learning
tokenizer.py
HTMLTokenizer.processEntityInAttribute
processEntityInAttribute
This method replaces the need for "entityInAttributeValueState".
[ "This", "method", "replaces", "the", "need", "for", "\"entityInAttributeValueState\"." ]
def processEntityInAttribute(self, allowedChar): self.consumeEntity(allowedChar=allowedChar, fromAttribute=True)
['def', 'processEntityInAttribute(self,', 'allowedChar):', 'self.consumeEntity(allowedChar=allowedChar,', 'fromAttribute=True)']
131,063
BrainCog-X/Brain-Cog
network.py
SpikingDQN.forward
forward
Mapping: x -> Q(x, \*).
[ "Mapping:", "x", "->", "Q(x,", "\\*)." ]
def forward(self, x: Union[np.ndarray, torch.Tensor], state: Optional[Any]=None, info: Dict[str, Any]={}) -> Tuple[torch.Tensor, Any]: self.reset() x = torch.as_tensor(x, device=self.device, dtype=torch.float32) / 255.0 qs = [] for i in range(self._time_window): value = self.net(x) qs.ap...
['def', 'forward(self,', 'x:', 'Union[np.ndarray,', 'torch.Tensor],', 'state:', 'Optional[Any]=None,', 'info:', 'Dict[str,', 'Any]={})', '->', 'Tuple[torch.Tensor,', 'Any]:', 'self.reset()', 'x', '=', 'torch.as_tensor(x,', 'device=self.device,', 'dtype=torch.float32)', '/', '255.0', 'qs', '=', '[]', 'for', 'i', 'in', '...
108,100
deepmind/pycolab
engine_test.py
EngineTest.testRewardAndEpisodeEndWithCustomDiscount
testRewardAndEpisodeEndWithCustomDiscount
Game entities can assign reward, terminate game with custom discount.
[ "Game", "entities", "can", "assign", "reward,", "terminate", "game", "with", "custom", "discount." ]
def testRewardAndEpisodeEndWithCustomDiscount(self): self._do_test_reward_and_episode_end(expected_discount=0.5, q_pre_update=lambda actions, board, layers, backdrop, things, the_plot: the_plot.terminate_episode(0.5))
['def', 'testRewardAndEpisodeEndWithCustomDiscount(self):', 'self._do_test_reward_and_episode_end(expected_discount=0.5,', 'q_pre_update=lambda', 'actions,', 'board,', 'layers,', 'backdrop,', 'things,', 'the_plot:', 'the_plot.terminate_episode(0.5))']
819,299
instadeepai/jumanji
env_test.py
TestDenseCVRP.test_cvrp_dense__trajectory_action
test_cvrp_dense__trajectory_action
Tests a trajectory by visiting nodes in increasing and cyclic order, visiting the depot when the next node in the list surpasses the current capacity of the agent.
[ "Tests", "a", "trajectory", "by", "visiting", "nodes", "in", "increasing", "and", "cyclic", "order,", "visiting", "the", "depot", "when", "the", "next", "node", "in", "the", "list", "surpasses", "the", "current", "capacity", "of", "the", "agent." ]
def test_cvrp_dense__trajectory_action(self, cvrp_dense_reward: CVRP) -> None: step_fn = jax.jit(cvrp_dense_reward.step) key = jax.random.PRNGKey(0) (state, timestep) = cvrp_dense_reward.reset(key) pending_position = None while not timestep.last(): assert not state.visited_mask.all() ...
['def', 'test_cvrp_dense__trajectory_action(self,', 'cvrp_dense_reward:', 'CVRP)', '->', 'None:', 'step_fn', '=', 'jax.jit(cvrp_dense_reward.step)', 'key', '=', 'jax.random.PRNGKey(0)', '(state,', 'timestep)', '=', 'cvrp_dense_reward.reset(key)', 'pending_position', '=', 'None', 'while', 'not', 'timestep.last():', 'ass...
594,362
Ruturaj123/Flowchart-Detection
feature_column_test.py
CrossedColumnTest.test_name_ordered_alphabetically
test_name_ordered_alphabetically
Tests that the name does not depend on the order of given columns.
[ "Tests", "that", "the", "name", "does", "not", "depend", "on", "the", "order", "of", "given", "columns." ]
def test_name_ordered_alphabetically(self): a = fc.numeric_column('a', dtype=dtypes.int32) b = fc.bucketized_column(a, boundaries=[0, 1]) crossed1 = fc.crossed_column(['d1', 'd2'], 10) crossed2 = fc.crossed_column([crossed1, 'c', b], 10) self.assertEqual('a_bucketized_X_c_X_d1_X_d2', crossed2.name)
['def', 'test_name_ordered_alphabetically(self):', 'a', '=', "fc.numeric_column('a',", 'dtype=dtypes.int32)', 'b', '=', 'fc.bucketized_column(a,', 'boundaries=[0,', '1])', 'crossed1', '=', "fc.crossed_column(['d1',", "'d2'],", '10)', 'crossed2', '=', 'fc.crossed_column([crossed1,', "'c',", 'b],', '10)', "self.assertEqu...
605,293
mayurilk/Natural-Language-Processing
a3_test.py
TestA3.test_labels
test_labels
Test that NER labels are returned.
[ "Test", "that", "NER", "labels", "are", "returned." ]
def test_labels(self): (dicts, labels) = make_feature_dicts(data, token=True, caps=False, pos=False, chunk=False, context=False) self.assertEqual('I-ORG', labels[0]) self.assertEqual('O', labels[1]) self.assertEqual(10, len(labels))
['def', 'test_labels(self):', '(dicts,', 'labels)', '=', 'make_feature_dicts(data,', 'token=True,', 'caps=False,', 'pos=False,', 'chunk=False,', 'context=False)', "self.assertEqual('I-ORG',", 'labels[0])', "self.assertEqual('O',", 'labels[1])', 'self.assertEqual(10,', 'len(labels))']
704,593
SajalGoel/Natural-Language-Processing
a2_test.py
TestA2.test_hmm_viterbi2
test_hmm_viterbi2
Test viterbi algorithm on 'time flies like an arrow' Here, we've modified the model to make the most probable path be N,N,V,D,N .
[ "Test", "viterbi", "algorithm", "on", "'time", "flies", "like", "an", "arrow'", "Here,", "we've", "modified", "the", "model", "to", "make", "the", "most", "probable", "path", "be", "N,N,V,D,N", "." ]
def test_hmm_viterbi2(self): model = HMM() model.states = ['D', 'N', 'P', 'V'] model.start_probas = {'D': 0.3, 'N': 0.4, 'P': 0.1, 'V': 0.2} model.emission_probas = {'D': {'time': 0.0, 'flies': 0.0, 'like': 0.0, 'an': 1.0, 'arrow': 0.0}, 'V': {'time': 0.0, 'flies': 0.1, 'like': 0.9, 'an': 0.0, 'arrow': ...
['def', 'test_hmm_viterbi2(self):', 'model', '=', 'HMM()', 'model.states', '=', "['D',", "'N',", "'P',", "'V']", 'model.start_probas', '=', "{'D':", '0.3,', "'N':", '0.4,', "'P':", '0.1,', "'V':", '0.2}', 'model.emission_probas', '=', "{'D':", "{'time':", '0.0,', "'flies':", '0.0,', "'like':", '0.0,', "'an':", '1.0,', ...
703,805
megvii-research/MSCL
pose_loading.py
GeneratePoseTarget.generate_a_heatmap
generate_a_heatmap
Generate pseudo heatmap for one keypoint in one frame.
[ "Generate", "pseudo", "heatmap", "for", "one", "keypoint", "in", "one", "frame." ]
def generate_a_heatmap(self, img_h, img_w, centers, sigma, max_values): heatmap = np.zeros([img_h, img_w], dtype=np.float32) for (center, max_value) in zip(centers, max_values): (mu_x, mu_y) = (center[0], center[1]) if max_value < self.eps: continue st_x = max(int(mu_x - 3 * ...
['def', 'generate_a_heatmap(self,', 'img_h,', 'img_w,', 'centers,', 'sigma,', 'max_values):', 'heatmap', '=', 'np.zeros([img_h,', 'img_w],', 'dtype=np.float32)', 'for', '(center,', 'max_value)', 'in', 'zip(centers,', 'max_values):', '(mu_x,', 'mu_y)', '=', '(center[0],', 'center[1])', 'if', 'max_value', '<', 'self.eps:...
264,787
yoonc5536/computer_vision
inputs.py
create_train_input_fn
create_train_input_fn
Creates a train `input` function for `Estimator`.
[ "Creates", "a", "train", "`input`", "function", "for", "`Estimator`." ]
def create_train_input_fn(train_config, train_input_config, model_config): def _train_input_fn(params=None): if not isinstance(train_config, train_pb2.TrainConfig): raise TypeError('For training mode, the `train_config` must be a train_pb2.TrainConfig.') if not isinstance(train_input_co...
['def', 'create_train_input_fn(train_config,', 'train_input_config,', 'model_config):', 'def', '_train_input_fn(params=None):', 'if', 'not', 'isinstance(train_config,', 'train_pb2.TrainConfig):', 'raise', "TypeError('For", 'training', 'mode,', 'the', '`train_config`', 'must', 'be', 'a', "train_pb2.TrainConfig.')", 'if'...
503,421
MycroftAI/mycroft-core
__init__.py
VlcService.play
play
Play playlist using vlc.
[ "Play", "playlist", "using", "vlc." ]
def play(self, repeat=False): LOG.debug('VLCService Play') if repeat: self.list_player.set_playback_mode(vlc.PlaybackMode.loop) else: self.list_player.set_playback_mode(vlc.PlaybackMode.default) self.list_player.play()
['def', 'play(self,', 'repeat=False):', "LOG.debug('VLCService", "Play')", 'if', 'repeat:', 'self.list_player.set_playback_mode(vlc.PlaybackMode.loop)', 'else:', 'self.list_player.set_playback_mode(vlc.PlaybackMode.default)', 'self.list_player.play()']
290,245
DYZhang09/SAM3D
create_data.py
semantickitti_data_prep
semantickitti_data_prep
Prepare the info file for SemanticKITTI dataset.
[ "Prepare", "the", "info", "file", "for", "SemanticKITTI", "dataset." ]
def semantickitti_data_prep(info_prefix, out_dir): semantickitti_converter.create_semantickitti_info_file(info_prefix, out_dir)
['def', 'semantickitti_data_prep(info_prefix,', 'out_dir):', 'semantickitti_converter.create_semantickitti_info_file(info_prefix,', 'out_dir)']
845,189
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
image_processing.py
batch_inputs
batch_inputs
Contruct batches of training or evaluation examples from the image dataset.
[ "Contruct", "batches", "of", "training", "or", "evaluation", "examples", "from", "the", "image", "dataset." ]
def batch_inputs(dataset, batch_size, train, num_preprocess_threads=None, num_readers=1): with tf.name_scope('batch_processing'): data_files = dataset.data_files() if data_files is None: raise ValueError('No data files found for this dataset') if train: filename_queue...
['def', 'batch_inputs(dataset,', 'batch_size,', 'train,', 'num_preprocess_threads=None,', 'num_readers=1):', 'with', "tf.name_scope('batch_processing'):", 'data_files', '=', 'dataset.data_files()', 'if', 'data_files', 'is', 'None:', 'raise', "ValueError('No", 'data', 'files', 'found', 'for', 'this', "dataset')", 'if', ...
55,198
facebookresearch/minihack
models.py
Crop.forward
forward
Calculates centered crop around given x,y coordinates.
[ "Calculates", "centered", "crop", "around", "given", "x,y", "coordinates." ]
def forward(self, inputs, coordinates): assert inputs.shape[1] == self.height, 'expected %d but found %d' % (self.height, inputs.shape[1]) assert inputs.shape[2] == self.width, 'expected %d but found %d' % (self.width, inputs.shape[2]) permute_results = False if inputs.dim() == 3: inputs = input...
['def', 'forward(self,', 'inputs,', 'coordinates):', 'assert', 'inputs.shape[1]', '==', 'self.height,', "'expected", '%d', 'but', 'found', "%d'", '%', '(self.height,', 'inputs.shape[1])', 'assert', 'inputs.shape[2]', '==', 'self.width,', "'expected", '%d', 'but', 'found', "%d'", '%', '(self.width,', 'inputs.shape[2])',...
670,759
nicknochnack/RealTimeSignLanguageTFJS
post_training_quantization.py
restore_model
restore_model
Restore variables from the checkpoint into the provided session.
[ "Restore", "variables", "from", "the", "checkpoint", "into", "the", "provided", "session." ]
def restore_model(sess, checkpoint_path, enable_ema=True): if enable_ema: ema = tf.train.ExponentialMovingAverage(decay=0.0) ema_vars = tf.trainable_variables() + tf.get_collection('moving_vars') for v in tf.global_variables(): if 'moving_mean' in v.name or 'moving_variance' in v...
['def', 'restore_model(sess,', 'checkpoint_path,', 'enable_ema=True):', 'if', 'enable_ema:', 'ema', '=', 'tf.train.ExponentialMovingAverage(decay=0.0)', 'ema_vars', '=', 'tf.trainable_variables()', '+', "tf.get_collection('moving_vars')", 'for', 'v', 'in', 'tf.global_variables():', 'if', "'moving_mean'", 'in', 'v.name'...
831,275
nancheng58/Self-supervised-learning-for-Sequential-Recommender-Systems
macridvae.py
MacridVAE.get_rating_matrix
get_rating_matrix
Get a batch of user's feature with the user's id and history interaction matrix.
[ "Get", "a", "batch", "of", "user's", "feature", "with", "the", "user's", "id", "and", "history", "interaction", "matrix." ]
def get_rating_matrix(self, user): col_indices = self.history_item_id[user].flatten() row_indices = torch.arange(user.shape[0]).to(self.device).repeat_interleave(self.history_item_id.shape[1], dim=0) rating_matrix = torch.zeros(1).to(self.device).repeat(user.shape[0], self.n_items) rating_matrix.index_p...
['def', 'get_rating_matrix(self,', 'user):', 'col_indices', '=', 'self.history_item_id[user].flatten()', 'row_indices', '=', 'torch.arange(user.shape[0]).to(self.device).repeat_interleave(self.history_item_id.shape[1],', 'dim=0)', 'rating_matrix', '=', 'torch.zeros(1).to(self.device).repeat(user.shape[0],', 'self.n_ite...
341,916
unixpickle/anyrl-py
test_wrappers.py
test_downsample_rate_2
test_downsample_rate_2
Test DownsampleEnv with rate=2.
[ "Test", "DownsampleEnv", "with", "rate=2." ]
def test_downsample_rate_2(): low = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) high = np.array([[9, 10, 11, 12], [13, 14, 15, 16]]) env = DownsampleEnv(ShapeEnv(low, high), 2) assert env.observation_space.shape == (1, 2) assert (env.observation_space.low == np.array([[1, 3]])).all() assert (env.obse...
['def', 'test_downsample_rate_2():', 'low', '=', 'np.array([[1,', '2,', '3,', '4],', '[5,', '6,', '7,', '8]])', 'high', '=', 'np.array([[9,', '10,', '11,', '12],', '[13,', '14,', '15,', '16]])', 'env', '=', 'DownsampleEnv(ShapeEnv(low,', 'high),', '2)', 'assert', 'env.observation_space.shape', '==', '(1,', '2)', 'asser...
33,742
google-research/scenic
train_utils.py
psum_metric_normalizer
psum_metric_normalizer
Applies psum over the given tuple of (metric, normalizer).
[ "Applies", "psum", "over", "the", "given", "tuple", "of", "(metric,", "normalizer)." ]
def psum_metric_normalizer(metrics: Tuple[jnp.ndarray, jnp.ndarray]) -> Tuple[jnp.ndarray, jnp.ndarray]: psumed_metric = jnp.sum(jax.lax.psum(metrics[0], axis_name='batch')) psumed_normalizer = jnp.sum(jax.lax.psum(metrics[1], axis_name='batch')) return (psumed_metric, psumed_normalizer)
['def', 'psum_metric_normalizer(metrics:', 'Tuple[jnp.ndarray,', 'jnp.ndarray])', '->', 'Tuple[jnp.ndarray,', 'jnp.ndarray]:', 'psumed_metric', '=', 'jnp.sum(jax.lax.psum(metrics[0],', "axis_name='batch'))", 'psumed_normalizer', '=', 'jnp.sum(jax.lax.psum(metrics[1],', "axis_name='batch'))", 'return', '(psumed_metric,'...
846,344
QData/deepWordBug
math2html.py
Postprocessor.postcurrent
postcurrent
Postprocess the current element taking into account next and last.
[ "Postprocess", "the", "current", "element", "taking", "into", "account", "next", "and", "last." ]
def postcurrent(self, next): stage = self.stages.getstage(self.current) if not stage: return self.current return stage.postprocess(self.last, self.current, next)
['def', 'postcurrent(self,', 'next):', 'stage', '=', 'self.stages.getstage(self.current)', 'if', 'not', 'stage:', 'return', 'self.current', 'return', 'stage.postprocess(self.last,', 'self.current,', 'next)']
542,557
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
base.py
LocalTree.dupNode
dupNode
Called by the parser to create a duplicate of this tree.
[ "Called", "by", "the", "parser", "to", "create", "a", "duplicate", "of", "this", "tree." ]
def dupNode(self): get = lambda v: getattr(self, v, None) return LocalTree(self, get('lexer'), get('parser'))
['def', 'dupNode(self):', 'get', '=', 'lambda', 'v:', 'getattr(self,', 'v,', 'None)', 'return', 'LocalTree(self,', "get('lexer'),", "get('parser'))"]
17,471
weimin17/Object-Detection_HelmetDetection
imagenet_main.py
get_filenames
get_filenames
Return filenames for dataset.
[ "Return", "filenames", "for", "dataset." ]
def get_filenames(is_training, data_dir): if is_training: return [os.path.join(data_dir, 'train-%05d-of-01024' % i) for i in range(_NUM_TRAIN_FILES)] else: return [os.path.join(data_dir, 'validation-%05d-of-00128' % i) for i in range(128)]
['def', 'get_filenames(is_training,', 'data_dir):', 'if', 'is_training:', 'return', '[os.path.join(data_dir,', "'train-%05d-of-01024'", '%', 'i)', 'for', 'i', 'in', 'range(_NUM_TRAIN_FILES)]', 'else:', 'return', '[os.path.join(data_dir,', "'validation-%05d-of-00128'", '%', 'i)', 'for', 'i', 'in', 'range(128)]']
761,104
wbsth/cs50ai
tictactoe.py
player
player
Returns player who has the next turn on a board.
[ "Returns", "player", "who", "has", "the", "next", "turn", "on", "a", "board." ]
def player(board): (numX, numO) = (0, 0) for row in board: for cell in row: if cell == X: numX += 1 elif cell == O: numO += 1 if numX > numO: return O elif not terminal(board) and numX == numO: return X else: ret...
['def', 'player(board):', '(numX,', 'numO)', '=', '(0,', '0)', 'for', 'row', 'in', 'board:', 'for', 'cell', 'in', 'row:', 'if', 'cell', '==', 'X:', 'numX', '+=', '1', 'elif', 'cell', '==', 'O:', 'numO', '+=', '1', 'if', 'numX', '>', 'numO:', 'return', 'O', 'elif', 'not', 'terminal(board)', 'and', 'numX', '==', 'numO:',...
192,126
Xianpeng919/MonoCon
kitti_dataset.py
KittiDataset.bbox2result_kitti2d
bbox2result_kitti2d
Convert 2D detection results to kitti format for evaluation and test submission.
[ "Convert", "2D", "detection", "results", "to", "kitti", "format", "for", "evaluation", "and", "test", "submission." ]
def bbox2result_kitti2d(self, net_outputs, class_names, pklfile_prefix=None, submission_prefix=None): assert len(net_outputs) == len(self.data_infos), 'invalid list length of network outputs' det_annos = [] print('\nConverting prediction to KITTI format') for (i, bboxes_per_sample) in enumerate(mmcv.tra...
['def', 'bbox2result_kitti2d(self,', 'net_outputs,', 'class_names,', 'pklfile_prefix=None,', 'submission_prefix=None):', 'assert', 'len(net_outputs)', '==', 'len(self.data_infos),', "'invalid", 'list', 'length', 'of', 'network', "outputs'", 'det_annos', '=', '[]', "print('\\nConverting", 'prediction', 'to', 'KITTI', "f...
654,446
Wuziyi616/Artificial_Intelligence_Project1
tangram_element.py
Element.get_midpoint
get_midpoint
Get the midpoint of the whole element by averaging all x and y coordinates.
[ "Get", "the", "midpoint", "of", "the", "whole", "element", "by", "averaging", "all", "x", "and", "y", "coordinates." ]
def get_midpoint(self): x = 0.0 y = 0.0 for point in self.points: x += point.x / self.point_num y += point.y / self.point_num return Point(x=x, y=y)
['def', 'get_midpoint(self):', 'x', '=', '0.0', 'y', '=', '0.0', 'for', 'point', 'in', 'self.points:', 'x', '+=', 'point.x', '/', 'self.point_num', 'y', '+=', 'point.y', '/', 'self.point_num', 'return', 'Point(x=x,', 'y=y)']
92,163
exiawsh/StreamPETR
positional_encoding.py
nerf_positional_encoding
nerf_positional_encoding
Apply positional encoding to the input.
[ "Apply", "positional", "encoding", "to", "the", "input." ]
def nerf_positional_encoding(tensor, num_encoding_functions=6, include_input=False, log_sampling=True) -> torch.Tensor: encoding = [tensor] if include_input else [] frequency_bands = None if log_sampling: frequency_bands = 2.0 ** torch.linspace(0.0, num_encoding_functions - 1, num_encoding_functions...
['def', 'nerf_positional_encoding(tensor,', 'num_encoding_functions=6,', 'include_input=False,', 'log_sampling=True)', '->', 'torch.Tensor:', 'encoding', '=', '[tensor]', 'if', 'include_input', 'else', '[]', 'frequency_bands', '=', 'None', 'if', 'log_sampling:', 'frequency_bands', '=', '2.0', '**', 'torch.linspace(0.0,...
910,095
tensorflow/agents
greedy_reward_prediction_agent.py
GreedyRewardPredictionAgent.reward_loss
reward_loss
Computes loss for reward prediction training.
[ "Computes", "loss", "for", "reward", "prediction", "training." ]
def reward_loss(self, observations: types.NestedTensor, actions: types.Tensor, rewards: types.Tensor, weights: Optional[types.Float]=None, training: bool=False) -> types.Tensor: with tf.name_scope('loss'): sample_weights = weights if weights is not None else 1 if self._heteroscedastic: (...
['def', 'reward_loss(self,', 'observations:', 'types.NestedTensor,', 'actions:', 'types.Tensor,', 'rewards:', 'types.Tensor,', 'weights:', 'Optional[types.Float]=None,', 'training:', 'bool=False)', '->', 'types.Tensor:', 'with', "tf.name_scope('loss'):", 'sample_weights', '=', 'weights', 'if', 'weights', 'is', 'not', '...
22,519
spite-triangle/artificial_intelligence
cookies.py
RequestsCookieJar.list_paths
list_paths
Utility method to list all the paths in the jar.
[ "Utility", "method", "to", "list", "all", "the", "paths", "in", "the", "jar." ]
def list_paths(self): paths = [] for cookie in iter(self): if cookie.path not in paths: paths.append(cookie.path) return paths
['def', 'list_paths(self):', 'paths', '=', '[]', 'for', 'cookie', 'in', 'iter(self):', 'if', 'cookie.path', 'not', 'in', 'paths:', 'paths.append(cookie.path)', 'return', 'paths']
155,528
AlexGeControl/Artificial-Intelligence-01-Graph-Search-02-Pacman
pyparsing.py
ParseResults.append
append
Add single element to end of ParseResults list of elements.
[ "Add", "single", "element", "to", "end", "of", "ParseResults", "list", "of", "elements." ]
def append(self, item): self.__toklist.append(item)
['def', 'append(self,', 'item):', 'self.__toklist.append(item)']
35,799
AboudyKreidieh/h-baselines
replay_buffer.py
HierReplayBuffer.load
load
Load parameters for the replay buffer.
[ "Load", "parameters", "for", "the", "replay", "buffer." ]
def load(self, save_path): self._obs_t = np.load(save_path + '.obs_t.npy') self._context_t = np.load(save_path + '.context_t.npy') self._action_t = np.load(save_path + '.action_t.npy') self._reward_t = np.load(save_path + '.reward_t.npy') self._done_t = np.load(save_path + '.done_t.npy') (self.b...
['def', 'load(self,', 'save_path):', 'self._obs_t', '=', 'np.load(save_path', '+', "'.obs_t.npy')", 'self._context_t', '=', 'np.load(save_path', '+', "'.context_t.npy')", 'self._action_t', '=', 'np.load(save_path', '+', "'.action_t.npy')", 'self._reward_t', '=', 'np.load(save_path', '+', "'.reward_t.npy')", 'self._done...
573,953
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform
categorical.py
Categorical.size
size
Return the len of myself.
[ "Return", "the", "len", "of", "myself." ]
def size(self) -> int: return self._codes.size
['def', 'size(self)', '->', 'int:', 'return', 'self._codes.size']
82,539
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
pdb.py
Pdb.do_longlist
do_longlist
longlist | ll List the whole source code for the current function or frame.
[ "longlist", "|", "ll", "List", "the", "whole", "source", "code", "for", "the", "current", "function", "or", "frame." ]
def do_longlist(self, arg): filename = self.curframe.f_code.co_filename breaklist = self.get_file_breaks(filename) try: (lines, lineno) = getsourcelines(self.curframe) except OSError as err: self.error(err) return self._print_lines(lines, lineno, breaklist, self.curframe)
['def', 'do_longlist(self,', 'arg):', 'filename', '=', 'self.curframe.f_code.co_filename', 'breaklist', '=', 'self.get_file_breaks(filename)', 'try:', '(lines,', 'lineno)', '=', 'getsourcelines(self.curframe)', 'except', 'OSError', 'as', 'err:', 'self.error(err)', 'return', 'self._print_lines(lines,', 'lineno,', 'break...
429,135
myothida/Supervised-Machine-Learning
test_ridge.py
test_ridge_positive_regression_test
test_ridge_positive_regression_test
Test that positive Ridge finds true positive coefficients.
[ "Test", "that", "positive", "Ridge", "finds", "true", "positive", "coefficients." ]
def test_ridge_positive_regression_test(solver, fit_intercept, alpha): X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]]) coef = np.array([1, -10]) if fit_intercept: intercept = 20 y = X.dot(coef) + intercept else: y = X.dot(coef) model = Ridge(alpha=alpha, positive=True, solver=...
['def', 'test_ridge_positive_regression_test(solver,', 'fit_intercept,', 'alpha):', 'X', '=', 'np.array([[1,', '2],', '[3,', '4],', '[5,', '6],', '[7,', '8]])', 'coef', '=', 'np.array([1,', '-10])', 'if', 'fit_intercept:', 'intercept', '=', '20', 'y', '=', 'X.dot(coef)', '+', 'intercept', 'else:', 'y', '=', 'X.dot(coef...
364,166
tensorflow/agents
sac_train_eval.py
train_eval
train_eval
Trains and evaluates SAC.
[ "Trains", "and", "evaluates", "SAC." ]
def train_eval(root_dir, strategy: tf.distribute.Strategy, env_name='HalfCheetah-v2', initial_collect_steps=10000, num_iterations=3200000, actor_fc_layers=(256, 256), critic_obs_fc_layers=None, critic_action_fc_layers=None, critic_joint_fc_layers=(256, 256), batch_size=256, actor_learning_rate=0.0003, critic_learning_r...
['def', 'train_eval(root_dir,', 'strategy:', 'tf.distribute.Strategy,', "env_name='HalfCheetah-v2',", 'initial_collect_steps=10000,', 'num_iterations=3200000,', 'actor_fc_layers=(256,', '256),', 'critic_obs_fc_layers=None,', 'critic_action_fc_layers=None,', 'critic_joint_fc_layers=(256,', '256),', 'batch_size=256,', 'a...
23,490
gunthercox/ChatterBot
paicehusk.py
PaiceHuskStemmer.stem
stem
Returns a stemmed version of the argument string.
[ "Returns", "a", "stemmed", "version", "of", "the", "argument", "string." ]
def stem(self, word): rules = self.rules match = self.stem_expr.match(word) if not match: return word stem = self.strip_prefix(match.group(0)) is_intact = True continuing = True while continuing: pfv = self.first_vowel(stem) rulelist = rules.get(stem[-1]) if n...
['def', 'stem(self,', 'word):', 'rules', '=', 'self.rules', 'match', '=', 'self.stem_expr.match(word)', 'if', 'not', 'match:', 'return', 'word', 'stem', '=', 'self.strip_prefix(match.group(0))', 'is_intact', '=', 'True', 'continuing', '=', 'True', 'while', 'continuing:', 'pfv', '=', 'self.first_vowel(stem)', 'rulelist'...
484,500
enuguru/artificial_intelligence_and_machine_learning
generic.py
Learner.forget
forget
Resets the Learner to its original state.
[ "Resets", "the", "Learner", "to", "its", "original", "state." ]
def forget(self): raise NotImplementedError('Subclass should have implemented this method.')
['def', 'forget(self):', 'raise', "NotImplementedError('Subclass", 'should', 'have', 'implemented', 'this', "method.')"]
164,352
implus/GFocalV2
base_roi_extractor.py
BaseRoIExtractor.num_inputs
num_inputs
int: Number of input feature maps.
[ "int:", "Number", "of", "input", "feature", "maps." ]
def num_inputs(self): return len(self.featmap_strides)
['def', 'num_inputs(self):', 'return', 'len(self.featmap_strides)']
557,769
PacktPublishing/Hands-On-Artificial--for-Banking
pep425tags.py
get_impl_tag
get_impl_tag
Returns the Tag for this specific implementation.
[ "Returns", "the", "Tag", "for", "this", "specific", "implementation." ]
def get_impl_tag(): return '{}{}'.format(get_abbr_impl(), get_impl_ver())
['def', 'get_impl_tag():', 'return', "'{}{}'.format(get_abbr_impl(),", 'get_impl_ver())']
237,423
krfricke/rl-benchmark
db.py
BenchmarkDatabase.save_benchmark
save_benchmark
Save benchmark to database.
[ "Save", "benchmark", "to", "database." ]
def save_benchmark(self, benchmark_data): raise NotImplementedError
['def', 'save_benchmark(self,', 'benchmark_data):', 'raise', 'NotImplementedError']
841,818
loicmarie/hands-detection
check.py
NotIn
NotIn
Raises an error if |key| is in |container|.
[ "Raises", "an", "error", "if", "|key|", "is", "in", "|container|." ]
def NotIn(key, container, message='', error=ValueError): if key in container: raise error('Expected (%s) is not in (%s): %s' % (key, container, message))
['def', 'NotIn(key,', 'container,', "message='',", 'error=ValueError):', 'if', 'key', 'in', 'container:', 'raise', "error('Expected", '(%s)', 'is', 'not', 'in', '(%s):', "%s'", '%', '(key,', 'container,', 'message))']
575,503
myothida/Supervised-Machine-Learning
egg_info.py
FileList.prune
prune
Filter out files from 'dir/'.
[ "Filter", "out", "files", "from", "'dir/'." ]
def prune(self, dir): match = translate_pattern(os.path.join(dir, '**')) return self._remove_files(match.match)
['def', 'prune(self,', 'dir):', 'match', '=', 'translate_pattern(os.path.join(dir,', "'**'))", 'return', 'self._remove_files(match.match)']
446,997
mideind/GreynirServer
currency.py
QCurUnit
QCurUnit
Obtain the ISO currency code from the last three letters in the child nonterminal name.
[ "Obtain", "the", "ISO", "currency", "code", "from", "the", "last", "three", "letters", "in", "the", "child", "nonterminal", "name." ]
def QCurUnit(node: Node, params: QueryStateDict, result: Result) -> None: child = cast(NonterminalNode, node.child) currency = child.nt_base[-3:] add_currency(currency, result)
['def', 'QCurUnit(node:', 'Node,', 'params:', 'QueryStateDict,', 'result:', 'Result)', '->', 'None:', 'child', '=', 'cast(NonterminalNode,', 'node.child)', 'currency', '=', 'child.nt_base[-3:]', 'add_currency(currency,', 'result)']
581,075
nilearn/nilearn
test_hemodynamic_models.py
test_sample_condition_3
test_sample_condition_3
Test the experimental condition sampling -- oversampling=10.
[ "Test", "the", "experimental", "condition", "sampling", "--", "oversampling=10." ]
def test_sample_condition_3(): condition = ([1, 20, 36.5], [2, 2, 2], [1, 1, 1]) frame_times = np.linspace(0, 49, 50) (reg, _) = _sample_condition(condition, frame_times, oversampling=10, min_onset=0) assert_almost_equal(reg.sum(), 60.0) assert reg[10] == 1 assert reg[380] == 1 assert reg[21...
['def', 'test_sample_condition_3():', 'condition', '=', '([1,', '20,', '36.5],', '[2,', '2,', '2],', '[1,', '1,', '1])', 'frame_times', '=', 'np.linspace(0,', '49,', '50)', '(reg,', '_)', '=', '_sample_condition(condition,', 'frame_times,', 'oversampling=10,', 'min_onset=0)', 'assert_almost_equal(reg.sum(),', '60.0)', ...
723,870
Speedwagon13/CS-3600-Introduction-to--
message.py
Message.is_multipart
is_multipart
Return True if the message consists of multiple parts.
[ "Return", "True", "if", "the", "message", "consists", "of", "multiple", "parts." ]
def is_multipart(self): return isinstance(self._payload, list)
['def', 'is_multipart(self):', 'return', 'isinstance(self._payload,', 'list)']
140,144
cjrd/self-supervised-pretraining
misc.py
unmap
unmap
Unmap a subset of item (data) back to the original set of items (of size count).
[ "Unmap", "a", "subset", "of", "item", "(data)", "back", "to", "the", "original", "set", "of", "items", "(of", "size", "count)." ]
def unmap(data, count, inds, fill=0): if data.dim() == 1: ret = data.new_full((count,), fill) ret[inds] = data else: new_size = (count,) + data.size()[1:] ret = data.new_full(new_size, fill) ret[inds, :] = data return ret
['def', 'unmap(data,', 'count,', 'inds,', 'fill=0):', 'if', 'data.dim()', '==', '1:', 'ret', '=', 'data.new_full((count,),', 'fill)', 'ret[inds]', '=', 'data', 'else:', 'new_size', '=', '(count,)', '+', 'data.size()[1:]', 'ret', '=', 'data.new_full(new_size,', 'fill)', 'ret[inds,', ':]', '=', 'data', 'return', 'ret']
843,810
liuhuiwisdom/object_detection
np_box_list.py
BoxList.num_boxes
num_boxes
Return number of boxes held in collections.
[ "Return", "number", "of", "boxes", "held", "in", "collections." ]
def num_boxes(self): return self.data['boxes'].shape[0]
['def', 'num_boxes(self):', 'return', "self.data['boxes'].shape[0]"]
793,208
eora-ai/torchok
resnet.py
tv_resnet152
tv_resnet152
Constructs a ResNet-152 model w/ Torchvision pretrained weights.
[ "Constructs", "a", "ResNet-152", "model", "w/", "Torchvision", "pretrained", "weights." ]
def tv_resnet152(pretrained=False, **kwargs): model_args = dict(block=Bottleneck, layers=[3, 8, 36, 3], **kwargs) return _create_resnet('tv_resnet152', pretrained, **model_args)
['def', 'tv_resnet152(pretrained=False,', '**kwargs):', 'model_args', '=', 'dict(block=Bottleneck,', 'layers=[3,', '8,', '36,', '3],', '**kwargs)', 'return', "_create_resnet('tv_resnet152',", 'pretrained,', '**model_args)']
903,200
imranparuk/speaker-recognition-3d-cnn
train.py
one_hot_embedding
one_hot_embedding
Embedding labels to one-hot form.
[ "Embedding", "labels", "to", "one-hot", "form." ]
def one_hot_embedding(labels, num_classes): y = torch.eye(num_classes) return y[labels]
['def', 'one_hot_embedding(labels,', 'num_classes):', 'y', '=', 'torch.eye(num_classes)', 'return', 'y[labels]']
894,796
Alexander-Parker/youtube_nlp
proxy.py
Proxy.socks_username
socks_username
Returns socks proxy username setting.
[ "Returns", "socks", "proxy", "username", "setting." ]
def socks_username(self): return self.socksUsername
['def', 'socks_username(self):', 'return', 'self.socksUsername']
970,821
open-mmlab/mmdetection3d
voxelize.py
DynamicScatter3D.forward
forward
Scatters points/features into voxels.
[ "Scatters", "points/features", "into", "voxels." ]
def forward(self, points: torch.Tensor, coors: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: if coors.size(-1) == 3: return self.forward_single(points, coors) else: batch_size = coors[-1, 0] + 1 (voxels, voxel_coors) = ([], []) for i in range(batch_size): inds =...
['def', 'forward(self,', 'points:', 'torch.Tensor,', 'coors:', 'torch.Tensor)', '->', 'Tuple[torch.Tensor,', 'torch.Tensor]:', 'if', 'coors.size(-1)', '==', '3:', 'return', 'self.forward_single(points,', 'coors)', 'else:', 'batch_size', '=', 'coors[-1,', '0]', '+', '1', '(voxels,', 'voxel_coors)', '=', '([],', '[])', '...
631,849
enuguru/artificial_intelligence_and_machine_
firebird.py
FBColumnDropper.visit_column
visit_column
Firebird supports 'DROP col' instead of 'DROP COLUMN col' syntax Drop primary key and unique constraints if dropped column is referencing it.
[ "Firebird", "supports", "'DROP", "col'", "instead", "of", "'DROP", "COLUMN", "col'", "syntax", "Drop", "primary", "key", "and", "unique", "constraints", "if", "dropped", "column", "is", "referencing", "it." ]
def visit_column(self, column): if column.primary_key: if column.table.primary_key.columns.contains_column(column): column.table.primary_key.drop() for index in column.table.indexes: if column.name in [col.name for col in index.columns]: index.drop() for cons in colum...
['def', 'visit_column(self,', 'column):', 'if', 'column.primary_key:', 'if', 'column.table.primary_key.columns.contains_column(column):', 'column.table.primary_key.drop()', 'for', 'index', 'in', 'column.table.indexes:', 'if', 'column.name', 'in', '[col.name', 'for', 'col', 'in', 'index.columns]:', 'index.drop()', 'for'...
158,710
tensorlayer/TensorLayerX
method_decorator.py
protected_method
protected_method
Decorator for making an instance method private.
[ "Decorator", "for", "making", "an", "instance", "method", "private." ]
def protected_method(func): def func_wrapper(*args, **kwargs): outer_frame = inspect.stack()[1][0] caller = inspect.getmro(outer_frame.f_locals['self'].__class__)[:-1] target = inspect.getmro(args[0].__class__)[:-1] share_subsclass = False for cls_ in target: if ...
['def', 'protected_method(func):', 'def', 'func_wrapper(*args,', '**kwargs):', 'outer_frame', '=', 'inspect.stack()[1][0]', 'caller', '=', "inspect.getmro(outer_frame.f_locals['self'].__class__)[:-1]", 'target', '=', 'inspect.getmro(args[0].__class__)[:-1]', 'share_subsclass', '=', 'False', 'for', 'cls_', 'in', 'target...
923,738
rudranil723/mini-main
edit.py
FormMixin.form_invalid
form_invalid
If the form is invalid, render the invalid form.
[ "If", "the", "form", "is", "invalid,", "render", "the", "invalid", "form." ]
def form_invalid(self, form): return self.render_to_response(self.get_context_data(form=form))
['def', 'form_invalid(self,', 'form):', 'return', 'self.render_to_response(self.get_context_data(form=form))']
316,918
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
pdb.py
Pdb.do_args
do_args
a(rgs) Print the argument list of the current function.
[ "a(rgs)", "Print", "the", "argument", "list", "of", "the", "current", "function." ]
def do_args(self, arg): co = self.curframe.f_code dict = self.curframe_locals n = co.co_argcount if co.co_flags & 4: n = n + 1 if co.co_flags & 8: n = n + 1 for i in range(n): name = co.co_varnames[i] if name in dict: self.message('%s = %r' % (name, di...
['def', 'do_args(self,', 'arg):', 'co', '=', 'self.curframe.f_code', 'dict', '=', 'self.curframe_locals', 'n', '=', 'co.co_argcount', 'if', 'co.co_flags', '&', '4:', 'n', '=', 'n', '+', '1', 'if', 'co.co_flags', '&', '8:', 'n', '=', 'n', '+', '1', 'for', 'i', 'in', 'range(n):', 'name', '=', 'co.co_varnames[i]', 'if', '...
429,130
matsu0228/nlp-jp
notebookapp.py
NotebookWebApplication.init_handlers
init_handlers
Load the (URL pattern, handler) tuples for each component.
[ "Load", "the", "(URL", "pattern,", "handler)", "tuples", "for", "each", "component." ]
def init_handlers(self, settings): handlers = [] handlers.extend(load_handlers('tree.handlers')) handlers.extend([('/login', settings['login_handler_class'])]) handlers.extend([('/logout', settings['logout_handler_class'])]) handlers.extend(load_handlers('files.handlers')) handlers.extend(load_h...
['def', 'init_handlers(self,', 'settings):', 'handlers', '=', '[]', "handlers.extend(load_handlers('tree.handlers'))", "handlers.extend([('/login',", "settings['login_handler_class'])])", "handlers.extend([('/logout',", "settings['logout_handler_class'])])", "handlers.extend(load_handlers('files.handlers'))", "handlers...
790,491
AarohiSingla/Object-Detection-Web-App-Using-YOLOv7-and-Flask
add_nms.py
RegisterNMS.save
save
Save the ONNX model to the given location.
[ "Save", "the", "ONNX", "model", "to", "the", "given", "location." ]
def save(self, output_path): self.graph.cleanup().toposort() model = gs.export_onnx(self.graph) onnx.save(model, output_path) LOGGER.info(f'Saved ONNX model to {output_path}')
['def', 'save(self,', 'output_path):', 'self.graph.cleanup().toposort()', 'model', '=', 'gs.export_onnx(self.graph)', 'onnx.save(model,', 'output_path)', "LOGGER.info(f'Saved", 'ONNX', 'model', 'to', "{output_path}')"]
748,456
ViTAE-Transformer/ViTDet
seesaw_loss.py
SeesawLoss.get_activation
get_activation
Get custom activation of cls_score.
[ "Get", "custom", "activation", "of", "cls_score." ]
def get_activation(self, cls_score): (cls_score_classes, cls_score_objectness) = self._split_cls_score(cls_score) score_classes = F.softmax(cls_score_classes, dim=-1) score_objectness = F.softmax(cls_score_objectness, dim=-1) score_pos = score_objectness[..., [0]] score_neg = score_objectness[..., [...
['def', 'get_activation(self,', 'cls_score):', '(cls_score_classes,', 'cls_score_objectness)', '=', 'self._split_cls_score(cls_score)', 'score_classes', '=', 'F.softmax(cls_score_classes,', 'dim=-1)', 'score_objectness', '=', 'F.softmax(cls_score_objectness,', 'dim=-1)', 'score_pos', '=', 'score_objectness[...,', '[0]]...
945,717
Katja-M/Python_NaturalLanguageProcessing
blocking_input.py
BlockingKeyMouseInput.post_event
post_event
Determine if it is a key event.
[ "Determine", "if", "it", "is", "a", "key", "event." ]
def post_event(self): if self.events: self.keyormouse = self.events[-1].name == 'key_press_event' else: _log.warning('No events yet.')
['def', 'post_event(self):', 'if', 'self.events:', 'self.keyormouse', '=', 'self.events[-1].name', '==', "'key_press_event'", 'else:', "_log.warning('No", 'events', "yet.')"]
864,390
fcjian/TOOD
utils.py
replace_ImageToTensor
replace_ImageToTensor
Replace the ImageToTensor transform in a data pipeline to DefaultFormatBundle, which is normally useful in batch inference.
[ "Replace", "the", "ImageToTensor", "transform", "in", "a", "data", "pipeline", "to", "DefaultFormatBundle,", "which", "is", "normally", "useful", "in", "batch", "inference." ]
def replace_ImageToTensor(pipelines): pipelines = copy.deepcopy(pipelines) for (i, pipeline) in enumerate(pipelines): if pipeline['type'] == 'MultiScaleFlipAug': assert 'transforms' in pipeline pipeline['transforms'] = replace_ImageToTensor(pipeline['transforms']) elif pi...
['def', 'replace_ImageToTensor(pipelines):', 'pipelines', '=', 'copy.deepcopy(pipelines)', 'for', '(i,', 'pipeline)', 'in', 'enumerate(pipelines):', 'if', "pipeline['type']", '==', "'MultiScaleFlipAug':", 'assert', "'transforms'", 'in', 'pipeline', "pipeline['transforms']", '=', "replace_ImageToTensor(pipeline['transfo...
901,911
deepmind/dm_control
humanoid.py
run_pure_state
run_pure_state
Returns the Run task.
[ "Returns", "the", "Run", "task." ]
def run_pure_state(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): physics = Physics.from_xml_string(*get_model_and_assets()) task = Humanoid(move_speed=_RUN_SPEED, pure_state=True, random=random) environment_kwargs = environment_kwargs or {} return control.Environment(physics, ta...
['def', 'run_pure_state(time_limit=_DEFAULT_TIME_LIMIT,', 'random=None,', 'environment_kwargs=None):', 'physics', '=', 'Physics.from_xml_string(*get_model_and_assets())', 'task', '=', 'Humanoid(move_speed=_RUN_SPEED,', 'pure_state=True,', 'random=random)', 'environment_kwargs', '=', 'environment_kwargs', 'or', '{}', 'r...
165,477
googleapis/python-aiplatform
client.py
DatasetServiceClient.parse_common_location_path
parse_common_location_path
Parse a location path into its component segments.
[ "Parse", "a", "location", "path", "into", "its", "component", "segments." ]
def parse_common_location_path(path: str) -> Dict[str, str]: m = re.match('^projects/(?P<project>.+?)/locations/(?P<location>.+?)$', path) return m.groupdict() if m else {}
['def', 'parse_common_location_path(path:', 'str)', '->', 'Dict[str,', 'str]:', 'm', '=', "re.match('^projects/(?P<project>.+?)/locations/(?P<location>.+?)$',", 'path)', 'return', 'm.groupdict()', 'if', 'm', 'else', '{}']
812,165
for-ai/rl
replay_buffers.py
ReplayBuffer.add
add
Add a single element to the replay buffer.
[ "Add", "a", "single", "element", "to", "the", "replay", "buffer." ]
def add(self, data: Any) -> int: if self._transform is not None and (is_tensor_collection(data) or len(self._transform)): data = self._transform.inv(data) return self._add(data)
['def', 'add(self,', 'data:', 'Any)', '->', 'int:', 'if', 'self._transform', 'is', 'not', 'None', 'and', '(is_tensor_collection(data)', 'or', 'len(self._transform)):', 'data', '=', 'self._transform.inv(data)', 'return', 'self._add(data)']
858,795
danamyu/hedgehog_detector
tune.py
run_tuner_loop
run_tuner_loop
Run tuning loop for this worker.
[ "Run", "tuning", "loop", "for", "this", "worker." ]
def run_tuner_loop(ns): is_chief = FLAGS.task_id == 0 tuning_space = ns.define_tuner_hparam_space(hparam_space_type=FLAGS.hparam_space) fixed_hparams = parse_hparams_string(FLAGS.fixed_hparams) for (name, value) in fixed_hparams.iteritems(): tuning_space[name] = [value] tuning_space_size = n...
['def', 'run_tuner_loop(ns):', 'is_chief', '=', 'FLAGS.task_id', '==', '0', 'tuning_space', '=', 'ns.define_tuner_hparam_space(hparam_space_type=FLAGS.hparam_space)', 'fixed_hparams', '=', 'parse_hparams_string(FLAGS.fixed_hparams)', 'for', '(name,', 'value)', 'in', 'fixed_hparams.iteritems():', 'tuning_space[name]', '...
589,394
vturrisi/solo-learn
mocov3.py
MoCoV3.momentum_forward
momentum_forward
Performs the forward pass of the momentum backbone and projector.
[ "Performs", "the", "forward", "pass", "of", "the", "momentum", "backbone", "and", "projector." ]
def momentum_forward(self, X: torch.Tensor) -> Dict: out = super().momentum_forward(X) k = self.momentum_projector(out['feats']) out.update({'k': k}) return out
['def', 'momentum_forward(self,', 'X:', 'torch.Tensor)', '->', 'Dict:', 'out', '=', 'super().momentum_forward(X)', 'k', '=', "self.momentum_projector(out['feats'])", "out.update({'k':", 'k})', 'return', 'out']
393,647
myothida/Supervised-Machine-Learning
test_impute.py
test_simple_imputer_keep_empty_features
test_simple_imputer_keep_empty_features
Check the behaviour of `keep_empty_features` with all strategies but 'constant'.
[ "Check", "the", "behaviour", "of", "`keep_empty_features`", "with", "all", "strategies", "but", "'constant'." ]
def test_simple_imputer_keep_empty_features(strategy, array_type, keep_empty_features): X = np.array([[np.nan, 2], [np.nan, 3], [np.nan, 6]]) X = _convert_container(X, array_type) imputer = SimpleImputer(strategy=strategy, keep_empty_features=keep_empty_features) for method in ['fit_transform', 'transfo...
['def', 'test_simple_imputer_keep_empty_features(strategy,', 'array_type,', 'keep_empty_features):', 'X', '=', 'np.array([[np.nan,', '2],', '[np.nan,', '3],', '[np.nan,', '6]])', 'X', '=', '_convert_container(X,', 'array_type)', 'imputer', '=', 'SimpleImputer(strategy=strategy,', 'keep_empty_features=keep_empty_feature...
364,032
es-amit/Artificial-Intelligence
search.py
NQueensProblem.goal_test
goal_test
Check if all columns filled, no conflicts.
[ "Check", "if", "all", "columns", "filled,", "no", "conflicts." ]
def goal_test(self, state): if state[-1] == -1: return False return not any((self.conflicted(state, state[col], col) for col in range(len(state))))
['def', 'goal_test(self,', 'state):', 'if', 'state[-1]', '==', '-1:', 'return', 'False', 'return', 'not', 'any((self.conflicted(state,', 'state[col],', 'col)', 'for', 'col', 'in', 'range(len(state))))']
118,458
Ruturaj123/Flowchart-Detection
gmm_ops.py
gmm
gmm
Creates the graph for Gaussian mixture model (GMM) clustering.
[ "Creates", "the", "graph", "for", "Gaussian", "mixture", "model", "(GMM)", "clustering." ]
def gmm(inp, initial_clusters, num_clusters, random_seed, covariance_type=FULL_COVARIANCE, params='wmc'): initial_means = None if initial_clusters != 'random' and (not isinstance(initial_clusters, ops.Tensor)): initial_means = constant_op.constant(initial_clusters, dtype=dtypes.float32) inp = inp if...
['def', 'gmm(inp,', 'initial_clusters,', 'num_clusters,', 'random_seed,', 'covariance_type=FULL_COVARIANCE,', "params='wmc'):", 'initial_means', '=', 'None', 'if', 'initial_clusters', '!=', "'random'", 'and', '(not', 'isinstance(initial_clusters,', 'ops.Tensor)):', 'initial_means', '=', 'constant_op.constant(initial_cl...
603,005
flow-project/flow
test_environments.py
TestBottleneckAccelEnv.test_additional_env_params
test_additional_env_params
Ensures that not returning the correct params leads to an error.
[ "Ensures", "that", "not", "returning", "the", "correct", "params", "leads", "to", "an", "error." ]
def test_additional_env_params(self): self.assertTrue(test_additional_params(env_class=BottleneckAccelEnv, sim_params=self.sim_params, network=self.network, additional_params={'max_accel': 3, 'max_decel': 3, 'lane_change_duration': 5, 'disable_tb': True, 'disable_ramp_metering': True, 'target_velocity': 30, 'add_rl...
['def', 'test_additional_env_params(self):', 'self.assertTrue(test_additional_params(env_class=BottleneckAccelEnv,', 'sim_params=self.sim_params,', 'network=self.network,', "additional_params={'max_accel':", '3,', "'max_decel':", '3,', "'lane_change_duration':", '5,', "'disable_tb':", 'True,', "'disable_ramp_metering':...
212,449
rudranil723/mini-main
backend_wx.py
GraphicsContextWx.unselect
unselect
Select a Null bitmap into this wxDC instance.
[ "Select", "a", "Null", "bitmap", "into", "this", "wxDC", "instance." ]
def unselect(self): if sys.platform == 'win32': self.dc.SelectObject(wx.NullBitmap) self.IsSelected = False
['def', 'unselect(self):', 'if', 'sys.platform', '==', "'win32':", 'self.dc.SelectObject(wx.NullBitmap)', 'self.IsSelected', '=', 'False']
320,054
apeterswu/RL4NMT
common_layers.py
shift_right_3d
shift_right_3d
Shift the second dimension of x right by one.
[ "Shift", "the", "second", "dimension", "of", "x", "right", "by", "one." ]
def shift_right_3d(x, pad_value=None): if pad_value is None: shifted_targets = tf.pad(x, [[0, 0], [1, 0], [0, 0]])[:, :-1, :] else: shifted_targets = tf.concat([pad_value, x], axis=1)[:, :-1, :] return shifted_targets
['def', 'shift_right_3d(x,', 'pad_value=None):', 'if', 'pad_value', 'is', 'None:', 'shifted_targets', '=', 'tf.pad(x,', '[[0,', '0],', '[1,', '0],', '[0,', '0]])[:,', ':-1,', ':]', 'else:', 'shifted_targets', '=', 'tf.concat([pad_value,', 'x],', 'axis=1)[:,', ':-1,', ':]', 'return', 'shifted_targets']
331,520
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
graph_builder_test.py
GraphBuilderTest.testTrainingWithLazyAdamAndNoAveraging
testTrainingWithLazyAdamAndNoAveraging
Adds code coverage for lazy ADAM without the use of moving averaging.
[ "Adds", "code", "coverage", "for", "lazy", "ADAM", "without", "the", "use", "of", "moving", "averaging." ]
def testTrainingWithLazyAdamAndNoAveraging(self): self.RunTraining(self.MakeHyperparams(learning_method='lazyadam', use_moving_average=False))
['def', 'testTrainingWithLazyAdamAndNoAveraging(self):', "self.RunTraining(self.MakeHyperparams(learning_method='lazyadam',", 'use_moving_average=False))']
28,340
pantelis/artificial-intelligence
test_polynomial.py
TestPolynomial.test_poly_int_overflow
test_poly_int_overflow
Regression test for gh-5096.
[ "Regression", "test", "for", "gh-5096." ]
def test_poly_int_overflow(self): v = np.arange(1, 21) assert_almost_equal(np.poly(v), np.poly(np.diag(v)))
['def', 'test_poly_int_overflow(self):', 'v', '=', 'np.arange(1,', '21)', 'assert_almost_equal(np.poly(v),', 'np.poly(np.diag(v)))']
170,602
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
core.py
contours_to_mask
contours_to_mask
Creates a binary mask for contours.
[ "Creates", "a", "binary", "mask", "for", "contours." ]
def contours_to_mask(contours, shape): canvas = np.zeros(shape, np.uint8) cv2.drawContours(canvas, contours, contourIdx=-1, color=1) return canvas
['def', 'contours_to_mask(contours,', 'shape):', 'canvas', '=', 'np.zeros(shape,', 'np.uint8)', 'cv2.drawContours(canvas,', 'contours,', 'contourIdx=-1,', 'color=1)', 'return', 'canvas']
12,035
myothida/Supervised-Machine-Learning
_compat.py
share_axis
share_axis
Handle changes to post-hoc axis sharing.
[ "Handle", "changes", "to", "post-hoc", "axis", "sharing." ]
def share_axis(ax0, ax1, which): if Version(mpl.__version__) < Version('3.5.0'): group = getattr(ax0, f'get_shared_{which}_axes')() group.join(ax1, ax0) else: getattr(ax1, f'share{which}')(ax0)
['def', 'share_axis(ax0,', 'ax1,', 'which):', 'if', 'Version(mpl.__version__)', '<', "Version('3.5.0'):", 'group', '=', 'getattr(ax0,', "f'get_shared_{which}_axes')()", 'group.join(ax1,', 'ax0)', 'else:', 'getattr(ax1,', "f'share{which}')(ax0)"]
446,734
AboudyKreidieh/h-baselines
envs.py
Environment.context_space
context_space
Return the shape and bounds of the contextual term.
[ "Return", "the", "shape", "and", "bounds", "of", "the", "contextual", "term." ]
def context_space(self): if self.use_contexts: if self.random_contexts: context_low = [] context_high = [] for context_i in self.context_range: (low, high) = context_i context_low.append(low) context_high.append(high) ...
['def', 'context_space(self):', 'if', 'self.use_contexts:', 'if', 'self.random_contexts:', 'context_low', '=', '[]', 'context_high', '=', '[]', 'for', 'context_i', 'in', 'self.context_range:', '(low,', 'high)', '=', 'context_i', 'context_low.append(low)', 'context_high.append(high)', 'return', 'Box(low=np.asarray(conte...
573,885
asiddhant/Active-NLP
utils.py
char_mapping
char_mapping
Create a dictionary and mapping of characters, sorted by frequency.
[ "Create", "a", "dictionary", "and", "mapping", "of", "characters,", "sorted", "by", "frequency." ]
def char_mapping(sentences): chars = [''.join([w[0] for w in s]) for s in sentences] dico = create_dico(chars) dico['<PAD>'] = 10000000 (char_to_id, id_to_char) = create_mapping(dico) print('Found %i unique characters' % len(dico)) return (dico, char_to_id, id_to_char)
['def', 'char_mapping(sentences):', 'chars', '=', "[''.join([w[0]", 'for', 'w', 'in', 's])', 'for', 's', 'in', 'sentences]', 'dico', '=', 'create_dico(chars)', "dico['<PAD>']", '=', '10000000', '(char_to_id,', 'id_to_char)', '=', 'create_mapping(dico)', "print('Found", '%i', 'unique', "characters'", '%', 'len(dico))', ...
39,726
intelligent-environments-lab/CityLearn
energy_model.py
StorageTank.max_input_power
max_input_power
Maximum amount of power that the storage unit can use to charge [kW].
[ "Maximum", "amount", "of", "power", "that", "the", "storage", "unit", "can", "use", "to", "charge", "[kW]." ]
def max_input_power(self) -> float: return self.__max_input_power
['def', 'max_input_power(self)', '->', 'float:', 'return', 'self.__max_input_power']
105,750
open-mmlab/mmdetection3d
data_preprocessor.py
Det3DDataPreprocessor.sparse_quantize
sparse_quantize
Sparse Quantization for voxel coordinates used in Minkunet.
[ "Sparse", "Quantization", "for", "voxel", "coordinates", "used", "in", "Minkunet." ]
def sparse_quantize(self, coords: np.ndarray, return_index: bool=False, return_inverse: bool=False) -> List[np.ndarray]: (_, indices, inverse_indices) = np.unique(self.ravel_hash(coords), return_index=True, return_inverse=True) coords = coords[indices] outputs = [] if return_index: outputs += [i...
['def', 'sparse_quantize(self,', 'coords:', 'np.ndarray,', 'return_index:', 'bool=False,', 'return_inverse:', 'bool=False)', '->', 'List[np.ndarray]:', '(_,', 'indices,', 'inverse_indices)', '=', 'np.unique(self.ravel_hash(coords),', 'return_index=True,', 'return_inverse=True)', 'coords', '=', 'coords[indices]', 'outpu...
631,844
googleinterns/wss
resnet_v1_beta.py
resnet_v1_small_beta_block
resnet_v1_small_beta_block
Helper function for creating a resnet_18 beta variant bottleneck block.
[ "Helper", "function", "for", "creating", "a", "resnet_18", "beta", "variant", "bottleneck", "block." ]
def resnet_v1_small_beta_block(scope, base_depth, num_units, stride): block_args = [] for _ in range(num_units - 1): block_args.append({'depth': base_depth, 'stride': 1, 'unit_rate': 1}) block_args.append({'depth': base_depth, 'stride': stride, 'unit_rate': 1}) return resnet_utils.Block(scope, l...
['def', 'resnet_v1_small_beta_block(scope,', 'base_depth,', 'num_units,', 'stride):', 'block_args', '=', '[]', 'for', '_', 'in', 'range(num_units', '-', '1):', "block_args.append({'depth':", 'base_depth,', "'stride':", '1,', "'unit_rate':", '1})', "block_args.append({'depth':", 'base_depth,', "'stride':", 'stride,', "'...
960,760
tensorflow/privacy
gdp_accountant.py
compute_eps_poisson
compute_eps_poisson
Compute epsilon given delta from inverse dual of Poisson subsampling.
[ "Compute", "epsilon", "given", "delta", "from", "inverse", "dual", "of", "Poisson", "subsampling." ]
def compute_eps_poisson(epoch, noise_multi, n, batch_size, delta): return eps_from_mu(compute_mu_poisson(epoch, noise_multi, n, batch_size), delta)
['def', 'compute_eps_poisson(epoch,', 'noise_multi,', 'n,', 'batch_size,', 'delta):', 'return', 'eps_from_mu(compute_mu_poisson(epoch,', 'noise_multi,', 'n,', 'batch_size),', 'delta)']
824,602
leonnnop/GMMSeg
class_names.py
isaid_palette
isaid_palette
iSAID palette for external use.
[ "iSAID", "palette", "for", "external", "use." ]
def isaid_palette(): return [[0, 0, 0], [0, 0, 63], [0, 63, 63], [0, 63, 0], [0, 63, 127], [0, 63, 191], [0, 63, 255], [0, 127, 63], [0, 127, 127], [0, 0, 127], [0, 0, 191], [0, 0, 255], [0, 191, 127], [0, 127, 191], [0, 127, 255], [0, 100, 155]]
['def', 'isaid_palette():', 'return', '[[0,', '0,', '0],', '[0,', '0,', '63],', '[0,', '63,', '63],', '[0,', '63,', '0],', '[0,', '63,', '127],', '[0,', '63,', '191],', '[0,', '63,', '255],', '[0,', '127,', '63],', '[0,', '127,', '127],', '[0,', '0,', '127],', '[0,', '0,', '191],', '[0,', '0,', '255],', '[0,', '191,', ...
578,342
weimin17/Object-Detection_HelmetDetection
digraph_ops.py
ValidArcAndTokenMasks
ValidArcAndTokenMasks
Returns 0/1 masks for valid arcs and tokens.
[ "Returns", "0/1", "masks", "for", "valid", "arcs", "and", "tokens." ]
def ValidArcAndTokenMasks(lengths, max_length, dtype=tf.float32): lengths_bx1 = tf.expand_dims(lengths, 1) sequence_m = tf.range(tf.cast(max_length, lengths.dtype.base_dtype)) sequence_1xm = tf.expand_dims(sequence_m, 0) valid_token_bxm = tf.cast(sequence_1xm < lengths_bx1, dtype) valid_arc_bxmxm = ...
['def', 'ValidArcAndTokenMasks(lengths,', 'max_length,', 'dtype=tf.float32):', 'lengths_bx1', '=', 'tf.expand_dims(lengths,', '1)', 'sequence_m', '=', 'tf.range(tf.cast(max_length,', 'lengths.dtype.base_dtype))', 'sequence_1xm', '=', 'tf.expand_dims(sequence_m,', '0)', 'valid_token_bxm', '=', 'tf.cast(sequence_1xm', '<...
753,284
PratikRamdasi/Computer-Vision
keras_darknet19.py
DarknetConv2D
DarknetConv2D
Wrapper to set Darknet weight regularizer for Convolution2D.
[ "Wrapper", "to", "set", "Darknet", "weight", "regularizer", "for", "Convolution2D." ]
def DarknetConv2D(*args, **kwargs): darknet_conv_kwargs = {'kernel_regularizer': l2(0.0005)} darknet_conv_kwargs.update(kwargs) return _DarknetConv2D(*args, **darknet_conv_kwargs)
['def', 'DarknetConv2D(*args,', '**kwargs):', 'darknet_conv_kwargs', '=', "{'kernel_regularizer':", 'l2(0.0005)}', 'darknet_conv_kwargs.update(kwargs)', 'return', '_DarknetConv2D(*args,', '**darknet_conv_kwargs)']
469,916
ViCCo-Group/thingsvision
helpers.py
parse_img_name
parse_img_name
Check whether image file has allowed extension.
[ "Check", "whether", "image", "file", "has", "allowed", "extension." ]
def parse_img_name(img_name: str) -> bool: return re.search(EXTENSIONS, img_name)
['def', 'parse_img_name(img_name:', 'str)', '->', 'bool:', 'return', 're.search(EXTENSIONS,', 'img_name)']
916,158
rishab-sharma/object_detection
train.py
add_model_training_inputs
add_model_training_inputs
Load the training dataset and attach the training inputs to the model.
[ "Load", "the", "training", "dataset", "and", "attach", "the", "training", "inputs", "to", "the", "model." ]
def add_model_training_inputs(model): logger = logging.getLogger(__name__) logger.info('Loading dataset: {}'.format(cfg.TRAIN.DATASETS)) roidb = combined_roidb_for_training(cfg.TRAIN.DATASETS, cfg.TRAIN.PROPOSAL_FILES) logger.info('{:d} roidb entries'.format(len(roidb))) model_builder.add_training_i...
['def', 'add_model_training_inputs(model):', 'logger', '=', 'logging.getLogger(__name__)', "logger.info('Loading", 'dataset:', "{}'.format(cfg.TRAIN.DATASETS))", 'roidb', '=', 'combined_roidb_for_training(cfg.TRAIN.DATASETS,', 'cfg.TRAIN.PROPOSAL_FILES)', "logger.info('{:d}", 'roidb', "entries'.format(len(roidb)))", 'm...
773,638
aeon-toolkit/aeon
test_k_shapes.py
test_kshapes
test_kshapes
Test implementation of Kshapes.
[ "Test", "implementation", "of", "Kshapes." ]
def test_kshapes(): max_train = 5 (X_train, y_train) = load_basic_motions(split='train') (X_test, y_test) = load_basic_motions(split='test') kshapes = TimeSeriesKShapes(random_state=1, n_clusters=3) kshapes.fit(X_train[0:max_train]) test_shape_result = kshapes.predict(X_test[0:max_train]) sc...
['def', 'test_kshapes():', 'max_train', '=', '5', '(X_train,', 'y_train)', '=', "load_basic_motions(split='train')", '(X_test,', 'y_test)', '=', "load_basic_motions(split='test')", 'kshapes', '=', 'TimeSeriesKShapes(random_state=1,', 'n_clusters=3)', 'kshapes.fit(X_train[0:max_train])', 'test_shape_result', '=', 'kshap...
399,345
enuguru/artificial_intelligence_and_machine_learning
test_helpers.py
StdStreamCapturingMixin.cleanup_std_streams
cleanup_std_streams
Restore stdout and stderr.
[ "Restore", "stdout", "and", "stderr." ]
def cleanup_std_streams(self): sys.stdout = self.old_stdout sys.stderr = self.old_stderr
['def', 'cleanup_std_streams(self):', 'sys.stdout', '=', 'self.old_stdout', 'sys.stderr', '=', 'self.old_stderr']
157,647
jiaxi-wu/MPSR
eval_instances.py
computeBoxIntersection
computeBoxIntersection
Compute intersection between GT instance and prediction.
[ "Compute", "intersection", "between", "GT", "instance", "and", "prediction." ]
def computeBoxIntersection(gt, pred): (xmin, ymin, xmax, ymax) = getIntersectionBox(gt['box'], pred['box']) intersection = (xmax - xmin) * (ymax - ymin) return intersection
['def', 'computeBoxIntersection(gt,', 'pred):', '(xmin,', 'ymin,', 'xmax,', 'ymax)', '=', "getIntersectionBox(gt['box'],", "pred['box'])", 'intersection', '=', '(xmax', '-', 'xmin)', '*', '(ymax', '-', 'ymin)', 'return', 'intersection']
657,013
yinyunie/ScenePriors
test_forward.py
TestForward.test_principal_point
test_principal_point
Test shifting the principal point.
[ "Test", "shifting", "the", "principal", "point." ]
def test_principal_point(self): from pytorch3d.renderer.points.pulsar import Renderer LOGGER.info('Setting up rendering test for shifted principal point...') n_points = 1 width = 1000 height = 1000 renderer = Renderer(width, height, n_points, n_channels=1) vert_pos = torch.tensor([[0.0, 0.0,...
['def', 'test_principal_point(self):', 'from', 'pytorch3d.renderer.points.pulsar', 'import', 'Renderer', "LOGGER.info('Setting", 'up', 'rendering', 'test', 'for', 'shifted', 'principal', "point...')", 'n_points', '=', '1', 'width', '=', '1000', 'height', '=', '1000', 'renderer', '=', 'Renderer(width,', 'height,', 'n_po...
330,222
NoGameNoLife00/mybolg
compiler.py
CodeGenerator.newline
newline
Add one or more newlines before the next write.
[ "Add", "one", "or", "more", "newlines", "before", "the", "next", "write." ]
def newline(self, node=None, extra=0): self._new_lines = max(self._new_lines, 1 + extra) if node is not None and node.lineno != self._last_line: self._write_debug_info = node.lineno self._last_line = node.lineno
['def', 'newline(self,', 'node=None,', 'extra=0):', 'self._new_lines', '=', 'max(self._new_lines,', '1', '+', 'extra)', 'if', 'node', 'is', 'not', 'None', 'and', 'node.lineno', '!=', 'self._last_line:', 'self._write_debug_info', '=', 'node.lineno', 'self._last_line', '=', 'node.lineno']
289,427
sony/nnabla-rl
replay_buffer.py
ReplayBuffer.sample_indices
sample_indices
Sample experiences for given indices from the replay buffer.
[ "Sample", "experiences", "for", "given", "indices", "from", "the", "replay", "buffer." ]
def sample_indices(self, indices: Sequence[int], num_steps: int=1) -> Tuple[Union[Sequence[Experience], Tuple[Sequence[Experience], ...]], Dict[str, Any]]: if len(indices) == 0: raise ValueError('Indices are empty') if num_steps < 1: raise ValueError(f'num_steps: {num_steps} should be greater th...
['def', 'sample_indices(self,', 'indices:', 'Sequence[int],', 'num_steps:', 'int=1)', '->', 'Tuple[Union[Sequence[Experience],', 'Tuple[Sequence[Experience],', '...]],', 'Dict[str,', 'Any]]:', 'if', 'len(indices)', '==', '0:', 'raise', "ValueError('Indices", 'are', "empty')", 'if', 'num_steps', '<', '1:', 'raise', "Val...
734,316
matsu0228/nlp-jp
runtime.py
Context.resolve_or_missing
resolve_or_missing
Resolves a variable like :meth:`resolve` but returns the special `missing` value if it cannot be found.
[ "Resolves", "a", "variable", "like", ":meth:`resolve`", "but", "returns", "the", "special", "`missing`", "value", "if", "it", "cannot", "be", "found." ]
def resolve_or_missing(self, key): if self._legacy_resolve_mode: rv = self.resolve(key) if isinstance(rv, Undefined): rv = missing return rv return resolve_or_missing(self, key)
['def', 'resolve_or_missing(self,', 'key):', 'if', 'self._legacy_resolve_mode:', 'rv', '=', 'self.resolve(key)', 'if', 'isinstance(rv,', 'Undefined):', 'rv', '=', 'missing', 'return', 'rv', 'return', 'resolve_or_missing(self,', 'key)']
787,946
Megvii-BaseDetection/DenseTeacher
runner.py
SemiRunner.run_step
run_step
Implement the standard training logic described above.
[ "Implement", "the", "standard", "training", "logic", "described", "above." ]
def run_step(self): assert self.model.training, '[IterRunner] model was changed to eval mode!' start = time.perf_counter() try: data = next(self._data_loader_iter) except StopIteration: self.epoch += 1 if hasattr(self.data_loader.sampler, 'set_epoch'): self.data_loade...
['def', 'run_step(self):', 'assert', 'self.model.training,', "'[IterRunner]", 'model', 'was', 'changed', 'to', 'eval', "mode!'", 'start', '=', 'time.perf_counter()', 'try:', 'data', '=', 'next(self._data_loader_iter)', 'except', 'StopIteration:', 'self.epoch', '+=', '1', 'if', 'hasattr(self.data_loader.sampler,', "'set...
538,085
NJU-LHRS/official-CMID
pretrain_model.py
MomentumUpdater.update_tau
update_tau
Computes the next value for the weighting decrease coefficient tau using cosine annealing.
[ "Computes", "the", "next", "value", "for", "the", "weighting", "decrease", "coefficient", "tau", "using", "cosine", "annealing." ]
def update_tau(self, cur_step: int, max_steps: int): self.cur_tau = self.final_tau - (self.final_tau - self.base_tau) * (math.cos(math.pi * cur_step / max_steps) + 1) / 2
['def', 'update_tau(self,', 'cur_step:', 'int,', 'max_steps:', 'int):', 'self.cur_tau', '=', 'self.final_tau', '-', '(self.final_tau', '-', 'self.base_tau)', '*', '(math.cos(math.pi', '*', 'cur_step', '/', 'max_steps)', '+', '1)', '/', '2']
250,205
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
vgslspecs_test.py
VgslspecsTest.testReshapeDepth
testReshapeDepth
Tests that depth can be reshaped to the x dimension.
[ "Tests", "that", "depth", "can", "be", "reshaped", "to", "the", "x", "dimension." ]
def testReshapeDepth(self): self.ExpectScaledSize('[Cl5,5,16 Mp3,3 (Lrys32 Lbys16 Lfys32) S3(3x0)2,3]', (self.batch_size, 1, self.max_width, 32))
['def', 'testReshapeDepth(self):', "self.ExpectScaledSize('[Cl5,5,16", 'Mp3,3', '(Lrys32', 'Lbys16', 'Lfys32)', "S3(3x0)2,3]',", '(self.batch_size,', '1,', 'self.max_width,', '32))']
27,784
deepmind/meltingpot
substrate_factory.py
SubstrateFactory.action_spec
action_spec
Returns spec of action expected from a single player.
[ "Returns", "spec", "of", "action", "expected", "from", "a", "single", "player." ]
def action_spec(self) -> dm_env.specs.DiscreteArray: return self._action_spec
['def', 'action_spec(self)', '->', 'dm_env.specs.DiscreteArray:', 'return', 'self._action_spec']
285,590
nicknochnack/RealTimeSignLanguageTFJS
utils.py
natural_sort
natural_sort
Sort the list into natural alphanumeric order.
[ "Sort", "the", "list", "into", "natural", "alphanumeric", "order." ]
def natural_sort(list, key=lambda s: s): def get_alphanum_key_func(key): convert = lambda text: int(text) if text.isdigit() else text return lambda s: [convert(c) for c in re.split('([0-9]+)', key(s))] sort_key = get_alphanum_key_func(key) list.sort(key=sort_key)
['def', 'natural_sort(list,', 'key=lambda', 's:', 's):', 'def', 'get_alphanum_key_func(key):', 'convert', '=', 'lambda', 'text:', 'int(text)', 'if', 'text.isdigit()', 'else', 'text', 'return', 'lambda', 's:', '[convert(c)', 'for', 'c', 'in', "re.split('([0-9]+)',", 'key(s))]', 'sort_key', '=', 'get_alphanum_key_func(ke...
850,168
boostcampaitech2/semantic-segmentation-level2-cv-07
autoassign_head.py
AutoAssignHead.get_pos_loss_single
get_pos_loss_single
Calculate the positive loss of all points in gt_bboxes.
[ "Calculate", "the", "positive", "loss", "of", "all", "points", "in", "gt_bboxes." ]
def get_pos_loss_single(self, cls_score, objectness, reg_loss, gt_labels, center_prior_weights): p_loc = torch.exp(-reg_loss) p_cls = (cls_score * objectness)[:, gt_labels] p_pos = p_cls * p_loc confidence_weight = torch.exp(p_pos * 3) p_pos_weight = confidence_weight * center_prior_weights / (confi...
['def', 'get_pos_loss_single(self,', 'cls_score,', 'objectness,', 'reg_loss,', 'gt_labels,', 'center_prior_weights):', 'p_loc', '=', 'torch.exp(-reg_loss)', 'p_cls', '=', '(cls_score', '*', 'objectness)[:,', 'gt_labels]', 'p_pos', '=', 'p_cls', '*', 'p_loc', 'confidence_weight', '=', 'torch.exp(p_pos', '*', '3)', 'p_po...
857,015
enuguru/artificial_intelligence_and_machine_
syntax.py
SyntaxNode.is_ws
is_ws
Returns True if this node is ignorable whitespace.
[ "Returns", "True", "if", "this", "node", "is", "ignorable", "whitespace." ]
def is_ws(self): return False
['def', 'is_ws(self):', 'return', 'False']
133,566