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
rifqind/Agent-Programs-3KS1
nbbase.py
new_text_cell
new_text_cell
Create a new text cell.
[ "Create", "a", "new", "text", "cell." ]
def new_text_cell(text=None): cell = NotebookNode() if text is not None: cell.text = unicode_type(text) cell.cell_type = u'text' return cell
['def', 'new_text_cell(text=None):', 'cell', '=', 'NotebookNode()', 'if', 'text', 'is', 'not', 'None:', 'cell.text', '=', 'unicode_type(text)', 'cell.cell_type', '=', "u'text'", 'return', 'cell']
42,932
Liwb5/ReinforcementLearning
PPO_HalfCheetah.py
PPOBuffer.store
store
Append one timestep of agent-environment interaction to the buffer.
[ "Append", "one", "timestep", "of", "agent-environment", "interaction", "to", "the", "buffer." ]
def store(self, obs, act, rew, val, logp): assert self.ptr < self.max_size i = self.ptr self.obs_buf[i] = obs self.act_buf[i] = act self.rew_buf[i] = rew self.val_buf[i] = val self.logp_buf[i] = logp self.ptr += 1
['def', 'store(self,', 'obs,', 'act,', 'rew,', 'val,', 'logp):', 'assert', 'self.ptr', '<', 'self.max_size', 'i', '=', 'self.ptr', 'self.obs_buf[i]', '=', 'obs', 'self.act_buf[i]', '=', 'act', 'self.rew_buf[i]', '=', 'rew', 'self.val_buf[i]', '=', 'val', 'self.logp_buf[i]', '=', 'logp', 'self.ptr', '+=', '1']
345,190
Ruturaj123/Flowchart-Detection
device.py
DeviceSpec.merge_from
merge_from
Merge the properties of "dev" into this `DeviceSpec`.
[ "Merge", "the", "properties", "of", "\"dev\"", "into", "this", "`DeviceSpec`." ]
def merge_from(self, dev): if dev.job is not None: self.job = dev.job if dev.replica is not None: self.replica = dev.replica if dev.task is not None: self.task = dev.task if dev.device_type is not None: self.device_type = dev.device_type if dev.device_index is not Non...
['def', 'merge_from(self,', 'dev):', 'if', 'dev.job', 'is', 'not', 'None:', 'self.job', '=', 'dev.job', 'if', 'dev.replica', 'is', 'not', 'None:', 'self.replica', '=', 'dev.replica', 'if', 'dev.task', 'is', 'not', 'None:', 'self.task', '=', 'dev.task', 'if', 'dev.device_type', 'is', 'not', 'None:', 'self.device_type', ...
605,322
atulkum/object_detection
label_map_util.py
load_labelmap
load_labelmap
Loads label map proto.
[ "Loads", "label", "map", "proto." ]
def load_labelmap(path): with tf.gfile.GFile(path, 'r') as fid: label_map_string = fid.read() label_map = string_int_label_map_pb2.StringIntLabelMap() try: text_format.Merge(label_map_string, label_map) except text_format.ParseError: label_map.ParseFromString(...
['def', 'load_labelmap(path):', 'with', 'tf.gfile.GFile(path,', "'r')", 'as', 'fid:', 'label_map_string', '=', 'fid.read()', 'label_map', '=', 'string_int_label_map_pb2.StringIntLabelMap()', 'try:', 'text_format.Merge(label_map_string,', 'label_map)', 'except', 'text_format.ParseError:', 'label_map.ParseFromString(labe...
793,040
audioku/meta-transfer-learning
args.py
train_kwargs
train_kwargs
Build kwargs for the train() function from the parsed command-line arguments.
[ "Build", "kwargs", "for", "the", "train()", "function", "from", "the", "parsed", "command-line", "arguments." ]
def train_kwargs(parsed_args): return {'num_classes': parsed_args.classes, 'num_shots': parsed_args.shots, 'train_shots': parsed_args.train_shots or None, 'inner_batch_size': parsed_args.inner_batch, 'inner_iters': parsed_args.inner_iters, 'replacement': parsed_args.replacement, 'meta_step_size': parsed_args.meta_s...
['def', 'train_kwargs(parsed_args):', 'return', "{'num_classes':", 'parsed_args.classes,', "'num_shots':", 'parsed_args.shots,', "'train_shots':", 'parsed_args.train_shots', 'or', 'None,', "'inner_batch_size':", 'parsed_args.inner_batch,', "'inner_iters':", 'parsed_args.inner_iters,', "'replacement':", 'parsed_args.rep...
633,367
neokarn/computer_vision
visualization_utils_test.py
VisualizationUtilsTest.test_draw_bounding_boxes_on_image_tensors_grayscale
test_draw_bounding_boxes_on_image_tensors_grayscale
Tests the case where input image tensor has one channel.
[ "Tests", "the", "case", "where", "input", "image", "tensor", "has", "one", "channel." ]
def test_draw_bounding_boxes_on_image_tensors_grayscale(self): category_index = {1: {'id': 1, 'name': 'dog'}} image_np = self.create_test_grayscale_image() images_np = np.stack((image_np, image_np), axis=0) with tf.Graph().as_default(): images_tensor = tf.constant(value=images_np, dtype=tf.uint8...
['def', 'test_draw_bounding_boxes_on_image_tensors_grayscale(self):', 'category_index', '=', '{1:', "{'id':", '1,', "'name':", "'dog'}}", 'image_np', '=', 'self.create_test_grayscale_image()', 'images_np', '=', 'np.stack((image_np,', 'image_np),', 'axis=0)', 'with', 'tf.Graph().as_default():', 'images_tensor', '=', 'tf...
514,118
karoly-hars/GAN_image_colorizing
helpers.py
save_test_sample
save_test_sample
Create a grid of ground truth, grayscale and 2 colorized images (from different sources) and save + display it to the user.
[ "Create", "a", "grid", "of", "ground", "truth,", "grayscale", "and", "2", "colorized", "images", "(from", "different", "sources)", "and", "save", "+", "display", "it", "to", "the", "user." ]
def save_test_sample(real_imgs_lab, fake_imgs_lab1, fake_imgs_lab2, save_path, plot_size=14, scale=1.6, show=False): batch_size = real_imgs_lab.size()[0] plot_size = min(plot_size, batch_size) canvas = np.ones((plot_size * 32 + (plot_size + 1) * 6, 4 * 32 + 5 * 8, 3), dtype=np.uint8) * 255 real_imgs_lab...
['def', 'save_test_sample(real_imgs_lab,', 'fake_imgs_lab1,', 'fake_imgs_lab2,', 'save_path,', 'plot_size=14,', 'scale=1.6,', 'show=False):', 'batch_size', '=', 'real_imgs_lab.size()[0]', 'plot_size', '=', 'min(plot_size,', 'batch_size)', 'canvas', '=', 'np.ones((plot_size', '*', '32', '+', '(plot_size', '+', '1)', '*'...
566,973
google-research/rigl
tf_sparse_utils.py
wrap_layer
wrap_layer
Wraps a keras layer to be used by sparse training.
[ "Wraps", "a", "keras", "layer", "to", "be", "used", "by", "sparse", "training." ]
def wrap_layer(layer, mode='constant', initial_sparsity=0.0, final_sparsity=0.9, begin_step=200000, end_step=600000, frequency=10000): if mode == 'constant': schedule = pruning_schedule.ConstantSparsity(target_sparsity=0, begin_step=1000000000) elif mode == 'prune': logging.info('Pruning schedul...
['def', 'wrap_layer(layer,', "mode='constant',", 'initial_sparsity=0.0,', 'final_sparsity=0.9,', 'begin_step=200000,', 'end_step=600000,', 'frequency=10000):', 'if', 'mode', '==', "'constant':", 'schedule', '=', 'pruning_schedule.ConstantSparsity(target_sparsity=0,', 'begin_step=1000000000)', 'elif', 'mode', '==', "'pr...
841,656
Kvatsx/Artificial-Intelligence-Assignments
tree.py
Scope.iter_funcdefs
iter_funcdefs
Returns a generator of `funcdef` nodes.
[ "Returns", "a", "generator", "of", "`funcdef`", "nodes." ]
def iter_funcdefs(self): return self._search_in_scope('funcdef')
['def', 'iter_funcdefs(self):', 'return', "self._search_in_scope('funcdef')"]
74,473
ratschlab/dpsom
somvae_model.py
SOMVAE.loss
loss
Aggregates the loss terms into the total loss.
[ "Aggregates", "the", "loss", "terms", "into", "the", "total", "loss." ]
def loss(self): loss = self.loss_reconstruction + self.alpha * self.loss_commit + self.beta * self.loss_som + self.gamma * self.loss_probabilities + self.tau * self.loss_z_prob tf.summary.scalar('loss', loss) return loss
['def', 'loss(self):', 'loss', '=', 'self.loss_reconstruction', '+', 'self.alpha', '*', 'self.loss_commit', '+', 'self.beta', '*', 'self.loss_som', '+', 'self.gamma', '*', 'self.loss_probabilities', '+', 'self.tau', '*', 'self.loss_z_prob', "tf.summary.scalar('loss',", 'loss)', 'return', 'loss']
167,027
intel/neural-compressor
tuning_structs.py
OpTuningConfig.from_state
from_state
Create the tuning config from dict.
[ "Create", "the", "tuning", "config", "from", "dict." ]
def from_state(cls, config: Dict): cls(**config)
['def', 'from_state(cls,', 'config:', 'Dict):', 'cls(**config)']
738,777
accel-brain/accel-brain-code
annealing_model.py
AnnealingModel.fit_dist_mat
fit_dist_mat
Fit ovserved data points.
[ "Fit", "ovserved", "data", "points." ]
def fit_dist_mat(self, dist_mat_arr): warnings.warn('This property will be removed in future version. Use `var_arr`.', FutureWarning) self.var_arr = dist_mat_arr
['def', 'fit_dist_mat(self,', 'dist_mat_arr):', "warnings.warn('This", 'property', 'will', 'be', 'removed', 'in', 'future', 'version.', 'Use', "`var_arr`.',", 'FutureWarning)', 'self.var_arr', '=', 'dist_mat_arr']
7,243
asyml/texar
data_iterators.py
TrainTestFeedableDataIterator.restart_val_dataset
restart_val_dataset
Restarts the validation dataset so that next iteration will fetch data from the beginning of the validation dataset.
[ "Restarts", "the", "validation", "dataset", "so", "that", "next", "iteration", "will", "fetch", "data", "from", "the", "beginning", "of", "the", "validation", "dataset." ]
def restart_val_dataset(self, sess): if self._val_name not in self._datasets: raise ValueError('Val data not provided.') self.restart_dataset(sess, self._val_name)
['def', 'restart_val_dataset(self,', 'sess):', 'if', 'self._val_name', 'not', 'in', 'self._datasets:', 'raise', "ValueError('Val", 'data', 'not', "provided.')", 'self.restart_dataset(sess,', 'self._val_name)']
924,531
AiIsBetter/computer_vision
model_lib_test.py
ModelLibTest.test_model_fn_in_train_mode_freeze_box_predictor
test_model_fn_in_train_mode_freeze_box_predictor
Tests model_fn TRAIN mode with FeatureExtractor variables frozen.
[ "Tests", "model_fn", "TRAIN", "mode", "with", "FeatureExtractor", "variables", "frozen." ]
def test_model_fn_in_train_mode_freeze_box_predictor(self): configs = _get_configs_for_model(MODEL_NAME_FOR_TEST) train_config = configs['train_config'] train_config.update_trainable_variables.append('FeatureExtractor') train_config.update_trainable_variables.append('BoxPredictor') train_config.free...
['def', 'test_model_fn_in_train_mode_freeze_box_predictor(self):', 'configs', '=', '_get_configs_for_model(MODEL_NAME_FOR_TEST)', 'train_config', '=', "configs['train_config']", "train_config.update_trainable_variables.append('FeatureExtractor')", "train_config.update_trainable_variables.append('BoxPredictor')", "train...
503,779
Ds-Kang/NaturalLanguageProcessing
searchPatterns.py
ExtractPhrases
ExtractPhrases
Método que compara recursivamente em cada sub-árvore da árvore(myTree) dada o padrão(phrase) requerido e retorna a lista de frases nas quais este se faz presente.
[ "Método", "que", "compara", "recursivamente", "em", "cada", "sub-árvore", "da", "árvore(myTree)", "dada", "o", "padrão(phrase)", "requerido", "e", "retorna", "a", "lista", "de", "frases", "nas", "quais", "este", "se", "faz", "presente." ]
def ExtractPhrases(myTree, phrase): myPhrases = [] if myTree.label() == phrase: treeTmp = myTree.copy(True) word = '' for w in treeTmp.leaves(): if len(word) == 0: word = w[0] else: word = word + ' ' + w[0] myPhrases.append(...
['def', 'ExtractPhrases(myTree,', 'phrase):', 'myPhrases', '=', '[]', 'if', 'myTree.label()', '==', 'phrase:', 'treeTmp', '=', 'myTree.copy(True)', 'word', '=', "''", 'for', 'w', 'in', 'treeTmp.leaves():', 'if', 'len(word)', '==', '0:', 'word', '=', 'w[0]', 'else:', 'word', '=', 'word', '+', "'", "'", '+', 'w[0]', 'myP...
675,049
TJU-DRL-LAB/AI-Optimizer
conv_ha.py
decoder
decoder
Compute the data distribution of an observation from its state.
[ "Compute", "the", "data", "distribution", "of", "an", "observation", "from", "its", "state." ]
def decoder(state, data_shape): kwargs = dict(strides=2, activation=tf.nn.relu) hidden = tf.layers.dense(state, 1024, None) hidden = tf.reshape(hidden, [-1, 1, 1, hidden.shape[-1].value]) hidden = tf.layers.conv2d_transpose(hidden, 128, 5, **kwargs) hidden = tf.layers.conv2d_transpose(hidden, 64, 5,...
['def', 'decoder(state,', 'data_shape):', 'kwargs', '=', 'dict(strides=2,', 'activation=tf.nn.relu)', 'hidden', '=', 'tf.layers.dense(state,', '1024,', 'None)', 'hidden', '=', 'tf.reshape(hidden,', '[-1,', '1,', '1,', 'hidden.shape[-1].value])', 'hidden', '=', 'tf.layers.conv2d_transpose(hidden,', '128,', '5,', '**kwar...
70,334
Samjith888/Keras-retinanet-Training-on-custom-datasets-for---
generator.py
Generator.has_label
has_label
Returns True if label is a known label.
[ "Returns", "True", "if", "label", "is", "a", "known", "label." ]
def has_label(self, label): raise NotImplementedError('has_label method not implemented')
['def', 'has_label(self,', 'label):', 'raise', "NotImplementedError('has_label", 'method', 'not', "implemented')"]
595,907
flavioschneider/rl-transfer-
test_tanh_gaussian_mlp_policy.py
TestTanhGaussianMLPPolicy.test_get_action
test_get_action
Test Tanh Gaussian Policy get action function.
[ "Test", "Tanh", "Gaussian", "Policy", "get", "action", "function." ]
def test_get_action(self, hidden_sizes): env_spec = GymEnv(DummyBoxEnv()) obs_dim = env_spec.observation_space.flat_dim act_dim = env_spec.action_space.flat_dim obs = torch.ones(obs_dim, dtype=torch.float32).unsqueeze(0) init_std = 2.0 policy = TanhGaussianMLPPolicy(env_spec=env_spec, hidden_siz...
['def', 'test_get_action(self,', 'hidden_sizes):', 'env_spec', '=', 'GymEnv(DummyBoxEnv())', 'obs_dim', '=', 'env_spec.observation_space.flat_dim', 'act_dim', '=', 'env_spec.action_space.flat_dim', 'obs', '=', 'torch.ones(obs_dim,', 'dtype=torch.float32).unsqueeze(0)', 'init_std', '=', '2.0', 'policy', '=', 'TanhGaussi...
861,876
myothida/Supervised-Machine-Learning
fontBuilder.py
FontBuilder.setupAvar
setupAvar
Adds an axis variations table to the font.
[ "Adds", "an", "axis", "variations", "table", "to", "the", "font." ]
def setupAvar(self, axes): from .varLib import _add_avar _add_avar(self.font, OrderedDict(enumerate(axes)))
['def', 'setupAvar(self,', 'axes):', 'from', '.varLib', 'import', '_add_avar', '_add_avar(self.font,', 'OrderedDict(enumerate(axes)))']
360,723
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
preprocessing.py
scale_up_augmentation
scale_up_augmentation
Scales an image randomly >100% up to some max scale.
[ "Scales", "an", "image", "randomly", ">100%", "up", "to", "some", "max", "scale." ]
def scale_up_augmentation(image, max_scale): (image, original_central_bbox) = pad_to_max(image, max_scale) aug_max = 1.0 aug_min = 1.0 / max_scale area_range = (aug_min, aug_max) min_object_covered = 1.0 image = scale_augment_crop(image, original_central_bbox, area_range, min_object_covered) ...
['def', 'scale_up_augmentation(image,', 'max_scale):', '(image,', 'original_central_bbox)', '=', 'pad_to_max(image,', 'max_scale)', 'aug_max', '=', '1.0', 'aug_min', '=', '1.0', '/', 'max_scale', 'area_range', '=', '(aug_min,', 'aug_max)', 'min_object_covered', '=', '1.0', 'image', '=', 'scale_augment_crop(image,', 'or...
112,261
dbash/zerowaste
post_processing.py
merge_semantic_and_instance
merge_semantic_and_instance
Post-processing for panoptic segmentation, by merging semantic segmentation label and class agnostic instance segmentation label.
[ "Post-processing", "for", "panoptic", "segmentation,", "by", "merging", "semantic", "segmentation", "label", "and", "class", "agnostic", "instance", "segmentation", "label." ]
def merge_semantic_and_instance(sem_seg, ins_seg, semantic_thing_seg, label_divisor, thing_ids, stuff_area, void_label): pan_seg = torch.zeros_like(sem_seg) + void_label is_thing = (ins_seg > 0) & (semantic_thing_seg > 0) class_id_tracker = Counter() instance_ids = torch.unique(ins_seg) for ins_id i...
['def', 'merge_semantic_and_instance(sem_seg,', 'ins_seg,', 'semantic_thing_seg,', 'label_divisor,', 'thing_ids,', 'stuff_area,', 'void_label):', 'pan_seg', '=', 'torch.zeros_like(sem_seg)', '+', 'void_label', 'is_thing', '=', '(ins_seg', '>', '0)', '&', '(semantic_thing_seg', '>', '0)', 'class_id_tracker', '=', 'Count...
971,711
google/deepvariant
debruijn_graph_wrap_test.py
DeBruijnGraphWrapTest.test_adding_edges_with_bad_positions
test_adding_edges_with_bad_positions
Test that we filter out edges containing low-quality basecalls.
[ "Test", "that", "we", "filter", "out", "edges", "containing", "low-quality", "basecalls." ]
def test_adding_edges_with_bad_positions(self, bad_position, dropped_edges): ref_str = 'GATTACA' read_str = 'GATTACA' kmer_indices = {'GA': 0, 'AT': 1, 'TT': 2, 'TA': 3, 'AC': 4, 'CA': 5} def kmer_to_index_edge(kmer_edge): (k1, k2) = kmer_edge.split('->') return '{}->{}'.format(kmer_ind...
['def', 'test_adding_edges_with_bad_positions(self,', 'bad_position,', 'dropped_edges):', 'ref_str', '=', "'GATTACA'", 'read_str', '=', "'GATTACA'", 'kmer_indices', '=', "{'GA':", '0,', "'AT':", '1,', "'TT':", '2,', "'TA':", '3,', "'AC':", '4,', "'CA':", '5}', 'def', 'kmer_to_index_edge(kmer_edge):', '(k1,', 'k2)', '='...
540,499
aisingapore/PeekingDuck
test_create_node.py
TestCliCreateNode.test_invalid_cli_options
test_invalid_cli_options
Tests cases when at least one `node_` related option is used with `config_path` and when all three `node_` related options are used with `config_path`.
[ "Tests", "cases", "when", "at", "least", "one", "`node_`", "related", "option", "is", "used", "with", "`config_path`", "and", "when", "all", "three", "`node_`", "related", "options", "are", "used", "with", "`config_path`." ]
def test_invalid_cli_options(self, extra_options): extra_args = [[f'--{option}', 'value'] for option in extra_options] with pytest.raises(ValueError) as excinfo: CliRunner().invoke(cli, ['create-node', '--config_path', 'value'] + [arg for arg_pair in extra_args for arg in arg_pair], catch_exceptions=Fal...
['def', 'test_invalid_cli_options(self,', 'extra_options):', 'extra_args', '=', "[[f'--{option}',", "'value']", 'for', 'option', 'in', 'extra_options]', 'with', 'pytest.raises(ValueError)', 'as', 'excinfo:', 'CliRunner().invoke(cli,', "['create-node',", "'--config_path',", "'value']", '+', '[arg', 'for', 'arg_pair', 'i...
767,195
intel/neural-compressor
client.py
run_query_task_result
run_query_task_result
Query task result according to id.
[ "Query", "task", "result", "according", "to", "id." ]
def run_query_task_result(args): task_id = args.task_id port = str(config.grpc_api_port) channel = grpc.insecure_channel('localhost:' + port) stub = neural_solution_pb2_grpc.TaskServiceStub(channel) request = neural_solution_pb2.TaskId(task_id=task_id) response = stub.QueryTaskResult(request) ...
['def', 'run_query_task_result(args):', 'task_id', '=', 'args.task_id', 'port', '=', 'str(config.grpc_api_port)', 'channel', '=', "grpc.insecure_channel('localhost:'", '+', 'port)', 'stub', '=', 'neural_solution_pb2_grpc.TaskServiceStub(channel)', 'request', '=', 'neural_solution_pb2.TaskId(task_id=task_id)', 'response...
721,839
Ruturaj123/Flowchart-Detection
dnn_test.py
DNNRegressorTest.testCustomMetrics
testCustomMetrics
Tests custom evaluation metrics.
[ "Tests", "custom", "evaluation", "metrics." ]
def testCustomMetrics(self): def _input_fn(num_epochs=None): labels = constant_op.constant([[1.0], [0.0], [0.0], [0.0]]) features = {'x': input_lib.limit_epochs(array_ops.ones(shape=[4, 1], dtype=dtypes.float32), num_epochs=num_epochs)} return (features, labels) def _my_metric_op(predi...
['def', 'testCustomMetrics(self):', 'def', '_input_fn(num_epochs=None):', 'labels', '=', 'constant_op.constant([[1.0],', '[0.0],', '[0.0],', '[0.0]])', 'features', '=', "{'x':", 'input_lib.limit_epochs(array_ops.ones(shape=[4,', '1],', 'dtype=dtypes.float32),', 'num_epochs=num_epochs)}', 'return', '(features,', 'labels...
603,957
matsu0228/nlp-jp
connection.py
MWSConnection.get_feed_submission_list_by_next_token
get_feed_submission_list_by_next_token
Returns a list of feed submissions using the NextToken parameter.
[ "Returns", "a", "list", "of", "feed", "submissions", "using", "the", "NextToken", "parameter." ]
def get_feed_submission_list_by_next_token(self, request, response, **kw): return self._post_request(request, kw, response)
['def', 'get_feed_submission_list_by_next_token(self,', 'request,', 'response,', '**kw):', 'return', 'self._post_request(request,', 'kw,', 'response)']
784,926
ZhAnGToNG1/transfer_learning_cspt
coco_panoptic.py
CocoPanopticDataset.get_ann_info
get_ann_info
Get COCO annotation by index.
[ "Get", "COCO", "annotation", "by", "index." ]
def get_ann_info(self, idx): img_id = self.data_infos[idx]['id'] ann_ids = self.coco.get_ann_ids(img_ids=[img_id]) ann_info = self.coco.load_anns(ann_ids) ann_info = [i for i in ann_info if i['image_id'] == img_id] return self._parse_ann_info(self.data_infos[idx], ann_info)
['def', 'get_ann_info(self,', 'idx):', 'img_id', '=', "self.data_infos[idx]['id']", 'ann_ids', '=', 'self.coco.get_ann_ids(img_ids=[img_id])', 'ann_info', '=', 'self.coco.load_anns(ann_ids)', 'ann_info', '=', '[i', 'for', 'i', 'in', 'ann_info', 'if', "i['image_id']", '==', 'img_id]', 'return', 'self._parse_ann_info(sel...
963,819
OPEN-AIR-SUN/Viewpoint-Bottleneck
common.py
convert_region_type
convert_region_type
Convert the integer region_type to the corresponding RegionType enum object.
[ "Convert", "the", "integer", "region_type", "to", "the", "corresponding", "RegionType", "enum", "object." ]
def convert_region_type(region_type): return int_to_region_type[region_type]
['def', 'convert_region_type(region_type):', 'return', 'int_to_region_type[region_type]']
380,098
cheind/gcsl
mock_dynamixel_sdk.py
MockDynamixelSdk.GroupSyncWrite
GroupSyncWrite
Returns a mock sync write operation.
[ "Returns", "a", "mock", "sync", "write", "operation." ]
def GroupSyncWrite(self, port_handler, unused_packet_handler, address: int, size: int): op = mock.Mock(spec=[]) op.params = set() device = port_handler.device def addParam(motor_id: int, value: bytes): if motor_id not in device or motor_id in op.params: return False if len(v...
['def', 'GroupSyncWrite(self,', 'port_handler,', 'unused_packet_handler,', 'address:', 'int,', 'size:', 'int):', 'op', '=', 'mock.Mock(spec=[])', 'op.params', '=', 'set()', 'device', '=', 'port_handler.device', 'def', 'addParam(motor_id:', 'int,', 'value:', 'bytes):', 'if', 'motor_id', 'not', 'in', 'device', 'or', 'mot...
202,148
BillZito/transfer-learning
pytorch_image_anomaly_detection_model.py
PyTorchImageAnomalyDetectionModel.train_simsiam
train_simsiam
Trains a SimSiam model using the specified dataset.
[ "Trains", "a", "SimSiam", "model", "using", "the", "specified", "dataset." ]
def train_simsiam(self, dataset, output_dir, epochs, feature_dim, pred_dim, batch_size=64, initial_checkpoints=None, generate_checkpoints=False, precision='float32'): self.LR = 0.171842137353148 self.batch_size = batch_size self.batch_size_ss = 64 self.epochs = epochs self.simsiam = True dataset...
['def', 'train_simsiam(self,', 'dataset,', 'output_dir,', 'epochs,', 'feature_dim,', 'pred_dim,', 'batch_size=64,', 'initial_checkpoints=None,', 'generate_checkpoints=False,', "precision='float32'):", 'self.LR', '=', '0.171842137353148', 'self.batch_size', '=', 'batch_size', 'self.batch_size_ss', '=', '64', 'self.epoch...
928,230
googleapis/python-aiplatform
test_language_models.py
TestLanguageModels.test_tune_text_generation_model_ga
test_tune_text_generation_model_ga
Tests tuning the text generation model.
[ "Tests", "tuning", "the", "text", "generation", "model." ]
def test_tune_text_generation_model_ga(self, mock_pipeline_service_create, mock_pipeline_job_get, mock_pipeline_bucket_exists, job_spec, mock_load_yaml_and_json, mock_gcs_from_string, mock_gcs_upload, mock_request_urlopen, mock_get_tuned_model): aiplatform.init(project=_TEST_PROJECT, location=_TEST_LOCATION, encryp...
['def', 'test_tune_text_generation_model_ga(self,', 'mock_pipeline_service_create,', 'mock_pipeline_job_get,', 'mock_pipeline_bucket_exists,', 'job_spec,', 'mock_load_yaml_and_json,', 'mock_gcs_from_string,', 'mock_gcs_upload,', 'mock_request_urlopen,', 'mock_get_tuned_model):', 'aiplatform.init(project=_TEST_PROJECT,'...
863,027
BMIRDS/deepslide
utils_model.py
parse_val_acc
parse_val_acc
Parse the validation accuracy from the filename.
[ "Parse", "the", "validation", "accuracy", "from", "the", "filename." ]
def parse_val_acc(model_path: Path) -> float: return float(f"{'.'.join(model_path.name.split('.')[:-1]).split('_')[-1][2:]}")
['def', 'parse_val_acc(model_path:', 'Path)', '->', 'float:', 'return', 'float(f"{\'.\'.join(model_path.name.split(\'.\')[:-1]).split(\'_\')[-1][2:]}")']
539,814
marlbenchmark/off-policy
StarCraft2_Env.py
StarCraft2Env.get_obs_size
get_obs_size
Returns the size of the observation.
[ "Returns", "the", "size", "of", "the", "observation." ]
def get_obs_size(self): own_feats = self.get_obs_own_feats_size() move_feats = self.get_obs_move_feats_size() (n_enemies, n_enemy_feats) = self.get_obs_enemy_feats_size() (n_allies, n_ally_feats) = self.get_obs_ally_feats_size() enemy_feats = n_enemies * n_enemy_feats ally_feats = n_allies * n_a...
['def', 'get_obs_size(self):', 'own_feats', '=', 'self.get_obs_own_feats_size()', 'move_feats', '=', 'self.get_obs_move_feats_size()', '(n_enemies,', 'n_enemy_feats)', '=', 'self.get_obs_enemy_feats_size()', '(n_allies,', 'n_ally_feats)', '=', 'self.get_obs_ally_feats_size()', 'enemy_feats', '=', 'n_enemies', '*', 'n_e...
755,490
bislara/Object-detection-GUI
box_coder_builder.py
build
build
Builds a box coder object based on the box coder config.
[ "Builds", "a", "box", "coder", "object", "based", "on", "the", "box", "coder", "config." ]
def build(box_coder_config): if not isinstance(box_coder_config, box_coder_pb2.BoxCoder): raise ValueError('box_coder_config not of type box_coder_pb2.BoxCoder.') if box_coder_config.WhichOneof('box_coder_oneof') == 'faster_rcnn_box_coder': return faster_rcnn_box_coder.FasterRcnnBoxCoder(scale_f...
['def', 'build(box_coder_config):', 'if', 'not', 'isinstance(box_coder_config,', 'box_coder_pb2.BoxCoder):', 'raise', "ValueError('box_coder_config", 'not', 'of', 'type', "box_coder_pb2.BoxCoder.')", 'if', "box_coder_config.WhichOneof('box_coder_oneof')", '==', "'faster_rcnn_box_coder':", 'return', 'faster_rcnn_box_cod...
726,359
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
train_eval.py
AdversarialCrypto.get_message_and_key
get_message_and_key
Generate random pseudo-boolean key and message values.
[ "Generate", "random", "pseudo-boolean", "key", "and", "message", "values." ]
def get_message_and_key(self): batch_size = tf.placeholder_with_default(FLAGS.batch_size, shape=[]) in_m = batch_of_random_bools(batch_size, TEXT_SIZE) in_k = batch_of_random_bools(batch_size, KEY_SIZE) return (in_m, in_k)
['def', 'get_message_and_key(self):', 'batch_size', '=', 'tf.placeholder_with_default(FLAGS.batch_size,', 'shape=[])', 'in_m', '=', 'batch_of_random_bools(batch_size,', 'TEXT_SIZE)', 'in_k', '=', 'batch_of_random_bools(batch_size,', 'KEY_SIZE)', 'return', '(in_m,', 'in_k)']
14,131
danamyu/hedgehog_detector
preprocessing_factory.py
get_preprocessing
get_preprocessing
Returns preprocessing_fn(image, height, width, **kwargs).
[ "Returns", "preprocessing_fn(image,", "height,", "width,", "**kwargs)." ]
def get_preprocessing(name, is_training=False): preprocessing_fn_map = {'cifarnet': cifarnet_preprocessing, 'inception': inception_preprocessing, 'inception_v1': inception_preprocessing, 'inception_v2': inception_preprocessing, 'inception_v3': inception_preprocessing, 'inception_v4': inception_preprocessing, 'incep...
['def', 'get_preprocessing(name,', 'is_training=False):', 'preprocessing_fn_map', '=', "{'cifarnet':", 'cifarnet_preprocessing,', "'inception':", 'inception_preprocessing,', "'inception_v1':", 'inception_preprocessing,', "'inception_v2':", 'inception_preprocessing,', "'inception_v3':", 'inception_preprocessing,', "'inc...
590,471
YanWei123/Deep-AutoEncoder-based-Lossy-Geometry-Compression-for-Point-Clouds
signal_conv_test.py
SignalTest.test_3d_valid_spatial
test_3d_valid_spatial
Test 3D valid convolutions with different supports/strides.
[ "Test", "3D", "valid", "convolutions", "with", "different", "supports/strides." ]
def test_3d_valid_spatial(self): batch = 1 padding = 'valid' channels = 1 filters = 1 channel_separable = False activation = None use_bias = False for input_support in [(8, 7, 3), (5, 6, 4)]: for kernel_support in [(1, 2, 3), (2, 1, 2), (3, 3, 3)]: for corr in [False,...
['def', 'test_3d_valid_spatial(self):', 'batch', '=', '1', 'padding', '=', "'valid'", 'channels', '=', '1', 'filters', '=', '1', 'channel_separable', '=', 'False', 'activation', '=', 'None', 'use_bias', '=', 'False', 'for', 'input_support', 'in', '[(8,', '7,', '3),', '(5,', '6,', '4)]:', 'for', 'kernel_support', 'in', ...
516,888
kujason/avod
evaluator_utils.py
save_predictions_in_kitti_format
save_predictions_in_kitti_format
Converts a set of network predictions into text files required for KITTI evaluation.
[ "Converts", "a", "set", "of", "network", "predictions", "into", "text", "files", "required", "for", "KITTI", "evaluation." ]
def save_predictions_in_kitti_format(model, checkpoint_name, data_split, score_threshold, global_step): dataset = model.dataset score_threshold = round(score_threshold, 3) predictions_root_dir = avod.root_dir() + '/data/outputs/' + checkpoint_name + '/predictions' final_predictions_root_dir = prediction...
['def', 'save_predictions_in_kitti_format(model,', 'checkpoint_name,', 'data_split,', 'score_threshold,', 'global_step):', 'dataset', '=', 'model.dataset', 'score_threshold', '=', 'round(score_threshold,', '3)', 'predictions_root_dir', '=', 'avod.root_dir()', '+', "'/data/outputs/'", '+', 'checkpoint_name', '+', "'/pre...
420,746
piggyandy/artificial-intelligence
core.py
doc_note
doc_note
Adds a Notes section to an existing docstring.
[ "Adds", "a", "Notes", "section", "to", "an", "existing", "docstring." ]
def doc_note(initialdoc, note): if initialdoc is None: return if note is None: return initialdoc notesplit = re.split('\\n\\s*?Notes\\n\\s*?-----', initialdoc) notedoc = 'Notes\n -----\n %s' % note if len(notesplit) > 1: notedoc = '\n\n ' + notedoc + '\n' return ...
['def', 'doc_note(initialdoc,', 'note):', 'if', 'initialdoc', 'is', 'None:', 'return', 'if', 'note', 'is', 'None:', 'return', 'initialdoc', 'notesplit', '=', "re.split('\\\\n\\\\s*?Notes\\\\n\\\\s*?-----',", 'initialdoc)', 'notedoc', '=', "'Notes\\n", '-----\\n', "%s'", '%', 'note', 'if', 'len(notesplit)', '>', '1:', '...
171,388
BMW-InnovationLab/BMW-TensorFlow-Inference-API-CPU
visualization_utils.py
save_image_array_as_png
save_image_array_as_png
Saves an image (represented as a numpy array) to PNG.
[ "Saves", "an", "image", "(represented", "as", "a", "numpy", "array)", "to", "PNG." ]
def save_image_array_as_png(image, output_path): image_pil = Image.fromarray(np.uint8(image)).convert('RGB') with tf.gfile.Open(output_path, 'w') as fid: image_pil.save(fid, 'PNG')
['def', 'save_image_array_as_png(image,', 'output_path):', 'image_pil', '=', "Image.fromarray(np.uint8(image)).convert('RGB')", 'with', 'tf.gfile.Open(output_path,', "'w')", 'as', 'fid:', 'image_pil.save(fid,', "'PNG')"]
463,898
open-mmlab/mmdetection3d
fcos_mono3d_head.py
FCOSMono3DHead.get_direction_target
get_direction_target
Encode direction to 0 ~ num_bins-1.
[ "Encode", "direction", "to", "0", "~", "num_bins-1." ]
def get_direction_target(reg_targets: Tensor, dir_offset: int=0, dir_limit_offset: float=0.0, num_bins: int=2, one_hot: bool=True) -> Tensor: rot_gt = reg_targets[..., 6] offset_rot = limit_period(rot_gt - dir_offset, dir_limit_offset, 2 * np.pi) dir_cls_targets = torch.floor(offset_rot / (2 * np.pi / num_b...
['def', 'get_direction_target(reg_targets:', 'Tensor,', 'dir_offset:', 'int=0,', 'dir_limit_offset:', 'float=0.0,', 'num_bins:', 'int=2,', 'one_hot:', 'bool=True)', '->', 'Tensor:', 'rot_gt', '=', 'reg_targets[...,', '6]', 'offset_rot', '=', 'limit_period(rot_gt', '-', 'dir_offset,', 'dir_limit_offset,', '2', '*', 'np....
631,894
ashwanitanwar/nmt-transfer-learning-xlm-r
metrics.py
log_derived
log_derived
Log a scalar value derived from other meters.
[ "Log", "a", "scalar", "value", "derived", "from", "other", "meters." ]
def log_derived(key: str, fn: Callable[[MetersDict], float], priority: int=20): for agg in get_active_aggregators(): if key not in agg: agg.add_meter(key, MetersDict._DerivedMeter(fn), priority)
['def', 'log_derived(key:', 'str,', 'fn:', 'Callable[[MetersDict],', 'float],', 'priority:', 'int=20):', 'for', 'agg', 'in', 'get_active_aggregators():', 'if', 'key', 'not', 'in', 'agg:', 'agg.add_meter(key,', 'MetersDict._DerivedMeter(fn),', 'priority)']
733,320
LucasAlegre/morl-baselines
pql.py
PQL.get_local_pcs
get_local_pcs
Collect the local PCS in a given state.
[ "Collect", "the", "local", "PCS", "in", "a", "given", "state." ]
def get_local_pcs(self, state: int=0): q_sets = [self.get_q_set(state, action) for action in range(self.num_actions)] candidates = set().union(*q_sets) return get_non_dominated(candidates)
['def', 'get_local_pcs(self,', 'state:', 'int=0):', 'q_sets', '=', '[self.get_q_set(state,', 'action)', 'for', 'action', 'in', 'range(self.num_actions)]', 'candidates', '=', 'set().union(*q_sets)', 'return', 'get_non_dominated(candidates)']
655,923
mideind/GreynirServer
test_greynir.py
test_api
test_api
Call API routes and validate response.
[ "Call", "API", "routes", "and", "validate", "response." ]
def test_api(client: FlaskClient): for r in API_ROUTES: resp = client.post(str(r)) assert resp.content_type.startswith(API_CONTENT_TYPE) == True
['def', 'test_api(client:', 'FlaskClient):', 'for', 'r', 'in', 'API_ROUTES:', 'resp', '=', 'client.post(str(r))', 'assert', 'resp.content_type.startswith(API_CONTENT_TYPE)', '==', 'True']
581,316
locationlabs/mockredis
sortedset.py
SortedSet.scorerange
scorerange
Return (score, member) pairs between min and max scores.
[ "Return", "(score,", "member)", "pairs", "between", "min", "and", "max", "scores." ]
def scorerange(self, start, end, start_inclusive=True, end_inclusive=True): if not self: return [] left = bisect_left(self._scores, (start,)) right = bisect_right(self._scores, (end,)) if end_inclusive: while right < len(self) and self._scores[right][0] == end: right += 1 ...
['def', 'scorerange(self,', 'start,', 'end,', 'start_inclusive=True,', 'end_inclusive=True):', 'if', 'not', 'self:', 'return', '[]', 'left', '=', 'bisect_left(self._scores,', '(start,))', 'right', '=', 'bisect_right(self._scores,', '(end,))', 'if', 'end_inclusive:', 'while', 'right', '<', 'len(self)', 'and', 'self._sco...
240,640
tusen-ai/simpledet
memonger_v2.py
is_param
is_param
Quick script to check if name is a parameter.
[ "Quick", "script", "to", "check", "if", "name", "is", "a", "parameter." ]
def is_param(name): if name == 'data': return False if name.endswith('weight'): return True if name.endswith('bias'): return True if name.endswith('beta'): return True if name.endswith('gamma'): return True return False
['def', 'is_param(name):', 'if', 'name', '==', "'data':", 'return', 'False', 'if', "name.endswith('weight'):", 'return', 'True', 'if', "name.endswith('bias'):", 'return', 'True', 'if', "name.endswith('beta'):", 'return', 'True', 'if', "name.endswith('gamma'):", 'return', 'True', 'return', 'False']
883,208
cagbal/ros_people_object_detection_tensorflow
label_map_util.py
get_label_map_dict
get_label_map_dict
Reads a label map and returns a dictionary of label names to id.
[ "Reads", "a", "label", "map", "and", "returns", "a", "dictionary", "of", "label", "names", "to", "id." ]
def get_label_map_dict(label_map_path, use_display_name=False): label_map = load_labelmap(label_map_path) label_map_dict = {} for item in label_map.item: if use_display_name: label_map_dict[item.display_name] = item.id else: label_map_dict[item.name] = item.id ret...
['def', 'get_label_map_dict(label_map_path,', 'use_display_name=False):', 'label_map', '=', 'load_labelmap(label_map_path)', 'label_map_dict', '=', '{}', 'for', 'item', 'in', 'label_map.item:', 'if', 'use_display_name:', 'label_map_dict[item.display_name]', '=', 'item.id', 'else:', 'label_map_dict[item.name]', '=', 'it...
827,657
IntelLabs/coach
kubernetes_orchestrator.py
Kubernetes.deploy_worker
deploy_worker
Deploys the rollout worker(s) in Kubernetes.
[ "Deploys", "the", "rollout", "worker(s)", "in", "Kubernetes." ]
def deploy_worker(self): worker_params = self.params.run_type_params.get(str(RunType.ROLLOUT_WORKER), None) if not worker_params: return False worker_params.command += ['--memory_backend_params', json.dumps(self.params.memory_backend_parameters.__dict__)] worker_params.command += ['--data_store_...
['def', 'deploy_worker(self):', 'worker_params', '=', 'self.params.run_type_params.get(str(RunType.ROLLOUT_WORKER),', 'None)', 'if', 'not', 'worker_params:', 'return', 'False', 'worker_params.command', '+=', "['--memory_backend_params',", 'json.dumps(self.params.memory_backend_parameters.__dict__)]', 'worker_params.com...
124,635
bsingh17/Natural-Language-Processing
evaluate.py
rouge_log
rouge_log
Log ROUGE results to screen and write to file.
[ "Log", "ROUGE", "results", "to", "screen", "and", "write", "to", "file." ]
def rouge_log(results_dict, dir_to_write, output_file): log_str = '' for x in ['1', '2', 'l']: log_str += '\nROUGE-%s:\n' % x for y in ['f_score', 'recall', 'precision']: key = 'rouge_%s_%s' % (x, y) key_cb = key + '_cb' key_ce = key + '_ce' val = ...
['def', 'rouge_log(results_dict,', 'dir_to_write,', 'output_file):', 'log_str', '=', "''", 'for', 'x', 'in', "['1',", "'2',", "'l']:", 'log_str', '+=', "'\\nROUGE-%s:\\n'", '%', 'x', 'for', 'y', 'in', "['f_score',", "'recall',", "'precision']:", 'key', '=', "'rouge_%s_%s'", '%', '(x,', 'y)', 'key_cb', '=', 'key', '+', ...
703,016
lektor/lektor-archive
editor.py
make_editor_session
make_editor_session
Creates an editor session for the given path object.
[ "Creates", "an", "editor", "session", "for", "the", "given", "path", "object." ]
def make_editor_session(pad, path, is_attachment=None, alt=PRIMARY_ALT, datamodel=None): if alt != PRIMARY_ALT and (not pad.db.config.is_valid_alternative(alt)): raise BadEdit('Attempted to edit an invalid alternative (%s)' % alt) raw_data = pad.db.load_raw_data(path, cls=OrderedDict, alt=alt) id = ...
['def', 'make_editor_session(pad,', 'path,', 'is_attachment=None,', 'alt=PRIMARY_ALT,', 'datamodel=None):', 'if', 'alt', '!=', 'PRIMARY_ALT', 'and', '(not', 'pad.db.config.is_valid_alternative(alt)):', 'raise', "BadEdit('Attempted", 'to', 'edit', 'an', 'invalid', 'alternative', "(%s)'", '%', 'alt)', 'raw_data', '=', 'p...
216,435
Ruturaj123/Flowchart-Detection
reader_ops_test.py
TFRecordIteratorTest.testBadFile
testBadFile
Verify that tf_record_iterator throws an exception on bad TFRecords.
[ "Verify", "that", "tf_record_iterator", "throws", "an", "exception", "on", "bad", "TFRecords." ]
def testBadFile(self): fn = os.path.join(self.get_temp_dir(), 'bad_file') with tf_record.TFRecordWriter(fn) as writer: writer.write(b'123') fn_truncated = os.path.join(self.get_temp_dir(), 'bad_file_truncated') with open(fn, 'rb') as f: with open(fn_truncated, 'wb') as f2: f2...
['def', 'testBadFile(self):', 'fn', '=', 'os.path.join(self.get_temp_dir(),', "'bad_file')", 'with', 'tf_record.TFRecordWriter(fn)', 'as', 'writer:', "writer.write(b'123')", 'fn_truncated', '=', 'os.path.join(self.get_temp_dir(),', "'bad_file_truncated')", 'with', 'open(fn,', "'rb')", 'as', 'f:', 'with', 'open(fn_trunc...
605,654
danielajisafe/Real-Time-Object-detection-API
preprocessor.py
random_jitter_boxes
random_jitter_boxes
Randomly jitter boxes in image.
[ "Randomly", "jitter", "boxes", "in", "image." ]
def random_jitter_boxes(boxes, ratio=0.05, seed=None): def random_jitter_box(box, ratio, seed): rand_numbers = tf.random_uniform([1, 1, 4], minval=-ratio, maxval=ratio, dtype=tf.float32, seed=seed) box_width = tf.subtract(box[0, 0, 3], box[0, 0, 1]) box_height = tf.subtract(box[0, 0, 2], bo...
['def', 'random_jitter_boxes(boxes,', 'ratio=0.05,', 'seed=None):', 'def', 'random_jitter_box(box,', 'ratio,', 'seed):', 'rand_numbers', '=', 'tf.random_uniform([1,', '1,', '4],', 'minval=-ratio,', 'maxval=ratio,', 'dtype=tf.float32,', 'seed=seed)', 'box_width', '=', 'tf.subtract(box[0,', '0,', '3],', 'box[0,', '0,', '...
849,452
intel/neural-compressor
quantize_graph_common.py
QuantizeGraphHelper.set_attr_string
set_attr_string
Set the node's attr which data type is string.
[ "Set", "the", "node's", "attr", "which", "data", "type", "is", "string." ]
def set_attr_string(node, key, value): node.attr[key].CopyFrom(attr_value_pb2.AttrValue(s=value))
['def', 'set_attr_string(node,', 'key,', 'value):', 'node.attr[key].CopyFrom(attr_value_pb2.AttrValue(s=value))']
737,627
llSourcell/autoencoder_demo
input_data.py
extract_labels
extract_labels
Extract the labels into a 1D uint8 numpy array [index].
[ "Extract", "the", "labels", "into", "a", "1D", "uint8", "numpy", "array", "[index]." ]
def extract_labels(filename, one_hot=False): print('Extracting', filename) with gzip.open(filename) as bytestream: magic = _read32(bytestream) if magic != 2049: raise ValueError('Invalid magic number %d in MNIST label file: %s' % (magic, filename)) num_items = _read32(bytestr...
['def', 'extract_labels(filename,', 'one_hot=False):', "print('Extracting',", 'filename)', 'with', 'gzip.open(filename)', 'as', 'bytestream:', 'magic', '=', '_read32(bytestream)', 'if', 'magic', '!=', '2049:', 'raise', "ValueError('Invalid", 'magic', 'number', '%d', 'in', 'MNIST', 'label', 'file:', "%s'", '%', '(magic,...
419,671
sktime/sktime
test_kernel_k_means.py
test_kernel_k_means
test_kernel_k_means
Test implementation of kernel k means.
[ "Test", "implementation", "of", "kernel", "k", "means." ]
def test_kernel_k_means(): (X_train, y_train) = load_basic_motions(split='train') (X_test, y_test) = load_basic_motions(split='test') kernel_kmeans = TimeSeriesKernelKMeans(random_state=1, n_clusters=3) kernel_kmeans.fit(X_train) test_shape_result = kernel_kmeans.predict(X_test) score = kernel_k...
['def', 'test_kernel_k_means():', '(X_train,', 'y_train)', '=', "load_basic_motions(split='train')", '(X_test,', 'y_test)', '=', "load_basic_motions(split='test')", 'kernel_kmeans', '=', 'TimeSeriesKernelKMeans(random_state=1,', 'n_clusters=3)', 'kernel_kmeans.fit(X_train)', 'test_shape_result', '=', 'kernel_kmeans.pre...
886,078
zackmcnulty/CSE_446-Machine_Learning
misc_util.py
is_local_src_dir
is_local_src_dir
Return true if directory is local directory.
[ "Return", "true", "if", "directory", "is", "local", "directory." ]
def is_local_src_dir(directory): if not is_string(directory): return False abs_dir = os.path.abspath(directory) c = os.path.commonprefix([os.getcwd(), abs_dir]) new_dir = abs_dir[len(c):].split(os.sep) if new_dir and (not new_dir[0]): new_dir = new_dir[1:] if new_dir and new_dir[...
['def', 'is_local_src_dir(directory):', 'if', 'not', 'is_string(directory):', 'return', 'False', 'abs_dir', '=', 'os.path.abspath(directory)', 'c', '=', 'os.path.commonprefix([os.getcwd(),', 'abs_dir])', 'new_dir', '=', 'abs_dir[len(c):].split(os.sep)', 'if', 'new_dir', 'and', '(not', 'new_dir[0]):', 'new_dir', '=', 'n...
195,740
wonheeML/mtl-ssl
resnet_v2_test.py
ResnetUtilsTest.testEndPointsV2
testEndPointsV2
Test the end points of a tiny v2 bottleneck network.
[ "Test", "the", "end", "points", "of", "a", "tiny", "v2", "bottleneck", "network." ]
def testEndPointsV2(self): blocks = [resnet_v2.resnet_v2_block('block1', base_depth=1, num_units=2, stride=2), resnet_v2.resnet_v2_block('block2', base_depth=2, num_units=2, stride=1)] inputs = create_test_input(2, 32, 16, 3) with slim.arg_scope(resnet_utils.resnet_arg_scope()): (_, end_points) = se...
['def', 'testEndPointsV2(self):', 'blocks', '=', "[resnet_v2.resnet_v2_block('block1',", 'base_depth=1,', 'num_units=2,', 'stride=2),', "resnet_v2.resnet_v2_block('block2',", 'base_depth=2,', 'num_units=2,', 'stride=1)]', 'inputs', '=', 'create_test_input(2,', '32,', '16,', '3)', 'with', 'slim.arg_scope(resnet_utils.re...
643,294
AEProgrammer/object_detection
keypoint_ops.py
rot90
rot90
Rotates the keypoints counter-clockwise by 90 degrees.
[ "Rotates", "the", "keypoints", "counter-clockwise", "by", "90", "degrees." ]
def rot90(keypoints, scope=None): with tf.name_scope(scope, 'Rot90'): keypoints = tf.transpose(keypoints, [1, 0, 2]) (v, u) = tf.split(value=keypoints[:, :, ::-1], num_or_size_splits=2, axis=2) v = 1.0 - v new_keypoints = tf.concat([v, u], 2) new_keypoints = tf.transpose(new_...
['def', 'rot90(keypoints,', 'scope=None):', 'with', 'tf.name_scope(scope,', "'Rot90'):", 'keypoints', '=', 'tf.transpose(keypoints,', '[1,', '0,', '2])', '(v,', 'u)', '=', 'tf.split(value=keypoints[:,', ':,', '::-1],', 'num_or_size_splits=2,', 'axis=2)', 'v', '=', '1.0', '-', 'v', 'new_keypoints', '=', 'tf.concat([v,',...
771,406
ivanmontero/autobot
finetune.py
SummarizationModule.freeze_embeds
freeze_embeds
Freeze token embeddings and positional embeddings for bart, just token embeddings for t5.
[ "Freeze", "token", "embeddings", "and", "positional", "embeddings", "for", "bart,", "just", "token", "embeddings", "for", "t5." ]
def freeze_embeds(self): if self.model_type == 't5': freeze_params(self.model.shared) for d in [self.model.encoder, self.model.decoder]: freeze_params(d.embed_tokens) elif self.model_type == 'fsmt': for d in [self.model.model.encoder, self.model.model.decoder]: fr...
['def', 'freeze_embeds(self):', 'if', 'self.model_type', '==', "'t5':", 'freeze_params(self.model.shared)', 'for', 'd', 'in', '[self.model.encoder,', 'self.model.decoder]:', 'freeze_params(d.embed_tokens)', 'elif', 'self.model_type', '==', "'fsmt':", 'for', 'd', 'in', '[self.model.model.encoder,', 'self.model.model.dec...
417,723
IIM-TTIJ/MVA2023SmallObjectDetection4SpottingBirds
centripetal_head.py
CentripetalHead.get_bboxes
get_bboxes
Transform network output for a batch into bbox predictions.
[ "Transform", "network", "output", "for", "a", "batch", "into", "bbox", "predictions." ]
def get_bboxes(self, tl_heats, br_heats, tl_offs, br_offs, tl_guiding_shifts, br_guiding_shifts, tl_centripetal_shifts, br_centripetal_shifts, img_metas, rescale=False, with_nms=True): assert tl_heats[-1].shape[0] == br_heats[-1].shape[0] == len(img_metas) result_list = [] for img_id in range(len(img_metas)...
['def', 'get_bboxes(self,', 'tl_heats,', 'br_heats,', 'tl_offs,', 'br_offs,', 'tl_guiding_shifts,', 'br_guiding_shifts,', 'tl_centripetal_shifts,', 'br_centripetal_shifts,', 'img_metas,', 'rescale=False,', 'with_nms=True):', 'assert', 'tl_heats[-1].shape[0]', '==', 'br_heats[-1].shape[0]', '==', 'len(img_metas)', 'resu...
650,891
adammck/pygsm
gsmmodem.py
TestGsmModem.testSendSms
testSendSms
Checks that the GsmModem accepts outgoing SMS, when the text is within ASCII chars 22 - 126.
[ "Checks", "that", "the", "GsmModem", "accepts", "outgoing", "SMS,", "when", "the", "text", "is", "within", "ASCII", "chars", "22", "-", "126." ]
def testSendSms(self): device = MockSenderDevice() gsm = pygsm.GsmModem(device=device).boot() gsm.send_sms('1234', 'Test Message') self.assertEqual(device.sent_messages[0]['recipient'], '1234') self.assertEqual(device.sent_messages[0]['text'], 'Test Message')
['def', 'testSendSms(self):', 'device', '=', 'MockSenderDevice()', 'gsm', '=', 'pygsm.GsmModem(device=device).boot()', "gsm.send_sms('1234',", "'Test", "Message')", "self.assertEqual(device.sent_messages[0]['recipient'],", "'1234')", "self.assertEqual(device.sent_messages[0]['text'],", "'Test", "Message')"]
296,676
kevinzakka/form2fit
misc.py
clip_uv
clip_uv
Ensures pixel coordinates are within image bounds.
[ "Ensures", "pixel", "coordinates", "are", "within", "image", "bounds." ]
def clip_uv(uv, rows, cols): uv[:, 0] = np.clip(uv[:, 0], 0, rows - 1) uv[:, 1] = np.clip(uv[:, 1], 0, cols - 1) return uv
['def', 'clip_uv(uv,', 'rows,', 'cols):', 'uv[:,', '0]', '=', 'np.clip(uv[:,', '0],', '0,', 'rows', '-', '1)', 'uv[:,', '1]', '=', 'np.clip(uv[:,', '1],', '0,', 'cols', '-', '1)', 'return', 'uv']
213,215
ldkong1205/LaserMix
detr3d_head.py
DETR3DHead.loss_by_feat
loss_by_feat
Compute loss of the head.
[ "Compute", "loss", "of", "the", "head." ]
def loss_by_feat(self, batch_gt_instances_3d: InstanceList, preds_dicts: Dict[str, Tensor], batch_gt_instances_3d_ignore: OptInstanceList=None) -> Dict: assert batch_gt_instances_3d_ignore is None, f'{self.__class__.__name__} only supports for batch_gt_instances_3d_ignore setting to None.' all_cls_scores = pred...
['def', 'loss_by_feat(self,', 'batch_gt_instances_3d:', 'InstanceList,', 'preds_dicts:', 'Dict[str,', 'Tensor],', 'batch_gt_instances_3d_ignore:', 'OptInstanceList=None)', '->', 'Dict:', 'assert', 'batch_gt_instances_3d_ignore', 'is', 'None,', "f'{self.__class__.__name__}", 'only', 'supports', 'for', 'batch_gt_instance...
624,519
MANGA-UOFA/NAUS
iterators.py
CountingIterator.take
take
Truncate the iterator to n elements at most.
[ "Truncate", "the", "iterator", "to", "n", "elements", "at", "most." ]
def take(self, n): self.total = min(self.total, n) if hasattr(self._itr, 'take'): self._itr.take(max(n - self.n, 0)) return self
['def', 'take(self,', 'n):', 'self.total', '=', 'min(self.total,', 'n)', 'if', 'hasattr(self._itr,', "'take'):", 'self._itr.take(max(n', '-', 'self.n,', '0))', 'return', 'self']
291,358
DevHunterYZ/Natural-Language-Processing
UnigramModel.py
UnigramModel.score
score
Takes a list of strings, returns a score of that sentence.
[ "Takes", "a", "list", "of", "strings,", "returns", "a", "score", "of", "that", "sentence." ]
def score(self, sentence): score = 0.0 for token in sentence: count = self.unigramCounts[token] if count > 0: score += math.log(count) score -= math.log(self.total) return score
['def', 'score(self,', 'sentence):', 'score', '=', '0.0', 'for', 'token', 'in', 'sentence:', 'count', '=', 'self.unigramCounts[token]', 'if', 'count', '>', '0:', 'score', '+=', 'math.log(count)', 'score', '-=', 'math.log(self.total)', 'return', 'score']
684,454
flytocc/mae-paddle
mixup.py
cutmix_bbox_and_lam
cutmix_bbox_and_lam
Generate bbox and apply lambda correction.
[ "Generate", "bbox", "and", "apply", "lambda", "correction." ]
def cutmix_bbox_and_lam(img_shape, lam, ratio_minmax=None, correct_lam=True, count=None): if ratio_minmax is not None: (yl, yu, xl, xu) = rand_bbox_minmax(img_shape, ratio_minmax, count=count) else: (yl, yu, xl, xu) = rand_bbox(img_shape, lam, count=count) if correct_lam or ratio_minmax is n...
['def', 'cutmix_bbox_and_lam(img_shape,', 'lam,', 'ratio_minmax=None,', 'correct_lam=True,', 'count=None):', 'if', 'ratio_minmax', 'is', 'not', 'None:', '(yl,', 'yu,', 'xl,', 'xu)', '=', 'rand_bbox_minmax(img_shape,', 'ratio_minmax,', 'count=count)', 'else:', '(yl,', 'yu,', 'xl,', 'xu)', '=', 'rand_bbox(img_shape,', 'l...
627,043
google-research/scenic
test_model_utils.py
MetricTest.test_weighted_recall
test_weighted_recall
Tests the topk recall computation.
[ "Tests", "the", "topk", "recall", "computation." ]
def test_weighted_recall(self): logits = np.array([[[2, 3, 4], [4, 3, 2], [4, 2, 3], [3, 2, 4], [4, 2, 3]]]) labels = np.array([[[1, 1, 0], [1, 1, 0], [1, 0, 0], [1, 0, 0], [0, 0, 0]]]) batch_size = 8 logits = jnp.tile(logits, [batch_size, 1, 1]) labels = jnp.tile(labels, [batch_size, 1, 1]) rec...
['def', 'test_weighted_recall(self):', 'logits', '=', 'np.array([[[2,', '3,', '4],', '[4,', '3,', '2],', '[4,', '2,', '3],', '[3,', '2,', '4],', '[4,', '2,', '3]]])', 'labels', '=', 'np.array([[[1,', '1,', '0],', '[1,', '1,', '0],', '[1,', '0,', '0],', '[1,', '0,', '0],', '[0,', '0,', '0]]])', 'batch_size', '=', '8', '...
846,234
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
template.py
Base.indent
indent
Returns the indent string for this item.
[ "Returns", "the", "indent", "string", "for", "this", "item." ]
def indent(self): return self.config.last('indentPrefix', ' ')
['def', 'indent(self):', 'return', "self.config.last('indentPrefix',", "'", "')"]
10,849
zhaxuefan/Computer-Vision
keras_yolo.py
yolo_boxes_to_corners
yolo_boxes_to_corners
Convert YOLO box predictions to bounding box corners.
[ "Convert", "YOLO", "box", "predictions", "to", "bounding", "box", "corners." ]
def yolo_boxes_to_corners(box_xy, box_wh): box_mins = box_xy - box_wh / 2.0 box_maxes = box_xy + box_wh / 2.0 return K.concatenate([box_mins[..., 1:2], box_mins[..., 0:1], box_maxes[..., 1:2], box_maxes[..., 0:1]])
['def', 'yolo_boxes_to_corners(box_xy,', 'box_wh):', 'box_mins', '=', 'box_xy', '-', 'box_wh', '/', '2.0', 'box_maxes', '=', 'box_xy', '+', 'box_wh', '/', '2.0', 'return', 'K.concatenate([box_mins[...,', '1:2],', 'box_mins[...,', '0:1],', 'box_maxes[...,', '1:2],', 'box_maxes[...,', '0:1]])']
470,168
AiIsBetter/computer_vision
rec_postprocess.py
BaseRecLabelDecode.decode
decode
convert text-index into text-label.
[ "convert", "text-index", "into", "text-label." ]
def decode(self, text_index, text_prob=None, is_remove_duplicate=False): result_list = [] ignored_tokens = self.get_ignored_tokens() batch_size = len(text_index) for batch_idx in range(batch_size): char_list = [] conf_list = [] for idx in range(len(text_index[batch_idx])): ...
['def', 'decode(self,', 'text_index,', 'text_prob=None,', 'is_remove_duplicate=False):', 'result_list', '=', '[]', 'ignored_tokens', '=', 'self.get_ignored_tokens()', 'batch_size', '=', 'len(text_index)', 'for', 'batch_idx', 'in', 'range(batch_size):', 'char_list', '=', '[]', 'conf_list', '=', '[]', 'for', 'idx', 'in',...
502,431
bhateharsh/computer_vision
config_util_test.py
ConfigUtilTest.testOverWriteRetainOriginalImages
testOverWriteRetainOriginalImages
Tests that `train_shuffle` keyword arguments are applied correctly.
[ "Tests", "that", "`train_shuffle`", "keyword", "arguments", "are", "applied", "correctly." ]
def testOverWriteRetainOriginalImages(self): original_retain_original_images = True desired_retain_original_images = False pipeline_config_path = os.path.join(self.get_temp_dir(), 'pipeline.config') pipeline_config = pipeline_pb2.TrainEvalPipelineConfig() pipeline_config.eval_config.retain_original_...
['def', 'testOverWriteRetainOriginalImages(self):', 'original_retain_original_images', '=', 'True', 'desired_retain_original_images', '=', 'False', 'pipeline_config_path', '=', 'os.path.join(self.get_temp_dir(),', "'pipeline.config')", 'pipeline_config', '=', 'pipeline_pb2.TrainEvalPipelineConfig()', 'pipeline_config.e...
512,357
KalleHallden/InstaAutomator
pep425tags.py
get_flag
get_flag
Use a fallback method for determining SOABI flags if the needed config var is unset or unavailable.
[ "Use", "a", "fallback", "method", "for", "determining", "SOABI", "flags", "if", "the", "needed", "config", "var", "is", "unset", "or", "unavailable." ]
def get_flag(var, fallback, expected=True, warn=True): val = get_config_var(var) if val is None: if warn: logger.debug("Config variable '%s' is unset, Python ABI tag may be incorrect", var) return fallback() return val == expected
['def', 'get_flag(var,', 'fallback,', 'expected=True,', 'warn=True):', 'val', '=', 'get_config_var(var)', 'if', 'val', 'is', 'None:', 'if', 'warn:', 'logger.debug("Config', 'variable', "'%s'", 'is', 'unset,', 'Python', 'ABI', 'tag', 'may', 'be', 'incorrect",', 'var)', 'return', 'fallback()', 'return', 'val', '==', 'exp...
232,784
mit-gfx/PGMORL
util.py
flatten_grads
flatten_grads
Flattens a variables and their gradients.
[ "Flattens", "a", "variables", "and", "their", "gradients." ]
def flatten_grads(var_list, grads): return tf.concat([tf.reshape(grad, [U.numel(v)]) for (v, grad) in zip(var_list, grads)], 0)
['def', 'flatten_grads(var_list,', 'grads):', 'return', 'tf.concat([tf.reshape(grad,', '[U.numel(v)])', 'for', '(v,', 'grad)', 'in', 'zip(var_list,', 'grads)],', '0)']
768,562
jfzhuang/IFR
metrics.py
total_intersect_and_union
total_intersect_and_union
Calculate Total Intersection and Union.
[ "Calculate", "Total", "Intersection", "and", "Union." ]
def total_intersect_and_union(results, gt_seg_maps, num_classes, ignore_index, label_map=dict(), reduce_zero_label=False): num_imgs = len(results) assert len(gt_seg_maps) == num_imgs total_area_intersect = torch.zeros((num_classes,), dtype=torch.float64) total_area_union = torch.zeros((num_classes,), dt...
['def', 'total_intersect_and_union(results,', 'gt_seg_maps,', 'num_classes,', 'ignore_index,', 'label_map=dict(),', 'reduce_zero_label=False):', 'num_imgs', '=', 'len(results)', 'assert', 'len(gt_seg_maps)', '==', 'num_imgs', 'total_area_intersect', '=', 'torch.zeros((num_classes,),', 'dtype=torch.float64)', 'total_are...
597,510
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
resnet_model.py
block_layer
block_layer
Creates one layer of blocks for the ResNet model.
[ "Creates", "one", "layer", "of", "blocks", "for", "the", "ResNet", "model." ]
def block_layer(inputs, filters, block_fn, blocks, strides, is_training, name, data_format): filters_out = 4 * filters if block_fn is bottleneck_block else filters def projection_shortcut(inputs): return conv2d_fixed_padding(inputs=inputs, filters=filters_out, kernel_size=1, strides=strides, data_forma...
['def', 'block_layer(inputs,', 'filters,', 'block_fn,', 'blocks,', 'strides,', 'is_training,', 'name,', 'data_format):', 'filters_out', '=', '4', '*', 'filters', 'if', 'block_fn', 'is', 'bottleneck_block', 'else', 'filters', 'def', 'projection_shortcut(inputs):', 'return', 'conv2d_fixed_padding(inputs=inputs,', 'filter...
14,063
matsu0228/nlp-jp
_trustregion.py
BaseQuadraticSubproblem.hess
hess
Value of hessian of objective function at current iteration.
[ "Value", "of", "hessian", "of", "objective", "function", "at", "current", "iteration." ]
def hess(self): if self._h is None: self._h = self._hess(self._x) return self._h
['def', 'hess(self):', 'if', 'self._h', 'is', 'None:', 'self._h', '=', 'self._hess(self._x)', 'return', 'self._h']
805,675
Speech-Lab-IITM/CCC-wav2vec-2.0
trainer.py
Trainer.get_model
get_model
Get the (non-wrapped) model instance.
[ "Get", "the", "(non-wrapped)", "model", "instance." ]
def get_model(self): return self._model
['def', 'get_model(self):', 'return', 'self._model']
103,518
SamsungLabs/imvoxelnet
test_config.py
test_config_build_pipeline
test_config_build_pipeline
Test that all detection models defined in the configs can be initialized.
[ "Test", "that", "all", "detection", "models", "defined", "in", "the", "configs", "can", "be", "initialized." ]
def test_config_build_pipeline(): from mmcv import Config from mmdet3d.datasets.pipelines import Compose config_dpath = _get_config_directory() print('Found config_dpath = {!r}'.format(config_dpath)) config_names = ['pointpillars/hv_pointpillars_secfpn_sbn-all_4x8_2x_nus-3d.py'] print('Using {} ...
['def', 'test_config_build_pipeline():', 'from', 'mmcv', 'import', 'Config', 'from', 'mmdet3d.datasets.pipelines', 'import', 'Compose', 'config_dpath', '=', '_get_config_directory()', "print('Found", 'config_dpath', '=', "{!r}'.format(config_dpath))", 'config_names', '=', "['pointpillars/hv_pointpillars_secfpn_sbn-all_...
612,159
rlworkgroup/garage
_dtypes.py
EpisodeBatch.from_list
from_list
Create a EpisodeBatch from a list of episodes.
[ "Create", "a", "EpisodeBatch", "from", "a", "list", "of", "episodes." ]
def from_list(cls, env_spec, paths): lengths = np.asarray([len(p['rewards']) for p in paths]) if all((len(path['observations']) == length + 1 for (path, length) in zip(paths, lengths))): last_observations = np.asarray([p['observations'][-1] for p in paths]) observations = np.concatenate([p['obse...
['def', 'from_list(cls,', 'env_spec,', 'paths):', 'lengths', '=', "np.asarray([len(p['rewards'])", 'for', 'p', 'in', 'paths])', 'if', "all((len(path['observations'])", '==', 'length', '+', '1', 'for', '(path,', 'length)', 'in', 'zip(paths,', 'lengths))):', 'last_observations', '=', "np.asarray([p['observations'][-1]", ...
200,142
gopinath-balu/computer_vision
multitracker.py
STrack.tlwh
tlwh
Get current position in bounding box format `(top left x, top left y, width, height)`.
[ "Get", "current", "position", "in", "bounding", "box", "format", "`(top", "left", "x,", "top", "left", "y,", "width,", "height)`." ]
def tlwh(self): if self.mean is None: return self._tlwh.copy() ret = self.mean[:4].copy() ret[2] *= ret[3] ret[:2] -= ret[2:] / 2 return ret
['def', 'tlwh(self):', 'if', 'self.mean', 'is', 'None:', 'return', 'self._tlwh.copy()', 'ret', '=', 'self.mean[:4].copy()', 'ret[2]', '*=', 'ret[3]', 'ret[:2]', '-=', 'ret[2:]', '/', '2', 'return', 'ret']
476,058
xvjiarui/VFS
build_rawframes.py
extract_frame
extract_frame
Generate optical flow using dense flow.
[ "Generate", "optical", "flow", "using", "dense", "flow." ]
def extract_frame(vid_item): (full_path, vid_path, vid_id, method, task) = vid_item if '/' in vid_path: act_name = osp.basename(osp.dirname(vid_path)) out_full_path = osp.join(args.out_dir, act_name) else: out_full_path = args.out_dir if task == 'rgb': if args.use_opencv:...
['def', 'extract_frame(vid_item):', '(full_path,', 'vid_path,', 'vid_id,', 'method,', 'task)', '=', 'vid_item', 'if', "'/'", 'in', 'vid_path:', 'act_name', '=', 'osp.basename(osp.dirname(vid_path))', 'out_full_path', '=', 'osp.join(args.out_dir,', 'act_name)', 'else:', 'out_full_path', '=', 'args.out_dir', 'if', 'task'...
379,721
mapbox/robosat
rasterize.py
feature_to_mercator
feature_to_mercator
Normalize feature and converts coords to 3857.
[ "Normalize", "feature", "and", "converts", "coords", "to", "3857." ]
def feature_to_mercator(feature): src_crs = CRS.from_epsg(4326) dst_crs = CRS.from_epsg(3857) geometry = feature['geometry'] if geometry['type'] == 'Polygon': xys = (zip(*part) for part in geometry['coordinates']) xys = (list(zip(*transform(src_crs, dst_crs, *xy))) for xy in xys) ...
['def', 'feature_to_mercator(feature):', 'src_crs', '=', 'CRS.from_epsg(4326)', 'dst_crs', '=', 'CRS.from_epsg(3857)', 'geometry', '=', "feature['geometry']", 'if', "geometry['type']", '==', "'Polygon':", 'xys', '=', '(zip(*part)', 'for', 'part', 'in', "geometry['coordinates'])", 'xys', '=', '(list(zip(*transform(src_c...
825,997
triaquae/triaquae
__init__.py
BaseDatabaseWrapper.is_managed
is_managed
Checks whether the transaction manager is in manual or in auto state.
[ "Checks", "whether", "the", "transaction", "manager", "is", "in", "manual", "or", "in", "auto", "state." ]
def is_managed(self): if self.transaction_state: return self.transaction_state[-1] return settings.TRANSACTIONS_MANAGED
['def', 'is_managed(self):', 'if', 'self.transaction_state:', 'return', 'self.transaction_state[-1]', 'return', 'settings.TRANSACTIONS_MANAGED']
423,305
greydanus/mr_london
urls.py
BytesURL.encode_netloc
encode_netloc
Returns the netloc unchanged as bytes.
[ "Returns", "the", "netloc", "unchanged", "as", "bytes." ]
def encode_netloc(self): return self.netloc
['def', 'encode_netloc(self):', 'return', 'self.netloc']
264,213
wonheeML/mtl-ssl
rfcn_meta_arch.py
RFCNMetaArch.predict_with_window
predict_with_window
Predicts the output tensors from 2nd stage of FasterRCNN.
[ "Predicts", "the", "output", "tensors", "from", "2nd", "stage", "of", "FasterRCNN." ]
def predict_with_window(self, prediction_dict, window_boxes_normalized=None): mtl = self._mtl if window_boxes_normalized == None: window_boxes_normalized = tf.stack(self.window_lists(fields.BoxListFields.boxes)) rpn_features = prediction_dict['rpn_features_to_crop'] if mtl.stop_gradient_for_aux_...
['def', 'predict_with_window(self,', 'prediction_dict,', 'window_boxes_normalized=None):', 'mtl', '=', 'self._mtl', 'if', 'window_boxes_normalized', '==', 'None:', 'window_boxes_normalized', '=', 'tf.stack(self.window_lists(fields.BoxListFields.boxes))', 'rpn_features', '=', "prediction_dict['rpn_features_to_crop']", '...
643,104
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
Wald_Friedman_utils.py
make_distribution_plots
make_distribution_plots
This generates the figure that shows the initial versions of the distributions and plots their combinations.
[ "This", "generates", "the", "figure", "that", "shows", "the", "initial", "versions", "of", "the", "distributions", "and", "plots", "their", "combinations." ]
def make_distribution_plots(f0, f1): (fig, ax) = plt.subplots(2, figsize=(10, 8)) ax[0].set_title('Original Distributions') ax[0].set_xlabel('$k$ Values') ax[0].set_ylabel('Probability of $z_k$') ax[0].plot(f0, label='$f_0$') ax[0].plot(f1, label='$f_1$') ax[0].legend() ax[1].set_title('...
['def', 'make_distribution_plots(f0,', 'f1):', '(fig,', 'ax)', '=', 'plt.subplots(2,', 'figsize=(10,', '8))', "ax[0].set_title('Original", "Distributions')", "ax[0].set_xlabel('$k$", "Values')", "ax[0].set_ylabel('Probability", 'of', "$z_k$')", 'ax[0].plot(f0,', "label='$f_0$')", 'ax[0].plot(f1,', "label='$f_1$')", 'ax...
12,246
rudranil723/mini-main
distro.py
LinuxDistribution.oslevel_info
oslevel_info
Return AIX' oslevel command output.
[ "Return", "AIX'", "oslevel", "command", "output." ]
def oslevel_info(self) -> str: return self._oslevel_info
['def', 'oslevel_info(self)', '->', 'str:', 'return', 'self._oslevel_info']
268,383
boostcampaitech2/semantic-segmentation-level2-cv-07
anchor_head.py
AnchorHead.loss
loss
Compute losses of the head.
[ "Compute", "losses", "of", "the", "head." ]
def loss(self, cls_scores, bbox_preds, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore=None): featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores] assert len(featmap_sizes) == self.anchor_generator.num_levels device = cls_scores[0].device (anchor_list, valid_flag_list) = self.get_anchors(fe...
['def', 'loss(self,', 'cls_scores,', 'bbox_preds,', 'gt_bboxes,', 'gt_labels,', 'img_metas,', 'gt_bboxes_ignore=None):', 'featmap_sizes', '=', '[featmap.size()[-2:]', 'for', 'featmap', 'in', 'cls_scores]', 'assert', 'len(featmap_sizes)', '==', 'self.anchor_generator.num_levels', 'device', '=', 'cls_scores[0].device', '...
857,003
dvlab-research/VoxelNeXt
fastai_optim.py
split_bn_bias
split_bn_bias
Split the layers in `layer_groups` into batchnorm (`bn_types`) and non-batchnorm groups.
[ "Split", "the", "layers", "in", "`layer_groups`", "into", "batchnorm", "(`bn_types`)", "and", "non-batchnorm", "groups." ]
def split_bn_bias(layer_groups): split_groups = [] for l in layer_groups: (l1, l2) = ([], []) for c in l.children(): if isinstance(c, bn_types): l2.append(c) else: l1.append(c) split_groups += [nn.Sequential(*l1), nn.Sequential(*l2)...
['def', 'split_bn_bias(layer_groups):', 'split_groups', '=', '[]', 'for', 'l', 'in', 'layer_groups:', '(l1,', 'l2)', '=', '([],', '[])', 'for', 'c', 'in', 'l.children():', 'if', 'isinstance(c,', 'bn_types):', 'l2.append(c)', 'else:', 'l1.append(c)', 'split_groups', '+=', '[nn.Sequential(*l1),', 'nn.Sequential(*l2)]', '...
939,754
priorfire4411/artificial_intelligence
glibc.py
libc_ver
libc_ver
Try to determine the glibc version Returns a tuple of strings (lib, version) which default to empty strings in case the lookup fails.
[ "Try", "to", "determine", "the", "glibc", "version", "Returns", "a", "tuple", "of", "strings", "(lib,", "version)", "which", "default", "to", "empty", "strings", "in", "case", "the", "lookup", "fails." ]
def libc_ver(): glibc_version = glibc_version_string() if glibc_version is None: return ('', '') else: return ('glibc', glibc_version)
['def', 'libc_ver():', 'glibc_version', '=', 'glibc_version_string()', 'if', 'glibc_version', 'is', 'None:', 'return', "('',", "'')", 'else:', 'return', "('glibc',", 'glibc_version)']
141,765
google-research/fixmatch
vat_utils.py
generate_perturbation
generate_perturbation
Generate an adversarial perturbation.
[ "Generate", "an", "adversarial", "perturbation." ]
def generate_perturbation(x, logit, forward, epsilon, xi=1e-06): d = tf.random_normal(shape=tf.shape(x)) for _ in range(1): d = xi * get_normalized_vector(d) logit_p = logit logit_m = forward(x + d) dist = kl_divergence_with_logit(logit_p, logit_m) grad = tf.gradients(tf....
['def', 'generate_perturbation(x,', 'logit,', 'forward,', 'epsilon,', 'xi=1e-06):', 'd', '=', 'tf.random_normal(shape=tf.shape(x))', 'for', '_', 'in', 'range(1):', 'd', '=', 'xi', '*', 'get_normalized_vector(d)', 'logit_p', '=', 'logit', 'logit_m', '=', 'forward(x', '+', 'd)', 'dist', '=', 'kl_divergence_with_logit(log...
211,050
liujiaxing7/object_detection_evaluation
recall.py
setRecallParam
setRecallParam
Check proposal_nums and iou_thrs and set correct format.
[ "Check", "proposal_nums", "and", "iou_thrs", "and", "set", "correct", "format." ]
def setRecallParam(proposal_nums, iou_thrs): if isinstance(proposal_nums, Sequence): _proposal_nums = np.array(proposal_nums) elif isinstance(proposal_nums, int): _proposal_nums = np.array([proposal_nums]) else: _proposal_nums = proposal_nums if iou_thrs is None: _iou_thr...
['def', 'setRecallParam(proposal_nums,', 'iou_thrs):', 'if', 'isinstance(proposal_nums,', 'Sequence):', '_proposal_nums', '=', 'np.array(proposal_nums)', 'elif', 'isinstance(proposal_nums,', 'int):', '_proposal_nums', '=', 'np.array([proposal_nums])', 'else:', '_proposal_nums', '=', 'proposal_nums', 'if', 'iou_thrs', '...
794,471
onnx/onnx
serialization.py
_Registry.get_format_from_file_extension
get_format_from_file_extension
Get the corresponding format from a file extension.
[ "Get", "the", "corresponding", "format", "from", "a", "file", "extension." ]
def get_format_from_file_extension(self, file_extension: str) -> str | None: return self._extension_to_format.get(file_extension)
['def', 'get_format_from_file_extension(self,', 'file_extension:', 'str)', '->', 'str', '|', 'None:', 'return', 'self._extension_to_format.get(file_extension)']
756,441
sek788432/Waymo-2D-Object-Detection
xlnet_base_test.py
MaskComputationTests.test_permutation_input_uni_mask
test_permutation_input_uni_mask
Tests if an input, permutation and causal mask are provided.
[ "Tests", "if", "an", "input,", "permutation", "and", "causal", "mask", "are", "provided." ]
def test_permutation_input_uni_mask(self): seq_length = 4 batch_size = 1 memory_length = 0 input_mask = np.array([[1, 1, 1, 0]]) permutation_mask = np.array([[[0, 1, 1, 1], [1, 0, 1, 1], [1, 1, 0, 1], [1, 1, 1, 0]]]) expected_query_mask = np.array([[[[0, 0, 0, 0], [1, 0, 0, 0], [1, 1, 0, 0], [1,...
['def', 'test_permutation_input_uni_mask(self):', 'seq_length', '=', '4', 'batch_size', '=', '1', 'memory_length', '=', '0', 'input_mask', '=', 'np.array([[1,', '1,', '1,', '0]])', 'permutation_mask', '=', 'np.array([[[0,', '1,', '1,', '1],', '[1,', '0,', '1,', '1],', '[1,', '1,', '0,', '1],', '[1,', '1,', '1,', '0]]])...
972,693
PaddlePaddle/PARL
submission_template.py
Board.add_stone
add_stone
Create copy of board containing new stone.
[ "Create", "copy", "of", "board", "containing", "new", "stone." ]
def add_stone(self, column, player): (available_idx,) = np.where(self.np_pieces[:, column] == 0) if len(available_idx) == 0: raise ValueError("Can't play column %s on board %s" % (column, self)) self.np_pieces[available_idx[-1]][column] = player
['def', 'add_stone(self,', 'column,', 'player):', '(available_idx,)', '=', 'np.where(self.np_pieces[:,', 'column]', '==', '0)', 'if', 'len(available_idx)', '==', '0:', 'raise', 'ValueError("Can\'t', 'play', 'column', '%s', 'on', 'board', '%s"', '%', '(column,', 'self))', 'self.np_pieces[available_idx[-1]][column]', '='...
277,656
rfk/playitagainsam
util.py
find_executable
find_executable
Find an executable by searching the user's $PATH.
[ "Find", "an", "executable", "by", "searching", "the", "user's", "$PATH." ]
def find_executable(filename, environ=None): if environ is None: environ = os.environ path = environ.get('PATH', '/usr/local/bin:/usr/bin:/bin').split(':') for dirpath in path: dirpath = os.path.abspath(dirpath.strip()) filepath = os.path.normpath(os.path.join(dirpath, filename)) ...
['def', 'find_executable(filename,', 'environ=None):', 'if', 'environ', 'is', 'None:', 'environ', '=', 'os.environ', 'path', '=', "environ.get('PATH',", "'/usr/local/bin:/usr/bin:/bin').split(':')", 'for', 'dirpath', 'in', 'path:', 'dirpath', '=', 'os.path.abspath(dirpath.strip())', 'filepath', '=', 'os.path.normpath(o...
305,498
OgutuOndati/NaturalLanguageProcessing
run_classifier.py
convert_single_example
convert_single_example
Converts a single `InputExample` into a single `InputFeatures`.
[ "Converts", "a", "single", "`InputExample`", "into", "a", "single", "`InputFeatures`." ]
def convert_single_example(ex_index, example, label_list, max_seq_length, tokenizer): if isinstance(example, PaddingInputExample): return InputFeatures(input_ids=[0] * max_seq_length, input_mask=[0] * max_seq_length, segment_ids=[0] * max_seq_length, label_id=0, is_real_example=False) label_map = {} ...
['def', 'convert_single_example(ex_index,', 'example,', 'label_list,', 'max_seq_length,', 'tokenizer):', 'if', 'isinstance(example,', 'PaddingInputExample):', 'return', 'InputFeatures(input_ids=[0]', '*', 'max_seq_length,', 'input_mask=[0]', '*', 'max_seq_length,', 'segment_ids=[0]', '*', 'max_seq_length,', 'label_id=0...
713,972
gunthercox/ChatterBot
test_core.py
TestMaskedArrayArithmetic.test_basic_ufuncs
test_basic_ufuncs
Test various functions such as sin, cos.
[ "Test", "various", "functions", "such", "as", "sin,", "cos." ]
def test_basic_ufuncs(self): (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d assert_equal(np.cos(x), cos(xm)) assert_equal(np.cosh(x), cosh(xm)) assert_equal(np.sin(x), sin(xm)) assert_equal(np.sinh(x), sinh(xm)) assert_equal(np.tan(x), tan(xm)) assert_equal(np.tanh(x), tanh(xm)) assert_...
['def', 'test_basic_ufuncs(self):', '(x,', 'y,', 'a10,', 'm1,', 'm2,', 'xm,', 'ym,', 'z,', 'zm,', 'xf)', '=', 'self.d', 'assert_equal(np.cos(x),', 'cos(xm))', 'assert_equal(np.cosh(x),', 'cosh(xm))', 'assert_equal(np.sin(x),', 'sin(xm))', 'assert_equal(np.sinh(x),', 'sinh(xm))', 'assert_equal(np.tan(x),', 'tan(xm))', '...
531,997
Hareric/Natural-Language-Processing
data_structures.py
Document.from_sentences
from_sentences
Populate the sentence list.
[ "Populate", "the", "sentence", "list." ]
def from_sentences(sentences, **kwargs): doc = Document() doc.input_file = kwargs.get('input_file', None) for (i, sentence) in enumerate(sentences): s = Sentence(words=sentence['words']) s.pos = sentence['POS'] s.stems = sentence['lemmas'] for (k, infos) in sentence.items(): ...
['def', 'from_sentences(sentences,', '**kwargs):', 'doc', '=', 'Document()', 'doc.input_file', '=', "kwargs.get('input_file',", 'None)', 'for', '(i,', 'sentence)', 'in', 'enumerate(sentences):', 's', '=', "Sentence(words=sentence['words'])", 's.pos', '=', "sentence['POS']", 's.stems', '=', "sentence['lemmas']", 'for', ...
638,034
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
imagenet_data.py
ImagenetData.num_examples_per_epoch
num_examples_per_epoch
Returns the number of examples in the data set.
[ "Returns", "the", "number", "of", "examples", "in", "the", "data", "set." ]
def num_examples_per_epoch(self): if self.subset == 'train': return 1281167 if self.subset == 'validation': return 50000
['def', 'num_examples_per_epoch(self):', 'if', 'self.subset', '==', "'train':", 'return', '1281167', 'if', 'self.subset', '==', "'validation':", 'return', '50000']
48,912